libdictenstein 0.1.0

High-performance dictionary data structures (trie, DAWG, double-array trie, suffix automaton, lock-free durable persistent ART) behind one trait API; pairs with liblevenshtein for fuzzy matching
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
//! Write-Ahead Log (WAL) for crash recovery.
//!
//! This module implements a redo-only WAL for the PersistentARTrie. The WAL
//! ensures durability by logging operations before they are applied to the
//! main data structure.
//!
//! # Design
//!
//! The WAL uses a redo-only approach:
//! - Operations are logged before being applied
//! - On crash recovery, the log is replayed from the last checkpoint
//! - Periodic checkpoints truncate the log
//!
//! # Record Format
//!
//! Each record has the following layout:
//! ```text
//! +----------+----------+----------+----------+----------+
//! | CRC32    | Length   | LSN      | Type     | Payload  |
//! | (4 bytes)| (4 bytes)| (8 bytes)| (1 byte) | (varies) |
//! +----------+----------+----------+----------+----------+
//! ```
//!
//! # Group Commit
//!
//! For performance, multiple operations can be batched into a single fsync:
//! - Writers append to the log buffer
//! - A background thread (or explicit flush) fsyncs periodically
//! - Writers wait for their LSN to be durable before returning
//!
//! # Example
//!
//! ```text
//! use libdictenstein::persistent_artrie::wal::{Wal, WalRecord, WalRecordType};
//!
//! let mut wal = Wal::create("data.wal")?;
//!
//! // Log an insert operation
//! let lsn = wal.append(WalRecord::Insert {
//!     term: "hello".as_bytes().to_vec(),
//!     value: None,
//! })?;
//!
//! // Ensure durability
//! wal.sync()?;
//!
//! // On recovery
//! let mut wal = Wal::open("data.wal")?;
//! for record in wal.iter() {
//!     // Replay the operation
//! }
//! ```

// wal.rs is now a thin re-export hub for the wal/ sub-modules plus the
// `Lsn` type alias, the `crc32` helper, the disabled legacy GroupCommit
// stub, and the integration test suite at the bottom of this file. std
// imports for the tests live inside `mod tests`.

/// Log Sequence Number - monotonically increasing identifier for log records.
pub type Lsn = u64;

// `WalConfig` was relocated to the sibling `wal::config` module; re-exported
// here under its original path.
pub use config::WalConfig;

mod config;

/// CRC32 for record integrity verification.
pub(super) fn crc32(data: &[u8]) -> u32 {
    // Simple CRC32 implementation (IEEE polynomial)
    let mut crc: u32 = 0xFFFFFFFF;
    for byte in data {
        crc ^= *byte as u32;
        for _ in 0..8 {
            if crc & 1 != 0 {
                crc = (crc >> 1) ^ 0xEDB88320;
            } else {
                crc >>= 1;
            }
        }
    }
    !crc
}

// `WalRecord` + `WalRecordType` (record-type discriminant + payload codec)
// were relocated to the sibling `wal::codec` module; re-exported here under
// their original paths.
pub use codec::{WalRecord, WalRecordType};

mod codec;

// `WalError` was relocated to the sibling `wal::error` module; re-exported
// here under its original path.
pub use error::WalError;

mod error;

// `WalHeader` was relocated to the sibling `wal::header` module; re-exported
// here under its original path.
pub use header::{RankRegime, WalHeader};

mod header;

// `WalWriter` was relocated to the sibling `wal::writer` module; re-exported
// here under its original path.
pub use writer::WalWriter;

mod writer;

// `WalReader` and `WalRecordIterator` were relocated to the sibling
// `wal::reader` module; re-exported here under their original paths.
pub use reader::{WalReader, WalRecordIterator};

mod reader;

// DISABLED — the legacy `GroupCommit` stub claimed to batch but its
// `append_sync` synchronously fsync'd every record ("For simplicity, sync
// immediately"). Production batching lives in
// `crate::persistent_artrie_core::group_commit::GroupCommitCoordinator`
// (background thread, AIMD batching, oneshot channels) and is selected via
// `DurabilityPolicy::GroupCommit` routing through
// `WalWriter::sync_async` from `dict_impl::sync()`. The stub had no
// remaining callers; commenting it out per CLAUDE.md to keep the audit
// trail clear.
//
// pub struct GroupCommit {
//     wal: Arc<WalWriter>,
//     pending: Mutex<Vec<(Lsn, std::sync::mpsc::Sender<Result<(), WalError>>)>>,
//     #[allow(dead_code)]
//     sync_interval_ms: u64,
// }
//
// impl GroupCommit {
//     pub fn new(wal: Arc<WalWriter>, sync_interval_ms: u64) -> Self { ... }
//     pub fn append_sync(&self, record: WalRecord) -> Result<Lsn, WalError> {
//         let lsn = self.wal.append(record)?;
//         self.wal.sync()?;            // <-- this defeats the batching premise
//         Ok(lsn)
//     }
//     pub fn wal(&self) -> &WalWriter { &self.wal }
// }

// =============================================================================
// Concurrent WAL Writes - Async Sync Support
// =============================================================================
//
// The following types enable concurrent writes during sync/truncate operations.
// The key insight is that we can rotate to a new WAL segment (O(1) rename) before
// syncing the old segment, allowing writes to continue while a background thread
// handles the expensive fsync operation.
//
// Architecture:
//
// ```text
// Writer ──→ append() ──→ [new_segment.wal] ──→ continues immediately
////                          rotate (O(1))
//////                     Background Thread
//                     ┌─────────────────┐
//                     │ old_segment:    │
//                     │ 1. fsync()      │
//                     │ 2. archive()    │
//                     │ 3. notify()     │
//                     └─────────────────┘
// ```

// The async-write subsystem (SegmentSyncManager + AsyncWalWriter +
// PendingSegment + SyncHandle + collect_all_segments) was moved into the
// sibling wal/ sub-modules, taking its imports with it. The stale block of
// std imports that used to live here has been removed.

// `AsyncWalConfig` was relocated to the sibling `wal::async_config` module;
// re-exported here under its original path.
pub use async_config::AsyncWalConfig;

mod async_config;

// `PendingSegment` was relocated to the sibling `wal::pending_segment` module;
// re-exported here under its original path.
pub use pending_segment::PendingSegment;

mod pending_segment;

// `AsyncWalError` was relocated to the sibling `wal::async_error` module;
// re-exported here under its original path.
pub use async_error::AsyncWalError;

mod async_error;

// `SyncHandle` was relocated to the sibling `wal::sync_handle` module;
// re-exported here under its original path.
pub use sync_handle::SyncHandle;

mod sync_handle;

// `WalSyncBackend` trait + `StdFsync` + `IoUringFsync` impls were relocated to
// the sibling `wal::sync_backend` module. They are re-exported below so
// downstream code (and the rest of this file) can keep using the unqualified
// names `WalSyncBackend`, `StdFsync`, `IoUringFsync`.
#[cfg(feature = "io-uring-backend")]
pub use sync_backend::IoUringFsync;
pub use sync_backend::{StdFsync, WalSyncBackend};

mod sync_backend;

// `SegmentSyncManager`, `AsyncWalWriter`, and the `collect_all_segments`
// recovery helper were relocated to the sibling `wal::async_writer` module;
// re-exported here under their original paths.
pub use async_writer::{collect_all_segments, AsyncWalWriter, SegmentSyncManager};

mod async_writer;

#[cfg(test)]
mod tests {
    use super::*;
    use std::io;
    use std::path::PathBuf;
    use std::time::Duration;
    use tempfile::tempdir;

    #[test]
    fn test_crc32() {
        let data = b"hello world";
        let crc = crc32(data);
        assert_eq!(crc, 0x0D4A1185); // Known CRC32 value
    }

    #[test]
    fn test_wal_record_serialize_deserialize() {
        let record = WalRecord::Insert {
            term: b"hello".to_vec(),
            value: Some(b"world".to_vec()),
        };
        let payload = record.serialize_payload();
        let deserialized =
            WalRecord::deserialize(WalRecordType::Insert, &payload).expect("deserialize failed");

        assert_eq!(record, deserialized);
    }

    #[test]
    fn test_wal_record_remove() {
        let record = WalRecord::Remove {
            term: b"goodbye".to_vec(),
        };
        let payload = record.serialize_payload();
        let deserialized =
            WalRecord::deserialize(WalRecordType::Remove, &payload).expect("deserialize failed");

        assert_eq!(record, deserialized);
    }

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

        let wal = WalWriter::create(&wal_path).expect("create WAL");

        let lsn1 = wal
            .append(WalRecord::Insert {
                term: b"hello".to_vec(),
                value: None,
            })
            .expect("append");

        let lsn2 = wal
            .append(WalRecord::Insert {
                term: b"world".to_vec(),
                value: Some(b"value".to_vec()),
            })
            .expect("append");

        assert_eq!(lsn1, 1);
        assert_eq!(lsn2, 2);

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

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

        // Write records
        {
            let wal = WalWriter::create(&wal_path).expect("create WAL");
            wal.append(WalRecord::Insert {
                term: b"hello".to_vec(),
                value: None,
            })
            .expect("append");
            wal.append(WalRecord::Remove {
                term: b"world".to_vec(),
            })
            .expect("append");
            wal.sync().expect("sync");
        }

        // Read records
        let reader = WalReader::new(&wal_path).expect("open WAL");
        let records: Vec<_> = reader.iter().collect();

        assert_eq!(records.len(), 2);

        let (lsn1, rec1) = records[0].as_ref().expect("record 1");
        assert_eq!(*lsn1, 1);
        assert!(matches!(rec1, WalRecord::Insert { term, .. } if term == b"hello"));

        let (lsn2, rec2) = records[1].as_ref().expect("record 2");
        assert_eq!(*lsn2, 2);
        assert!(matches!(rec2, WalRecord::Remove { term } if term == b"world"));
    }

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

        {
            let wal = WalWriter::create(&wal_path).expect("create WAL");
            wal.append(WalRecord::Insert {
                term: b"test".to_vec(),
                value: None,
            })
            .expect("append");
            wal.checkpoint(1).expect("checkpoint");
        }

        // Verify checkpoint LSN is persisted
        let header = WalReader::read_header(&wal_path).expect("read header");
        assert_eq!(header.checkpoint_lsn, 1);
    }

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

        // Create and write
        {
            let wal = WalWriter::create(&wal_path).expect("create WAL");
            wal.append(WalRecord::Insert {
                term: b"first".to_vec(),
                value: None,
            })
            .expect("append");
            wal.sync().expect("sync");
        }

        // Reopen and append more
        {
            let wal = WalWriter::open(&wal_path).expect("open WAL");
            assert_eq!(wal.current_lsn(), 2); // Next LSN should be 2
            wal.append(WalRecord::Insert {
                term: b"second".to_vec(),
                value: None,
            })
            .expect("append");
            wal.sync().expect("sync");
        }

        // Verify all records
        let reader = WalReader::new(&wal_path).expect("open WAL");
        let records: Vec<_> = reader.iter().collect();
        assert_eq!(records.len(), 2);
    }

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

        // Create WAL and write some records
        {
            let wal = WalWriter::create(&wal_path).expect("create WAL");
            wal.append(WalRecord::Insert {
                term: b"first".to_vec(),
                value: None,
            })
            .expect("append");
            wal.append(WalRecord::Insert {
                term: b"second".to_vec(),
                value: None,
            })
            .expect("append");
            wal.checkpoint(2).expect("checkpoint");
            wal.sync().expect("sync");

            // Verify records exist before truncate
            assert_eq!(wal.current_lsn(), 4); // 2 inserts + 1 checkpoint = LSN 3, next is 4

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

            // Verify LSN is reset
            assert_eq!(wal.current_lsn(), 1);
            assert_eq!(wal.synced_lsn(), 0);
            assert_eq!(wal.checkpoint_lsn(), 0);
        }

        // Verify WAL is empty after truncate
        let reader = WalReader::new(&wal_path).expect("open WAL");
        let records: Vec<_> = reader.iter().collect();
        assert_eq!(records.len(), 0, "WAL should be empty after truncate");

        // Verify we can append new records after truncate
        {
            let wal = WalWriter::open(&wal_path).expect("open WAL");
            assert_eq!(wal.current_lsn(), 1); // Should start fresh

            let lsn = wal
                .append(WalRecord::Insert {
                    term: b"new_record".to_vec(),
                    value: None,
                })
                .expect("append after truncate");
            assert_eq!(lsn, 1);
            wal.sync().expect("sync");
        }

        // Verify new record is readable
        let reader = WalReader::new(&wal_path).expect("open WAL");
        let records: Vec<_> = reader.iter().collect();
        assert_eq!(records.len(), 1);
        let (lsn, rec) = records[0].as_ref().expect("record");
        assert_eq!(*lsn, 1);
        assert!(matches!(rec, WalRecord::Insert { term, .. } if term == b"new_record"));
    }

    #[test]
    fn test_wal_archive_rotation() {
        let dir = tempdir().expect("create temp dir");
        let wal_path = dir.path().join("test.wal");
        let archive_dir = dir.path().join("wal_archive");

        let config = WalConfig {
            archive_enabled: true,
            archive_dir: archive_dir.clone(),
            max_segments: 10,
            max_archive_bytes: 10 << 30, // 10 GB
        };

        // Create WAL and write records
        let wal = WalWriter::create(&wal_path).expect("create WAL");
        wal.append(WalRecord::Insert {
            term: b"record1".to_vec(),
            value: Some(b"value1".to_vec()),
        })
        .expect("append");
        wal.append(WalRecord::Insert {
            term: b"record2".to_vec(),
            value: None,
        })
        .expect("append");
        wal.checkpoint(2).expect("checkpoint");
        wal.sync().expect("sync");

        // Rotate to archive
        let archive_path = wal.rotate_to_archive(&config).expect("rotate");

        // Verify archive segment was created
        assert!(archive_path.exists(), "Archive segment should exist");
        assert!(
            archive_path
                .extension()
                .map_or(false, |ext| ext == "segment"),
            "Archive should have .segment extension"
        );

        // Verify active WAL was recreated and is empty
        assert!(wal_path.exists(), "Active WAL should exist");
        let reader = WalReader::new(&wal_path).expect("open active WAL");
        let records: Vec<_> = reader.iter().collect();
        assert_eq!(
            records.len(),
            0,
            "Active WAL should be empty after rotation"
        );

        // Verify archived segment contains the records
        let reader = WalReader::new(&archive_path).expect("open archive");
        let records: Vec<_> = reader.iter().collect();
        assert_eq!(
            records.len(),
            3,
            "Archive should have 3 records (2 inserts + 1 checkpoint)"
        );
    }

    #[test]
    fn test_wal_collect_segments() {
        let dir = tempdir().expect("create temp dir");
        let wal_path = dir.path().join("test.wal");
        let archive_dir = dir.path().join("wal_archive");

        let config = WalConfig {
            archive_enabled: true,
            archive_dir: archive_dir.clone(),
            max_segments: 10,
            max_archive_bytes: 10 << 30,
        };

        // Create WAL
        let wal = WalWriter::create(&wal_path).expect("create WAL");

        // Initially should have no segments (active WAL is empty)
        let segments = wal.collect_wal_segments(&config).expect("collect");
        assert_eq!(segments.len(), 0, "No segments when WAL is empty");

        // Add records and rotate multiple times
        for i in 0..3 {
            wal.append(WalRecord::Insert {
                term: format!("term{}", i).into_bytes(),
                value: None,
            })
            .expect("append");
            wal.checkpoint(i as u64 + 1).expect("checkpoint");
            wal.sync().expect("sync");
            wal.rotate_to_archive(&config).expect("rotate");
            // Small delay to ensure unique timestamps for segment naming
            std::thread::sleep(std::time::Duration::from_millis(2));
        }

        // Add one more record to active WAL
        wal.append(WalRecord::Insert {
            term: b"active_term".to_vec(),
            value: None,
        })
        .expect("append");
        wal.sync().expect("sync");

        // Collect segments
        let segments = wal.collect_wal_segments(&config).expect("collect");
        assert_eq!(segments.len(), 4, "Should have 3 archived + 1 active");

        // Verify segments are in chronological order
        for i in 0..3 {
            let ext = segments[i].extension().unwrap_or_default();
            assert_eq!(ext, "segment", "Archived segments should come first");
        }
        assert_eq!(segments[3], wal_path, "Active WAL should be last");
    }

    #[test]
    fn test_wal_archive_pruning_by_count() {
        let dir = tempdir().expect("create temp dir");
        let wal_path = dir.path().join("test.wal");
        let archive_dir = dir.path().join("wal_archive");

        let config = WalConfig {
            archive_enabled: true,
            archive_dir: archive_dir.clone(),
            max_segments: 3, // Only keep 3 segments
            max_archive_bytes: u64::MAX,
        };

        // Create WAL and rotate many times.
        //
        // **F7 FIX-D exemption:** `prune_segments_if_needed` NEVER prunes an UN-SUBSUMED
        // segment (`first_lsn > checkpoint_lsn`) — committed records the dense image does
        // not cover must be retained until a checkpoint subsumes them. So to exercise
        // count-pruning we must ADVANCE the durable checkpoint frontier above each rotated
        // segment's records BEFORE rotating: append a record, `checkpoint(current_lsn)` so
        // the segment's records become subsumed (`first_lsn <= checkpoint_lsn`), THEN
        // rotate. The rotate carries the checkpoint frontier and prunes the now-subsumed
        // OLDEST segments down to `max_segments`.
        let wal = WalWriter::create(&wal_path).expect("create WAL");

        for i in 0..6 {
            wal.append(WalRecord::Insert {
                term: format!("term{}", i).into_bytes(),
                value: None,
            })
            .expect("append");
            wal.sync().expect("sync");
            // Subsume everything written so far (the rotate prunes only subsumed segments).
            let frontier = wal.current_lsn().saturating_sub(1);
            wal.checkpoint(frontier).expect("checkpoint");
            wal.rotate_to_archive(&config).expect("rotate");
            // Small delay to ensure unique timestamps for segment naming
            std::thread::sleep(std::time::Duration::from_millis(2));
        }

        // Count segments in archive.
        let segments: Vec<_> = std::fs::read_dir(&archive_dir)
            .expect("read archive dir")
            .filter_map(|e| e.ok())
            .filter(|e| e.path().extension().map_or(false, |ext| ext == "segment"))
            .collect();

        // Subsumed segments are pruned down to max_segments (3).
        assert!(
            segments.len() <= config.max_segments,
            "Should have at most {} subsumed segments, found {}",
            config.max_segments,
            segments.len()
        );
    }

    #[test]
    fn test_wal_archive_disabled() {
        let dir = tempdir().expect("create temp dir");
        let wal_path = dir.path().join("test.wal");
        let archive_dir = dir.path().join("wal_archive");

        let config = WalConfig {
            archive_enabled: false, // Disabled
            archive_dir: archive_dir.clone(),
            max_segments: 10,
            max_archive_bytes: 10 << 30,
        };

        // Create WAL and write records
        let wal = WalWriter::create(&wal_path).expect("create WAL");
        wal.append(WalRecord::Insert {
            term: b"test".to_vec(),
            value: None,
        })
        .expect("append");
        wal.sync().expect("sync");

        // Collect segments should still work (returns active WAL only)
        let segments = wal.collect_wal_segments(&config).expect("collect");
        assert_eq!(segments.len(), 1);
        assert_eq!(segments[0], wal_path);

        // Archive dir should not exist
        assert!(
            !archive_dir.exists(),
            "Archive dir should not be created when disabled"
        );
    }

    #[test]
    fn test_wal_config_default() {
        let config = WalConfig::default();
        assert!(config.archive_enabled);
        assert_eq!(config.max_segments, 10);
        assert_eq!(config.max_archive_bytes, 10 << 30); // 10 GB
    }

    #[test]
    fn test_batch_insert_serialize_deserialize() {
        // Test empty batch
        let record = WalRecord::BatchInsert { entries: vec![] };
        let buf = record.serialize_payload();
        let deserialized =
            WalRecord::deserialize(WalRecordType::BatchInsert, &buf).expect("deserialize");
        match deserialized {
            WalRecord::BatchInsert { entries } => {
                assert_eq!(entries.len(), 0);
            }
            _ => panic!("Expected BatchInsert"),
        }

        // Test batch with multiple entries
        let entries = vec![
            (b"hello".to_vec(), Some(b"world".to_vec())),
            (b"foo".to_vec(), None),
            (b"bar".to_vec(), Some(b"baz".to_vec())),
        ];
        let record = WalRecord::BatchInsert {
            entries: entries.clone(),
        };
        let buf = record.serialize_payload();
        let deserialized =
            WalRecord::deserialize(WalRecordType::BatchInsert, &buf).expect("deserialize");
        match deserialized {
            WalRecord::BatchInsert {
                entries: deserialized_entries,
            } => {
                assert_eq!(deserialized_entries.len(), 3);
                assert_eq!(deserialized_entries[0].0, b"hello");
                assert_eq!(
                    deserialized_entries[0].1.as_ref().map(|v| v.as_slice()),
                    Some(b"world".as_slice())
                );
                assert_eq!(deserialized_entries[1].0, b"foo");
                assert!(deserialized_entries[1].1.is_none());
                assert_eq!(deserialized_entries[2].0, b"bar");
                assert_eq!(
                    deserialized_entries[2].1.as_ref().map(|v| v.as_slice()),
                    Some(b"baz".as_slice())
                );
            }
            _ => panic!("Expected BatchInsert"),
        }
    }

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

        // Create WAL and append a batch
        {
            let wal = WalWriter::create(&wal_path).expect("create WAL");
            let entries = vec![
                (b"term1".to_vec(), Some(b"value1".to_vec())),
                (b"term2".to_vec(), None),
                (b"term3".to_vec(), Some(b"value3".to_vec())),
            ];
            let lsn = wal.append_batch(&entries).expect("append_batch");
            assert_eq!(lsn, 1);
            wal.sync().expect("sync");
        }

        // Verify the batch can be read back
        let reader = WalReader::new(&wal_path).expect("open WAL");
        let records: Vec<_> = reader.iter().collect();
        assert_eq!(records.len(), 1);
        let (lsn, record) = records[0].as_ref().expect("record");
        assert_eq!(*lsn, 1);
        match record {
            WalRecord::BatchInsert { entries } => {
                assert_eq!(entries.len(), 3);
                assert_eq!(entries[0].0, b"term1");
                assert_eq!(entries[1].0, b"term2");
                assert_eq!(entries[2].0, b"term3");
            }
            _ => panic!("Expected BatchInsert"),
        }
    }

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

        // Create WAL and append an empty batch
        let wal = WalWriter::create(&wal_path).expect("create WAL");
        let lsn = wal.append_batch(&[]).expect("append_batch empty");
        assert_eq!(lsn, 1);
        wal.sync().expect("sync");

        // Verify empty batch can be read
        let reader = WalReader::new(&wal_path).expect("open WAL");
        let records: Vec<_> = reader.iter().collect();
        assert_eq!(records.len(), 1);
        let (_, record) = records[0].as_ref().expect("record");
        match record {
            WalRecord::BatchInsert { entries } => {
                assert_eq!(entries.len(), 0);
            }
            _ => panic!("Expected BatchInsert"),
        }
    }

    #[test]
    fn test_batch_insert_record_type() {
        let record = WalRecord::BatchInsert {
            entries: vec![(b"test".to_vec(), None)],
        };
        assert_eq!(record.record_type(), WalRecordType::BatchInsert);
    }

    // =========================================================================
    // TOCTOU Safety Tests
    //
    // These tests verify that the WAL implementation correctly handles
    // concurrent access patterns that could expose TOCTOU vulnerabilities.
    // =========================================================================

    /// Test that open_or_create handles concurrent access correctly.
    /// Multiple threads race to open/create the same WAL file.
    ///
    /// Note: This test verifies TOCTOU safety (no panics, no race-related failures),
    /// not that all threads get a valid WalWriter. Some threads may fail to open
    /// the file because another thread holds it with write access - this is
    /// expected behavior for exclusive file access.
    #[test]
    fn test_open_or_create_toctou_safety() {
        use std::sync::{Arc, Barrier};
        use std::thread;

        let temp_dir = tempdir().expect("create temp dir");
        let wal_path = temp_dir.path().join("concurrent.wal");

        let num_threads = 10;
        let barrier = Arc::new(Barrier::new(num_threads));
        let path = Arc::new(wal_path.clone());

        let handles: Vec<_> = (0..num_threads)
            .map(|_| {
                let barrier = Arc::clone(&barrier);
                let path = Arc::clone(&path);
                thread::spawn(move || {
                    barrier.wait();
                    // All threads race to open_or_create
                    WalWriter::open_or_create(path.as_ref())
                })
            })
            .collect();

        let results: Vec<_> = handles.into_iter().map(|h| h.join().unwrap()).collect();

        // At least one thread should succeed (the one that created the file)
        let successes = results.iter().filter(|r| r.is_ok()).count();
        assert!(successes >= 1, "At least one thread should succeed");

        // All threads should either succeed or fail with an expected error (Io)
        // No thread should fail with NotFound or AlreadyExists (those are TOCTOU symptoms)
        let toctou_failures = results
            .iter()
            .filter(|r| matches!(r, Err(WalError::NotFound) | Err(WalError::AlreadyExists)))
            .count();
        assert_eq!(
            toctou_failures, 0,
            "No threads should fail with TOCTOU-related errors (NotFound/AlreadyExists)"
        );

        // Verify the file was created
        assert!(
            wal_path.exists(),
            "WAL file should exist after concurrent access"
        );
    }

    /// Test that concurrent create with exclusive mode fails correctly for losers.
    #[test]
    fn test_create_exclusive_concurrent() {
        use std::sync::{Arc, Barrier};
        use std::thread;

        let temp_dir = tempdir().expect("create temp dir");
        let wal_path = temp_dir.path().join("exclusive.wal");

        let num_threads = 10;
        let barrier = Arc::new(Barrier::new(num_threads));
        let path = Arc::new(wal_path);

        let handles: Vec<_> = (0..num_threads)
            .map(|_| {
                let barrier = Arc::clone(&barrier);
                let path = Arc::clone(&path);
                thread::spawn(move || {
                    barrier.wait();
                    WalWriter::create(path.as_ref())
                })
            })
            .collect();

        let results: Vec<_> = handles.into_iter().map(|h| h.join().unwrap()).collect();

        // Exactly one should succeed, rest should get AlreadyExists
        let successes = results.iter().filter(|r| r.is_ok()).count();
        let already_exists = results
            .iter()
            .filter(|r| matches!(r, Err(WalError::AlreadyExists)))
            .count();

        assert_eq!(successes, 1, "Exactly one thread should create the file");
        assert_eq!(
            already_exists,
            num_threads - 1,
            "All other threads should get AlreadyExists"
        );
    }

    /// Test that open fails correctly when file is deleted during operation.
    ///
    /// This test exercises the race between opening a file and deleting it.
    /// The TOCTOU-safe implementation should handle this gracefully without panics.
    #[test]
    fn test_open_handles_concurrent_delete() {
        use std::sync::{Arc, Barrier};
        use std::thread;

        let temp_dir = tempdir().expect("create temp dir");
        let wal_path = temp_dir.path().join("delete_race.wal");

        // Create the file first
        let wal = WalWriter::create(&wal_path).expect("create WAL");
        wal.sync().expect("sync");
        drop(wal);

        let barrier = Arc::new(Barrier::new(2));
        let path = Arc::new(wal_path.clone());

        // Thread 1: Tries to open
        let open_barrier = Arc::clone(&barrier);
        let open_path = Arc::clone(&path);
        let open_handle = thread::spawn(move || {
            open_barrier.wait();
            WalWriter::open(open_path.as_ref())
        });

        // Thread 2: Deletes the file
        let delete_barrier = Arc::clone(&barrier);
        let delete_path = Arc::clone(&path);
        let delete_handle = thread::spawn(move || {
            delete_barrier.wait();
            std::fs::remove_file(delete_path.as_ref())
        });

        let open_result = open_handle.join().unwrap();
        let delete_result = delete_handle.join().unwrap();

        // This test verifies we don't panic or get unexpected errors.
        // Valid outcomes for open:
        // - Ok: open completed before delete
        // - NotFound: delete completed before open
        // - Io: delete happened during open (file partially read)
        let open_valid = match &open_result {
            Ok(_) => true,
            Err(WalError::NotFound) => true,
            Err(WalError::Io(_)) => true, // I/O error during read is valid
            Err(WalError::CorruptedRecord(_)) => true, // File deleted mid-read
            Err(WalError::UnexpectedEof) => true, // File deleted mid-read
            _ => false,
        };

        // Valid outcomes for delete:
        // - Ok: delete succeeded
        // - NotFound: file was already gone (shouldn't happen in this test, but valid)
        let delete_ok = delete_result.is_ok();
        let delete_not_found = delete_result
            .as_ref()
            .err()
            .map_or(false, |e| e.kind() == std::io::ErrorKind::NotFound);

        assert!(
            open_valid,
            "Open should succeed or fail with expected error (NotFound, Io, etc.)"
        );
        assert!(
            delete_ok || delete_not_found,
            "Delete should succeed or fail with NotFound"
        );
    }

    /// Test that open_or_create works correctly when file doesn't exist.
    #[test]
    fn test_open_or_create_creates_new() {
        let temp_dir = tempdir().expect("create temp dir");
        let wal_path = temp_dir.path().join("new.wal");

        // File shouldn't exist
        assert!(!wal_path.exists());

        let wal = WalWriter::open_or_create(&wal_path).expect("open_or_create");

        // File should now exist
        assert!(wal_path.exists());

        // Should be able to write records
        let lsn = wal
            .append(WalRecord::Insert {
                term: b"test".to_vec(),
                value: None,
            })
            .expect("append");
        assert_eq!(lsn, 1);
    }

    /// Test that open_or_create works correctly when file already exists.
    #[test]
    fn test_open_or_create_opens_existing() {
        let temp_dir = tempdir().expect("create temp dir");
        let wal_path = temp_dir.path().join("existing.wal");

        // Create file first
        {
            let wal = WalWriter::create(&wal_path).expect("create");
            wal.append(WalRecord::Insert {
                term: b"first".to_vec(),
                value: None,
            })
            .expect("append");
            wal.sync().expect("sync");
        }

        // Open with open_or_create
        let wal = WalWriter::open_or_create(&wal_path).expect("open_or_create");

        // Should continue from existing LSN
        assert_eq!(wal.current_lsn(), 2);

        // Can append more
        let lsn = wal
            .append(WalRecord::Insert {
                term: b"second".to_vec(),
                value: None,
            })
            .expect("append");
        assert_eq!(lsn, 2);
    }

    /// Test that create returns AlreadyExists for existing file (atomic check).
    #[test]
    fn test_create_already_exists() {
        let temp_dir = tempdir().expect("create temp dir");
        let wal_path = temp_dir.path().join("already_exists.wal");

        // Create first
        let _wal = WalWriter::create(&wal_path).expect("create");

        // Second create should fail
        let result = WalWriter::create(&wal_path);
        assert!(
            matches!(result, Err(WalError::AlreadyExists)),
            "Expected AlreadyExists error"
        );
    }

    /// Test that open returns NotFound for non-existent file (atomic check).
    #[test]
    fn test_open_not_found() {
        let temp_dir = tempdir().expect("create temp dir");
        let wal_path = temp_dir.path().join("nonexistent.wal");

        let result = WalWriter::open(&wal_path);
        assert!(
            matches!(result, Err(WalError::NotFound)),
            "Expected NotFound error"
        );
    }

    /// Test that create handles missing parent directory gracefully.
    #[test]
    fn test_create_creates_parent_dirs() {
        let temp_dir = tempdir().expect("create temp dir");
        let wal_path = temp_dir.path().join("nested/dirs/test.wal");

        // Parent dirs don't exist
        assert!(!wal_path.parent().unwrap().exists());

        // create should create them
        let wal = WalWriter::create(&wal_path).expect("create with nested dirs");

        // Verify file and dirs exist
        assert!(wal_path.exists());
        assert!(wal_path.parent().unwrap().exists());

        // Can write records
        let lsn = wal
            .append(WalRecord::Insert {
                term: b"test".to_vec(),
                value: None,
            })
            .expect("append");
        assert_eq!(lsn, 1);
    }

    // =========================================================================
    // Async WAL Writer Tests
    // =========================================================================

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

        let config = AsyncWalConfig {
            pending_dir: dir.path().join("wal_pending"),
            ..Default::default()
        };
        let archive_config = WalConfig {
            archive_enabled: true,
            archive_dir: dir.path().join("wal_archive"),
            ..Default::default()
        };

        let wal =
            AsyncWalWriter::create(&wal_path, config, archive_config).expect("create async WAL");

        // Append some records
        let lsn1 = wal
            .append(WalRecord::Insert {
                term: b"hello".to_vec(),
                value: None,
            })
            .expect("append");
        assert_eq!(lsn1, 1);

        let lsn2 = wal
            .append(WalRecord::Insert {
                term: b"world".to_vec(),
                value: Some(b"value".to_vec()),
            })
            .expect("append");
        assert_eq!(lsn2, 2);

        // Current LSN should be 3 (next to assign)
        assert_eq!(wal.current_lsn(), 3);
    }

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

        let config = AsyncWalConfig {
            pending_dir: dir.path().join("wal_pending"),
            ..Default::default()
        };
        let archive_config = WalConfig {
            archive_enabled: true,
            archive_dir: dir.path().join("wal_archive"),
            ..Default::default()
        };

        let wal =
            AsyncWalWriter::create(&wal_path, config, archive_config).expect("create async WAL");

        // Append records
        wal.append(WalRecord::Insert {
            term: b"term1".to_vec(),
            value: None,
        })
        .expect("append");

        wal.append(WalRecord::Insert {
            term: b"term2".to_vec(),
            value: None,
        })
        .expect("append");

        // Blocking sync
        let synced = wal.sync().expect("sync");
        assert_eq!(synced, 2);

        // Synced LSN should be updated
        assert_eq!(wal.synced_lsn(), 2);
    }

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

        let config = AsyncWalConfig {
            pending_dir: dir.path().join("wal_pending"),
            ..Default::default()
        };
        let archive_config = WalConfig {
            archive_enabled: true,
            archive_dir: dir.path().join("wal_archive"),
            ..Default::default()
        };

        let wal =
            AsyncWalWriter::create(&wal_path, config, archive_config).expect("create async WAL");

        // Append records
        for i in 0..5 {
            wal.append(WalRecord::Insert {
                term: format!("term{}", i).into_bytes(),
                value: None,
            })
            .expect("append");
        }

        // Get async sync handle
        let handle = wal.sync_async().expect("sync_async");
        assert_eq!(handle.target_lsn(), 5);

        // Initially may not be synced (depends on thread timing)
        // Wait for completion
        handle.wait().expect("wait");

        // Now should be synced
        assert!(handle.is_synced());
        assert_eq!(wal.synced_lsn(), 5);
    }

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

        let config = AsyncWalConfig {
            pending_dir: dir.path().join("wal_pending"),
            ..Default::default()
        };
        let archive_config = WalConfig {
            archive_enabled: true,
            archive_dir: dir.path().join("wal_archive"),
            ..Default::default()
        };

        let wal =
            AsyncWalWriter::create(&wal_path, config, archive_config).expect("create async WAL");

        // Append initial batch
        for i in 0..10 {
            wal.append(WalRecord::Insert {
                term: format!("batch1_term{}", i).into_bytes(),
                value: None,
            })
            .expect("append");
        }

        // Start async sync (this rotates the WAL)
        let handle = wal.sync_async().expect("sync_async");
        assert_eq!(handle.target_lsn(), 10);

        // Continue appending while sync is in progress!
        for i in 0..5 {
            let lsn = wal
                .append(WalRecord::Insert {
                    term: format!("batch2_term{}", i).into_bytes(),
                    value: None,
                })
                .expect("append during sync");
            // LSN should continue from previous batch
            assert_eq!(lsn, 11 + i as u64);
        }

        // Wait for first sync to complete
        handle.wait().expect("wait");

        // First batch should now be synced
        assert!(wal.synced_lsn() >= 10);

        // Sync the second batch
        let synced = wal.sync().expect("sync second batch");
        assert!(synced >= 15);
    }

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

        let config = AsyncWalConfig {
            pending_dir: dir.path().join("wal_pending"),
            max_pending_segments: 8, // Allow more pending segments
            ..Default::default()
        };
        let archive_config = WalConfig {
            archive_enabled: true,
            archive_dir: dir.path().join("wal_archive"),
            ..Default::default()
        };

        let wal =
            AsyncWalWriter::create(&wal_path, config, archive_config).expect("create async WAL");

        let mut handles = Vec::new();

        // Create multiple sync operations
        for batch in 0..3 {
            for i in 0..3 {
                wal.append(WalRecord::Insert {
                    term: format!("batch{}_term{}", batch, i).into_bytes(),
                    value: None,
                })
                .expect("append");
            }

            let handle = wal.sync_async().expect("sync_async");
            handles.push(handle);
        }

        // Wait for all syncs to complete (in order)
        for (i, handle) in handles.into_iter().enumerate() {
            handle.wait().expect("wait");
            // Each batch has 3 records
            assert!(handle.target_lsn() >= ((i + 1) * 3) as u64);
        }

        // Final synced LSN should cover all batches
        assert!(wal.synced_lsn() >= 9);
    }

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

        let config = AsyncWalConfig {
            pending_dir: dir.path().join("wal_pending"),
            ..Default::default()
        };
        let archive_config = WalConfig {
            archive_enabled: true,
            archive_dir: dir.path().join("wal_archive"),
            ..Default::default()
        };

        let wal =
            AsyncWalWriter::create(&wal_path, config, archive_config).expect("create async WAL");

        // Append a record
        wal.append(WalRecord::Insert {
            term: b"test".to_vec(),
            value: None,
        })
        .expect("append");

        // Get async handle
        let handle = wal.sync_async().expect("sync_async");

        // Wait with a very long timeout (should succeed)
        let completed = handle
            .wait_timeout(Duration::from_secs(10))
            .expect("wait_timeout");
        assert!(completed, "Sync should complete within timeout");
    }

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

        let config = AsyncWalConfig {
            pending_dir: dir.path().join("wal_pending"),
            ..Default::default()
        };
        let archive_config = WalConfig {
            archive_enabled: true,
            archive_dir: dir.path().join("wal_archive"),
            ..Default::default()
        };

        let wal =
            AsyncWalWriter::create(&wal_path, config, archive_config).expect("create async WAL");

        // Sync without any records (should be no-op)
        let handle = wal.sync_async().expect("sync_async empty");
        assert!(handle.is_synced()); // Already synced (nothing to sync)
    }

    #[test]
    fn test_async_wal_recovery_with_pending_segments() {
        let dir = tempdir().expect("create temp dir");
        let wal_path = dir.path().join("recovery_test.wal");
        let pending_dir = dir.path().join("wal_pending");
        let archive_dir = dir.path().join("wal_archive");

        let config = AsyncWalConfig {
            pending_dir: pending_dir.clone(),
            ..Default::default()
        };
        let archive_config = WalConfig {
            archive_enabled: true,
            archive_dir: archive_dir.clone(),
            ..Default::default()
        };

        // Create WAL and write some data
        {
            let wal = AsyncWalWriter::create(&wal_path, config.clone(), archive_config.clone())
                .expect("create async WAL");

            for i in 0..10 {
                wal.append(WalRecord::Insert {
                    term: format!("term{}", i).into_bytes(),
                    value: Some(format!("value{}", i).into_bytes()),
                })
                .expect("append");
            }

            // Sync to create archive segment
            wal.sync().expect("sync");
        }

        // Collect all segments using the recovery function
        let segments =
            collect_all_segments(&wal_path, &archive_config, &config).expect("collect segments");

        // Should have at least the active WAL (archive segment may have been created)
        assert!(!segments.is_empty(), "Should have at least one segment");

        // Verify we can read from the segments
        let mut total_records = 0;
        for segment in &segments {
            if let Ok(reader) = WalReader::new(segment) {
                for result in reader.iter() {
                    if result.is_ok() {
                        total_records += 1;
                    }
                }
            }
        }

        // Should have recovered all 10 records
        assert_eq!(total_records, 10, "Should recover all 10 records");
    }

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

        let config = AsyncWalConfig {
            pending_dir: dir.path().join("wal_pending"),
            ..Default::default()
        };
        let archive_config = WalConfig {
            archive_enabled: true,
            archive_dir: dir.path().join("wal_archive"),
            ..Default::default()
        };

        let wal =
            AsyncWalWriter::create(&wal_path, config, archive_config).expect("create async WAL");

        // Write and sync some data
        wal.append(WalRecord::Insert {
            term: b"test".to_vec(),
            value: None,
        })
        .expect("append");
        wal.sync().expect("sync");

        // Convert back to sync writer
        let sync_writer = wal.into_sync().expect("into_sync");

        // Should be able to continue using the sync writer
        // Note: After async sync, the WAL was rotated to archive and a fresh WAL was created.
        // So the new LSN starts from where it left off (continuing the sequence).
        let lsn = sync_writer
            .append(WalRecord::Insert {
                term: b"after_convert".to_vec(),
                value: None,
            })
            .expect("append after convert");
        // The LSN continues from the previous sequence, which was 1 before conversion.
        // After conversion and reopening, the WAL scanner finds no records (rotated to archive)
        // and starts fresh from LSN 1.
        assert!(lsn >= 1, "LSN should be at least 1");
    }

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

        let config = AsyncWalConfig {
            pending_dir: dir.path().join("wal_pending"),
            max_pending_segments: 2,        // Very low limit
            max_pending_bytes: 1024 * 1024, // 1MB
            ..Default::default()
        };
        let archive_config = WalConfig {
            archive_enabled: true,
            archive_dir: dir.path().join("wal_archive"),
            ..Default::default()
        };

        let wal =
            AsyncWalWriter::create(&wal_path, config, archive_config).expect("create async WAL");

        // Write enough data to trigger multiple rotations
        // This tests that backpressure kicks in when we have too many pending segments
        for batch in 0..5 {
            for i in 0..10 {
                wal.append(WalRecord::Insert {
                    term: format!("batch{}_term{}", batch, i).into_bytes(),
                    value: Some(vec![0u8; 100]), // Some data to make segments larger
                })
                .expect("append");
            }

            // Start async sync
            let handle = wal.sync_async().expect("sync_async");

            // Wait for this sync to complete before next batch
            // (simulates normal usage pattern)
            handle.wait().expect("wait");
        }

        // All data should be synced
        assert!(wal.synced_lsn() >= 50);
    }

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

        let config = AsyncWalConfig {
            pending_dir: dir.path().join("wal_pending"),
            ..Default::default()
        };
        let archive_config = WalConfig::default();

        let wal =
            AsyncWalWriter::create(&wal_path, config, archive_config).expect("create async WAL");

        wal.append(WalRecord::Insert {
            term: b"test".to_vec(),
            value: None,
        })
        .expect("append");

        let handle = wal.sync_async().expect("sync_async");

        // Debug should not panic
        let debug_str = format!("{:?}", handle);
        assert!(debug_str.contains("SyncHandle"));
        assert!(debug_str.contains("target_lsn"));
    }

    #[test]
    fn test_async_wal_config_defaults() {
        let config = AsyncWalConfig::default();
        assert_eq!(config.max_pending_segments, 4);
        assert_eq!(config.max_pending_bytes, 256 * 1024 * 1024);
        assert_eq!(config.idle_check_interval_ms, 10);
    }

    #[test]
    fn test_async_wal_error_display() {
        let wal_error = AsyncWalError::Wal(WalError::NotFound);
        let display = format!("{}", wal_error);
        assert!(display.contains("WAL error"));

        let sync_failed = AsyncWalError::SegmentSyncFailed {
            path: PathBuf::from("/test/path"),
            attempts: 5,
            last_error: io::Error::new(io::ErrorKind::Other, "test error"),
        };
        let display = format!("{}", sync_failed);
        assert!(display.contains("5 attempts"));

        let rotation_failed = AsyncWalError::RotationFailed {
            reason: "test reason".to_string(),
            source: None,
        };
        let display = format!("{}", rotation_failed);
        assert!(display.contains("test reason"));

        let timeout = AsyncWalError::SyncTimeout {
            target_lsn: 100,
            current_synced: 50,
            timeout_ms: 1000,
        };
        let display = format!("{}", timeout);
        assert!(display.contains("100"));
        assert!(display.contains("50"));
    }

    // =========================================================================
    // WAL Corruption / Truncated Payload Tests
    //
    // These tests verify that WalRecord::deserialize correctly handles
    // malformed/truncated payloads for all record types.
    // =========================================================================

    #[test]
    fn test_deserialize_insert_payload_too_short() {
        // Insert requires at least 5 bytes: term_len (4) + has_value (1)
        let payload = vec![0, 0, 0]; // Only 3 bytes
        let result = WalRecord::deserialize(WalRecordType::Insert, &payload);
        assert!(
            matches!(result, Err(WalError::CorruptedRecord(msg)) if msg.contains("payload too short"))
        );

        // Exactly 4 bytes is still too short
        let payload = vec![0, 0, 0, 0];
        let result = WalRecord::deserialize(WalRecordType::Insert, &payload);
        assert!(
            matches!(result, Err(WalError::CorruptedRecord(msg)) if msg.contains("payload too short"))
        );
    }

    #[test]
    fn test_deserialize_insert_term_truncated() {
        // term_len says 10, but only provide 4 bytes of term + no has_value
        let mut payload = Vec::new();
        payload.extend_from_slice(&10u32.to_le_bytes()); // term_len = 10
        payload.extend_from_slice(&[b'a', b'b', b'c', b'd']); // Only 4 bytes of term
        let result = WalRecord::deserialize(WalRecordType::Insert, &payload);
        assert!(
            matches!(result, Err(WalError::CorruptedRecord(msg)) if msg.contains("term truncated"))
        );
    }

    #[test]
    fn test_deserialize_insert_value_length_truncated() {
        // Valid term, has_value=1, but no value length bytes
        let mut payload = Vec::new();
        payload.extend_from_slice(&5u32.to_le_bytes()); // term_len = 5
        payload.extend_from_slice(b"hello"); // term
        payload.push(1); // has_value = true
                         // Missing value_len bytes
        let result = WalRecord::deserialize(WalRecordType::Insert, &payload);
        assert!(
            matches!(result, Err(WalError::CorruptedRecord(msg)) if msg.contains("value length truncated"))
        );

        // Only partial value_len
        payload.extend_from_slice(&[0, 0]); // Only 2 bytes of value_len
        let result = WalRecord::deserialize(WalRecordType::Insert, &payload);
        assert!(
            matches!(result, Err(WalError::CorruptedRecord(msg)) if msg.contains("value length truncated"))
        );
    }

    #[test]
    fn test_deserialize_insert_value_truncated() {
        // Valid term, has_value=1, value_len=10, but only 5 bytes of value
        let mut payload = Vec::new();
        payload.extend_from_slice(&5u32.to_le_bytes()); // term_len = 5
        payload.extend_from_slice(b"hello"); // term
        payload.push(1); // has_value = true
        payload.extend_from_slice(&10u32.to_le_bytes()); // value_len = 10
        payload.extend_from_slice(&[1, 2, 3, 4, 5]); // Only 5 bytes of value
        let result = WalRecord::deserialize(WalRecordType::Insert, &payload);
        assert!(
            matches!(result, Err(WalError::CorruptedRecord(msg)) if msg.contains("value truncated"))
        );
    }

    #[test]
    fn test_deserialize_insert_no_value_success() {
        // Valid insert with no value
        let mut payload = Vec::new();
        payload.extend_from_slice(&5u32.to_le_bytes()); // term_len = 5
        payload.extend_from_slice(b"hello"); // term
        payload.push(0); // has_value = false
        let result = WalRecord::deserialize(WalRecordType::Insert, &payload);
        assert!(result.is_ok());
        match result.unwrap() {
            WalRecord::Insert { term, value } => {
                assert_eq!(term, b"hello");
                assert!(value.is_none());
            }
            _ => panic!("Expected Insert"),
        }
    }

    #[test]
    fn test_deserialize_remove_payload_too_short() {
        // Remove requires at least 4 bytes for term_len
        let payload = vec![0, 0]; // Only 2 bytes
        let result = WalRecord::deserialize(WalRecordType::Remove, &payload);
        assert!(
            matches!(result, Err(WalError::CorruptedRecord(msg)) if msg.contains("payload too short"))
        );
    }

    #[test]
    fn test_deserialize_remove_term_truncated() {
        // term_len says 10, but only provide 3 bytes
        let mut payload = Vec::new();
        payload.extend_from_slice(&10u32.to_le_bytes()); // term_len = 10
        payload.extend_from_slice(&[b'a', b'b', b'c']); // Only 3 bytes
        let result = WalRecord::deserialize(WalRecordType::Remove, &payload);
        assert!(
            matches!(result, Err(WalError::CorruptedRecord(msg)) if msg.contains("term truncated"))
        );
    }

    #[test]
    fn test_deserialize_checkpoint_payload_too_short() {
        // Checkpoint requires 16 bytes: checkpoint_lsn (8) + timestamp (8)
        let payload = vec![0; 10]; // Only 10 bytes
        let result = WalRecord::deserialize(WalRecordType::Checkpoint, &payload);
        assert!(
            matches!(result, Err(WalError::CorruptedRecord(msg)) if msg.contains("payload too short"))
        );

        // 15 bytes is still too short
        let payload = vec![0; 15];
        let result = WalRecord::deserialize(WalRecordType::Checkpoint, &payload);
        assert!(
            matches!(result, Err(WalError::CorruptedRecord(msg)) if msg.contains("payload too short"))
        );
    }

    #[test]
    fn test_deserialize_begin_tx_payload_too_short() {
        // BeginTx requires 8 bytes for tx_id
        let payload = vec![0; 5]; // Only 5 bytes
        let result = WalRecord::deserialize(WalRecordType::BeginTx, &payload);
        assert!(
            matches!(result, Err(WalError::CorruptedRecord(msg)) if msg.contains("payload too short"))
        );
    }

    #[test]
    fn test_deserialize_commit_tx_payload_too_short() {
        // CommitTx requires 8 bytes for tx_id
        let payload = vec![0; 7]; // Only 7 bytes
        let result = WalRecord::deserialize(WalRecordType::CommitTx, &payload);
        assert!(
            matches!(result, Err(WalError::CorruptedRecord(msg)) if msg.contains("payload too short"))
        );
    }

    #[test]
    fn test_deserialize_abort_tx_payload_too_short() {
        // AbortTx requires 8 bytes for tx_id
        let payload = vec![0; 3]; // Only 3 bytes
        let result = WalRecord::deserialize(WalRecordType::AbortTx, &payload);
        assert!(
            matches!(result, Err(WalError::CorruptedRecord(msg)) if msg.contains("payload too short"))
        );
    }

    #[test]
    fn test_deserialize_increment_payload_too_short() {
        // Increment requires at least 4 bytes for term_len
        let payload = vec![0; 2]; // Only 2 bytes
        let result = WalRecord::deserialize(WalRecordType::Increment, &payload);
        assert!(
            matches!(result, Err(WalError::CorruptedRecord(msg)) if msg.contains("payload too short"))
        );
    }

    #[test]
    fn test_deserialize_increment_payload_truncated() {
        // term_len (4) + term + delta (8) + result (8) = 4 + term_len + 16
        let mut payload = Vec::new();
        payload.extend_from_slice(&5u32.to_le_bytes()); // term_len = 5
        payload.extend_from_slice(b"hello"); // term
        payload.extend_from_slice(&[0; 10]); // Only 10 bytes instead of 16 (delta + result)
        let result = WalRecord::deserialize(WalRecordType::Increment, &payload);
        assert!(matches!(result, Err(WalError::CorruptedRecord(msg)) if msg.contains("truncated")));
    }

    #[test]
    fn test_deserialize_upsert_payload_too_short() {
        // Upsert requires at least 4 bytes for term_len
        let payload = vec![0; 3]; // Only 3 bytes
        let result = WalRecord::deserialize(WalRecordType::Upsert, &payload);
        assert!(
            matches!(result, Err(WalError::CorruptedRecord(msg)) if msg.contains("payload too short"))
        );
    }

    #[test]
    fn test_deserialize_upsert_term_truncated() {
        // term_len says 10, but missing value_len
        let mut payload = Vec::new();
        payload.extend_from_slice(&5u32.to_le_bytes()); // term_len = 5
        payload.extend_from_slice(b"hello"); // term
                                             // Missing value_len (4 bytes)
        let result = WalRecord::deserialize(WalRecordType::Upsert, &payload);
        assert!(
            matches!(result, Err(WalError::CorruptedRecord(msg)) if msg.contains("term truncated"))
        );
    }

    #[test]
    fn test_deserialize_upsert_value_truncated() {
        // Valid term_len, term, value_len, but truncated value
        let mut payload = Vec::new();
        payload.extend_from_slice(&5u32.to_le_bytes()); // term_len = 5
        payload.extend_from_slice(b"hello"); // term
        payload.extend_from_slice(&10u32.to_le_bytes()); // value_len = 10
        payload.extend_from_slice(&[1, 2, 3]); // Only 3 bytes of value
        let result = WalRecord::deserialize(WalRecordType::Upsert, &payload);
        assert!(
            matches!(result, Err(WalError::CorruptedRecord(msg)) if msg.contains("value truncated"))
        );
    }

    #[test]
    fn test_deserialize_cas_payload_too_short() {
        // CAS requires at least 4 bytes for term_len
        let payload = vec![0; 2]; // Only 2 bytes
        let result = WalRecord::deserialize(WalRecordType::CompareAndSwap, &payload);
        assert!(
            matches!(result, Err(WalError::CorruptedRecord(msg)) if msg.contains("payload too short"))
        );
    }

    #[test]
    fn test_deserialize_cas_term_truncated() {
        // term_len + term but missing has_expected
        let mut payload = Vec::new();
        payload.extend_from_slice(&5u32.to_le_bytes()); // term_len = 5
        payload.extend_from_slice(b"hello"); // term
                                             // Missing has_expected byte
        let result = WalRecord::deserialize(WalRecordType::CompareAndSwap, &payload);
        assert!(
            matches!(result, Err(WalError::CorruptedRecord(msg)) if msg.contains("term truncated"))
        );
    }

    #[test]
    fn test_deserialize_cas_expected_length_truncated() {
        // Valid term, has_expected=1, but missing expected_len
        let mut payload = Vec::new();
        payload.extend_from_slice(&5u32.to_le_bytes()); // term_len = 5
        payload.extend_from_slice(b"hello"); // term
        payload.push(1); // has_expected = true
                         // Missing expected_len (4 bytes)
        let result = WalRecord::deserialize(WalRecordType::CompareAndSwap, &payload);
        assert!(
            matches!(result, Err(WalError::CorruptedRecord(msg)) if msg.contains("expected length truncated"))
        );
    }

    #[test]
    fn test_deserialize_cas_expected_truncated() {
        // Valid term, has_expected=1, expected_len=10, but truncated expected value
        let mut payload = Vec::new();
        payload.extend_from_slice(&5u32.to_le_bytes()); // term_len = 5
        payload.extend_from_slice(b"hello"); // term
        payload.push(1); // has_expected = true
        payload.extend_from_slice(&10u32.to_le_bytes()); // expected_len = 10
        payload.extend_from_slice(&[1, 2, 3]); // Only 3 bytes
        let result = WalRecord::deserialize(WalRecordType::CompareAndSwap, &payload);
        assert!(
            matches!(result, Err(WalError::CorruptedRecord(msg)) if msg.contains("expected truncated"))
        );
    }

    #[test]
    fn test_deserialize_cas_new_value_length_truncated() {
        // Valid term, has_expected=0, but missing new_value_len
        let mut payload = Vec::new();
        payload.extend_from_slice(&5u32.to_le_bytes()); // term_len = 5
        payload.extend_from_slice(b"hello"); // term
        payload.push(0); // has_expected = false
                         // Missing new_value_len (4 bytes)
        let result = WalRecord::deserialize(WalRecordType::CompareAndSwap, &payload);
        assert!(
            matches!(result, Err(WalError::CorruptedRecord(msg)) if msg.contains("new_value length truncated"))
        );
    }

    #[test]
    fn test_deserialize_cas_new_value_truncated() {
        // Valid term, has_expected=0, new_value_len=10, but truncated new_value
        let mut payload = Vec::new();
        payload.extend_from_slice(&5u32.to_le_bytes()); // term_len = 5
        payload.extend_from_slice(b"hello"); // term
        payload.push(0); // has_expected = false
        payload.extend_from_slice(&10u32.to_le_bytes()); // new_value_len = 10
        payload.extend_from_slice(&[1, 2, 3, 4, 5]); // Only 5 bytes (missing success byte too)
        let result = WalRecord::deserialize(WalRecordType::CompareAndSwap, &payload);
        assert!(
            matches!(result, Err(WalError::CorruptedRecord(msg)) if msg.contains("new_value truncated"))
        );
    }

    #[test]
    fn test_deserialize_batch_insert_payload_too_short() {
        // BatchInsert requires at least 4 bytes for count
        let payload = vec![0; 2]; // Only 2 bytes
        let result = WalRecord::deserialize(WalRecordType::BatchInsert, &payload);
        assert!(
            matches!(result, Err(WalError::CorruptedRecord(msg)) if msg.contains("payload too short"))
        );
    }

    #[test]
    fn test_deserialize_batch_insert_entry_term_len_truncated() {
        // count=2, but entry 0 is incomplete
        let mut payload = Vec::new();
        payload.extend_from_slice(&2u32.to_le_bytes()); // count = 2
                                                        // Entry 0: incomplete term_len
        payload.extend_from_slice(&[0, 0]); // Only 2 bytes of term_len
        let result = WalRecord::deserialize(WalRecordType::BatchInsert, &payload);
        assert!(
            matches!(result, Err(WalError::CorruptedRecord(msg)) if msg.contains("entry 0 term_len truncated"))
        );
    }

    #[test]
    fn test_deserialize_batch_insert_entry_term_truncated() {
        // count=1, term_len=10 but only 3 bytes of term
        let mut payload = Vec::new();
        payload.extend_from_slice(&1u32.to_le_bytes()); // count = 1
        payload.extend_from_slice(&10u32.to_le_bytes()); // term_len = 10
        payload.extend_from_slice(&[b'a', b'b', b'c']); // Only 3 bytes of term
        let result = WalRecord::deserialize(WalRecordType::BatchInsert, &payload);
        assert!(
            matches!(result, Err(WalError::CorruptedRecord(msg)) if msg.contains("entry 0 term truncated"))
        );
    }

    #[test]
    fn test_deserialize_batch_insert_entry_value_len_truncated() {
        // count=1, valid term, has_value=1, but missing value_len
        let mut payload = Vec::new();
        payload.extend_from_slice(&1u32.to_le_bytes()); // count = 1
        payload.extend_from_slice(&5u32.to_le_bytes()); // term_len = 5
        payload.extend_from_slice(b"hello"); // term
        payload.push(1); // has_value = true
                         // Missing value_len (4 bytes)
        let result = WalRecord::deserialize(WalRecordType::BatchInsert, &payload);
        assert!(
            matches!(result, Err(WalError::CorruptedRecord(msg)) if msg.contains("entry 0 value_len truncated"))
        );
    }

    #[test]
    fn test_deserialize_batch_insert_entry_value_truncated() {
        // count=1, valid term, has_value=1, value_len=10, but only 3 bytes of value
        let mut payload = Vec::new();
        payload.extend_from_slice(&1u32.to_le_bytes()); // count = 1
        payload.extend_from_slice(&5u32.to_le_bytes()); // term_len = 5
        payload.extend_from_slice(b"hello"); // term
        payload.push(1); // has_value = true
        payload.extend_from_slice(&10u32.to_le_bytes()); // value_len = 10
        payload.extend_from_slice(&[1, 2, 3]); // Only 3 bytes of value
        let result = WalRecord::deserialize(WalRecordType::BatchInsert, &payload);
        assert!(
            matches!(result, Err(WalError::CorruptedRecord(msg)) if msg.contains("entry 0 value truncated"))
        );
    }

    #[test]
    fn test_deserialize_batch_insert_second_entry_truncated() {
        // Test truncation at second entry to ensure loop index is correct
        let mut payload = Vec::new();
        payload.extend_from_slice(&2u32.to_le_bytes()); // count = 2

        // Entry 0: complete
        payload.extend_from_slice(&3u32.to_le_bytes()); // term_len = 3
        payload.extend_from_slice(b"foo"); // term
        payload.push(0); // has_value = false

        // Entry 1: incomplete term
        payload.extend_from_slice(&10u32.to_le_bytes()); // term_len = 10
        payload.extend_from_slice(&[b'a', b'b']); // Only 2 bytes of term

        let result = WalRecord::deserialize(WalRecordType::BatchInsert, &payload);
        assert!(
            matches!(result, Err(WalError::CorruptedRecord(msg)) if msg.contains("entry 1 term truncated"))
        );
    }

    #[test]
    fn test_deserialize_valid_increment() {
        // Valid Increment record
        let mut payload = Vec::new();
        payload.extend_from_slice(&5u32.to_le_bytes()); // term_len = 5
        payload.extend_from_slice(b"count"); // term
        payload.extend_from_slice(&42i64.to_le_bytes()); // delta
        payload.extend_from_slice(&100i64.to_le_bytes()); // result

        let result = WalRecord::deserialize(WalRecordType::Increment, &payload);
        assert!(result.is_ok());
        match result.unwrap() {
            WalRecord::Increment {
                term,
                delta,
                result: res,
            } => {
                assert_eq!(term, b"count");
                assert_eq!(delta, 42);
                assert_eq!(res, 100);
            }
            _ => panic!("Expected Increment"),
        }
    }

    #[test]
    fn test_deserialize_valid_cas_with_expected() {
        // Valid CAS with expected value
        let mut payload = Vec::new();
        payload.extend_from_slice(&3u32.to_le_bytes()); // term_len = 3
        payload.extend_from_slice(b"key"); // term
        payload.push(1); // has_expected = true
        payload.extend_from_slice(&3u32.to_le_bytes()); // expected_len = 3
        payload.extend_from_slice(b"old"); // expected
        payload.extend_from_slice(&3u32.to_le_bytes()); // new_value_len = 3
        payload.extend_from_slice(b"new"); // new_value
        payload.push(1); // success = true

        let result = WalRecord::deserialize(WalRecordType::CompareAndSwap, &payload);
        assert!(result.is_ok());
        match result.unwrap() {
            WalRecord::CompareAndSwap {
                term,
                expected,
                new_value,
                success,
            } => {
                assert_eq!(term, b"key");
                assert_eq!(expected, Some(b"old".to_vec()));
                assert_eq!(new_value, b"new");
                assert!(success);
            }
            _ => panic!("Expected CompareAndSwap"),
        }
    }

    #[test]
    fn test_deserialize_valid_cas_without_expected() {
        // Valid CAS without expected value (insert if not exists)
        let mut payload = Vec::new();
        payload.extend_from_slice(&3u32.to_le_bytes()); // term_len = 3
        payload.extend_from_slice(b"key"); // term
        payload.push(0); // has_expected = false
        payload.extend_from_slice(&5u32.to_le_bytes()); // new_value_len = 5
        payload.extend_from_slice(b"value"); // new_value
        payload.push(0); // success = false

        let result = WalRecord::deserialize(WalRecordType::CompareAndSwap, &payload);
        assert!(result.is_ok());
        match result.unwrap() {
            WalRecord::CompareAndSwap {
                term,
                expected,
                new_value,
                success,
            } => {
                assert_eq!(term, b"key");
                assert!(expected.is_none());
                assert_eq!(new_value, b"value");
                assert!(!success);
            }
            _ => panic!("Expected CompareAndSwap"),
        }
    }

    #[test]
    fn test_deserialize_valid_transaction_records() {
        // Valid BeginTx
        let payload = 12345u64.to_le_bytes().to_vec();
        let result = WalRecord::deserialize(WalRecordType::BeginTx, &payload);
        assert!(result.is_ok());
        match result.unwrap() {
            WalRecord::BeginTx { tx_id } => assert_eq!(tx_id, 12345),
            _ => panic!("Expected BeginTx"),
        }

        // Valid CommitTx
        let result = WalRecord::deserialize(WalRecordType::CommitTx, &payload);
        assert!(result.is_ok());
        match result.unwrap() {
            WalRecord::CommitTx { tx_id } => assert_eq!(tx_id, 12345),
            _ => panic!("Expected CommitTx"),
        }

        // Valid AbortTx
        let result = WalRecord::deserialize(WalRecordType::AbortTx, &payload);
        assert!(result.is_ok());
        match result.unwrap() {
            WalRecord::AbortTx { tx_id } => assert_eq!(tx_id, 12345),
            _ => panic!("Expected AbortTx"),
        }
    }

    #[test]
    fn test_deserialize_valid_checkpoint() {
        // Valid Checkpoint
        let mut payload = Vec::new();
        payload.extend_from_slice(&100u64.to_le_bytes()); // checkpoint_lsn
        payload.extend_from_slice(&1234567890u64.to_le_bytes()); // timestamp

        let result = WalRecord::deserialize(WalRecordType::Checkpoint, &payload);
        assert!(result.is_ok());
        match result.unwrap() {
            WalRecord::Checkpoint {
                checkpoint_lsn,
                timestamp,
            } => {
                assert_eq!(checkpoint_lsn, 100);
                assert_eq!(timestamp, 1234567890);
            }
            _ => panic!("Expected Checkpoint"),
        }
    }

    #[test]
    fn test_invalid_record_type() {
        // Test TryFrom<u8> for WalRecordType with invalid values
        let result = WalRecordType::try_from(0u8);
        assert!(matches!(result, Err(WalError::InvalidRecordType(0))));

        // 16 is beyond the current max (CommitRank = 15, the Order-A replay-order
        // fix's commit-generation marker; 15 is now VALID — see the assertion
        // below). The first invalid discriminant moved 15 → 16 with that addition.
        let result = WalRecordType::try_from(16u8);
        assert!(matches!(result, Err(WalError::InvalidRecordType(16))));

        let result = WalRecordType::try_from(255u8);
        assert!(matches!(result, Err(WalError::InvalidRecordType(255))));

        // Valid types should work (1-15 are all valid now)
        assert!(WalRecordType::try_from(1u8).is_ok()); // Insert
        assert!(WalRecordType::try_from(10u8).is_ok()); // BatchInsert
        assert!(WalRecordType::try_from(12u8).is_ok()); // VersionUpdate
        assert!(WalRecordType::try_from(14u8).is_ok()); // VersionGc
        assert!(WalRecordType::try_from(15u8).is_ok()); // CommitRank (Order-A fix)
    }

    #[test]
    fn test_wal_error_display_and_source() {
        // Test WalError Display implementations
        let io_err = WalError::Io(io::Error::new(io::ErrorKind::Other, "test io error"));
        let display = format!("{}", io_err);
        assert!(display.contains("WAL I/O error"));

        let invalid = WalError::InvalidRecordType(99);
        let display = format!("{}", invalid);
        assert!(display.contains("99"));

        let corrupted = WalError::CorruptedRecord("test corruption".into());
        let display = format!("{}", corrupted);
        assert!(display.contains("test corruption"));

        let eof = WalError::UnexpectedEof;
        let display = format!("{}", eof);
        assert!(display.contains("Unexpected end"));

        let exists = WalError::AlreadyExists;
        let display = format!("{}", exists);
        assert!(display.contains("already exists"));

        let not_found = WalError::NotFound;
        let display = format!("{}", not_found);
        assert!(display.contains("not found"));

        let parent_not_found = WalError::ParentNotFound(PathBuf::from("/test/path"));
        let display = format!("{}", parent_not_found);
        assert!(display.contains("/test/path"));

        // Test source() method
        use std::error::Error;
        let io_err = WalError::Io(io::Error::new(io::ErrorKind::Other, "test"));
        assert!(io_err.source().is_some());

        let corrupted = WalError::CorruptedRecord("test".into());
        assert!(corrupted.source().is_none());
    }

    // ==================== Version-Based WAL Tests ====================

    #[test]
    fn test_version_update_roundtrip() {
        let record = WalRecord::VersionUpdate {
            version_id: 42,
            root_ptr: 0x1234_5678_9ABC_DEF0,
            node_count: 1000,
            timestamp: 1699999999,
        };

        assert_eq!(record.record_type(), WalRecordType::VersionUpdate);

        let payload = record.serialize_payload();
        assert_eq!(payload.len(), 32); // 4 x u64 = 32 bytes

        let deserialized =
            WalRecord::deserialize(WalRecordType::VersionUpdate, &payload).expect("deserialize");

        match deserialized {
            WalRecord::VersionUpdate {
                version_id,
                root_ptr,
                node_count,
                timestamp,
            } => {
                assert_eq!(version_id, 42);
                assert_eq!(root_ptr, 0x1234_5678_9ABC_DEF0);
                assert_eq!(node_count, 1000);
                assert_eq!(timestamp, 1699999999);
            }
            _ => panic!("Expected VersionUpdate"),
        }
    }

    #[test]
    fn test_version_durable_roundtrip() {
        let record = WalRecord::VersionDurable {
            version_id: 99,
            checksum: 0xDEAD_BEEF,
        };

        assert_eq!(record.record_type(), WalRecordType::VersionDurable);

        let payload = record.serialize_payload();
        assert_eq!(payload.len(), 12); // u64 + u32 = 12 bytes

        let deserialized =
            WalRecord::deserialize(WalRecordType::VersionDurable, &payload).expect("deserialize");

        match deserialized {
            WalRecord::VersionDurable {
                version_id,
                checksum,
            } => {
                assert_eq!(version_id, 99);
                assert_eq!(checksum, 0xDEAD_BEEF);
            }
            _ => panic!("Expected VersionDurable"),
        }
    }

    #[test]
    fn test_version_gc_roundtrip() {
        let record = WalRecord::VersionGc {
            version_ids: vec![1, 5, 10, 42, 100],
        };

        assert_eq!(record.record_type(), WalRecordType::VersionGc);

        let payload = record.serialize_payload();
        assert_eq!(payload.len(), 4 + 5 * 8); // count (4) + 5 x u64 (40) = 44 bytes

        let deserialized =
            WalRecord::deserialize(WalRecordType::VersionGc, &payload).expect("deserialize");

        match deserialized {
            WalRecord::VersionGc { version_ids } => {
                assert_eq!(version_ids, vec![1, 5, 10, 42, 100]);
            }
            _ => panic!("Expected VersionGc"),
        }
    }

    #[test]
    fn test_version_gc_empty() {
        let record = WalRecord::VersionGc {
            version_ids: vec![],
        };

        let payload = record.serialize_payload();
        assert_eq!(payload.len(), 4); // just the count

        let deserialized =
            WalRecord::deserialize(WalRecordType::VersionGc, &payload).expect("deserialize");

        match deserialized {
            WalRecord::VersionGc { version_ids } => {
                assert!(version_ids.is_empty());
            }
            _ => panic!("Expected VersionGc"),
        }
    }

    #[test]
    fn test_version_update_too_short() {
        let result = WalRecord::deserialize(WalRecordType::VersionUpdate, &[0; 31]);
        assert!(result.is_err());
    }

    #[test]
    fn test_version_durable_too_short() {
        let result = WalRecord::deserialize(WalRecordType::VersionDurable, &[0; 11]);
        assert!(result.is_err());
    }

    #[test]
    fn test_version_gc_too_short() {
        // count = 5 but only 3 version IDs provided
        let mut payload = vec![];
        payload.extend_from_slice(&5u32.to_le_bytes()); // count = 5
        payload.extend_from_slice(&1u64.to_le_bytes());
        payload.extend_from_slice(&2u64.to_le_bytes());
        payload.extend_from_slice(&3u64.to_le_bytes());
        // Missing 2 more version IDs

        let result = WalRecord::deserialize(WalRecordType::VersionGc, &payload);
        assert!(result.is_err());
    }
}