reasonkit-mem 0.1.7

High-performance vector database & RAG memory layer - hybrid search, embeddings, RAPTOR trees, BM25 fusion, and semantic retrieval for AI systems
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
//! Write-Ahead Log (WAL) System for ReasonKit Memory
//!
//! Provides durability guarantees for memory operations through journaling.
//! All writes are persisted to the WAL before being applied to the main storage,
//! ensuring crash recovery and data integrity.
//!
//! # Architecture
//!
//! ```text
//! +-----------------------------------------------------------------------+
//! |                           WAL Architecture                            |
//! +-----------------------------------------------------------------------+
//! |                                                                       |
//! |  +---------------+    +---------------+    +-------------------------+|
//! |  | Memory Write  |--->|  WAL Append   |--->| Storage Backend Apply   ||
//! |  |   Request     |    |   (fsync)     |    | (Qdrant/File/InMemory)  ||
//! |  +---------------+    +---------------+    +-------------------------+|
//! |         |                   |                        |                |
//! |         |                   |                        |                |
//! |         v                   v                        v                |
//! |  +---------------+    +---------------+    +-------------------------+|
//! |  |   Response    |<---|  Checkpoint   |<---|    Truncate Old WAL     ||
//! |  +---------------+    +---------------+    +-------------------------+|
//! |                                                                       |
//! +-----------------------------------------------------------------------+
//! ```
//!
//! ## File Layout
//!
//! ```text
//! {wal_dir}/
//! +-- segment_00000001.wal      # Active segment (append-only)
//! +-- segment_00000002.wal      # Previous segment
//! +-- checkpoint_00000005.ckpt  # Latest checkpoint
//! +-- checkpoint_00000003.ckpt  # Previous checkpoint (retained for safety)
//! +-- wal.meta                  # WAL metadata (current LSN, active segment)
//! ```
//!
//! ## WAL Entry Format (Binary)
//!
//! ```text
//! +------------------------------------------------------------------------+
//! |                         WAL Entry (Variable Size)                       |
//! +--------+-------------+-----------+--------------+------------+---------+
//! | Magic  | Entry Size  | Checksum  |  LSN (u64)   | Timestamp  |  OpType |
//! | 4 bytes|  4 bytes    |  4 bytes  |   8 bytes    |  8 bytes   | 1 byte  |
//! +--------+-------------+-----------+--------------+------------+---------+
//! |                         Payload (Variable)                              |
//! |                    [JSON-encoded WalOperation]                          |
//! +------------------------------------------------------------------------+
//! |                      Entry Checksum (4 bytes)                           |
//! +------------------------------------------------------------------------+
//!
//! Total Header: 29 bytes + variable payload + 4 byte trailer
//! ```
//!
//! # Recovery Algorithm (Pseudocode)
//!
//! ```text
//! PROCEDURE recover():
//!     // Phase 1: Crash Detection
//!     meta = load_wal_metadata()
//!     IF meta.clean_shutdown == false:
//!         log("Crash detected, starting recovery...")
//!
//!     // Phase 2: Find Latest Valid Checkpoint
//!     checkpoints = scan_checkpoint_files()
//!     SORT checkpoints BY id DESCENDING
//!
//!     latest_valid_checkpoint = NULL
//!     FOR each checkpoint IN checkpoints:
//!         IF validate_checkpoint(checkpoint):
//!             latest_valid_checkpoint = checkpoint
//!             BREAK
//!
//!     // Phase 3: Determine Replay Start Point
//!     IF latest_valid_checkpoint != NULL:
//!         replay_start_lsn = latest_valid_checkpoint.lsn
//!         load_checkpoint_state(latest_valid_checkpoint)
//!     ELSE:
//!         replay_start_lsn = 0
//!         initialize_empty_state()
//!
//!     // Phase 4: Scan and Collect Entries
//!     segments = scan_segment_files()
//!     SORT segments BY segment_number
//!
//!     entries_to_replay = []
//!     FOR each segment IN segments:
//!         position = 0
//!         WHILE position < segment.size:
//!             TRY:
//!                 header = read_header(segment, position)
//!                 IF NOT validate_header_checksum(header):
//!                     log_error("Corrupted header at {}", position)
//!                     position = scan_for_magic(segment, position + 1)
//!                     CONTINUE
//!
//!                 payload = read_payload(segment, position, header.size)
//!                 IF NOT validate_payload_checksum(payload):
//!                     log_error("Corrupted payload at {}", position)
//!                     position += header.size
//!                     CONTINUE
//!
//!                 entry = parse_entry(header, payload)
//!                 IF entry.lsn >= replay_start_lsn:
//!                     entries_to_replay.append(entry)
//!
//!                 position += header.entry_size
//!             CATCH incomplete_read:
//!                 BREAK
//!
//!     // Phase 5: Replay Entries in Order
//!     SORT entries_to_replay BY lsn
//!     FOR each entry IN entries_to_replay:
//!         apply_operation(entry)
//!
//!     // Phase 6: Finalize
//!     current_lsn = last_replayed_lsn + 1
//!     mark_recovery_complete()
//!     RETURN RecoveryReport
//! ```
//!
//! # Usage
//!
//! ```rust,ignore
//! use reasonkit_mem::storage::wal::{WriteAheadLog, WalConfig, WalOperation, SyncMode};
//! use std::path::PathBuf;
//! use std::time::Duration;
//!
//! #[tokio::main]
//! async fn main() -> anyhow::Result<()> {
//!     let config = WalConfig {
//!         dir: PathBuf::from("./wal"),
//!         segment_size_mb: 64,
//!         sync_mode: SyncMode::Batched(Duration::from_millis(100)),
//!     };
//!
//!     let wal = WriteAheadLog::new(config).await?;
//!
//!     // Log an insert operation
//!     let lsn = wal.append(WalOperation::Insert {
//!         id: uuid::Uuid::new_v4(),
//!         content: "Hello, World!".to_string(),
//!         embedding: vec![0.1, 0.2, 0.3],
//!     }).await?;
//!
//!     // Checkpoint to mark operations as durable
//!     wal.checkpoint().await?;
//!
//!     Ok(())
//! }
//! ```

use crate::{MemError, MemResult};
use async_trait::async_trait;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::fs::{File, OpenOptions};
use std::io::{BufRead, BufReader, BufWriter, Read, Seek, SeekFrom, Write};
use std::path::PathBuf;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::Arc;
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
use tokio::sync::{Mutex, RwLock};
use uuid::Uuid;

// ============================================================================
// Constants
// ============================================================================

/// WAL segment file prefix
const SEGMENT_PREFIX: &str = "wal_";
/// WAL segment file extension
const SEGMENT_EXTENSION: &str = ".log";
/// Checkpoint file prefix
const CHECKPOINT_PREFIX: &str = "checkpoint_";
/// Checkpoint file extension
const CHECKPOINT_EXTENSION: &str = ".ckpt";
/// Magic bytes for WAL entry header: "WAL1"
const WAL_MAGIC: [u8; 4] = [0x57, 0x41, 0x4C, 0x31];
/// Magic bytes for checkpoint files: "CKPT"
const CHECKPOINT_MAGIC: [u8; 4] = [0x43, 0x4B, 0x50, 0x54];
/// Version of the WAL format
const WAL_VERSION: u8 = 1;
/// Default checkpoint retention count
const DEFAULT_CHECKPOINT_RETENTION: usize = 2;

// ============================================================================
// Log Sequence Number
// ============================================================================

/// Log Sequence Number - monotonically increasing identifier for each WAL entry
#[derive(
    Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize, Default,
)]
pub struct LogSequenceNumber(pub u64);

impl LogSequenceNumber {
    /// Create a new LSN from raw value
    pub const fn new(value: u64) -> Self {
        Self(value)
    }

    /// Get the raw LSN value
    pub const fn value(&self) -> u64 {
        self.0
    }

    /// Increment and return the next LSN
    pub fn next(&self) -> Self {
        Self(self.0 + 1)
    }
}

impl std::fmt::Display for LogSequenceNumber {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "LSN({})", self.0)
    }
}

impl From<u64> for LogSequenceNumber {
    fn from(value: u64) -> Self {
        Self(value)
    }
}

// ============================================================================
// Checkpoint ID
// ============================================================================

/// Checkpoint identifier
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, Default)]
pub struct CheckpointId(pub u64);

impl CheckpointId {
    /// Create a new checkpoint ID
    pub const fn new(value: u64) -> Self {
        Self(value)
    }

    /// Get the underlying value
    pub const fn value(&self) -> u64 {
        self.0
    }
}

impl std::fmt::Display for CheckpointId {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "CKPT({})", self.0)
    }
}

// ============================================================================
// WAL Operations
// ============================================================================

/// Operations that can be logged to the WAL
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub enum WalOperation {
    /// Insert a new document/chunk with embedding
    Insert {
        /// Unique identifier
        id: Uuid,
        /// Text content
        content: String,
        /// Embedding vector
        embedding: Vec<f32>,
    },
    /// Update an existing document/chunk
    Update {
        /// Unique identifier
        id: Uuid,
        /// Updated text content
        content: String,
        /// Updated embedding vector
        embedding: Vec<f32>,
    },
    /// Delete a document/chunk
    Delete {
        /// Unique identifier to delete
        id: Uuid,
    },
    /// Batch insert operation (atomic)
    BatchInsert {
        /// List of items to insert
        items: Vec<BatchItem>,
    },
    /// Batch delete operation (atomic)
    BatchDelete {
        /// List of IDs to delete
        ids: Vec<Uuid>,
    },
    /// Checkpoint marker - all operations before this LSN are durable
    Checkpoint {
        /// Log Sequence Number at checkpoint
        lsn: u64,
        /// Checkpoint ID for tracking
        checkpoint_id: u64,
    },
    /// Transaction begin marker
    TxnBegin {
        /// Transaction ID
        txn_id: Uuid,
    },
    /// Transaction commit marker
    TxnCommit {
        /// Transaction ID
        txn_id: Uuid,
    },
    /// Transaction rollback marker
    TxnRollback {
        /// Transaction ID
        txn_id: Uuid,
    },
}

/// Item for batch operations
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct BatchItem {
    /// Unique identifier
    pub id: Uuid,
    /// Text content
    pub content: String,
    /// Embedding vector
    pub embedding: Vec<f32>,
}

impl WalOperation {
    /// Get the operation type as a string for logging/debugging
    pub fn op_type(&self) -> &'static str {
        match self {
            WalOperation::Insert { .. } => "INSERT",
            WalOperation::Update { .. } => "UPDATE",
            WalOperation::Delete { .. } => "DELETE",
            WalOperation::BatchInsert { .. } => "BATCH_INSERT",
            WalOperation::BatchDelete { .. } => "BATCH_DELETE",
            WalOperation::Checkpoint { .. } => "CHECKPOINT",
            WalOperation::TxnBegin { .. } => "TXN_BEGIN",
            WalOperation::TxnCommit { .. } => "TXN_COMMIT",
            WalOperation::TxnRollback { .. } => "TXN_ROLLBACK",
        }
    }
}

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

/// A single entry in the WAL with full metadata
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WalEntry {
    /// Log Sequence Number - monotonically increasing
    pub lsn: u64,
    /// Unix timestamp in microseconds
    pub timestamp: i64,
    /// The operation being logged
    pub operation: WalOperation,
    /// CRC32 checksum of the entry (excluding this field)
    pub checksum: u32,
}

impl WalEntry {
    /// Create a new WAL entry with computed checksum
    pub fn new(lsn: u64, operation: WalOperation) -> Self {
        let timestamp = chrono::Utc::now().timestamp_micros();
        let mut entry = WalEntry {
            lsn,
            timestamp,
            operation,
            checksum: 0,
        };
        entry.checksum = compute_checksum(&entry);
        entry
    }

    /// Verify the checksum of this entry
    pub fn verify(&self) -> bool {
        verify_checksum(self)
    }

    /// Get the size of this entry when serialized
    pub fn serialized_size(&self) -> MemResult<usize> {
        let data = wal_serialize(self)?;
        // Header: magic (4) + version (1) + length (4) + data + trailing length (4)
        Ok(4 + 1 + 4 + data.len() + 4)
    }

    /// Get the LSN as a LogSequenceNumber
    pub fn lsn(&self) -> LogSequenceNumber {
        LogSequenceNumber::new(self.lsn)
    }
}

// ============================================================================
// Checkpoint
// ============================================================================

/// Checkpoint data structure for recovery
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Checkpoint {
    /// Checkpoint ID
    pub id: CheckpointId,
    /// LSN at checkpoint creation
    pub lsn: LogSequenceNumber,
    /// Timestamp of checkpoint creation (unix seconds)
    pub created_at: u64,
    /// Snapshot of document IDs present at checkpoint
    pub document_ids: Vec<Uuid>,
    /// Snapshot of chunk IDs present at checkpoint
    pub chunk_ids: Vec<Uuid>,
    /// Additional metadata
    pub metadata: HashMap<String, String>,
    /// Checksum of the checkpoint data
    pub checksum: u32,
}

impl Checkpoint {
    /// Create a new checkpoint
    pub fn new(
        id: u64,
        lsn: LogSequenceNumber,
        document_ids: Vec<Uuid>,
        chunk_ids: Vec<Uuid>,
    ) -> Self {
        let created_at = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap_or_default()
            .as_secs();

        let mut checkpoint = Self {
            id: CheckpointId::new(id),
            lsn,
            created_at,
            document_ids,
            chunk_ids,
            metadata: HashMap::new(),
            checksum: 0,
        };
        checkpoint.checksum = checkpoint.compute_checksum();
        checkpoint
    }

    /// Compute checksum for validation
    fn compute_checksum(&self) -> u32 {
        let data = serde_json::to_vec(&(&self.id, &self.lsn, &self.created_at, &self.document_ids))
            .unwrap_or_default();
        crc32_compute(&data)
    }

    /// Validate checkpoint integrity
    pub fn validate(&self) -> bool {
        let expected = self.compute_checksum();
        self.checksum == expected
    }

    /// Serialize to bytes with magic header
    pub fn to_bytes(&self) -> MemResult<Vec<u8>> {
        let json = serde_json::to_vec(self)
            .map_err(|e| MemError::storage(format!("Failed to serialize checkpoint: {}", e)))?;

        let mut buf = Vec::with_capacity(4 + 1 + json.len());
        buf.extend_from_slice(&CHECKPOINT_MAGIC);
        buf.push(WAL_VERSION);
        buf.extend_from_slice(&json);

        Ok(buf)
    }

    /// Deserialize from bytes
    pub fn from_bytes(buf: &[u8]) -> MemResult<Self> {
        if buf.len() < 5 {
            return Err(MemError::storage("Buffer too small for checkpoint"));
        }

        if buf[0..4] != CHECKPOINT_MAGIC {
            return Err(MemError::storage("Invalid checkpoint magic"));
        }

        if buf[4] > WAL_VERSION {
            return Err(MemError::storage(format!(
                "Unsupported checkpoint version: {}",
                buf[4]
            )));
        }

        let checkpoint: Checkpoint = serde_json::from_slice(&buf[5..])
            .map_err(|e| MemError::storage(format!("Failed to deserialize checkpoint: {}", e)))?;

        if !checkpoint.validate() {
            return Err(MemError::storage("Checkpoint checksum validation failed"));
        }

        Ok(checkpoint)
    }
}

// ============================================================================
// Recovery Report
// ============================================================================

/// Report from WAL recovery process
#[derive(Debug, Clone, Default)]
pub struct RecoveryReport {
    /// Number of entries recovered
    pub entries_recovered: u64,
    /// Number of entries skipped due to corruption
    pub entries_skipped: u64,
    /// Number of entries replayed successfully
    pub entries_replayed: u64,
    /// Last valid LSN found
    pub last_valid_lsn: LogSequenceNumber,
    /// Checkpoint used for recovery (if any)
    pub checkpoint_used: Option<CheckpointId>,
    /// Recovery duration in milliseconds
    pub duration_ms: u64,
    /// Errors encountered during recovery
    pub errors: Vec<RecoveryError>,
    /// Whether recovery was successful
    pub success: bool,
}

/// Error encountered during recovery
#[derive(Debug, Clone)]
pub struct RecoveryError {
    /// LSN where error occurred (if known)
    pub lsn: Option<LogSequenceNumber>,
    /// Segment file where error occurred
    pub segment: Option<PathBuf>,
    /// Error message
    pub message: String,
    /// Whether this was a fatal error
    pub fatal: bool,
}

// ============================================================================
// Synchronization Mode
// ============================================================================

/// Synchronization mode for WAL writes
#[derive(Debug, Clone)]
pub enum SyncMode {
    /// Fsync after each write - maximum durability, lowest performance
    Immediate,
    /// Fsync at specified intervals - balanced durability/performance
    Batched(Duration),
    /// OS-managed sync - highest performance, lower durability guarantees
    Async,
}

impl Default for SyncMode {
    fn default() -> Self {
        SyncMode::Batched(Duration::from_millis(100))
    }
}

// ============================================================================
// WAL Configuration
// ============================================================================

/// Configuration for the Write-Ahead Log
#[derive(Debug, Clone)]
pub struct WalConfig {
    /// Directory to store WAL segment files
    pub dir: PathBuf,
    /// Maximum size of each segment file in megabytes
    pub segment_size_mb: usize,
    /// Synchronization mode for durability
    pub sync_mode: SyncMode,
    /// Number of checkpoints to retain
    pub checkpoint_retention: usize,
    /// Pre-allocate segment files for performance
    pub preallocate_segments: bool,
}

impl Default for WalConfig {
    fn default() -> Self {
        Self {
            dir: PathBuf::from("./wal"),
            segment_size_mb: 64,
            sync_mode: SyncMode::default(),
            checkpoint_retention: DEFAULT_CHECKPOINT_RETENTION,
            preallocate_segments: true,
        }
    }
}

impl WalConfig {
    /// Create a new WAL config with the specified directory
    pub fn new(dir: PathBuf) -> Self {
        Self {
            dir,
            ..Default::default()
        }
    }

    /// Set the segment size in megabytes
    pub fn with_segment_size(mut self, size_mb: usize) -> Self {
        self.segment_size_mb = size_mb;
        self
    }

    /// Set the sync mode
    pub fn with_sync_mode(mut self, mode: SyncMode) -> Self {
        self.sync_mode = mode;
        self
    }

    /// Set checkpoint retention count
    pub fn with_checkpoint_retention(mut self, count: usize) -> Self {
        self.checkpoint_retention = count;
        self
    }

    /// Get the segment size in bytes
    fn segment_size_bytes(&self) -> usize {
        self.segment_size_mb * 1024 * 1024
    }
}

// ============================================================================
// WAL Trait (API Interface)
// ============================================================================

/// Write-Ahead Log trait defining the core operations
///
/// This trait provides a unified interface for WAL implementations,
/// enabling both file-based and in-memory variants.
#[async_trait]
pub trait WriteAheadLogTrait: Send + Sync {
    /// Append an operation to the WAL
    ///
    /// Returns the LSN assigned to this operation.
    /// The operation is guaranteed to be durable after this call returns
    /// (subject to sync_mode configuration).
    async fn append(&self, op: WalOperation) -> MemResult<LogSequenceNumber>;

    /// Append a batch of operations atomically
    ///
    /// All operations in the batch are assigned consecutive LSNs.
    /// Returns the LSN of the first operation.
    async fn append_batch(&self, ops: Vec<WalOperation>) -> MemResult<LogSequenceNumber>;

    /// Force sync all pending writes to disk
    ///
    /// This is a no-op in Immediate sync mode.
    async fn sync(&self) -> MemResult<()>;

    /// Create a checkpoint of the current state
    ///
    /// Checkpoints enable faster recovery by providing a snapshot
    /// of the system state, reducing the number of log entries
    /// that need to be replayed.
    async fn checkpoint(&self) -> MemResult<CheckpointId>;

    /// Recover from WAL after a crash
    ///
    /// This should be called during startup. It will:
    /// 1. Find the latest valid checkpoint
    /// 2. Replay all entries after the checkpoint
    /// 3. Return a report of the recovery process
    async fn recover(&self) -> MemResult<RecoveryReport>;

    /// Truncate WAL entries before the given LSN
    ///
    /// Used after successful checkpoint to reclaim disk space.
    /// Entries before the LSN will be permanently deleted.
    async fn truncate_before(&self, lsn: LogSequenceNumber) -> MemResult<()>;

    /// Get the current LSN (next LSN to be assigned)
    async fn current_lsn(&self) -> LogSequenceNumber;

    /// Get the last synced LSN (guaranteed durable)
    async fn synced_lsn(&self) -> LogSequenceNumber;

    /// Read entries from a given LSN (for replication/debugging)
    async fn read_from(
        &self,
        start_lsn: LogSequenceNumber,
        limit: usize,
    ) -> MemResult<Vec<WalEntry>>;

    /// Close the WAL gracefully
    async fn close(&self) -> MemResult<()>;
}

// ============================================================================
// Segment Metadata
// ============================================================================

/// Metadata for a WAL segment file
#[derive(Debug, Clone)]
struct SegmentMeta {
    /// Segment number (used for file naming)
    segment_id: u64,
    /// Path to the segment file
    path: PathBuf,
    /// First LSN in this segment
    first_lsn: u64,
    /// Last LSN in this segment (None if segment is empty)
    last_lsn: Option<u64>,
    /// Current size in bytes
    size_bytes: u64,
}

// ============================================================================
// Segment Writer
// ============================================================================

/// Writer for a single WAL segment
struct SegmentWriter {
    /// Buffered writer
    writer: BufWriter<File>,
    /// Segment metadata
    meta: SegmentMeta,
    /// Whether we need to sync
    needs_sync: bool,
}

impl SegmentWriter {
    /// Create a new segment writer
    fn new(meta: SegmentMeta) -> MemResult<Self> {
        let file = OpenOptions::new()
            .create(true)
            .append(true)
            .open(&meta.path)
            .map_err(|e| MemError::storage(format!("Failed to open WAL segment: {}", e)))?;

        Ok(Self {
            writer: BufWriter::with_capacity(64 * 1024, file), // 64KB buffer
            meta,
            needs_sync: false,
        })
    }

    /// Write an entry to this segment
    fn write_entry(&mut self, entry: &WalEntry) -> MemResult<()> {
        let data = wal_serialize(entry)?;
        let len = data.len() as u32;

        // Write entry format:
        // [magic: 4 bytes][version: 1 byte][length: 4 bytes][data: N bytes][length: 4 bytes]
        // Trailing length allows reverse scanning

        self.writer
            .write_all(&WAL_MAGIC)
            .map_err(|e| MemError::storage(format!("Failed to write WAL magic: {}", e)))?;

        self.writer
            .write_all(&[WAL_VERSION])
            .map_err(|e| MemError::storage(format!("Failed to write WAL version: {}", e)))?;

        self.writer
            .write_all(&len.to_le_bytes())
            .map_err(|e| MemError::storage(format!("Failed to write entry length: {}", e)))?;

        self.writer
            .write_all(&data)
            .map_err(|e| MemError::storage(format!("Failed to write entry data: {}", e)))?;

        self.writer
            .write_all(&len.to_le_bytes())
            .map_err(|e| MemError::storage(format!("Failed to write trailing length: {}", e)))?;

        // Update metadata
        self.meta.size_bytes += 4 + 1 + 4 + data.len() as u64 + 4;
        self.meta.last_lsn = Some(entry.lsn);
        self.needs_sync = true;

        Ok(())
    }

    /// Flush the buffer to disk
    fn flush(&mut self) -> MemResult<()> {
        self.writer
            .flush()
            .map_err(|e| MemError::storage(format!("Failed to flush WAL buffer: {}", e)))
    }

    /// Sync to disk (fsync)
    fn sync(&mut self) -> MemResult<()> {
        self.flush()?;
        self.writer
            .get_ref()
            .sync_all()
            .map_err(|e| MemError::storage(format!("Failed to sync WAL segment: {}", e)))?;
        self.needs_sync = false;
        Ok(())
    }
}

// ============================================================================
// Write-Ahead Log Implementation
// ============================================================================

/// Write-Ahead Log for durable storage operations
pub struct WriteAheadLog {
    /// Configuration
    config: WalConfig,
    /// Current segment writer (protected by mutex for write access)
    current_segment: Arc<Mutex<SegmentWriter>>,
    /// Current Log Sequence Number
    current_lsn: AtomicU64,
    /// Last synced LSN
    synced_lsn: AtomicU64,
    /// LSN of the last checkpoint
    last_checkpoint: AtomicU64,
    /// Checkpoint counter
    checkpoint_counter: AtomicU64,
    /// List of all segment metadata
    segments: Arc<RwLock<Vec<SegmentMeta>>>,
    /// Background sync task handle (for batched mode)
    #[allow(dead_code)]
    sync_handle: Option<tokio::task::JoinHandle<()>>,
    /// Flag to signal shutdown to background tasks
    shutdown: Arc<AtomicU64>,
    /// Closed flag
    closed: AtomicU64,
}

impl WriteAheadLog {
    /// Create a new Write-Ahead Log
    pub async fn new(config: WalConfig) -> MemResult<Self> {
        // Create WAL directory if it doesn't exist
        std::fs::create_dir_all(&config.dir)
            .map_err(|e| MemError::storage(format!("Failed to create WAL directory: {}", e)))?;

        // Discover existing segments
        let (segments, current_lsn, last_checkpoint, checkpoint_id) =
            Self::discover_segments(&config).await?;

        // Create or open current segment
        let current_segment = if segments.is_empty() {
            Self::create_new_segment(&config, 0, current_lsn)?
        } else {
            let last = segments.last().unwrap();
            // Check if we need to rotate
            if last.size_bytes >= config.segment_size_bytes() as u64 {
                Self::create_new_segment(&config, last.segment_id + 1, current_lsn)?
            } else {
                SegmentWriter::new(last.clone())?
            }
        };

        let segments = Arc::new(RwLock::new(segments));
        let current_segment = Arc::new(Mutex::new(current_segment));
        let shutdown = Arc::new(AtomicU64::new(0));

        // Start background sync task if using batched mode
        let sync_handle = match &config.sync_mode {
            SyncMode::Batched(interval) => {
                let interval = *interval;
                let segment_clone = current_segment.clone();
                let shutdown_clone = shutdown.clone();

                Some(tokio::spawn(async move {
                    let mut ticker = tokio::time::interval(interval);
                    loop {
                        ticker.tick().await;

                        // Check for shutdown
                        if shutdown_clone.load(Ordering::SeqCst) != 0 {
                            break;
                        }

                        // Sync if needed
                        let mut segment = segment_clone.lock().await;
                        if segment.needs_sync {
                            if let Err(e) = segment.sync() {
                                tracing::error!("Background WAL sync failed: {}", e);
                            }
                        }
                    }
                }))
            }
            _ => None,
        };

        Ok(Self {
            config,
            current_segment,
            current_lsn: AtomicU64::new(current_lsn),
            synced_lsn: AtomicU64::new(current_lsn.saturating_sub(1)),
            last_checkpoint: AtomicU64::new(last_checkpoint),
            checkpoint_counter: AtomicU64::new(checkpoint_id),
            segments,
            sync_handle,
            shutdown,
            closed: AtomicU64::new(0),
        })
    }

    /// Discover existing WAL segments and determine current state
    async fn discover_segments(config: &WalConfig) -> MemResult<(Vec<SegmentMeta>, u64, u64, u64)> {
        let mut segments = Vec::new();
        let mut max_lsn: u64 = 0;
        let mut last_checkpoint: u64 = 0;
        let mut max_checkpoint_id: u64 = 0;

        // Read directory entries
        let entries = std::fs::read_dir(&config.dir)
            .map_err(|e| MemError::storage(format!("Failed to read WAL directory: {}", e)))?;

        let mut segment_files: Vec<(u64, PathBuf)> = Vec::new();

        for entry in entries {
            let entry =
                entry.map_err(|e| MemError::storage(format!("Failed to read dir entry: {}", e)))?;
            let path = entry.path();

            if let Some(name) = path.file_name().and_then(|n| n.to_str()) {
                if name.starts_with(SEGMENT_PREFIX) && name.ends_with(SEGMENT_EXTENSION) {
                    // Extract segment ID from filename
                    let id_str = name
                        .trim_start_matches(SEGMENT_PREFIX)
                        .trim_end_matches(SEGMENT_EXTENSION);
                    if let Ok(id) = u64::from_str_radix(id_str, 16) {
                        segment_files.push((id, path));
                    }
                }
            }
        }

        // Sort by segment ID
        segment_files.sort_by_key(|(id, _)| *id);

        // Process each segment
        for (segment_id, path) in segment_files {
            let file = File::open(&path)
                .map_err(|e| MemError::storage(format!("Failed to open segment: {}", e)))?;
            let size_bytes = file
                .metadata()
                .map_err(|e| MemError::storage(format!("Failed to get segment metadata: {}", e)))?
                .len();

            // Read entries to find first/last LSN and checkpoints
            let mut reader = BufReader::new(file);
            let mut first_lsn = None;
            let mut last_lsn = None;

            while let Ok(Some(entry)) = read_entry(&mut reader) {
                if first_lsn.is_none() {
                    first_lsn = Some(entry.lsn);
                }
                last_lsn = Some(entry.lsn);

                if entry.lsn > max_lsn {
                    max_lsn = entry.lsn;
                }

                if let WalOperation::Checkpoint { lsn, checkpoint_id } = &entry.operation {
                    if *lsn > last_checkpoint {
                        last_checkpoint = *lsn;
                    }
                    if *checkpoint_id > max_checkpoint_id {
                        max_checkpoint_id = *checkpoint_id;
                    }
                }
            }

            segments.push(SegmentMeta {
                segment_id,
                path,
                first_lsn: first_lsn.unwrap_or(0),
                last_lsn,
                size_bytes,
            });
        }

        // Also check for checkpoint files
        if let Ok(checkpoint) = Self::find_latest_checkpoint(&config.dir) {
            if checkpoint.lsn.value() > last_checkpoint {
                last_checkpoint = checkpoint.lsn.value();
            }
            if checkpoint.id.value() > max_checkpoint_id {
                max_checkpoint_id = checkpoint.id.value();
            }
        }

        Ok((
            segments,
            max_lsn + 1,
            last_checkpoint,
            max_checkpoint_id + 1,
        ))
    }

    /// Find the latest valid checkpoint file
    fn find_latest_checkpoint(dir: &PathBuf) -> MemResult<Checkpoint> {
        let mut checkpoints: Vec<(u64, PathBuf)> = Vec::new();

        let entries = std::fs::read_dir(dir)
            .map_err(|e| MemError::storage(format!("Failed to read directory: {}", e)))?;

        for entry in entries {
            let entry =
                entry.map_err(|e| MemError::storage(format!("Failed to read entry: {}", e)))?;
            let path = entry.path();

            if let Some(name) = path.file_name().and_then(|n| n.to_str()) {
                if name.starts_with(CHECKPOINT_PREFIX) && name.ends_with(CHECKPOINT_EXTENSION) {
                    let id_str = name
                        .trim_start_matches(CHECKPOINT_PREFIX)
                        .trim_end_matches(CHECKPOINT_EXTENSION);
                    if let Ok(id) = u64::from_str_radix(id_str, 16) {
                        checkpoints.push((id, path));
                    }
                }
            }
        }

        if checkpoints.is_empty() {
            return Err(MemError::not_found("No checkpoint files found"));
        }

        // Sort by ID descending and try each one
        checkpoints.sort_by(|a, b| b.0.cmp(&a.0));

        for (_, path) in checkpoints {
            let data = std::fs::read(&path)
                .map_err(|e| MemError::storage(format!("Failed to read checkpoint: {}", e)))?;

            match Checkpoint::from_bytes(&data) {
                Ok(ckpt) if ckpt.validate() => return Ok(ckpt),
                _ => continue,
            }
        }

        Err(MemError::not_found("No valid checkpoint files found"))
    }

    /// Create a new segment file
    fn create_new_segment(
        config: &WalConfig,
        segment_id: u64,
        first_lsn: u64,
    ) -> MemResult<SegmentWriter> {
        let filename = format!("{}{:016x}{}", SEGMENT_PREFIX, segment_id, SEGMENT_EXTENSION);
        let path = config.dir.join(filename);

        let meta = SegmentMeta {
            segment_id,
            path,
            first_lsn,
            last_lsn: None,
            size_bytes: 0,
        };

        SegmentWriter::new(meta)
    }

    /// Append an operation to the WAL
    ///
    /// Returns the Log Sequence Number (LSN) assigned to this operation.
    pub async fn append(&self, op: WalOperation) -> MemResult<u64> {
        if self.closed.load(Ordering::SeqCst) != 0 {
            return Err(MemError::storage("WAL is closed"));
        }

        let lsn = self.current_lsn.fetch_add(1, Ordering::SeqCst);
        let entry = WalEntry::new(lsn, op);

        let mut segment = self.current_segment.lock().await;

        // Check if we need to rotate to a new segment
        if segment.meta.size_bytes >= self.config.segment_size_bytes() as u64 {
            // Sync current segment before rotating
            segment.sync()?;

            // Update synced LSN
            if let Some(last) = segment.meta.last_lsn {
                self.synced_lsn.store(last, Ordering::SeqCst);
            }

            // Add current segment to list
            let mut segments = self.segments.write().await;
            segments.push(segment.meta.clone());

            // Create new segment
            let new_segment_id = segment.meta.segment_id + 1;
            *segment = Self::create_new_segment(&self.config, new_segment_id, lsn)?;
        }

        // Write the entry
        segment.write_entry(&entry)?;

        // Handle sync based on mode
        match &self.config.sync_mode {
            SyncMode::Immediate => {
                segment.sync()?;
                self.synced_lsn.store(lsn, Ordering::SeqCst);
            }
            SyncMode::Async | SyncMode::Batched(_) => {
                // Flush buffer but don't fsync
                segment.flush()?;
            }
        }

        tracing::trace!(
            lsn = lsn,
            op = entry.operation.op_type(),
            "WAL: Appended entry"
        );

        Ok(lsn)
    }

    /// Append multiple operations atomically
    pub async fn append_batch(&self, ops: Vec<WalOperation>) -> MemResult<u64> {
        if ops.is_empty() {
            return Ok(self.current_lsn.load(Ordering::SeqCst));
        }

        if self.closed.load(Ordering::SeqCst) != 0 {
            return Err(MemError::storage("WAL is closed"));
        }

        let first_lsn = self
            .current_lsn
            .fetch_add(ops.len() as u64, Ordering::SeqCst);
        let mut segment = self.current_segment.lock().await;

        for (i, op) in ops.into_iter().enumerate() {
            let lsn = first_lsn + i as u64;
            let entry = WalEntry::new(lsn, op);
            segment.write_entry(&entry)?;
        }

        // Handle sync based on mode
        match &self.config.sync_mode {
            SyncMode::Immediate => {
                segment.sync()?;
                self.synced_lsn.store(
                    self.current_lsn.load(Ordering::SeqCst) - 1,
                    Ordering::SeqCst,
                );
            }
            SyncMode::Async | SyncMode::Batched(_) => {
                segment.flush()?;
            }
        }

        Ok(first_lsn)
    }

    /// Force sync to disk
    pub async fn sync(&self) -> MemResult<()> {
        let mut segment = self.current_segment.lock().await;
        segment.sync()?;
        if let Some(last) = segment.meta.last_lsn {
            self.synced_lsn.store(last, Ordering::SeqCst);
        }
        Ok(())
    }

    /// Create a checkpoint
    ///
    /// A checkpoint marks all operations up to this point as durable.
    /// Returns the checkpoint ID.
    pub async fn checkpoint(&self) -> MemResult<CheckpointId> {
        // Force sync first
        self.sync().await?;

        let checkpoint_id = self.checkpoint_counter.fetch_add(1, Ordering::SeqCst);
        let checkpoint_lsn = self.current_lsn.load(Ordering::SeqCst);

        // Append checkpoint operation to WAL
        let lsn = self
            .append(WalOperation::Checkpoint {
                lsn: checkpoint_lsn,
                checkpoint_id,
            })
            .await?;

        // Force sync the checkpoint entry
        self.sync().await?;

        // Create checkpoint file
        let checkpoint = Checkpoint::new(
            checkpoint_id,
            LogSequenceNumber::new(checkpoint_lsn),
            vec![], // TODO: Collect actual document IDs
            vec![], // TODO: Collect actual chunk IDs
        );

        let checkpoint_path = self.config.dir.join(format!(
            "{}{:016x}{}",
            CHECKPOINT_PREFIX, checkpoint_id, CHECKPOINT_EXTENSION
        ));

        let data = checkpoint.to_bytes()?;
        std::fs::write(&checkpoint_path, data)
            .map_err(|e| MemError::storage(format!("Failed to write checkpoint file: {}", e)))?;

        // Update last checkpoint
        self.last_checkpoint.store(checkpoint_lsn, Ordering::SeqCst);

        // Cleanup old checkpoints
        self.cleanup_old_checkpoints().await?;

        tracing::info!(
            checkpoint_id = checkpoint_id,
            lsn = lsn,
            "WAL: Created checkpoint"
        );

        Ok(CheckpointId::new(checkpoint_id))
    }

    /// Cleanup old checkpoint files
    async fn cleanup_old_checkpoints(&self) -> MemResult<()> {
        let mut checkpoints: Vec<(u64, PathBuf)> = Vec::new();

        let entries = std::fs::read_dir(&self.config.dir)
            .map_err(|e| MemError::storage(format!("Failed to read directory: {}", e)))?;

        for entry in entries {
            let entry =
                entry.map_err(|e| MemError::storage(format!("Failed to read entry: {}", e)))?;
            let path = entry.path();

            if let Some(name) = path.file_name().and_then(|n| n.to_str()) {
                if name.starts_with(CHECKPOINT_PREFIX) && name.ends_with(CHECKPOINT_EXTENSION) {
                    let id_str = name
                        .trim_start_matches(CHECKPOINT_PREFIX)
                        .trim_end_matches(CHECKPOINT_EXTENSION);
                    if let Ok(id) = u64::from_str_radix(id_str, 16) {
                        checkpoints.push((id, path));
                    }
                }
            }
        }

        // Sort by ID descending
        checkpoints.sort_by(|a, b| b.0.cmp(&a.0));

        // Remove old checkpoints beyond retention
        for (_, path) in checkpoints.iter().skip(self.config.checkpoint_retention) {
            if let Err(e) = std::fs::remove_file(path) {
                tracing::warn!(path = ?path, error = %e, "Failed to remove old checkpoint");
            }
        }

        Ok(())
    }

    /// Recover entries from the WAL after crash
    ///
    /// Returns a recovery report with all recovered entries.
    pub async fn recover(&self) -> MemResult<RecoveryReport> {
        let start_time = Instant::now();
        let mut report = RecoveryReport::default();

        // Find latest checkpoint
        let replay_from = match Self::find_latest_checkpoint(&self.config.dir) {
            Ok(checkpoint) => {
                report.checkpoint_used = Some(checkpoint.id);
                checkpoint.lsn.value()
            }
            Err(_) => self.last_checkpoint.load(Ordering::SeqCst),
        };

        let segments = self.segments.read().await;

        // Find segments that may contain entries after checkpoint
        for seg_meta in segments.iter() {
            // Skip segments entirely before checkpoint
            if let Some(last_lsn) = seg_meta.last_lsn {
                if last_lsn < replay_from {
                    continue;
                }
            }

            // Read entries from this segment
            match File::open(&seg_meta.path) {
                Ok(file) => {
                    let mut reader = BufReader::new(file);
                    while let Ok(Some(entry)) = read_entry(&mut reader) {
                        if entry.lsn > replay_from
                            && !matches!(entry.operation, WalOperation::Checkpoint { .. })
                        {
                            if entry.verify() {
                                report.entries_recovered += 1;
                                report.entries_replayed += 1;
                                report.last_valid_lsn = entry.lsn();
                            } else {
                                report.entries_skipped += 1;
                                report.errors.push(RecoveryError {
                                    lsn: Some(entry.lsn()),
                                    segment: Some(seg_meta.path.clone()),
                                    message: "Invalid checksum".to_string(),
                                    fatal: false,
                                });
                            }
                        }
                    }
                }
                Err(e) => {
                    report.errors.push(RecoveryError {
                        lsn: None,
                        segment: Some(seg_meta.path.clone()),
                        message: format!("Failed to open segment: {}", e),
                        fatal: false,
                    });
                }
            }
        }

        // Also read from current segment
        {
            let segment = self.current_segment.lock().await;
            if segment.meta.path.exists() {
                if let Ok(file) = File::open(&segment.meta.path) {
                    let mut reader = BufReader::new(file);
                    while let Ok(Some(entry)) = read_entry(&mut reader) {
                        if entry.lsn > replay_from
                            && !matches!(entry.operation, WalOperation::Checkpoint { .. })
                        {
                            if entry.verify() {
                                report.entries_recovered += 1;
                                report.entries_replayed += 1;
                                report.last_valid_lsn = entry.lsn();
                            } else {
                                report.entries_skipped += 1;
                            }
                        }
                    }
                }
            }
        }

        report.duration_ms = start_time.elapsed().as_millis() as u64;
        report.success = report.errors.iter().all(|e| !e.fatal);

        tracing::info!(
            count = report.entries_recovered,
            skipped = report.entries_skipped,
            duration_ms = report.duration_ms,
            "WAL: Recovery completed"
        );

        Ok(report)
    }

    /// Truncate WAL segments before the given LSN
    ///
    /// This removes old segments that are no longer needed.
    /// Only segments where all entries have LSN < the given value will be removed.
    pub async fn truncate_before(&self, lsn: LogSequenceNumber) -> MemResult<()> {
        let mut segments = self.segments.write().await;

        // Find segments to remove
        let mut to_remove = Vec::new();
        let mut i = 0;
        while i < segments.len() {
            let seg = &segments[i];
            if let Some(last_lsn) = seg.last_lsn {
                if last_lsn < lsn.value() {
                    to_remove.push(i);
                }
            }
            i += 1;
        }

        // Remove segments (in reverse order to maintain indices)
        for &idx in to_remove.iter().rev() {
            let seg = segments.remove(idx);
            if let Err(e) = std::fs::remove_file(&seg.path) {
                tracing::warn!(
                    path = ?seg.path,
                    error = %e,
                    "WAL: Failed to remove old segment"
                );
            } else {
                tracing::info!(
                    segment_id = seg.segment_id,
                    last_lsn = ?seg.last_lsn,
                    "WAL: Removed old segment"
                );
            }
        }

        Ok(())
    }

    /// Get the current LSN
    pub fn get_current_lsn(&self) -> u64 {
        self.current_lsn.load(Ordering::SeqCst)
    }

    /// Get the last checkpoint LSN
    pub fn last_checkpoint_lsn(&self) -> u64 {
        self.last_checkpoint.load(Ordering::SeqCst)
    }

    /// Read entries from a given LSN
    pub async fn read_from(
        &self,
        start_lsn: LogSequenceNumber,
        limit: usize,
    ) -> MemResult<Vec<WalEntry>> {
        let mut result = Vec::with_capacity(limit);
        let segments = self.segments.read().await;

        // Read from all segments
        for seg_meta in segments.iter() {
            if result.len() >= limit {
                break;
            }

            if let Some(last_lsn) = seg_meta.last_lsn {
                if last_lsn < start_lsn.value() {
                    continue;
                }
            }

            if let Ok(file) = File::open(&seg_meta.path) {
                let mut reader = BufReader::new(file);
                while let Ok(Some(entry)) = read_entry(&mut reader) {
                    if entry.lsn >= start_lsn.value() && entry.verify() {
                        result.push(entry);
                        if result.len() >= limit {
                            break;
                        }
                    }
                }
            }
        }

        // Also read from current segment
        {
            let segment = self.current_segment.lock().await;
            if result.len() < limit && segment.meta.path.exists() {
                if let Ok(file) = File::open(&segment.meta.path) {
                    let mut reader = BufReader::new(file);
                    while let Ok(Some(entry)) = read_entry(&mut reader) {
                        if entry.lsn >= start_lsn.value() && entry.verify() {
                            result.push(entry);
                            if result.len() >= limit {
                                break;
                            }
                        }
                    }
                }
            }
        }

        // Sort by LSN
        result.sort_by_key(|e| e.lsn);

        Ok(result)
    }

    /// Close the WAL gracefully
    pub async fn close(&self) -> MemResult<()> {
        self.closed.store(1, Ordering::SeqCst);
        self.shutdown.store(1, Ordering::SeqCst);
        self.sync().await?;
        Ok(())
    }

    /// Get statistics about the WAL
    pub async fn stats(&self) -> WalStats {
        let segments = self.segments.read().await;
        let current = self.current_segment.lock().await;

        let total_segments = segments.len() + 1; // Include current
        let total_size: u64 =
            segments.iter().map(|s| s.size_bytes).sum::<u64>() + current.meta.size_bytes;

        WalStats {
            current_lsn: self.current_lsn.load(Ordering::SeqCst),
            synced_lsn: self.synced_lsn.load(Ordering::SeqCst),
            last_checkpoint_lsn: self.last_checkpoint.load(Ordering::SeqCst),
            total_segments,
            total_size_bytes: total_size,
        }
    }
}

impl Drop for WriteAheadLog {
    fn drop(&mut self) {
        // Signal shutdown to background tasks
        self.shutdown.store(1, Ordering::SeqCst);
    }
}

// ============================================================================
// Implement Trait for WriteAheadLog
// ============================================================================

#[async_trait]
impl WriteAheadLogTrait for WriteAheadLog {
    async fn append(&self, op: WalOperation) -> MemResult<LogSequenceNumber> {
        let lsn = WriteAheadLog::append(self, op).await?;
        Ok(LogSequenceNumber::new(lsn))
    }

    async fn append_batch(&self, ops: Vec<WalOperation>) -> MemResult<LogSequenceNumber> {
        let lsn = WriteAheadLog::append_batch(self, ops).await?;
        Ok(LogSequenceNumber::new(lsn))
    }

    async fn sync(&self) -> MemResult<()> {
        WriteAheadLog::sync(self).await
    }

    async fn checkpoint(&self) -> MemResult<CheckpointId> {
        WriteAheadLog::checkpoint(self).await
    }

    async fn recover(&self) -> MemResult<RecoveryReport> {
        WriteAheadLog::recover(self).await
    }

    async fn truncate_before(&self, lsn: LogSequenceNumber) -> MemResult<()> {
        WriteAheadLog::truncate_before(self, lsn).await
    }

    async fn current_lsn(&self) -> LogSequenceNumber {
        LogSequenceNumber::new(self.get_current_lsn())
    }

    async fn synced_lsn(&self) -> LogSequenceNumber {
        LogSequenceNumber::new(self.synced_lsn.load(Ordering::SeqCst))
    }

    async fn read_from(
        &self,
        start_lsn: LogSequenceNumber,
        limit: usize,
    ) -> MemResult<Vec<WalEntry>> {
        WriteAheadLog::read_from(self, start_lsn, limit).await
    }

    async fn close(&self) -> MemResult<()> {
        WriteAheadLog::close(self).await
    }
}

// ============================================================================
// In-Memory WAL (for testing)
// ============================================================================

/// In-memory WAL implementation for testing purposes
pub struct InMemoryWal {
    entries: RwLock<Vec<WalEntry>>,
    current_lsn: AtomicU64,
    checkpoints: RwLock<Vec<Checkpoint>>,
}

impl Default for InMemoryWal {
    fn default() -> Self {
        Self::new()
    }
}

impl InMemoryWal {
    /// Create a new in-memory WAL instance
    pub fn new() -> Self {
        Self {
            entries: RwLock::new(Vec::new()),
            current_lsn: AtomicU64::new(1),
            checkpoints: RwLock::new(Vec::new()),
        }
    }
}

#[async_trait]
impl WriteAheadLogTrait for InMemoryWal {
    async fn append(&self, op: WalOperation) -> MemResult<LogSequenceNumber> {
        let lsn = self.current_lsn.fetch_add(1, Ordering::SeqCst);
        let entry = WalEntry::new(lsn, op);

        let mut entries = self.entries.write().await;
        entries.push(entry);

        Ok(LogSequenceNumber::new(lsn))
    }

    async fn append_batch(&self, ops: Vec<WalOperation>) -> MemResult<LogSequenceNumber> {
        if ops.is_empty() {
            return Ok(LogSequenceNumber::new(
                self.current_lsn.load(Ordering::SeqCst),
            ));
        }

        let first_lsn = self
            .current_lsn
            .fetch_add(ops.len() as u64, Ordering::SeqCst);

        let mut entries = self.entries.write().await;
        for (i, op) in ops.into_iter().enumerate() {
            let entry = WalEntry::new(first_lsn + i as u64, op);
            entries.push(entry);
        }

        Ok(LogSequenceNumber::new(first_lsn))
    }

    async fn sync(&self) -> MemResult<()> {
        // No-op for in-memory
        Ok(())
    }

    async fn checkpoint(&self) -> MemResult<CheckpointId> {
        let checkpoints = self.checkpoints.read().await;
        let id = checkpoints.len() as u64 + 1;
        drop(checkpoints);

        let lsn = LogSequenceNumber::new(self.current_lsn.load(Ordering::SeqCst));
        let checkpoint = Checkpoint::new(id, lsn, vec![], vec![]);

        let mut checkpoints = self.checkpoints.write().await;
        checkpoints.push(checkpoint);

        Ok(CheckpointId::new(id))
    }

    async fn recover(&self) -> MemResult<RecoveryReport> {
        let entries = self.entries.read().await;
        let checkpoints = self.checkpoints.read().await;

        Ok(RecoveryReport {
            entries_recovered: entries.len() as u64,
            entries_skipped: 0,
            entries_replayed: entries.len() as u64,
            last_valid_lsn: entries.last().map(|e| e.lsn()).unwrap_or_default(),
            checkpoint_used: checkpoints.last().map(|c| c.id),
            duration_ms: 0,
            errors: vec![],
            success: true,
        })
    }

    async fn truncate_before(&self, lsn: LogSequenceNumber) -> MemResult<()> {
        let mut entries = self.entries.write().await;
        entries.retain(|e| e.lsn >= lsn.value());
        Ok(())
    }

    async fn current_lsn(&self) -> LogSequenceNumber {
        LogSequenceNumber::new(self.current_lsn.load(Ordering::SeqCst))
    }

    async fn synced_lsn(&self) -> LogSequenceNumber {
        // In-memory is always "synced"
        self.current_lsn().await
    }

    async fn read_from(
        &self,
        start_lsn: LogSequenceNumber,
        limit: usize,
    ) -> MemResult<Vec<WalEntry>> {
        let entries = self.entries.read().await;
        Ok(entries
            .iter()
            .filter(|e| e.lsn >= start_lsn.value())
            .take(limit)
            .cloned()
            .collect())
    }

    async fn close(&self) -> MemResult<()> {
        Ok(())
    }
}

// ============================================================================
// WAL Statistics
// ============================================================================

/// WAL statistics
#[derive(Debug, Clone)]
pub struct WalStats {
    /// Current Log Sequence Number
    pub current_lsn: u64,
    /// Last synced LSN
    pub synced_lsn: u64,
    /// Last checkpoint LSN
    pub last_checkpoint_lsn: u64,
    /// Number of segment files
    pub total_segments: usize,
    /// Total size of all segments in bytes
    pub total_size_bytes: u64,
}

// ============================================================================
// Helper Functions
// ============================================================================

/// Compute CRC32 checksum for a WAL entry
///
/// The checksum is computed over all fields except the checksum itself.
pub fn compute_checksum(entry: &WalEntry) -> u32 {
    // Create a copy with checksum zeroed for computation
    let entry_for_hash = WalEntry {
        lsn: entry.lsn,
        timestamp: entry.timestamp,
        operation: entry.operation.clone(),
        checksum: 0,
    };

    // Serialize and compute CRC32
    match wal_serialize(&entry_for_hash) {
        Ok(data) => crc32_compute(&data),
        Err(_) => 0,
    }
}

/// Verify the checksum of a WAL entry
pub fn verify_checksum(entry: &WalEntry) -> bool {
    let computed = compute_checksum(entry);
    computed == entry.checksum
}

/// Compute CRC32 checksum using the Castagnoli polynomial (CRC-32C)
fn crc32_compute(data: &[u8]) -> u32 {
    // CRC-32C polynomial: 0x1EDC6F41
    const CRC32C_TABLE: [u32; 256] = generate_crc32c_table();

    let mut crc: u32 = 0xFFFFFFFF;
    for byte in data {
        let index = ((crc ^ (*byte as u32)) & 0xFF) as usize;
        crc = (crc >> 8) ^ CRC32C_TABLE[index];
    }
    !crc
}

/// Generate CRC-32C lookup table at compile time
const fn generate_crc32c_table() -> [u32; 256] {
    const POLYNOMIAL: u32 = 0x82F63B78; // Reflected CRC-32C
    let mut table = [0u32; 256];
    let mut i = 0;
    while i < 256 {
        let mut crc = i as u32;
        let mut j = 0;
        while j < 8 {
            if crc & 1 != 0 {
                crc = (crc >> 1) ^ POLYNOMIAL;
            } else {
                crc >>= 1;
            }
            j += 1;
        }
        table[i] = crc;
        i += 1;
    }
    table
}

/// Serialize using JSON format
fn wal_serialize<T: Serialize>(value: &T) -> MemResult<Vec<u8>> {
    serde_json::to_vec(value)
        .map_err(|e| MemError::storage(format!("Failed to serialize WAL entry: {}", e)))
}

/// Deserialize using JSON format
fn wal_deserialize<T: for<'de> Deserialize<'de>>(data: &[u8]) -> MemResult<T> {
    serde_json::from_slice(data)
        .map_err(|e| MemError::storage(format!("Failed to deserialize WAL entry: {}", e)))
}

/// Read a single entry from a WAL segment
fn read_entry<R: Read + BufRead>(reader: &mut R) -> MemResult<Option<WalEntry>> {
    // Read magic bytes
    let mut magic = [0u8; 4];
    match reader.read_exact(&mut magic) {
        Ok(()) => {}
        Err(e) if e.kind() == std::io::ErrorKind::UnexpectedEof => return Ok(None),
        Err(e) => {
            return Err(MemError::storage(format!(
                "Failed to read WAL magic: {}",
                e
            )))
        }
    }

    if magic != WAL_MAGIC {
        return Err(MemError::storage("Invalid WAL magic bytes"));
    }

    // Read version
    let mut version = [0u8; 1];
    reader
        .read_exact(&mut version)
        .map_err(|e| MemError::storage(format!("Failed to read WAL version: {}", e)))?;

    if version[0] != WAL_VERSION {
        return Err(MemError::storage(format!(
            "Unsupported WAL version: {}",
            version[0]
        )));
    }

    // Read length
    let mut len_bytes = [0u8; 4];
    reader
        .read_exact(&mut len_bytes)
        .map_err(|e| MemError::storage(format!("Failed to read entry length: {}", e)))?;
    let len = u32::from_le_bytes(len_bytes) as usize;

    // Sanity check length
    if len > 100 * 1024 * 1024 {
        // 100MB max
        return Err(MemError::storage(format!(
            "WAL entry too large: {} bytes",
            len
        )));
    }

    // Read data
    let mut data = vec![0u8; len];
    reader
        .read_exact(&mut data)
        .map_err(|e| MemError::storage(format!("Failed to read entry data: {}", e)))?;

    // Read trailing length
    let mut trailing_len = [0u8; 4];
    reader
        .read_exact(&mut trailing_len)
        .map_err(|e| MemError::storage(format!("Failed to read trailing length: {}", e)))?;

    if u32::from_le_bytes(trailing_len) != len as u32 {
        return Err(MemError::storage("WAL entry length mismatch"));
    }

    // Deserialize
    let entry: WalEntry = wal_deserialize(&data)?;

    Ok(Some(entry))
}

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

#[cfg(test)]
mod tests {
    use super::*;
    use tempfile::TempDir;

    #[test]
    fn test_lsn_ordering() {
        let lsn1 = LogSequenceNumber::new(1);
        let lsn2 = LogSequenceNumber::new(2);
        let lsn3 = LogSequenceNumber::new(2);

        assert!(lsn1 < lsn2);
        assert_eq!(lsn2, lsn3);
        assert_eq!(lsn1.next(), lsn2);
    }

    #[test]
    fn test_checksum_computation() {
        let entry = WalEntry::new(
            1,
            WalOperation::Insert {
                id: Uuid::new_v4(),
                content: "test content".to_string(),
                embedding: vec![0.1, 0.2, 0.3],
            },
        );

        assert!(entry.verify());

        // Modify and verify checksum fails
        let mut modified = entry.clone();
        modified.lsn = 999;
        assert!(!modified.verify());
    }

    #[test]
    fn test_crc32_computation() {
        // Test vector: "123456789" should give 0xE3069283 for CRC-32C
        let data = b"123456789";
        let crc = crc32_compute(data);
        assert_eq!(crc, 0xE3069283);
    }

    #[test]
    fn test_checkpoint_serialization() {
        let checkpoint = Checkpoint::new(
            1,
            LogSequenceNumber::new(100),
            vec![Uuid::new_v4(), Uuid::new_v4()],
            vec![Uuid::new_v4()],
        );

        let bytes = checkpoint.to_bytes().unwrap();
        let recovered = Checkpoint::from_bytes(&bytes).unwrap();

        assert_eq!(checkpoint.id, recovered.id);
        assert_eq!(checkpoint.lsn, recovered.lsn);
        assert_eq!(checkpoint.document_ids.len(), recovered.document_ids.len());
    }

    #[tokio::test]
    async fn test_in_memory_wal() {
        let wal = InMemoryWal::new();

        // Append some entries
        let lsn1 = wal
            .append(WalOperation::Insert {
                id: Uuid::new_v4(),
                content: "doc1".to_string(),
                embedding: vec![0.1, 0.2, 0.3],
            })
            .await
            .unwrap();

        let lsn2 = wal
            .append(WalOperation::Insert {
                id: Uuid::new_v4(),
                content: "doc2".to_string(),
                embedding: vec![0.4, 0.5, 0.6],
            })
            .await
            .unwrap();

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

        // Read back
        let entries = wal.read_from(LogSequenceNumber::new(1), 10).await.unwrap();
        assert_eq!(entries.len(), 2);

        // Checkpoint
        let ckpt = wal.checkpoint().await.unwrap();
        assert_eq!(ckpt.value(), 1);

        // Recovery report
        let report = wal.recover().await.unwrap();
        assert!(report.success);
        assert_eq!(report.entries_recovered, 2);
    }

    #[tokio::test]
    async fn test_wal_basic_operations() {
        let temp_dir = TempDir::new().unwrap();
        let config =
            WalConfig::new(temp_dir.path().to_path_buf()).with_sync_mode(SyncMode::Immediate);

        let wal = WriteAheadLog::new(config).await.unwrap();

        // Append some entries
        let id1 = Uuid::new_v4();
        let lsn1 = wal
            .append(WalOperation::Insert {
                id: id1,
                content: "First entry".to_string(),
                embedding: vec![0.1, 0.2],
            })
            .await
            .unwrap();

        let id2 = Uuid::new_v4();
        let lsn2 = wal
            .append(WalOperation::Insert {
                id: id2,
                content: "Second entry".to_string(),
                embedding: vec![0.3, 0.4],
            })
            .await
            .unwrap();

        assert!(lsn2 > lsn1);

        // Create checkpoint
        wal.checkpoint().await.unwrap();

        // Check stats
        let stats = wal.stats().await;
        assert!(stats.current_lsn >= 3); // At least 2 inserts + 1 checkpoint
        assert_eq!(stats.total_segments, 1);
    }

    #[tokio::test]
    async fn test_wal_recovery() {
        let temp_dir = TempDir::new().unwrap();
        let config =
            WalConfig::new(temp_dir.path().to_path_buf()).with_sync_mode(SyncMode::Immediate);

        // Write some entries
        let id1 = Uuid::new_v4();
        let id2 = Uuid::new_v4();
        {
            let wal = WriteAheadLog::new(config.clone()).await.unwrap();

            wal.append(WalOperation::Insert {
                id: id1,
                content: "Before checkpoint".to_string(),
                embedding: vec![0.1],
            })
            .await
            .unwrap();

            wal.checkpoint().await.unwrap();

            wal.append(WalOperation::Insert {
                id: id2,
                content: "After checkpoint".to_string(),
                embedding: vec![0.2],
            })
            .await
            .unwrap();

            wal.close().await.unwrap();
        }

        // Recover
        let wal2 = WriteAheadLog::new(config).await.unwrap();
        let report = wal2.recover().await.unwrap();

        assert!(report.success);
        // Should have at least the entry after checkpoint
        assert!(report.entries_recovered >= 1);
    }

    #[tokio::test]
    async fn test_wal_batch_operations() {
        let temp_dir = TempDir::new().unwrap();
        let config =
            WalConfig::new(temp_dir.path().to_path_buf()).with_sync_mode(SyncMode::Immediate);

        let wal = WriteAheadLog::new(config).await.unwrap();

        // Batch insert
        let ops = vec![
            WalOperation::Insert {
                id: Uuid::new_v4(),
                content: "Batch 1".to_string(),
                embedding: vec![0.1],
            },
            WalOperation::Insert {
                id: Uuid::new_v4(),
                content: "Batch 2".to_string(),
                embedding: vec![0.2],
            },
            WalOperation::Insert {
                id: Uuid::new_v4(),
                content: "Batch 3".to_string(),
                embedding: vec![0.3],
            },
        ];

        let first_lsn = wal.append_batch(ops).await.unwrap();

        // Verify consecutive LSNs
        let entries = wal
            .read_from(LogSequenceNumber::new(first_lsn), 10)
            .await
            .unwrap();
        assert_eq!(entries.len(), 3);
        assert_eq!(entries[0].lsn, first_lsn);
        assert_eq!(entries[1].lsn, first_lsn + 1);
        assert_eq!(entries[2].lsn, first_lsn + 2);
    }

    #[tokio::test]
    async fn test_wal_segment_rotation() {
        let temp_dir = TempDir::new().unwrap();
        let config = WalConfig::new(temp_dir.path().to_path_buf())
            .with_segment_size(1) // 1MB segments
            .with_sync_mode(SyncMode::Immediate);

        let wal = WriteAheadLog::new(config).await.unwrap();

        // Write enough data to trigger rotation
        let large_embedding: Vec<f32> = (0..10000).map(|i| i as f32).collect();
        for i in 0..20 {
            wal.append(WalOperation::Insert {
                id: Uuid::new_v4(),
                content: format!("Entry {} with large embedding", i),
                embedding: large_embedding.clone(),
            })
            .await
            .unwrap();
        }

        let stats = wal.stats().await;
        assert!(stats.total_segments >= 1);
    }

    #[tokio::test]
    async fn test_wal_truncate() {
        let temp_dir = TempDir::new().unwrap();
        let config = WalConfig::new(temp_dir.path().to_path_buf())
            .with_segment_size(1) // Small segments for testing
            .with_sync_mode(SyncMode::Immediate);

        let wal = WriteAheadLog::new(config).await.unwrap();

        // Write entries and checkpoint
        for _ in 0..5 {
            wal.append(WalOperation::Insert {
                id: Uuid::new_v4(),
                content: "test".to_string(),
                embedding: vec![0.1; 1000],
            })
            .await
            .unwrap();
        }

        let checkpoint_id = wal.checkpoint().await.unwrap();

        // Truncate before checkpoint
        wal.truncate_before(LogSequenceNumber::new(wal.last_checkpoint_lsn()))
            .await
            .unwrap();

        assert!(checkpoint_id.value() > 0);
    }

    #[test]
    fn test_wal_operation_types() {
        let insert = WalOperation::Insert {
            id: Uuid::new_v4(),
            content: "test".to_string(),
            embedding: vec![],
        };
        assert_eq!(insert.op_type(), "INSERT");

        let update = WalOperation::Update {
            id: Uuid::new_v4(),
            content: "test".to_string(),
            embedding: vec![],
        };
        assert_eq!(update.op_type(), "UPDATE");

        let delete = WalOperation::Delete { id: Uuid::new_v4() };
        assert_eq!(delete.op_type(), "DELETE");

        let checkpoint = WalOperation::Checkpoint {
            lsn: 0,
            checkpoint_id: 1,
        };
        assert_eq!(checkpoint.op_type(), "CHECKPOINT");

        let batch = WalOperation::BatchInsert { items: vec![] };
        assert_eq!(batch.op_type(), "BATCH_INSERT");

        let txn_begin = WalOperation::TxnBegin {
            txn_id: Uuid::new_v4(),
        };
        assert_eq!(txn_begin.op_type(), "TXN_BEGIN");
    }

    #[test]
    fn test_wal_config_builder() {
        let config = WalConfig::new(PathBuf::from("/tmp/wal"))
            .with_segment_size(128)
            .with_sync_mode(SyncMode::Immediate)
            .with_checkpoint_retention(5);

        assert_eq!(config.segment_size_mb, 128);
        assert_eq!(config.checkpoint_retention, 5);
        assert!(matches!(config.sync_mode, SyncMode::Immediate));
    }

    #[test]
    fn test_entry_serialized_size() {
        let entry = WalEntry::new(
            1,
            WalOperation::Insert {
                id: Uuid::new_v4(),
                content: "Hello, World!".to_string(),
                embedding: vec![0.1, 0.2, 0.3, 0.4, 0.5],
            },
        );

        let size = entry.serialized_size().unwrap();
        assert!(size > 0);
        // Header overhead + data
        assert!(size > 50); // Reasonable minimum for the entry
    }

    #[tokio::test]
    async fn test_wal_trait_interface() {
        // Test the trait interface works with both implementations
        async fn use_wal(wal: &dyn WriteAheadLogTrait) -> MemResult<()> {
            let lsn = wal
                .append(WalOperation::Insert {
                    id: Uuid::new_v4(),
                    content: "test".to_string(),
                    embedding: vec![0.1],
                })
                .await?;

            assert!(lsn.value() > 0);
            Ok(())
        }

        // Test with InMemoryWal
        let mem_wal = InMemoryWal::new();
        use_wal(&mem_wal).await.unwrap();

        // Test with FileWal
        let temp_dir = TempDir::new().unwrap();
        let config =
            WalConfig::new(temp_dir.path().to_path_buf()).with_sync_mode(SyncMode::Immediate);
        let file_wal = WriteAheadLog::new(config).await.unwrap();
        use_wal(&file_wal).await.unwrap();
    }
}