hakodb 0.23.21

Embedded & Cloud-native Document Engine
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
use hashbrown::HashMap;
use std::path::{Path, PathBuf};

use crate::cancel::CancelToken;
use crate::config::{HakoConfig, DurabilityMode};
use crate::error::{HakoError, Result};
use std::sync::{Arc, Mutex, RwLock};
use std::time::UNIX_EPOCH;
use crate::memory::page_cache::PageCache;

use super::blob::{BlobManager, BlobWork};
use super::compaction::compact_segment;
use super::crypto::EncryptionContext;
use super::segment::Segment;
use super::wal::{Wal, WalOp};
use crossbeam_channel::Sender as CrossbeamSender;
use crate::document::hako_doc::HakoDoc;

/// Successful narrow-lock tier merges since process start: test
/// tripwire (a compaction race test that never merges is vacuous) and
/// operational visibility. One Relaxed increment per merge.
static TIER_COMPACTIONS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);

/// How many tier compactions completed (see above).
pub fn tier_compactions() -> usize {
    TIER_COMPACTIONS.load(std::sync::atomic::Ordering::Relaxed)
}

/// The loud empty-open diagnosis (#70): open recovered ZERO live docs for
/// a collection whose on-disk history is NOT empty. After the incident —
/// a live copy replayed nothing though its WAL held megabytes of real op
/// bytes — this state deserves a scream, not silence. Fires only when the
/// parser extracted ZERO ops while real record bytes or nonzero segment
/// files exist on disk (a tombstone-emptied collection replays ops, so it
/// stays quiet; a fresh dir has neither bytes nor segments).
fn empty_open_diagnosis_message(
    logical_name: &str,
    live_keys: usize,
    ops_replayed: usize,
    wal_data_bytes: u64,
    nonzero_segments: usize,
) -> Option<String> {
    if live_keys > 0 || ops_replayed > 0 {
        return None;
    }
    if wal_data_bytes < 1024 && nonzero_segments == 0 {
        // Nothing on disk claims history: fresh collection or pure
        // Interval tail loss (the copy simply lacks the in-memory part).
        return None;
    }
    Some(format!(
        "[hakodb][loud-open] collection '{}' recovered 0 live documents \
and the WAL replay produced 0 operations, yet its on-disk history is \
not empty: wal.log holds {} real record bytes and {} nonzero segment \
file(s). Likely causes: (a) a live copy whose WAL/segment tail was \
truncated mid-record, (b) the copy skipped segment files, (c) a \
hand-edit or corruption that detached the WAL from its history. \
Compare against the source directory before writing anything.",
        logical_name, wal_data_bytes, nonzero_segments
    ))
}


#[derive(Debug, Clone)] 
pub enum Pointer {
    Segment {
        segment_id: u64,
        offset: u64,
        len: u32,
    },
    Inlined(Arc<Vec<u8>>),
    Blob {
        offset: u64,
        len: u32,
    },
    BlobPending(Arc<HakoDoc>),
    BlobPendingData { 
        data: Arc<Vec<u8>>, 
        skeleton: Vec<u8> 
    },
    Deleted { timestamp: i64 },
}

#[derive(Debug, Clone)]
pub enum StorageMutation {
    Put { key: String, value: Vec<u8> },
    Delete { key: String },
}

struct SegmentMeta {
    // id: u64,
    level: u32,
    segment: Segment,
}

pub struct StorageEngine {
    base_dir: PathBuf,
    segments: HashMap<u64, SegmentMeta>,
    active_segment_id: u64,
    next_segment_id: u64,
    pub(crate) wal: Wal,
    pub(crate) next_tx_id: u64,
    compaction_threshold_bytes: usize,
    pub encryption: Option<EncryptionContext>,
    pub(crate) inlined_bytes: usize,
    pub(crate) max_inlined_bytes: usize,
    pub(crate) blob_threshold: usize,
    pub(crate) use_compression: bool, 
    pub(crate) collection_counts: HashMap<String, usize>,
    pub cache: Arc<Mutex<PageCache>>,
    pub mmap_size: usize,
    // Primary index: O(1) hash lookup. Ordered by insertion only when iterated
    // explicitly via `index.iter()`; reads use `get(key)` which is hash-based.
    pub index: HashMap<String, Pointer>,
    // Sorted key view for offset/cursor. Maintained on every index write under
    // the same exclusive lock that owns `index` (caller holds &mut StorageEngine
    // when calling update_index_entry), so no extra synchronisation needed.
    // Read by the executor via `sorted_key_range` and direct slice.
    pub(crate) sorted_keys: Vec<String>,
    /// Receiving buffer for [`Self::flush_pending_sorted`]'s merge pass. The
    /// two buffers ping-pong so a large merge never allocates in steady
    /// state — a fresh (n+m)-capacity Vec here once cost an mmap + page
    /// faults on EVERY small commit (#151 measurement).
    pub(crate) sorted_scratch: Vec<String>,
    pub blob_manager: Option<Arc<BlobManager>>,
    pub(crate) blob_tx: Option<CrossbeamSender<BlobWork>>,
    pub logical_name: String,
    // pub(crate) in_flight_blob_bytes: Arc<std::sync::atomic::AtomicUsize>,
    pub(crate) blob_flush_queue: std::collections::VecDeque<BlobWork>, 
    pub(crate) total_pending_blob_bytes: std::sync::atomic::AtomicUsize,
}

impl StorageEngine {
    pub fn open(
        base_dir: impl AsRef<Path>, 
        cfg: &HakoConfig,
        logical_name: String,
        encryption: Option<EncryptionContext>,
    ) -> Result<Self> {        let base_path = base_dir.as_ref().to_path_buf(); 
        std::fs::create_dir_all(&base_path)?;
        // std::fs::create_dir_all(base_dir.as_ref())?;

        // let encryption = cfg
        //     .encryption_key
        //     .as_ref()
        //     .map(|secret| EncryptionContext::from_secret(secret));

        let cache_limit_bytes = cfg.page_cache_capacity * cfg.page_size;
        let cache = Arc::new(Mutex::new(PageCache::new(cache_limit_bytes)));

        // ponytail: internal collections (checkpoints, room registry, scope
        // markers) hold bytes of data — a multi-MB WAL headroom per system
        // shard is phantom size (sparse zeros still count in logical length).
        let wal_reserve = if logical_name.starts_with("__") { 0 } else { cfg.wal_reserve_bytes };
        let mut wal = Wal::open(
            base_dir.as_ref().join("wal.log"),
            cfg.durability_mode,
            cfg.group_commit_max_ops,
            encryption.clone(),
            wal_reserve,
        )?;
        // Per-instance group-commit window (cluster fsync staggering).
        // Trigger mode is explicit; changing the interval is side-effect free.
        wal.set_group_commit_interval(cfg.group_commit_interval_ms);
        wal.set_commit_trigger_mode(cfg.commit_trigger_mode);

        let mut segments = HashMap::new();
        let mut max_id = 0;
        let mut active_segment_id = 0;

        let blob_file_raw = std::fs::OpenOptions::new()
            .create(true)
            .truncate(false)
            .read(true)
            // .append(true)
            .write(true)
            .open(base_path.join("blobs.dat"))?;

        // 1. Get metadata while we still have ownership of blob_file_raw
        let initial_size = blob_file_raw.metadata()?.len();

        // 2. Now move it into the Arc
        let blob_file = Arc::new(blob_file_raw);
            

        for entry in std::fs::read_dir(base_dir.as_ref())? {
            let entry = entry?;
            let name = entry.file_name();
            let name = name.to_string_lossy();
            if let Some((level, id)) = parse_segment_name(&name) {
                let segment = Segment::open(
                    entry.path(), 
                    id, 
                    encryption.clone(), 
                    Arc::clone(&cache), 
                    cfg.mmap_size
                )?;
                
                segments.insert(id, SegmentMeta { level, segment });
                if id > max_id { max_id = id; }
                if id >= active_segment_id { active_segment_id = id; }
            }
        }

        if segments.is_empty() {
            let path = segment_path(base_dir.as_ref(), 0, 0);
            let segment = Segment::open(
                path, 
                0, 
                encryption.clone(), 
                Arc::clone(&cache), 
                cfg.mmap_size
            )?;
            
            segments.insert(0, SegmentMeta { level: 0, segment });
            max_id = 0;
            active_segment_id = 0;
        }

        let mut engine = Self {
            base_dir: base_path,
            segments,
            active_segment_id,
            next_segment_id: max_id + 1,
            wal,
            index: HashMap::new(),
            next_tx_id: 1,
            compaction_threshold_bytes: cfg.auto_compaction_threshold_bytes,
            encryption: encryption.clone(),
            use_compression: cfg.use_compression,
            inlined_bytes: 0,
            blob_threshold: cfg.value_blob_threshold_bytes,
            max_inlined_bytes: cfg.max_inlined_memory_bytes,
            collection_counts: HashMap::new(),
            cache,
            mmap_size: cfg.mmap_size,
            sorted_keys: Vec::new(),
            sorted_scratch: Vec::new(),
            blob_manager: Some(Arc::new(BlobManager::new(
                blob_file,
                initial_size,
            ))),
            blob_tx: None,
            logical_name,
            blob_flush_queue: std::collections::VecDeque::with_capacity(1024),
            total_pending_blob_bytes: std::sync::atomic::AtomicUsize::new(0),
        };

        let engine_wal_ops_replayed = engine.recover()?;
        // Loud empty-open check (#70): a collection whose replay extracted
        // zero ops while disk history claims bytes/segments is the incident
        // shape — surface it on stderr before anything overwrites evidence.
        if let Some(msg) = empty_open_diagnosis_message(
            &engine.logical_name,
            engine.sorted_keys.len(),
            engine_wal_ops_replayed,
            engine.wal.data_len(),
            engine.segments.values().filter(|s| s.segment.current_size > 0).count(),
        ) {
            eprintln!("{}", msg);
        }
        // WAL hygiene: hot-small collections pile history that nothing ever
        // compacts (segments never spill at this volume). One bounded rewrite
        // on open when stale history dominates; best-effort, never fails open.
        // 2-a (insiden-hako-wal-20260928): the rewrite resets the file and
        // stages the snapshot in the RAM buffer — WITHOUT this flush a
        // SIGTERM before the next threshold-triggered append wipes the
        // collection (file zeros + data only in RAM, indefinitely on a
        // quiet server). One write_all+fdatasync per bloated open: off the
        // write hot path by construction.
        if engine.wal_snapshot_worthwhile()
            && engine.rewrite_wal_snapshot().is_ok() {
                let _ = engine.wal.flush();
            }
        Ok(engine)
    }

    fn recover(&mut self) -> Result<usize> {
        // ponytail: size the map from the WAL footprint (avoids rehash
        // churn on big replays; ops average well above 64B, so this
        // under-reserves rather than over-).
        let est = (self.wal.data_len() / 64).clamp(1024, 1_000_000) as usize;
        self.index.reserve(est);
        let mut ops_replayed = 0usize;
        for op in self.wal.replay()? {
            ops_replayed += 1;
            match op {
                WalOp::Put { key, segment_id, segment_offset, len } => {
                    let pointer = Pointer::Segment {
                        segment_id,
                        offset: segment_offset,
                        len
                    };
                    self.update_index_entry_nosort(key, pointer);
                }
                WalOp::Delete { key, timestamp  } => {
                    self.update_index_entry_nosort(key, Pointer::Deleted { timestamp });
                }
                WalOp::BeginTx { .. } | WalOp::CommitTx { .. } => {}
                WalOp::PutInlined { key, value } => {
                    let pointer = Pointer::Inlined(Arc::new(value));
                    self.update_index_entry_nosort(key, pointer);
                }
                WalOp::PutBlob { key, offset, len } => {
                    self.update_index_entry_nosort(key, Pointer::Blob { offset, len });
                }
                WalOp::ClearCollection { collection } => {
                    self.clear_collection_prefix(&collection);
                }
            }
        }
        // Rebuild sorted_keys from the recovered index. We pay the O(N log N)
        // sort once here instead of N x O(N) Vec::insert shifts during replay.
        let mut keys: Vec<String> = self
            .index
            .iter()
            .filter(|(_, p)| !matches!(p, Pointer::Deleted { .. }))
            .map(|(k, _)| k.clone())
            .collect();
        keys.sort();
        self.sorted_keys = keys;
        // ponytail: the live-count cache is exactly this set — seed it here
        // so count_prefix is O(1) from the first query (update_index_entry
        // maintains it afterwards; absent entries fall back to a scan).
        let live = self.sorted_keys.len();
        self.collection_counts.insert(self.logical_name.clone(), live);
        Ok(ops_replayed)
    }

    /// Vacuum: physically drop tombstones from the RAM index. The docs are
    /// already gone (a tombstone holds only a timestamp); this removes the
    /// markers themselves. Emits no WAL op, so it never replicates.
    /// Effect on sync: the collection version drops to the newest LIVE doc,
    /// so the next handshake pulls peers' state (restore-on-rejoin), and
    /// nothing is pushed outward. Orphaned blob bytes (if any) are left for
    /// blob-compaction, which owns that space.
    pub(crate) fn purge_tombstones(&mut self) -> usize {
        let dead: Vec<String> = self.index.iter()
            .filter(|(_, p)| matches!(p, Pointer::Deleted { .. }))
            .map(|(k, _)| k.clone())
            .collect();
        let n = dead.len();
        // ponytail: route through update_index_entry (None = remove) so the
        // sorted_keys view and byte accounting stay in lockstep. Batched
        // (#151): one merge instead of one O(n) remove per tombstone.
        let mut pending_sorted = Vec::new();
        for k in dead {
            self.update_index_entry_deferred(k, None, &mut pending_sorted);
        }
        self.flush_pending_sorted(&mut pending_sorted);
        n
    }

    /// Bulk replay path: map insert + inlined-bytes accounting only.
    /// Skips `sorted_keys` maintenance AND live-count churn — `recover()`
    /// rebuilds both once afterwards. Routing replay through the regular
    /// path is O(N²) Vec memmoves on unsorted WAL order plus a key clone
    /// per op. Old-pointer bytes ARE unaccounted (overwrites during
    /// replay must net out, or the snapshot heuristic misfires).
    fn update_index_entry_nosort(&mut self, key: String, new_pointer: Pointer) {
        match &new_pointer {
            Pointer::Inlined(d) => { self.inlined_bytes += d.len(); }
            Pointer::BlobPendingData { skeleton, .. } => { self.inlined_bytes += skeleton.len(); }
            _ => {}
        }
        if let Some(old) = self.index.insert(key, new_pointer) {
            match old {
                Pointer::Inlined(d) => { self.inlined_bytes = self.inlined_bytes.saturating_sub(d.len()); }
                Pointer::BlobPendingData { skeleton, .. } => { self.inlined_bytes = self.inlined_bytes.saturating_sub(skeleton.len()); }
                _ => {}
            }
        }
    }

    /// Shared map + memory-stats + live-count effect of an index entry
    /// update. The sorted-keys view is maintained by the caller: immediate
    /// in [`Self::update_index_entry`], batched in the deferred path.
    fn apply_pointer(&mut self, key: &str, new_pointer: Option<&Pointer>) {
        let new_is_live = matches!(new_pointer, Some(p) if !matches!(p, Pointer::Deleted { .. }));
        // 1. Perform the map operation once.
        // .insert() returns the previous value if it existed.
        let old_p = if let Some(p) = new_pointer {
            // Track memory stats for the NEW pointer
            match p {
                Pointer::Inlined(d) => { self.inlined_bytes += d.len(); }
                Pointer::BlobPendingData { skeleton, .. } => { self.inlined_bytes += skeleton.len(); }
                _ => {}
            }
            self.index.insert(key.to_string(), p.clone())
        } else {
            self.index.remove(key)
        };

        // ponytail: liveness computed before the move below.
        let old_was_live = old_p.as_ref().map(|v| !matches!(v, Pointer::Deleted { .. })).unwrap_or(false);
        if let Some(old_val) = old_p {
            // Subtract memory stats for the OLD pointer
            match old_val {
                Pointer::Inlined(ref d) => { self.inlined_bytes = self.inlined_bytes.saturating_sub(d.len()); }
                Pointer::BlobPendingData { ref skeleton, .. } => { self.inlined_bytes = self.inlined_bytes.saturating_sub(skeleton.len()); }
                _ => {}
            }
        }

        // --- COUNT LOGIC (live = non-Deleted) ---
        // ponytail: single entry()-based accounting for all transitions.
        // The old three-branch get_mut silently skipped absent keys, so
        // brand-new collections never got an entry and the map stayed
        // dead. Live<->tombstone flips adjust; live<->live and dead
        // removals (purge) don't.
        if old_was_live && !new_is_live {
            if let Some(count) = self.collection_counts.get_mut(&self.logical_name) {
                *count = count.saturating_sub(1);
            }
        } else if !old_was_live && new_is_live {
            *self.collection_counts.entry(self.logical_name.clone()).or_insert(0) += 1;
        }
    }

    pub(crate) fn update_index_entry(&mut self, key: String, new_pointer: Option<Pointer>) {
        self.apply_pointer(&key, new_pointer.as_ref());

        // Maintain the sorted_keys view in lockstep with `index`.
        // Only LIVE pointers go in sorted_keys — tombstones are excluded so the
        // sorted view is a clean offset/cursor index.
        // Insert: binary_search + insert (O(n) worst case but keys arrive in WAL
        //   replay order which is mostly sorted, so amortised O(log n)).
        // Remove: binary_search + remove (O(n) worst case but deletes are rare
        //   relative to inserts in steady state).
        // The caller holds &mut StorageEngine so no extra synchronisation needed.
        let new_is_live = matches!(new_pointer, Some(ref p) if !matches!(p, Pointer::Deleted { .. }));
        if new_is_live {
            match self.sorted_keys.binary_search(&key) {
                Ok(_) => {} // already present — overwrite kept key
                Err(pos) => self.sorted_keys.insert(pos, key.clone()),
            }
        } else if let Ok(pos) = self.sorted_keys.binary_search(&key) {
            self.sorted_keys.remove(pos);
        }
    }

    /// Batched twin of [`Self::update_index_entry`]: identical map/stats/count
    /// effect, but the sorted-keys view resolves only at
    /// [`Self::flush_pending_sorted`] — one merge per commit instead of one
    /// O(n) Vec memmove per key (#151). Callers MUST flush before releasing
    /// the shard write lock; readers hold only the read lock, so they never
    /// see pending keys. `pending` lives in the caller's scope, keeping the
    /// flush visually adjacent to the loop that fills it.
    pub(crate) fn update_index_entry_deferred(
        &mut self,
        key: String,
        new_pointer: Option<Pointer>,
        pending: &mut Vec<String>,
    ) {
        self.apply_pointer(&key, new_pointer.as_ref());
        // Only keys whose view membership actually changes go to pending;
        // pure pointer-type swaps (Inlined -> Segment etc.) and ghost deletes
        // keep their O(log n) no-op. Membership == presence in the view.
        let in_view = self.sorted_keys.binary_search(&key).is_ok();
        let new_is_live = matches!(new_pointer, Some(ref p) if !matches!(p, Pointer::Deleted { .. }));
        if new_is_live != in_view {
            pending.push(key);
        }
    }

    /// Resolve the keys collected by [`Self::update_index_entry_deferred`]
    /// into the sorted view. Three strategies, cheapest first:
    /// tail-ascending keys append with zero memmove; small batches take the
    /// direct binary_search + insert path (one bounded memmove each, no
    /// allocation — identical to the immediate API); large mid-inserting
    /// batches get one two-pointer merge through a reused scratch buffer
    /// (O(n + m) per commit, not O(n·m)). `self.index` is the liveness
    /// source of truth, so keys put and deleted inside the same batch
    /// resolve correctly in one pass.
    pub(crate) fn flush_pending_sorted(&mut self, pending: &mut Vec<String>) {
        if pending.is_empty() { return; }
        pending.sort_unstable();
        pending.dedup();

        // Fast path: every pending key is live and sorts after the whole
        // view (min(pending) > max(view)) — plain extend, zero memmove.
        let tail_ok = self.sorted_keys.last().is_none_or(|last| {
            pending.first().is_some_and(|k| k.as_str() > last.as_str())
        });
        if tail_ok && pending.iter().all(|k| self.is_live(k)) {
            self.sorted_keys.append(pending);
            return;
        }

        // Small batches: the direct path per key. A full merge would
        // allocate a fresh (n+m)-capacity buffer, and past the malloc mmap
        // threshold that means page faults on every commit — far worse than
        // a bounded memmove. 32 direct inserts ≈ the old per-key cost, so
        // nothing regresses here.
        if pending.len() <= 32 {
            for k in pending.drain(..) {
                if self.is_live(&k) {
                    if let Err(pos) = self.sorted_keys.binary_search(&k) {
                        self.sorted_keys.insert(pos, k);
                    }
                } else if let Ok(pos) = self.sorted_keys.binary_search(&k) {
                    self.sorted_keys.remove(pos);
                }
            }
            return;
        }

        // Large batch: one merge pass through the ping-pong scratch buffer.
        // Old keys pass through; pending keys slot in if live, drop out if
        // dead. The previous view's buffer becomes the next scratch, so a
        // steady-state merge never allocates.
        let mut old = std::mem::take(&mut self.sorted_keys);
        let mut merged = std::mem::take(&mut self.sorted_scratch);
        merged.clear();
        let mut pi = 0usize;
        for k in old.drain(..) {
            while pi < pending.len() && pending[pi].as_str() < k.as_str() {
                if self.is_live(&pending[pi]) { merged.push(std::mem::take(&mut pending[pi])); }
                pi += 1;
            }
            if pi < pending.len() && pending[pi].as_str() == k.as_str() {
                if self.is_live(&k) { merged.push(k); }
                pi += 1;
            } else {
                merged.push(k);
            }
        }
        for p in pending.drain(pi..) {
            if self.is_live(&p) { merged.push(p); }
        }
        self.sorted_keys = merged;
        self.sorted_scratch = old;
    }

    fn is_live(&self, key: &str) -> bool {
        matches!(self.index.get(key), Some(p) if !matches!(p, Pointer::Deleted { .. }))
    }

    /// Returns a half-half-open range `[start_pos, end_pos)` over the sorted key list,
    /// or `None` if the start key isn't found. The caller can then slice
    /// `self.sorted_keys[start_pos..end_pos]` and look up pointers via `self.index`.
    pub(crate) fn sorted_key_range(
        &self,
        start: Option<&str>,
        start_exclusive: bool,
        offset: Option<usize>,
        limit: Option<usize>,
    ) -> Option<(usize, usize)> {
        let total = self.sorted_keys.len();
        if total == 0 { return Some((0, 0)); }

        let start_pos = match start {
            // ponytail: mirror BTree range semantics — a missing anchor
            // starts at the next-greater key (insertion point), not empty.
            Some(s) => match self.sorted_keys.binary_search_by(|k| k.as_str().cmp(s)) {
                Ok(p) => p + (start_exclusive as usize) + offset.unwrap_or(0),
                Err(pos) => pos + offset.unwrap_or(0),
            },
            None => offset.unwrap_or(0),
        };
        let end_pos = match limit {
            Some(l) => (start_pos + l).min(total),
            None => total,
        };
        if start_pos >= total { return Some((total, total)); }
        Some((start_pos, end_pos))
    }

    /// Reverse mirror of [`Self::sorted_key_range`]: bounds for a descending
    /// walk over `sorted_keys` with an optional upper anchor. Returns the
    /// ascending slice `[s, e)` the executor walks with `.rev()`.
    /// `start_after(anchor)` = keys strictly below anchor;
    /// `start_at(anchor)` = keys at-or-below anchor; `None` = from the top.
    /// `offset` skips from the top, `limit` takes the next rows downward.
    pub(crate) fn sorted_key_range_reverse(
        &self,
        start: Option<&str>,
        start_exclusive: bool,
        offset: Option<usize>,
        limit: Option<usize>,
    ) -> Option<(usize, usize)> {
        let total = self.sorted_keys.len();
        if total == 0 { return Some((0, 0)); }

        let raw_end = match start {
            Some(s) => match self.sorted_keys.binary_search_by(|k| k.as_str().cmp(s)) {
                Ok(p) => p + (!start_exclusive as usize),
                Err(pos) => pos,
            },
            None => total,
        };
        let end = raw_end.saturating_sub(offset.unwrap_or(0));
        let s = match limit {
            Some(l) => end.saturating_sub(l),
            None => 0,
        };
        Some((s.min(end), end))
    }

    pub fn checkpoint_inlined_data(&mut self) -> Result<bool> {
        // Only trigger if we are over the limit
        if self.inlined_bytes < self.max_inlined_bytes {
            return Ok(false);
        }

        // 1. Gather all inlined documents
        let mut to_flush = Vec::new();
        for (key, pointer) in &self.index {
            if let Pointer::Inlined(data) = pointer {
                to_flush.push((key.clone(), (**data).clone()));
            }
        }

        if to_flush.is_empty() { return Ok(false); }

        // 2. Write to a new Segment (Level 0)
        let target_id = self.next_segment_id;
        self.next_segment_id += 1;
        let target_path = segment_path(&self.base_dir, 0, target_id);

        let mut target_segment = Segment::open(
            target_path, 
            target_id, 
            self.encryption.clone(), 
            Arc::clone(&self.cache), 
            self.mmap_size
        )?;

        // RENAME TO MATCH THE LOOP BELOW
        let mut new_pointers = HashMap::new();
        
        crate::storage::compaction::compact_segment(
            &mut target_segment, 
            &to_flush, 
            &mut new_pointers, 
            target_id,
            self.use_compression
        )?;
        
        target_segment.flush()?;

        // 3. Update the Index (Moves Pointer::Inlined -> Pointer::Segment)
        for (key, pointer) in new_pointers {
            self.update_index_entry(key, Some(pointer));
        }

        // 4. Register the new segment
        self.segments.insert(target_id, SegmentMeta {
            // id: target_id,
            level: 0,
            segment: target_segment,
        });

        // 5. Cleanup WAL (Remove the raw 'PutInlined' data from the log)
        self.rewrite_wal_snapshot()?;

        Ok(true)
    }

    /// Now this becomes Instant (O(1)) and accurate!
    pub fn list_collections(&self) -> Result<Vec<String>> {
        let mut cols: Vec<String> = self.collection_counts.keys().cloned().collect();
        cols.sort();
        Ok(cols)
    }

    pub fn apply_batch(
        &mut self, 
        mutations: &[StorageMutation], 
        is_remote: bool // Added to distinguish Local vs Sync
    ) -> Result<(Vec<BlobWork>, Vec<crate::storage::wal::WalOp>)> {
        let now = std::time::SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_micros() as i64;
        if mutations.is_empty() { return Ok((Vec::new(), Vec::new())); }

        let tx_id = self.next_tx_id;
        self.next_tx_id += 1;

        // Ensure we have space in the active segment
        self.maybe_rotate_active_segment()?;

        let mut wal_ops = Vec::with_capacity(mutations.len() + 2);
        wal_ops.push(WalOp::BeginTx { tx_id });

        let mut index_updates = Vec::new();
        let mut puts_to_segment = Vec::new();
        let mut segment_mutation_indices = Vec::new();
        let mut blob_work_todo = Vec::new();
        // let threshold = 

        // --- THE HOT LOOP: No Networking, No Cloning ---
        for (i, mutation) in mutations.iter().enumerate() {
            match mutation {
                StorageMutation::Put { key, value } => {
                    let len = value.len();
                    
                    
                    if len < 4096 { // Path 1: Tiny (Inline)
                        wal_ops.push(WalOp::PutInlined { key: key.clone(), value: value.clone() });
                        index_updates.push((key.clone(), Some(Pointer::Inlined(Arc::new(value.clone())))));
                    } else if len > self.blob_threshold { // Path 2: Large (Side-load to Blob File)
                        let arc_data = Arc::new(value.clone());
                        // FIX: Use Pointer::Inlined for raw byte batches
                        index_updates.push((key.clone(), Some(Pointer::Inlined(Arc::new(value.clone())))));
                        
                        blob_work_todo.push(BlobWork::Put {
                            collection: self.logical_name.clone(),
                            key: key.clone(),
                            data: arc_data,
                        });
                    } else { // Path 3: Medium (Standard Segment)
                        puts_to_segment.push(value.as_slice());
                        segment_mutation_indices.push(i);
                    }
                }
                StorageMutation::Delete { key } => {
                    wal_ops.push(WalOp::Delete { key: key.clone(), timestamp: now });
                    index_updates.push((key.clone(), Some(Pointer::Deleted { timestamp: now })));
                }
            }
        }

        // Write medium values to the active segment
        if !puts_to_segment.is_empty() {
            let active_id = self.active_segment_id;
            let active = self.segments.get_mut(&active_id).unwrap();
            let offsets = active.segment.append_batch(&puts_to_segment)?;

            for ((offset, len), mut_idx) in offsets.into_iter().zip(segment_mutation_indices) {
                if let StorageMutation::Put { key, .. } = &mutations[mut_idx] {
                    wal_ops.push(WalOp::Put { key: key.clone(), segment_id: active_id, segment_offset: offset, len });
                    index_updates.push((key.clone(), Some(Pointer::Segment { segment_id: active_id, offset, len })));
                }
            }
        }

        wal_ops.push(WalOp::CommitTx { tx_id });

        // --- THE DURABILITY STEP ---
        // Write to WAL with the 'is_remote' priority flag.
        self.wal.append_batch(&wal_ops, is_remote)?;

        // Update RAM Index
        // ponytail (#151): batched sorted-view maintenance — one merge per
        // commit instead of one O(n) Vec memmove per key. The flush below is
        // REQUIRED before this &mut self ends; readers never see pending keys.
        let mut pending_sorted = Vec::new();
        for (key, pointer) in index_updates {
            self.update_index_entry_deferred(key, pointer, &mut pending_sorted);
        }
        self.flush_pending_sorted(&mut pending_sorted);

        // RETURN: The blob work goes to the background thread. 
        // The replication work is handled by the Standalone Agent tailing the WAL.
        Ok((blob_work_todo, wal_ops))
    }

    /// Remove every live key of `collection` from RAM while keeping bytes on
    /// disk for compaction to reclaim. Returns the number of live keys removed.
    fn clear_collection_prefix(&mut self, _collection: &str) -> usize {
        // Storage shards are per collection and keys are bare doc ids, so a
        // collection clear means clearing this shard's whole live index.
        let mut removed = 0usize;
        let mut inlined_bytes = 0usize;
        for ptr in self.index.values() {
            if !matches!(ptr, Pointer::Deleted { .. }) {
                removed += 1;
                if let Pointer::Inlined(bytes) = ptr {
                    inlined_bytes += bytes.len();
                }
            }
        }
        self.index.clear();
        self.sorted_keys.clear();
        self.inlined_bytes = self.inlined_bytes.saturating_sub(inlined_bytes);
        if let Some(count) = self.collection_counts.get_mut(&self.logical_name) {
            *count = count.saturating_sub(removed);
        }
        removed
    }

    /// Collection-wide truncation: one WAL transaction, no per-document
    /// delete ops. Later compaction reclaims the orphaned bytes.
    pub fn clear_collection(&mut self, collection: &str) -> Result<usize> {
        let removed = self.index.values()
            .filter(|ptr| !matches!(ptr, Pointer::Deleted { .. }))
            .count();
        if removed == 0 {
            return Ok(0);
        }
        let tx_id = self.next_tx_id;
        self.next_tx_id += 1;
        let ops = [
            WalOp::BeginTx { tx_id },
            WalOp::ClearCollection { collection: collection.to_string() },
            WalOp::CommitTx { tx_id },
        ];
        self.wal.append_batch(&ops, false)?;
        self.clear_collection_prefix(collection);
        Ok(removed)
    }

    pub fn flush_all(&mut self) -> Result<()> {
        self.drain_blob_queue()?;
        if let Some(meta) = self.segments.get_mut(&self.active_segment_id) {
            meta.segment.flush()?;
        }
        self.wal.flush()?;
        Ok(())
    }

    pub fn drain_blob_queue(&mut self) -> Result<()> {
        let bm_handle = self.blob_manager.clone();
        let Some(bm) = bm_handle else { return Ok(()); };
        
        while let Some(work) = self.blob_flush_queue.pop_front() {
            // Note the addition of timestamp
            if let BlobWork::PutRaw { key, offset, data, skeleton, timestamp, .. } = work {
                // 1. Physical Write
                bm.write_at(data.as_slice(), offset)?;
                
                // 2. Atomic Swap with Timestamp Verification
                if !skeleton.is_empty() {
                    if let Some(Pointer::BlobPending(current_doc)) = self.index.get(&key) {
                        if current_doc.get_logical_time() == timestamp {
                            self.update_index_entry(key, Some(Pointer::Inlined(Arc::new(skeleton))));
                        }
                    }
                }
            }
        }
        bm.file().sync_all()?;
        Ok(())
    }

    /// `defer_heavy`: skip the segment spill while queries are in flight
    /// — the maintenance tick sheds it. Tier compaction left the &mut
    /// world entirely (see try_compact_tiers: merge I/O never holds a
    /// guard). WAL flush + segment rotation stay (cheap, and durability
    /// is never deferred). Bounded by the caller (max consecutive skips)
    /// so backlog drains under sustained load.
    pub fn run_background_maintenance(&mut self, defer_heavy: bool) -> Result<()> {
        // 2-c: Interval shards flush dirty buffers on the existing 500ms
        // system tick (off the request path) — closes the quiet-window where
        // a SIGKILL/power loss would take unflushed appends. Mode contracts
        // hold: Manual never auto-flushes, OnCommit flushes only at commit,
        // Always is already per-op. Idle shards = one is_empty check.
        // The predicate is interval-aware (not blind): a custom long window
        // must not degrade to tick cadence.
        if self.wal.should_tick_flush() {
            let _ = self.wal.flush();
        }
        self.maybe_rotate_active_segment()?;
        if defer_heavy {
            return Ok(());
        }
        // Check if RAM is full and spill to disk if needed.
        self.checkpoint_inlined_data()?;
        Ok(())
    }

    fn maybe_rotate_active_segment(&mut self) -> Result<()> {
        let size = self
            .segments
            .get_mut(&self.active_segment_id)
            .ok_or_else(|| HakoError::Corrupt("active segment missing".into()))?
            .segment
            .size_bytes()? as usize;

        if size < self.compaction_threshold_bytes.max(1024 * 1024) {
            return Ok(());
        }

        let new_id = self.next_segment_id;
        self.next_segment_id += 1;
        let path = segment_path(&self.base_dir, 0, new_id);
        // let encryption = self.encryption.clone();
        // FIX: Add missing 3 arguments
        let segment = Segment::open(
            path, 
            new_id, 
            self.encryption.clone(), 
            Arc::clone(&self.cache), 
            self.mmap_size
        )?;
        self.segments.insert(
            new_id,
            SegmentMeta {
                // id: new_id,
                level: 0,
                segment,
            },
        );
        self.active_segment_id = new_id;
        Ok(())
    }

    /// Narrow-lock tier compaction: reserve+collect (brief write) →
    /// merge (NO lock: segment reads, new-file writes) → commit (brief
    /// write: verify-then-swap + WAL rewrite/flush; old files closed and
    /// deleted only AFTER the guard drops). The tick calls this without
    /// holding any guard, so merge I/O never queues queries.
    ///
    /// Commit race rule: only entries whose live pointer still addresses
    /// a merged segment are swapped. Puts/deletes that landed mid-merge
    /// moved the pointer (or tombstoned it) — those keys are skipped:
    /// their bytes live elsewhere now, and the merged copy is dead space
    /// until this segment itself compacts (standard LSM behavior,
    /// bounded). Sources that vanished (a concurrent full `compact` ate
    /// them) abort the merge and delete the orphan target file.
    pub fn try_compact_tiers(shard: &Arc<RwLock<StorageEngine>>) -> Result<bool> {
        struct Prep {
            level: u32,
            s1: u64,
            s2: u64,
            target_level: u32,
            target_id: u64,
            base_dir: PathBuf,
            encryption: Option<EncryptionContext>,
            cache: Arc<Mutex<PageCache>>,
            mmap_size: usize,
            use_compression: bool,
        }
        // -- Phase 1: candidate + id reservation (brief write, metadata).
        let prep = {
            let mut storage = shard
                .write()
                .map_err(|_| HakoError::LockPoisoned("compact-prep".into()))?;
            let mut by_level: HashMap<u32, Vec<u64>> = HashMap::new();
            for (id, meta) in &storage.segments {
                if *id == storage.active_segment_id {
                    continue;
                }
                by_level.entry(meta.level).or_default().push(*id);
            }
            let mut candidate: Option<(u32, u64, u64)> = None;
            for (level, ids) in by_level {
                if ids.len() >= 2 {
                    candidate = Some((level, ids[0], ids[1]));
                    break;
                }
            }
            let Some((level, s1, s2)) = candidate else {
                return Ok(false);
            };
            let target_id = storage.next_segment_id;
            storage.next_segment_id += 1;
            Prep {
                level,
                s1,
                s2,
                target_level: level + 1,
                target_id,
                base_dir: storage.base_dir.clone(),
                encryption: storage.encryption.clone(),
                cache: Arc::clone(&storage.cache),
                mmap_size: storage.mmap_size,
                use_compression: storage.use_compression,
            }
        };
        // -- Phase 2: collect + merge with NO lock held.
        let entries: Vec<(String, Vec<u8>)> = {
            let storage = shard
                .read()
                .map_err(|_| HakoError::LockPoisoned("compact-collect".into()))?;
            let mut out = Vec::new();
            for (key, pointer) in &storage.index {
                if let Pointer::Segment { segment_id, .. } = pointer {
                    if *segment_id == prep.s1 || *segment_id == prep.s2 {
                        if let Some(value) = storage.read_pointer(pointer)? {
                            out.push((key.clone(), value));
                        }
                    }
                }
            }
            out
        };
        let target_path = segment_path(&prep.base_dir, prep.target_level, prep.target_id);
        let mut target = Segment::open(
            target_path.clone(),
            prep.target_id,
            prep.encryption,
            prep.cache,
            prep.mmap_size,
        )?;
        let mut new_index_subset = HashMap::new();
        if let Err(e) = compact_segment(
            &mut target,
            &entries,
            &mut new_index_subset,
            prep.target_id,
            prep.use_compression,
        ) {
            drop(target);
            let _ = std::fs::remove_file(&target_path);
            return Err(e);
        }
        // -- Phase 3: commit (brief write). Verify-then-swap per key.
        let mut target_opt = Some(target);
        let olds: Option<Vec<SegmentMeta>> = {
            let mut storage = shard
                .write()
                .map_err(|_| HakoError::LockPoisoned("compact-commit".into()))?;
            let sources_ok = [prep.s1, prep.s2].iter().all(|id| {
                matches!(storage.segments.get(id), Some(m) if m.level == prep.level)
            });
            if !sources_ok {
                None
            } else {
                let mut olds = Vec::with_capacity(2);
                for id in [prep.s1, prep.s2] {
                    if let Some(meta) = storage.segments.remove(&id) {
                        olds.push(meta);
                    }
                }
                for (k, p) in new_index_subset {
                    let still_merged = matches!(
                        storage.index.get(&k),
                        Some(Pointer::Segment { segment_id, .. })
                            if *segment_id == prep.s1 || *segment_id == prep.s2
                    );
                    if still_merged {
                        storage.index.insert(k, p);
                    }
                }
                storage.segments.insert(
                    prep.target_id,
                    SegmentMeta {
                        level: prep.target_level,
                        segment: target_opt.take().expect("merge target"),
                    },
                );
                storage.rewrite_wal_snapshot()?;
                // Same staged-without-flush hazard as before: sync now
                // (one fdatasync per compaction, not per write).
                storage.wal.flush()?;
                Some(olds)
            }
        };
        match olds {
            Some(olds) => {
                // File teardown outside any guard (close/remove can block
                // on some platforms — never hold a lock across it).
                for mut meta in olds {
                    let path = meta.segment.path().to_path_buf();
                    meta.segment.close();
                    let _ = std::fs::remove_file(path);
                }
                TIER_COMPACTIONS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
                Ok(true)
            }
            None => {
                drop(target_opt);
                let _ = std::fs::remove_file(&target_path);
                Ok(false)
            }
        }
    }

    pub(crate) fn rewrite_wal_snapshot(&mut self) -> Result<()> {
        self.wal.reset()?;
        let mut ops = Vec::with_capacity(self.index.len());
        for (key, pointer) in &self.index {
            match pointer {
                Pointer::Segment { segment_id, offset, len } => {
                    ops.push(WalOp::Put {
                        key: key.clone(),
                        segment_id: *segment_id,
                        segment_offset: *offset,
                        len: *len,
                    });
                }
                Pointer::Inlined(value) => {
                    ops.push(WalOp::PutInlined {
                        key: key.clone(),
                        value: (**value).clone(),
                    });
                }
                // v0.8.0 Recovery variants
                Pointer::Blob { offset, len } => {
                    ops.push(WalOp::PutBlob { key: key.clone(), offset: *offset, len: *len });
                }
                Pointer::BlobPending(pending_doc) => {
                    // pending_doc is Arc<HakoDoc>
                    let mut skeleton = (**pending_doc).clone();
                    if let Some(bm) = &self.blob_manager {
                        bm.extract_blobs_placeholder(&self.logical_name, &mut skeleton, self.blob_threshold);
                    }
                    ops.push(WalOp::PutInlined { key: key.clone(), value: skeleton.encode() });
                }
                Pointer::BlobPendingData { skeleton, .. } => {
                    // Transform worker finished. We already have the skeleton bytes.
                    ops.push(WalOp::PutInlined { key: key.clone(), value: skeleton.clone() });
                }
                Pointer::Deleted { timestamp } => {
                    ops.push(WalOp::Delete { key: key.clone(), timestamp: *timestamp });
                }
            }
        }
        self.wal.append_batch(&ops, false)?;
        Ok(())
    }


    pub(crate) fn read_pointer_internal(&self, pointer: &Pointer, use_cache: bool) -> Result<Option<Vec<u8>>> {
        match pointer {
            // PENDING: Serve directly from the Arc in memory (Fastest)
            Pointer::BlobPending(doc) => Ok(Some(doc.encode())),
            
            // Standard small documents stored directly in RAM.
            // ponytail: shared buffer — the query fast paths decode straight
            // from the Arc (no clone); this owned copy remains for callers
            // that must own their bytes (disk-spill paths, FFI snapshots).
            Pointer::Inlined(data) => Ok(Some((**data).clone())),
            
            // FINAL DISK STATE: Standard File/Mmap Read
            Pointer::Blob { offset, len } => {
                let bm = self.blob_manager.as_ref().unwrap();
                Ok(Some(bm.read_at(*offset, *len)?))
            },
            
            // PENDING REFINERY: Handle the intermediate state if used
            Pointer::BlobPendingData { data, .. } => Ok(Some((**data).clone())),

            // STANDARD SEGMENT DATA: (Handles its own compression/encryption)
            Pointer::Segment { segment_id, offset, len } => {
                let Some(meta) = self.segments.get(segment_id) else { return Ok(None); };
                Ok(Some(meta.segment.read_at(*offset, *len, use_cache)?))
            },

            Pointer::Deleted { .. } => Ok(None),
        }
    }


    // UPDATED: Use the internal helper to avoid E0004
    pub fn read_pointer(&self, pointer: &Pointer) -> Result<Option<Vec<u8>>> {
        self.read_pointer_internal(pointer, true)
    }

    /// Shared-bytes read: `Inlined` / `BlobPendingData` hand back the live
    /// Arc (zero copies); every other variant does one owned read wrapped
    /// in an Arc. Backs raw scans — bytes are opaque storage encoding.
    pub(crate) fn read_pointer_shared(&self, pointer: &Pointer) -> Result<Option<Arc<Vec<u8>>>> {
        match pointer {
            Pointer::Inlined(shared) => Ok(Some(Arc::clone(shared))),
            Pointer::BlobPendingData { data, .. } => Ok(Some(Arc::clone(data))),
            Pointer::BlobPending(doc) => Ok(Some(Arc::new(doc.encode()))),
            Pointer::Deleted { .. } => Ok(None),
            other => Ok(self.read_pointer_internal(other, true)?.map(Arc::new)),
        }
    }

    // UPDATED: Use the internal helper to avoid E0004
    pub fn read_pointer_uncached(&self, pointer: &Pointer) -> Result<Option<Vec<u8>>> {
        self.read_pointer_internal(pointer, false)
    }

    // UPDATED: Use the internal helper to avoid E0004
    pub fn read_pointer_uncached_by_key(&self, key: &str) -> Result<Option<Vec<u8>>> {
        let Some(pointer) = self.index.get(key) else { return Ok(None); }; 
        self.read_pointer_internal(pointer, false)
    }

    pub fn flush_wal(&mut self) -> Result<()> {
        self.wal.flush()
    }

    pub fn put(&mut self, key: String, value: &[u8]) -> Result<()> {
        let mutation = StorageMutation::Put {
            key,
            value: value.to_vec(),
        };

        // self.apply_batch(&[mutation])
        // let work = self.apply_batch(&[mutation])?;
        let (work, _committed_ops) = self.apply_batch(&[mutation], false)?;

        // 2. Since this is a synchronous put, we send the work here
        for w in work {
            if let Some(tx) = &self.blob_tx {
                let _ = tx.send(w);
            }
        }

        Ok(())
    }

    pub fn get(&self, key: &str) -> Result<Option<Vec<u8>>> {
        match self.index.get(key) {
            Some(Pointer::Deleted { .. }) => Ok(None), // Treat as non-existent
            Some(pointer) => self.read_pointer_internal(pointer, true),
            None => Ok(None),
        }
    }

    /// Shared-bytes point read: same lookup as [`Self::get`] but hands back
    /// the resident Arc (zero copies for inlined) instead of an owned Vec.
    /// Backs `DocView` point reads.
    pub(crate) fn get_shared(&self, key: &str) -> Result<Option<Arc<Vec<u8>>>> {
        match self.index.get(key) {
            Some(Pointer::Deleted { .. }) => Ok(None),
            Some(pointer) => self.read_pointer_shared(pointer),
            None => Ok(None),
        }
    }

    pub fn delete(&mut self, key: &str) -> Result<()> {
        let mutation = StorageMutation::Delete {
            key: key.to_string(),
        };

        // 1. Capture the work
        let (work, _committed_ops) = self.apply_batch(&[mutation], false)?;

        // 2. Send to background worker
        for w in work {
            if let Some(tx) = &self.blob_tx {
                let _ = tx.send(w);
            }
        }

        Ok(())
    }

    pub fn count_prefix(&self, prefix: &str) -> usize {
        if prefix.is_empty() || prefix == self.logical_name {
            // ponytail: O(1) live count (maintained by update_index_entry,
            // seeded at open). Absent entry falls back to the scan rather
            // than lying — correctness over speed, always.
            if let Some(n) = self.collection_counts.get(&self.logical_name) {
                return *n;
            }
            return self.index.values()
                .filter(|p| !matches!(p, Pointer::Deleted { .. }))
                .count();
        }
        // Fallback for sub-collection support if needed
        self.index.iter()
            .filter(|(k, p)| k.starts_with(prefix) && !matches!(p, Pointer::Deleted { .. }))
            .count()
    }

    pub fn scan_prefix(&self, prefix: &str) -> Result<Vec<(String, Vec<u8>)>> {
        let mut out = Vec::new();

        for (key, pointer) in &self.index {
            // Skip deleted and filter by prefix if one is provided
            if matches!(pointer, Pointer::Deleted { .. }) { continue; }
            if !prefix.is_empty() && !key.starts_with(prefix) { continue; }

            if let Some(value) = self.read_pointer(pointer)? {
                out.push((key.clone(), value));
            }
        }

        Ok(out)
    }

    /// WAL-bloat check: true when the log file holds mostly stale history
    /// and a snapshot rewrite would actually reclaim. Heuristic, not exact:
    /// past the compaction threshold AND over ~3x live inlined bytes.
    /// Tombstones count as zero live, so a dead-only WAL always qualifies
    /// once past the threshold. `inlined_bytes` is maintained on every index
    /// write, so this is O(1) — safe on open and on every manual compact.
    /// 2-b: measures REAL record bytes (Wal::data_len), never the sparse
    /// file length — the 4-8MB zero reservation used to qualify tiny
    /// collections and fire rewrites that (pre-2-a) wiped them on SIGTERM.
    pub(crate) fn wal_snapshot_worthwhile(&self) -> bool {
        let data_len = self.wal.data_len();
        data_len > self.compaction_threshold_bytes as u64
            && data_len > (self.inlined_bytes as u64).saturating_mul(3)
    }

    pub fn compact(&mut self) -> Result<()> {
        self.compact_with_cancel(None)
    }

    pub(crate) fn compact_with_cancel(
        &mut self,
        cancel: Option<&CancelToken>,
    ) -> Result<()> {
        if let Some(token) = cancel {
            token.check()?;
        }
        // 1. FORCED ROTATION: Ensure current data is eligible for compaction
        if self.segments.get(&self.active_segment_id)
            .is_some_and(|m| m.segment.size_bytes().unwrap_or(0) > 0)
        {
            let new_id = self.next_segment_id;
            self.next_segment_id += 1;
            let path = segment_path(&self.base_dir, 0, new_id);
            // let segment = Segment::open(path, self.encryption.clone())?;
            // FIX: Add missing 3 arguments
            let segment = Segment::open(
                path, 
                new_id, 
                self.encryption.clone(), 
                Arc::clone(&self.cache), 
                self.mmap_size
            )?;
            self.segments.insert(
                new_id, 
                SegmentMeta { 
                    // id: new_id, 
                    level: 0, 
                    segment 
                });
            self.active_segment_id = new_id;
        }

        if let Some(token) = cancel {
            token.check()?;
        }

        let immutable_ids: Vec<u64> = self.segments.keys()
            .filter(|&&id| id != self.active_segment_id)
            .cloned().collect();

        // ponytail: no segments to merge, but a hot-small collection can
        // still hold megabytes of stale WAL history (nothing ever spills).
        // Rewrite the snapshot when bloat dominates; otherwise a no-op.
        if immutable_ids.is_empty() {
            if self.wal_snapshot_worthwhile() {
                self.rewrite_wal_snapshot()?;
            }
            return Ok(());
        }

        // 2. GLOBAL MERGE: Collect ALL data from ALL immutable segments
        let mut entries = Vec::new();
        for (key, pointer) in &self.index {
            if let Some(token) = cancel {
                token.check()?;
            }
            if let Pointer::Segment { segment_id, .. } = pointer {
                if immutable_ids.contains(segment_id) {
                    if let Some(value) = self.read_pointer(pointer)? {
                        entries.push((key.clone(), value));
                    }
                }
            }
        }

        // 3. Write to ONE highly-optimized, compressed segment
        if let Some(token) = cancel {
            token.check()?;
        }
        let target_id = self.next_segment_id;
        self.next_segment_id += 1;
        let target_path = segment_path(&self.base_dir, 1, target_id);
        // let mut target = Segment::open(target_path, self.encryption.clone())?;
        // FIX: Add missing 3 arguments
        let mut target = Segment::open(
            target_path, 
            target_id, 
            self.encryption.clone(), 
            Arc::clone(&self.cache), 
            self.mmap_size
        )?;
        let mut rebuilt_index_subset = HashMap::new();

        compact_segment(&mut target, &entries, &mut rebuilt_index_subset, target_id, self.use_compression)?;

        // Cancelled before the swap: drop the half-built target and keep
        // every original segment exactly as it was.
        if let Some(token) = cancel {
            if token.is_cancelled() {
                let path = target.path().to_path_buf();
                target.close();
                let _ = std::fs::remove_file(path);
                return Err(HakoError::Cancelled);
            }
        }

        // 4. Atomic Swap
        for id in &immutable_ids {
            if let Some(mut meta) = self.segments.remove(id) {
                let path = meta.segment.path().to_path_buf();
                meta.segment.close();
                let _ = std::fs::remove_file(path);
            }
        }

        self.segments.insert(
            target_id, 
            SegmentMeta { 
                level: 1, 
                segment: target 
            });
        for (k, p) in rebuilt_index_subset { self.index.insert(k, p); }
        
        self.rewrite_wal_snapshot()?;
        Ok(())
    }

    pub fn set_durability_mode(&mut self, mode: DurabilityMode) { self.wal.set_durability_mode(mode); }

    /// Live group-commit window (clamped inside the WAL call, same as open).
    pub fn set_group_commit_interval_ms(&mut self, ms: u64) { self.wal.set_group_commit_interval(ms); }

    pub fn set_commit_trigger_mode(&mut self, mode: crate::config::CommitTriggerMode) {
        self.wal.set_commit_trigger_mode(mode);
    }

    pub fn base_dir(&self) -> &Path { &self.base_dir }

    /// Count of registered segment files (issue #32 stats surface).
    pub fn segment_count(&self) -> u32 {
        self.segments.len() as u32
    }

    pub fn backup(&mut self, destination_path: impl AsRef<Path>) -> Result<()> {
        // 1. Move all inlined data from RAM into segment files on Disk.
        // This ensures the backup is complete.
        self.checkpoint_inlined_data()?;
        
        // 2. Perform a physical sync of all files.
        self.flush_all()?;

        // 3. Create destination directory.
        std::fs::create_dir_all(destination_path.as_ref())?;

        // 4. Copy only relevant data and log files.
        for entry in std::fs::read_dir(&self.base_dir)? {
            let entry = entry?;
            let file_name = entry.file_name();
            let name_str = file_name.to_string_lossy();
            
            // We only back up data segments and the WAL.
            if name_str.ends_with(".dat") || name_str == "wal.log" {
                let dest = destination_path.as_ref().join(file_name);
                std::fs::copy(entry.path(), dest)?;
            }
        }
        Ok(())
    }

    /// Returns only the keys matching a prefix. 
    /// Extremely memory efficient because it doesn't touch the disk/mmap bodies.
    pub fn scan_prefix_keys(&self, prefix: &str) -> Vec<String> {
        self.index.iter()
            .filter(|(k, p)| {
                !matches!(p, Pointer::Deleted { .. }) && (prefix.is_empty() || k.starts_with(prefix))
            })
            .map(|(k, _)| k.clone())
            .collect()
    }

    pub fn scan_chunks<F>(&self, prefix: &str, chunk_size: usize, mut f: F) -> Result<()> 
    where F: FnMut(Vec<(String, Vec<u8>)>) -> Result<()> 
    {
        let keys = self.scan_prefix_keys(prefix);

        for chunk_keys in keys.chunks(chunk_size) {
            let mut chunk_data = Vec::with_capacity(chunk_keys.len());
            for key in chunk_keys {
                if let Some(ptr) = self.index.get(key) {
                    if let Some(val) = self.read_pointer(ptr)? {
                        chunk_data.push((key.clone(), val));
                    }
                }
            }
            f(chunk_data)?;
        }
        Ok(())
    }

    pub fn get_physical_index_snapshot(&self) -> Vec<(String, Pointer)> {
        self.index.iter()
            .map(|(k, p)| (k.clone(), p.clone()))
            .collect()
    }

    pub fn apply_replicated_ops(&mut self, ops: &[crate::storage::wal::WalOp]) -> Result<()> {
        self.wal.append_batch(ops, true)?;
        // ponytail (#151): batched sorted-view maintenance, flushed before
        // the exclusive borrow ends.
        let mut pending_sorted = Vec::new();
        for op in ops {
            if let WalOp::ClearCollection { collection } = op {
                self.clear_collection_prefix(collection);
                continue;
            }
            match op {
                // ponytail: route through update_index_entry (not direct
                // index.insert) so sorted_keys and the live-count cache stay
                // in lockstep — the old direct inserts skipped both.
                WalOp::Put { key, segment_id, segment_offset, len } => {
                    self.update_index_entry_deferred(key.clone(), Some(Pointer::Segment {
                        segment_id: *segment_id, offset: *segment_offset, len: *len
                    }), &mut pending_sorted);
                }
                WalOp::PutInlined { key, value } => {
                    self.update_index_entry_deferred(key.clone(), Some(Pointer::Inlined(Arc::new(value.clone()))), &mut pending_sorted);
                }
                WalOp::Delete { key, timestamp } => {
                    self.update_index_entry_deferred(key.clone(), Some(Pointer::Deleted { timestamp: *timestamp }), &mut pending_sorted);
                }
                WalOp::PutBlob { key, offset, len } => {
                    self.update_index_entry_deferred(key.clone(), Some(Pointer::Blob { offset: *offset, len: *len }), &mut pending_sorted);
                }
                _ => {}
            }
        }
        self.flush_pending_sorted(&mut pending_sorted);
        Ok(())
    }

    pub fn get_wal_checkpoint(&self) -> u64 {
        self.wal.file.metadata()
            .map(|m: std::fs::Metadata| m.len())
            .unwrap_or(0)
    }

    pub fn purge_old_tombstones(&mut self, max_age: std::time::Duration) {
        let now = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap().as_micros() as i64;
        let max_age_micros = max_age.as_micros() as i64;

        self.index.retain(|_, pointer| {
            if let Pointer::Deleted { timestamp } = pointer {
                // Keep if it's younger than the max age
                (now - *timestamp) < max_age_micros
            } else {
                true // Keep all real documents
            }
        });
    }

    /// #177 sweeper primitive: durable storage-level removal (WAL-first,
    /// then index drop) - mirrors the engine delete apply so a crash
    /// replays to the same end state.
    pub(crate) fn hard_delete_keys(&mut self, keys: &[String]) -> crate::error::Result<u64> {
        if keys.is_empty() {
            return Ok(0);
        }
        let tx_id = self.next_tx_id;
        self.next_tx_id += 1;
        let now = crate::util::clock::now_micros();
        let ops: Vec<WalOp> = keys
            .iter()
            .map(|k| WalOp::Delete { key: k.clone(), timestamp: now })
            .collect();
        self.wal.append_batch_fast(tx_id, &ops, false)?;
        for k in keys {
            self.index.remove(k);
        }
        Ok(keys.len() as u64)
    }

}

impl Drop for StorageEngine { fn drop(&mut self) { let _ = self.flush_all(); } }

fn segment_path(base: &Path, level: u32, id: u64) -> PathBuf { base.join(format!("segment-l{}-{}.dat", level, id)) }

fn parse_segment_name(name: &str) -> Option<(u32, u64)> {
    if !name.starts_with("segment-l") || !name.ends_with(".dat") {
        return None;
    }
    let core = &name[9..name.len() - 4];
    let (level, id) = core.split_once('-')?;
    Some((level.parse().ok()?, id.parse().ok()?))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::storage::wal::WalOp;

    fn tmp(label: &str) -> std::path::PathBuf {
        let nanos = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_nanos();
        std::env::temp_dir().join(format!("hako-eng-{label}-{nanos}-{}", std::process::id()))
    }

    fn cfg_for(mode: DurabilityMode) -> HakoConfig {
        HakoConfig {
            durability_mode: mode,
            wal_reserve_bytes: 0,
            auto_compaction_threshold_bytes: 1024,
            ..Default::default()
        }
    }

    /// 2-a: the open-time snapshot rewrite must hit disk, not just RAM.
    /// Builds stale history (10x overwrite, ~10KB WAL, 1KB live) so the
    /// rewrite fires on reopen, then asserts the file holds records
    /// immediately — pre-fix it was zeros until the next lucky append.
    #[test]
    fn open_rewrite_is_flushed() {
        let dir = tmp("rewrite");
        let big = vec![7u8; 1024];
        {
            let mut eng = StorageEngine::open(&dir, &cfg_for(DurabilityMode::Interval), "c".into(), None).unwrap();
            for _ in 0..10 {
                eng.put("k".into(), &big).unwrap();
            }
            // Drop flushes (Drop impl) — history lands, then reopen fires it.
        }
        let wal_path = dir.join("wal.log");
        assert!(std::fs::metadata(&wal_path).unwrap().len() > 4096, "history setup");
        {
            let eng = StorageEngine::open(&dir, &cfg_for(DurabilityMode::Interval), "c".into(), None).unwrap();
            // The rewrite fired on open (10KB history vs 1KB live) and
            // collapsed it: data_len is snapshot-sized, not history-sized.
            // Pre-fix the file was zeros here with data_len == 0 (staged).
            assert!(eng.wal.data_len() > 8, "snapshot flushed, data_len {}", eng.wal.data_len());
            assert!(eng.wal.data_len() < 4096, "history collapsed, data_len {}", eng.wal.data_len());
            assert_eq!(eng.get("k").unwrap().unwrap().len(), 1024, "live doc readable");
        }
        // No write happened after reopen: the file itself must hold records.
        let raw = std::fs::read(&wal_path).unwrap();
        assert!(raw.len() > 8, "snapshot flushed, not just staged");
        assert!(raw[0..8].iter().any(|&b| b != 0), "first header is a record, not zeros");
        let _ = std::fs::remove_dir_all(&dir);
    }

    /// #151: the batched sorted-view path must land the exact same view as
    /// the immediate path — out-of-order inserts, same-batch put+delete,
    /// updates of existing keys, and tail appends resolve in one flush.
    #[test]
    fn deferred_flush_merges_out_of_order_batch() {
        let dir = tmp("batchview");
        let mut eng = StorageEngine::open(&dir, &cfg_for(DurabilityMode::Interval), "c".into(), None).unwrap();

        let ops = vec![
            WalOp::PutInlined { key: "n_10".into(), value: vec![b'a'] },
            WalOp::PutInlined { key: "n_2".into(), value: vec![b'b'] },
            WalOp::PutInlined { key: "n_1".into(), value: vec![b'c'] },
            WalOp::PutInlined { key: "n_100".into(), value: vec![b'd'] },
            // put + delete of the same key inside one batch: pending must
            // resolve to absent, never a stray entry.
            WalOp::Delete { key: "n_2".into(), timestamp: 1 },
        ];
        eng.apply_replicated_ops(&ops).unwrap();
        let view: Vec<&str> = eng.sorted_keys.iter().map(|k| k.as_str()).collect();
        assert_eq!(view, vec!["n_1", "n_10", "n_100"], "one flush merged inserts + same-batch delete");
        for k in &eng.sorted_keys {
            assert!(eng.index.contains_key(k), "view key {:?} must be in index", k);
        }

        // Mixed second batch: update of an existing key (no duplicate), a
        // tail append (fast path), and a mid insert (merge path).
        let ops2 = vec![
            WalOp::PutInlined { key: "n_1".into(), value: vec![b'x'] },
            WalOp::PutInlined { key: "n_99".into(), value: vec![b'y'] },
            WalOp::PutInlined { key: "n_3".into(), value: vec![b'z'] },
        ];
        eng.apply_replicated_ops(&ops2).unwrap();
        let view2: Vec<&str> = eng.sorted_keys.iter().map(|k| k.as_str()).collect();
        assert_eq!(view2, vec!["n_1", "n_10", "n_100", "n_3", "n_99"], "mixed batch: update + tail + mid");
        assert_eq!(eng.get("n_1").unwrap().unwrap(), b"x", "updated bytes visible");

        // Merge path (pending > 32): 40 out-of-order keys in one batch must
        // land as one sorted, deduped view.
        let mut ops3: Vec<WalOp> = (0..40)
            .map(|i| WalOp::PutInlined { key: format!("m_{:03}", 39 - i), value: vec![b'v'] })
            .collect();
        // A duplicate within the same batch resolves to one entry.
        ops3.push(WalOp::PutInlined { key: "m_007".into(), value: vec![b'u'] });
        eng.apply_replicated_ops(&ops3).unwrap();
        let mut expected3: Vec<String> = (0..40).map(|i| format!("m_{:03}", i)).collect();
        expected3.sort();
        let view3: Vec<String> = eng.sorted_keys.iter().filter(|k| k.starts_with("m_")).cloned().collect();
        assert_eq!(view3, expected3, "large batch merges to one sorted deduped view");
        assert_eq!(eng.get("m_007").unwrap().unwrap(), b"u", "duplicate resolves to last write");
        let _ = std::fs::remove_dir_all(&dir);
    }

    /// 2-c: the maintenance tick flushes Interval buffers only.
    /// Manual never auto-flushes; OnCommit only at commit — both files
    /// must stay pristine while Interval lands.
    #[test]
    fn maintenance_flush_respects_mode() {
        for (mode, expect_bytes) in [
            (DurabilityMode::Interval, true),
            (DurabilityMode::Manual, false),
            (DurabilityMode::OnCommit, false),
        ] {
            let dir = tmp(&format!("maint-{mode:?}"));
            let mut eng = StorageEngine::open(&dir, &cfg_for(mode), "c".into(), None).unwrap();
            // One op, no commit marker, no thresholds: sits in the buffer.
            eng.wal
                .append(&WalOp::PutInlined { key: "k".into(), value: vec![1, 2, 3] }, false)
                .unwrap();
            // The tick predicate is time-aware (elapsed >= interval): sleep
            // past the 5ms test window so Interval is due. Monotonic clock
            // makes this one-directional (slowness only helps).
            std::thread::sleep(std::time::Duration::from_millis(10));
            eng.run_background_maintenance(false).unwrap();
            let len = std::fs::metadata(dir.join("wal.log")).unwrap().len();
            assert_eq!(len > 0, expect_bytes, "mode {mode:?}: file len {len}");
            let _ = std::fs::remove_dir_all(&dir);
        }
    }

    /// Configured interval gates flushing: a huge window holds appends in
    /// RAM (precondition for cluster fsync staggering — instances flush on
    /// their own cadence, not on every write).
    #[test]
    fn configured_interval_holds_and_releases() {
        let dir = tmp("interval");
        let mut cfg = HakoConfig {
            durability_mode: DurabilityMode::Interval,
            wal_reserve_bytes: 0,
            auto_compaction_threshold_bytes: 1024,
            group_commit_interval_ms: 30_000,
            ..Default::default()
        };
        // Clamp is honored at open (not just documented).
        cfg.group_commit_interval_ms = crate::config::clamp_group_commit_interval_ms(cfg.group_commit_interval_ms);
        let mut eng = StorageEngine::open(&dir, &cfg, "c".into(), None).unwrap();
        eng.put("k".into(), b"value-bytes").unwrap();
        assert!(eng.wal.has_pending(), "30s window must buffer, not flush");
        assert_eq!(eng.wal.data_len(), 0);
        eng.flush_all().unwrap();
        assert!(!eng.wal.has_pending());
        assert!(eng.wal.data_len() > 0, "explicit flush lands");
        let _ = std::fs::remove_dir_all(&dir);
    }

    /// Strict-time ignores the count trigger: 200 ops (> 128 legacy max)
    /// stay buffered inside a long window. This is the compromise that
    /// makes staggering work under burst (count-driven flushes would
    /// re-synchronize a balanced fleet).
    #[test]
    fn strict_time_ignores_count_trigger() {
        use crate::storage::wal::WalOp;

        let dir = tmp("strict-count");
        let cfg = HakoConfig {
            durability_mode: DurabilityMode::Interval,
            commit_trigger_mode: crate::config::CommitTriggerMode::StrictTime,
            wal_reserve_bytes: 0,
            auto_compaction_threshold_bytes: 1024,
            group_commit_interval_ms: 30_000,
            ..Default::default()
        };
        let mut eng = StorageEngine::open(&dir, &cfg, "c".into(), None).unwrap();
        let ops: Vec<WalOp> = (0..200)
            .map(|i| WalOp::PutInlined { key: format!("k{i}"), value: vec![i as u8; 16] })
            .collect();
        eng.wal.append_batch_fast(1, &ops, false).unwrap();
        assert!(eng.wal.has_pending(), "strict: 200 ops must NOT trip count flush");
        assert_eq!(eng.wal.data_len(), 0);
        let _ = std::fs::remove_dir_all(&dir);
    }

    fn copy_dir_shallow(src: &std::path::Path, dst: &std::path::Path) {
        std::fs::create_dir_all(dst).unwrap();
        for entry in std::fs::read_dir(src).unwrap().flatten() {
            let p = entry.path();
            if p.is_file() {
                std::fs::copy(&p, dst.join(entry.file_name())).unwrap();
            }
        }
    }

    fn any_nonzero_segment(dir: &std::path::Path) -> bool {
        std::fs::read_dir(dir)
            .unwrap()
            .flatten()
            .filter(|e| e.file_name().to_string_lossy().starts_with("segment-l0-"))
            .any(|e| e.metadata().unwrap().len() > 0)
    }

    /// Live-deployment diagnostic: small docs (< 4 KB) never touch segments —
    /// they live in WAL + RAM until per-shard inlined bytes exceed
    /// `max_inlined_memory_bytes`, at which point the maintenance checkpoint
    /// spills them into a new segment file. 0-byte segment files beside a
    /// fat WAL are therefore expected for small-doc rooms, not breakage.
    #[test]
    fn small_docs_spill_to_segment_at_inline_checkpoint() {
        use crate::storage::wal::WalOp;

        let dir = tmp("inline-spill");
        let doc = vec![5u8; 256];
        let mut cfg = cfg_for(DurabilityMode::Always);
        cfg.max_inlined_memory_bytes = 2048; // trip the checkpoint early
        cfg.value_blob_threshold_bytes = 8192; // keep this size on the inline path
        {
            let mut eng = StorageEngine::open(&dir, &cfg, "c".into(), None).unwrap();
            for i in 0..20 {
                eng.put(format!("k{i:03}"), &doc).unwrap();
            }
            assert!(
                eng.inlined_bytes > cfg.max_inlined_memory_bytes,
                "RAM inlined bytes must exceed the checkpoint trigger"
            );
            eng.run_background_maintenance(false).unwrap();
            assert!(
                any_nonzero_segment(&dir),
                "checkpoint must spill inlined docs into a segment file"
            );
            assert!(
                eng.get("k007").unwrap().is_some(),
                "doc must be reachable after spill"
            );
            assert!(eng.wal.data_len() > 0, "WAL still carries the ops");
            assert!(eng.wal.append_batch_fast(9, &[WalOp::CommitTx { tx_id: 9 }], false).is_ok(), "WAL stays writable after spill");
        }
        let eng2 = StorageEngine::open(&dir, &cfg_for(DurabilityMode::Always), "c".into(), None).unwrap();
        assert!(
            eng2.get("k007").unwrap().is_some(),
            "doc survives reopen after spill"
        );
        let _ = std::fs::remove_dir_all(&dir);
    }

    /// Medium docs (4 KB..blob_threshold) append to the active segment
    /// synchronously on the put path — this is the only segment-growing
    /// trigger besides the inline checkpoint.
    #[test]
    fn medium_docs_append_to_active_segment() {
        let dir = tmp("medium-seg");
        let doc = vec![1u8; 8192];
        let mut eng = StorageEngine::open(&dir, &cfg_for(DurabilityMode::Always), "c".into(), None).unwrap();
        eng.put("m-one".into(), &doc).unwrap();
        assert_eq!(
            eng.segments[&0].segment.current_size,
            4 + 8192,
            "segment tracks 4-byte length header + payload"
        );
        assert!(eng.get("m-one").unwrap().is_some(), "medium doc reads back through the segment pointer");
        eng.flush_all().unwrap();
        // Windows note: read_dir metadata can lag an unflushed append; assert
        // dir contents only after the segment is synced.
        assert!(any_nonzero_segment(&dir), "flush lands segment bytes on disk");
        let _ = std::fs::remove_dir_all(&dir);
    }

    /// Handshake fix for issue #70: a file copy taken while the writer is
    /// OPEN (the "manual backup of a running deployment" shape) must replay
    /// fully offline. Copied-once storage: the immediate query and the
    /// post-discovery query must both see the docs.
    #[test]
    fn copied_while_live_open_replays_offline() {
        let dir = tmp("copy-writer-live");
        let doc = vec![9u8; 512];
        {
            let mut eng = StorageEngine::open(&dir, &cfg_for(DurabilityMode::Always), "c".into(), None).unwrap();
            for i in 0..50 {
                eng.put(format!("src-{i:03}"), &doc).unwrap();
            }
            assert!(eng.wal.data_len() > 0, "Always flushes before the copy");
            copy_dir_shallow(&dir, &dir.with_extension("copy"));
        }
        let copy_dir = dir.with_extension("copy");
        let eng2 = StorageEngine::open(&copy_dir, &cfg_for(DurabilityMode::Always), "c".into(), None).unwrap();
        assert!(
            eng2.get("src-000").unwrap().is_some(),
            "first replayed doc must be visible immediately"
        );
        assert!(
            eng2.get("src-049").unwrap().is_some(),
            "last replayed doc must be visible immediately"
        );
        let _ = std::fs::remove_dir_all(&dir);
        let _ = std::fs::remove_dir_all(&copy_dir);
    }

    /// Loud empty-open diagnosis: the message fires exactly for the #70
    /// incident shape — zero live docs AND zero replayed ops while real
    /// record bytes or nonzero segments exist. Tombstone-emptied and
    /// fresh collections stay quiet.
    #[test]
    fn loud_open_diagnosis_fires_only_for_suspicious_states() {
        let msg = |live, ops, bytes, segs| {
            empty_open_diagnosis_message("c", live, ops, bytes, segs).is_some()
        };
        // Fresh dir: no bytes, no segments.
        assert!(!msg(0, 0, 0, 0), "fresh collection stays quiet");
        // Interval tail loss: copy lacks the in-memory part — nothing
        // on disk claims history, so no scream (data simply never landed).
        assert!(!msg(0, 0, 128, 0), "tiny pad-only WAL stays quiet");
        // Tombstone-emptied: replay extracted ops, live is 0. Legit.
        assert!(!msg(0, 12, 50_000, 3), "emptied-by-deletes stays quiet");
        // Live docs: healthy open never warns.
        assert!(!msg(7, 900, 900, 1));
        // The incident shape: parser extracted nothing, disk says megabytes.
        assert!(
            msg(0, 0, 7_230_007, 0),
            "real WAL bytes with zero replayed ops must scream"
        );
        // Segment-only copy (WAL lost / skipped): same scream.
        assert!(msg(0, 0, 0, 2));
        // And the message names the collection and the numbers.
        let text = empty_open_diagnosis_message("mhs", 0, 0, 103_698_999, 1).unwrap();
        assert!(text.contains("'mhs'") && text.contains("103698999"));
    }

    /// Arm 3 (deterministic): Interval durability + copy inside the quiet
    /// window — puts sit in the writer's RAM buffer, so the copy's WAL
    /// holds zero real bytes. The copy opens with ZERO docs and NO error:
    /// documented silent-loss shape. The loud-open diagnostic correctly
    /// does NOT fire here (disk never claimed the history), which is why
    /// Interval users must quiesce before copying.
    #[test]
    fn interval_quiet_window_copy_lacks_buffered_tail() {
        let dir = tmp("copy-interval-quiet");
        let mut cfg = cfg_for(DurabilityMode::Interval);
        // Pin both triggers off: no op-count flush, no time flush inside
        // the test window. Writes stay in the writer's RAM buffer.
        cfg.group_commit_max_ops = 1_000_000;
        cfg.group_commit_interval_ms = 60_000;
        let doc = vec![7u8; 512];
        {
            let mut eng = StorageEngine::open(&dir, &cfg, "c".into(), None).unwrap();
            for i in 0..50 {
                eng.put(format!("q-{i:03}"), &doc).unwrap();
            }
            assert!(eng.wal.has_pending(), "writes still buffered in RAM");
            assert_eq!(eng.wal.data_len(), 0, "nothing flushed inside the window");
            copy_dir_shallow(&dir, &dir.with_extension("copy"));
        }
        let copy_dir = dir.with_extension("copy");
        let eng2 = StorageEngine::open(&copy_dir, &cfg, "c".into(), None).unwrap();
        assert_eq!(eng2.wal.data_len(), 0, "copy WAL carries zero real bytes");
        assert!(
            eng2.get("q-000").unwrap().is_none(),
            "the buffered tail was never on disk: copy reads empty, no error"
        );
        assert_eq!(eng2.count_prefix("q"), 0, "documented zero state");
        let _ = std::fs::remove_dir_all(&dir);
        let _ = std::fs::remove_dir_all(&copy_dir);
    }
}