hakodb 0.21.10

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
use std::fs::{File, OpenOptions};
use std::io::{Read, Seek, SeekFrom, Write, BufReader};
use std::path::Path;
use std::time::{Duration, Instant};

use crate::config::DurabilityMode;
use crate::error::{HakoError, Result};

use super::crypto::EncryptionContext;

#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub enum WalOp {
    BeginTx {
        tx_id: u64,
    },
    Put {
        key: String,
        segment_id: u64,
        segment_offset: u64,
        len: u32,
    },
    Delete {
        key: String,
        timestamp: i64,
    },
    CommitTx {
        tx_id: u64,
    },
    PutInlined {
        key: String,
        value: Vec<u8>,
    },
    PutBlob {
        key: String,
        offset: u64,
        len: u32,
    },
}

pub struct Wal {
    pub(crate) file: File,
    /// Path, kept so tail() can open an independent read handle (see tail()).
    path: std::path::PathBuf,
    mode: DurabilityMode,
    group_commit_max_ops: usize,
    pending_ops_since_sync: usize,
    encryption: Option<EncryptionContext>,
    write_buffer: Vec<u8>,
    last_sync: Instant,
    group_commit_interval: Duration,
    /// Strict-time mode (custom interval): count/size triggers off, clock
    /// only (+ emergency cap). See HakoConfig docs for the rule.
    strict_interval: bool,
    reserve_bytes: u64,
    /// Real record bytes on disk (end-of-records), EXCLUDING the sparse
    /// preallocation reservation. File length lies (4-8MB of zeros);
    /// heuristics must use this or they fire on phantom size
    /// (insiden-hako-wal-20260928: open-time rewrite ratchet). Updated on
    /// replay/reset/flush; buffered-but-unflushed appends don't count
    /// (undercount = fewer rewrites = the safe direction).
    data_len: u64,
}

/// ponytail: every encoded op is >= 1 byte, so an all-zero 8-byte header can
/// only be unwritten preallocation padding (see open()). Readers treat it as
/// clean end-of-records: stop WITHOUT truncating (the reservation must
/// survive recovery) and WITHOUT erroring (tail() callers progress normally).
/// Emergency buffer cap for strict-time mode: memory bound, not latency.
/// Without it a sustained burst inside one long window grows RAM without
/// limit. Count/size triggers are OFF there by design; this is the only
/// non-clock flush left (besides explicit/Drop/rewrite flushes).
const STRICT_EMERGENCY_BYTES: usize = 16 * 1024 * 1024;

#[inline]
/// Validate WAL framing and CRC without replaying or repairing the file.
/// Used by offline restore to refuse truncated/corrupt backups before the
/// target directory is touched. Zero padding at the tail is accepted.
pub fn validate_file(path: &Path) -> Result<()> {
    let mut file = File::open(path)?;
    let total = file.metadata()?.len();
    let mut pos = 0u64;
    loop {
        if pos == total { return Ok(()); }
        if total - pos < 8 {
            return Err(HakoError::Corrupt(format!(
                "truncated WAL header in {}", path.display()
            )));
        }
        file.seek(SeekFrom::Start(pos))?;
        let mut header = [0u8; 8];
        file.read_exact(&mut header)?;
        if is_zero_header(&header) { return Ok(()); }
        let len = u32::from_le_bytes(header[0..4].try_into().unwrap()) as usize;
        let expected_crc = u32::from_le_bytes(header[4..8].try_into().unwrap());
        if len == 0 {
            return Err(HakoError::Corrupt(format!("empty WAL record in {}", path.display())));
        }
        if ((total - pos - 8) as usize) < len {
            return Err(HakoError::Corrupt(format!(
                "truncated WAL record in {}", path.display()
            )));
        }
        let mut payload = vec![0u8; len];
        file.read_exact(&mut payload)?;
        if crc32fast::hash(&payload) != expected_crc {
            return Err(HakoError::Corrupt(format!("WAL CRC mismatch in {}", path.display())));
        }
        pos += 8 + len as u64;
    }
}
fn is_zero_header(header: &[u8; 8]) -> bool {
    header.iter().all(|&b| b == 0)
}

/// Modes whose sync pattern benefits from WAL headroom: fsync happens per
/// commit, so avoiding file-growth metadata on the hot path pays off.
/// Interval (batched, rare syncs) and Manual (no mid-session sync) grow
/// the file with the data instead — no phantom size.
#[inline]
fn reserves_for_mode(mode: DurabilityMode) -> bool {
    matches!(
        mode,
        DurabilityMode::Always | DurabilityMode::OnCommit
    )
}

impl Wal {
    pub fn open(
        path: impl AsRef<Path>,
        mode: DurabilityMode,
        group_commit_max_ops: usize,
        encryption: Option<EncryptionContext>,
        reserve_bytes: u64,
    ) -> Result<Self> {
        let path_buf = path.as_ref().to_path_buf();
        let mut file = OpenOptions::new()
        .create(true)
        .truncate(false)
        .read(true)
        .write(true)
        .open(path)?;

        // ponytail: reserve headroom ONLY for fresh/tiny files (top-up to
        // one reserve, never stack). `end == len` always here, so the old
        // `len < end + reserve` condition was vacuously true and grew the
        // file by `reserve_bytes` on EVERY open — exact 4MB multiples per
        // launch in the wild (insiden-hako-wal-20261009: 14 collections x
        // ~21 launches = ~1GB of zero padding; NTFS allocates set_len
        // extensions as real clusters, so it cost real disk, not just
        // apparent size). Existing files already carry padding from their
        // first reservation; replay repositions the writer at end-of-real-
        // data so appends reuse it without extending the file. The zero
        // padding stays replay-safe: record headers are never all-zero
        // (every op encodes to >= 1 byte), so readers treat an all-zero
        // header as clean end-of-records (see replay()/tail()).
        let end = file.seek(SeekFrom::End(0))?;
        // Only Always/OnCommit reserve (see reserves_for_mode): the headroom
        // amortizes per-commit fsync metadata. Interval batches + rarely
        // syncs and Manual never syncs mid-session, so for them the file
        // grows with the data — reserving there only inflates apparent size.
        if reserves_for_mode(mode)
            && reserve_bytes > 0
            && file.metadata()?.len() < reserve_bytes
        {
            let _ = file.set_len(reserve_bytes);
        }
        file.seek(SeekFrom::Start(end))?;

        Ok(Self {
            file,
            path: path_buf,
            mode,
            group_commit_max_ops: group_commit_max_ops.max(1),
            pending_ops_since_sync: 0,
            encryption,
            write_buffer: Vec::with_capacity(1024 * 1024), // 1MB WAL buffer
            last_sync: Instant::now(),
            group_commit_interval: Duration::from_millis(5),
            strict_interval: false,
            reserve_bytes,
            // Unknown until the first replay/reset/flush recounts it;
            // heuristics must not run on file length meanwhile (see field).
            data_len: 0,
        })
    }

    pub fn append(&mut self, op: &WalOp, is_remote: bool) -> Result<()> {
        // 1. Remember where this specific record starts in the buffer
        let start_pos = self.write_buffer.len();

        // 2. Reserve 8 bytes for the Header (Length + CRC)
        self.write_buffer.extend_from_slice(&[0u8; 8]);

        // 3. ZERO-ALLOCATION ENCODING: Encode directly into the tail of the buffer
        // Note: We need a temporary buffer ONLY if encryption is enabled for the whole record
        if let Some(enc) = &self.encryption {
            let mut temp = Vec::with_capacity(128); // Small scratchpad
            encode_into(&mut temp, op);
            let ciphertext = enc.encrypt(&temp)?;
            self.write_buffer.extend_from_slice(&ciphertext);
        } else {
            encode_into(&mut self.write_buffer, op);
        }

        // 4. Calculate stats for THIS record
        let record_payload_end = self.write_buffer.len();
        let payload_len = (record_payload_end - (start_pos + 8)) as u32;
        let crc = crc32fast::hash(&self.write_buffer[start_pos + 8..record_payload_end]);

        // 5. Patch the header for this specific record in the buffer
        self.write_buffer[start_pos..start_pos + 4].copy_from_slice(&payload_len.to_le_bytes());
        self.write_buffer[start_pos + 4..start_pos + 8].copy_from_slice(&crc.to_le_bytes());

        self.pending_ops_since_sync += 1;

        // 6. DURABILITY CHECK: Decide if we should flush the buffer to disk
        let is_commit = matches!(op, WalOp::CommitTx { .. });
        self.maybe_sync(is_commit, is_remote)
    }

    pub fn append_raw(&mut self, op: &WalOp) -> Result<()> {
        // 1. Clear internal WAL buffer
        self.write_buffer.clear();
        
        // 2. Reserve header
        self.write_buffer.extend_from_slice(&[0u8; 8]);
        
        // 3. Encode Op metadata into buffer
        encode_into(&mut self.write_buffer, op);

        // 4. Calculate payload stats
        let payload_len = (self.write_buffer.len() - 8) as u32;
        let crc = crc32fast::hash(&self.write_buffer[8..]);

        // 5. Fill header (Write directly into the buffer)
        self.write_buffer[0..4].copy_from_slice(&payload_len.to_le_bytes());
        self.write_buffer[4..8].copy_from_slice(&crc.to_le_bytes());

        // 6. IO operation
        self.file.write_all(&self.write_buffer)?;
        
        if self.mode == DurabilityMode::Always {
            // ponytail: fdatasync, not fsync (restores pre-0.7 behavior).
            // POSIX requires fdatasync to persist whatever metadata is
            // needed to access the data (i.e. file size on growth), which is
            // all a WAL reader needs — mtime/atime lag is irrelevant, and
            // our preallocated size barely changes anyway. Same guarantee
            // SQLite/LMDB rely on; ~2-3x cheaper per commit on Linux.
            // (On Windows both map to FlushFileBuffers: no-op difference.)
            self.file.sync_data()?;
        }
        
        Ok(())
    }

    pub fn append_batch(&mut self, ops: &[WalOp], is_remote: bool) -> Result<()> {
        for op in ops {
            let start = self.write_buffer.len();
            self.write_buffer.extend_from_slice(&[0u8; 8]); // Header Space

            let mut temp_payload = Vec::new();
            encode_into(&mut temp_payload, op);

            let final_payload = if let Some(enc) = &self.encryption {
                enc.encrypt(&temp_payload)?
            } else {
                temp_payload
            };

            let crc = crc32fast::hash(&final_payload);
            let len = final_payload.len() as u32;

            self.write_buffer[start..start + 4].copy_from_slice(&len.to_le_bytes());
            self.write_buffer[start + 4..start + 8].copy_from_slice(&crc.to_le_bytes());
            self.write_buffer.extend_from_slice(&final_payload);
            
            self.pending_ops_since_sync += 1;
        }

        // --- NEW PERFORMANCE LOGIC ---
        let has_commit = ops.iter().any(|op| matches!(op, WalOp::CommitTx { .. }));
        
        // If this is remote sync data, we write to OS Page Cache but SKIP fsync.
        // This prevents the Manager's sync from slowing down the Cashier's disk.
        self.maybe_sync(has_commit, is_remote)
    }

    pub fn append_batch_fast(&mut self, tx_id: u64, ops: &[WalOp], is_remote: bool) -> Result<()> {
        // 1. Encode BeginTx
        self.append_to_buffer(&WalOp::BeginTx { tx_id });

        // 2. Encode all ops
        for op in ops {
            self.append_to_buffer(op);
        }

        // 3. Encode CommitTx
        self.append_to_buffer(&WalOp::CommitTx { tx_id });

        self.maybe_sync(true, is_remote)
    }

    fn append_to_buffer(&mut self, op: &WalOp) {
        let start = self.write_buffer.len();
        self.write_buffer.extend_from_slice(&[0u8; 8]); // Header

        // Encode directly into the buffer if not encrypted
        if let Some(enc) = &self.encryption {
            let mut temp = Vec::new(); // Fallback for encryption
            encode_into(&mut temp, op);
            let ciphertext = enc.encrypt(&temp).unwrap();
            self.write_buffer.extend_from_slice(&ciphertext);
        } else {
            encode_into(&mut self.write_buffer, op);
        }

        let payload_len = (self.write_buffer.len() - start - 8) as u32;
        let crc = crc32fast::hash(&self.write_buffer[start + 8..]);
        
        self.write_buffer[start..start+4].copy_from_slice(&payload_len.to_le_bytes());
        self.write_buffer[start+4..start+8].copy_from_slice(&crc.to_le_bytes());
        self.pending_ops_since_sync += 1;
    }

    pub fn flush(&mut self) -> Result<()> {
        if self.write_buffer.is_empty() {
            return Ok(());
        }

        // ONE Syscall to write multiple operations
        self.file.write_all(&self.write_buffer)?;

        // ponytail: fdatasync (see append() above for why). The torn-tail
        // crash window this theoretically widens is exactly what replay's
        // partial-record repair already handles.
        self.file.sync_data()?;

        // NOW we clear, after the data is safe on the platter
        self.write_buffer.clear();
        self.pending_ops_since_sync = 0;
        self.last_sync = Instant::now();
        // Cursor sits exactly at end-of-records after the write_all above.
        self.data_len = self.file.stream_position()?;
        Ok(())
    }

    fn maybe_sync(&mut self, is_commit: bool, is_remote: bool) -> Result<()> {
        if is_remote && self.mode != DurabilityMode::Always {
            // Write to OS buffer but skip the expensive physical disk flip (fsync)
            self.file.write_all(&self.write_buffer)?;
            self.write_buffer.clear();
            // data_len is the "real records" watermark tail() clamps against,
            // so it must track remote writes too even though we skipped fsync.
            self.data_len = self.file.stream_position()?;
            return Ok(());
        }

        let now = Instant::now();

        let should_flush = match self.mode {
            // Write and Sync every single time
            DurabilityMode::Always => true,

            // Pool operations, only write to disk when a transaction finishes
            DurabilityMode::OnCommit => is_commit,

            // The most performant mode: pool until time or volume threshold is hit.
            // Strict-time (custom interval): count/size triggers OFF — they
            // re-synchronize fleet flushes under balanced load, defeating
            // staggering. Clock only, plus the emergency buffer cap below.
            DurabilityMode::Interval if self.strict_interval => {
                is_commit && (
                    now.duration_since(self.last_sync) >= self.group_commit_interval
                    || self.write_buffer.len() > STRICT_EMERGENCY_BYTES
                )
            }

            // Legacy triple-trigger (default 5ms): benchmarks and gates
            // pin this behavior exactly; do not touch.
            DurabilityMode::Interval => {
                is_commit && (
                    self.pending_ops_since_sync >= self.group_commit_max_ops
                    || now.duration_since(self.last_sync) >= self.group_commit_interval
                    || self.write_buffer.len() > 124 * 1024 // Flush if buffer > 64KB
                )
            }

            DurabilityMode::Manual => false,
        };

        if should_flush {
            self.flush()?; // This writes the WHOLE buffer in one syscall and calls sync_all
        }
        Ok(())
    }

    pub fn replay_from_offset(&mut self, offset: u64) -> Result<Vec<WalOp>> {
        self.file.seek(SeekFrom::Start(offset))?;
        // ... (reuse existing replay logic)

        // 1. Move to start of file
        self.file.seek(SeekFrom::Start(0))?;
        
        // 2. Use BufReader to reduce syscalls during replay (Huge win for small records)
        let mut reader = BufReader::with_capacity(64 * 1024, &self.file);
        let mut raw_ops = Vec::new();
        let mut last_valid_pos = 0;
        
        // Scratchpad to avoid re-allocating memory for every record
        let mut payload_scratch = Vec::with_capacity(8192);
        let mut stopped_on_padding = false;

        loop {
            // A. Read Header (8 bytes: 4 for Len, 4 for CRC)
            let mut header = [0u8; 8];
            match reader.read_exact(&mut header) {
                Ok(_) => {}, // Successfully read exactly 8 bytes
                Err(e) if e.kind() == std::io::ErrorKind::UnexpectedEof => break,
                Err(e) => return Err(e.into()),
            }

            let len = u32::from_le_bytes(header[0..4].try_into().unwrap()) as usize;
            let expected_crc = u32::from_le_bytes(header[4..8].try_into().unwrap());

            // Preallocation padding (see open()): clean stop, keep reservation.
            if is_zero_header(&header) {
                stopped_on_padding = true;
                break;
            }

            // B. Read Payload into scratchpad
            payload_scratch.resize(len, 0);
            if let Err(e) = reader.read_exact(&mut payload_scratch) {
                // If we reach EOF here, it means the record was partially written during a crash
                if e.kind() == std::io::ErrorKind::UnexpectedEof { break; }
                return Err(e.into());
            }

            // C. Validate Integrity
            if crc32fast::hash(&payload_scratch) != expected_crc {
                // CRC Mismatch: Stop here. Data following this point is likely corrupt.
                // We don't return Err because we want to recover as much as possible.
                break;
            }

            // D. Handle Decryption
            let decoded_payload = if let Some(enc) = &self.encryption {
                enc.decrypt(&payload_scratch)?
            } else {
                // If no encryption, we borrow the scratchpad data
                payload_scratch.clone()
            };

            // E. Deserialize
            raw_ops.push(decode(&decoded_payload)?);
            
            // Increment the "Safe" position in the file
            last_valid_pos += (8 + len) as u64;
        }

        // 3. AUTO-REPAIR: If we stopped early due to corruption or partial write, 
        // truncate the file so future runs don't get stuck on the same bad data.
        // ponytail: never truncate preallocation padding — file length beyond
        // the last record is reservation, not junk (replay() below shares it).
        if last_valid_pos < self.file.metadata()?.len() && !stopped_on_padding {
            crate::util::log::info(&format!("WAL repair: truncating at {} bytes", last_valid_pos));
            self.file.set_len(last_valid_pos)?;
        }

        // 4. Seek so future appends continue exactly at end-of-records.
        // (NOT End(0): with preallocation those differ — see replay().)
        self.file.seek(SeekFrom::Start(last_valid_pos))?;
        self.data_len = last_valid_pos;

        // 5. Apply Transaction Logic (Only return ops from committed TXs)
        Ok(filter_committed_ops(raw_ops))
    }

    pub fn replay(&mut self) -> Result<Vec<WalOp>> {
        self.file.seek(SeekFrom::Start(0))?;
        let mut reader = BufReader::with_capacity(64 * 1024, &self.file);
        let mut raw_ops = Vec::new();
        let mut last_valid_pos = 0;
        let mut payload_scratch = Vec::with_capacity(8192);
        let mut stopped_on_padding = false;

        loop {
            let mut header = [0u8; 8];
            if reader.read_exact(&mut header).is_err() { break; }

            let len = u32::from_le_bytes(header[0..4].try_into().unwrap()) as usize;
            let expected_crc = u32::from_le_bytes(header[4..8].try_into().unwrap());

            // Preallocation padding (see open()): clean stop, keep reservation.
            if is_zero_header(&header) {
                stopped_on_padding = true;
                break;
            }

            if len == 0 { break; } 

            payload_scratch.resize(len, 0);
            if reader.read_exact(&mut payload_scratch).is_err() { 
                // Partial record at end of file - this is a candidate for truncation
                break; 
            }

            // PHYSICAL INTEGRITY CHECK
            if crc32fast::hash(&payload_scratch) != expected_crc {
                // Physical corruption detected. Stop and allow truncation.
                break; 
            }

            // DECRYPTION
            let decoded_payload = if let Some(enc) = &self.encryption {
                match enc.decrypt(&payload_scratch) {
                    Ok(p) => p,
                    Err(_) => {
                        // Decryption failed but CRC was correct! 
                        // This means the KEY is wrong. Do NOT truncate.
                        return Err(HakoError::Corrupt("Decryption failed. Wrong encryption key?".into()));
                    }
                }
            } else {
                payload_scratch.clone()
            };

            // LOGICAL DECODE
            match decode(&decoded_payload) {
                Ok(op) => {
                    raw_ops.push(op);
                    last_valid_pos += (8 + len) as u64;
                }
                Err(_) => {
                    // CRC was valid, but we can't read the data.
                    // If we are NOT in encryption mode, this might be encrypted data we're trying to read as plain.
                    if self.encryption.is_none() {
                        return Err(HakoError::Corrupt("Recognized valid data but failed to decode. Is this collection encrypted?".into()));
                    }
                    // Otherwise, this is a logical corruption, stop but don't truncate.
                    break;
                }
            }
        }

        // ONLY TRUNCATE if we actually hit a CRC failure or partial write.
        // If we stopped because of a logical Err above, we return before this line.
        // ponytail: never truncate preallocation padding (see open()).
        let current_file_len = self.file.metadata()?.len();
        if last_valid_pos < current_file_len && !stopped_on_padding {
            // Double check: if the next byte is valid, don't truncate, just error.
            // For now, let's just log it.
            crate::util::log::info(&format!("WAL repair: truncating {} bytes of tail junk", current_file_len - last_valid_pos));
            let _ = self.file.set_len(last_valid_pos);
        }

        // ponytail: resume exactly at end-of-records, NOT End(0) — with a
        // preallocated file those differ, and appending past the padding
        // would strand records replay can no longer reach.
        self.file.seek(SeekFrom::Start(last_valid_pos))?;
        self.data_len = last_valid_pos;
        Ok(filter_committed_ops(raw_ops))
    }

    pub fn reset(&mut self) -> Result<()> {
        // ponytail: clear the in-memory buffer too — otherwise the next
        // append_batch keeps the old WAL data in self.write_buffer and
        // flush() writes BOTH the historical ops and whatever was appended
        // after reset. Manual mode never flushes during a session, so the
        // buffer grows unbounded; on shutdown the rewrite_wal_snapshot
        // snapshot ends up double-written to disk.
        self.write_buffer.clear();
        self.file.set_len(0)?;
        // ponytail: re-reserve headroom after the wipe (see open()) —
        // metadata-only, so post-checkpoint appends don't regrow 1KB at a
        // time. Skipped unless the mode reserves (Interval/Manual files stay
        // exactly data-sized after compact/rewrite). Position stays at 0.
        if reserves_for_mode(self.mode) && self.reserve_bytes > 0 {
            let _ = self.file.set_len(self.reserve_bytes);
        }
        self.file.seek(SeekFrom::Start(0))?;
        self.pending_ops_since_sync = 0;
        self.data_len = 0;
        Ok(())
    }

    pub fn durability_mode(&self) -> DurabilityMode {
        self.mode
    }

    /// Real record bytes (see field): the honest input for size heuristics.
    pub fn data_len(&self) -> u64 {
        self.data_len
    }

    /// Physical file length (includes preallocated headroom): paired with
    /// data_len as the snapshot-staleness fingerprint. A WAL reset changes
    /// this even when record bytes coincide, so equal pairs mean untouched.
    pub fn file_len(&self) -> u64 {
        self.file.metadata().map(|m| m.len()).unwrap_or(0)
    }

    /// Buffered-but-unflushed bytes exist (the quiet-window at risk on SIGKILL).
    pub fn has_pending(&self) -> bool {
        !self.write_buffer.is_empty()
    }

    /// Maintenance-tick predicate (2-c): flush a dirty Interval buffer when
    /// its own configured window elapsed — NOT blindly every tick, or a
    /// custom (long) interval degrades to the 500ms tick cadence and fleet
    /// staggering breaks the same way count-triggers would.
    pub fn should_tick_flush(&self) -> bool {
        self.mode == DurabilityMode::Interval
            && self.has_pending()
            && Instant::now().duration_since(self.last_sync) >= self.group_commit_interval
    }

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

    /// Group-commit window (Interval mode). Applied from
    /// `HakoConfig::group_commit_interval_ms` at engine open (clamped).
    /// A non-default value also arms strict-time (see field docs).
    pub fn set_group_commit_interval(&mut self, ms: u64) {
        let ms = crate::config::clamp_group_commit_interval_ms(ms);
        self.group_commit_interval = Duration::from_millis(ms);
        self.strict_interval = ms != crate::config::DEFAULT_GROUP_COMMIT_INTERVAL_MS;
    }

    pub fn tail(&self, start_offset: u64) -> Result<(Vec<WalOp>, u64)> {
        // ponytail: fresh read handle per tail, never touch self.file's
        // cursor. try_clone shares the file position (DuplicateHandle/dup),
        // and even positional reads (pread/seek_read) advance the cursor on
        // some platforms — either way the next append would strand inside
        // preallocation padding where readers stop at the first zero header.
        // A separate open() is an independent description with its own
        // cursor, so tailing can never disturb concurrent appends.
        let file = File::open(&self.path)?;
        let file_len = file.metadata()?.len();

        // A reset/rewrite truncates the records but may leave preallocated
        // file_len; a tailer holding an offset from the old WAL would sit on
        // zero padding forever (callers only advance on non-empty ops).
        // Re-read the rebuilt WAL once instead. LWW + echo dedupe make the
        // replay safe; `>` keeps the normal caught-up case off the slow path.
        let start = if start_offset > self.data_len {
            0
        } else {
            start_offset
        };

        if start >= file_len {
            return Ok((vec![], file_len));
        }

        let mut reader = BufReader::new(file);
        let mut ops = Vec::new();
        let mut current_pos = start;
        // Skip to start on the fresh handle (its cursor is ours alone).
        reader.seek(SeekFrom::Start(start))?;

        loop {
            let mut header = [0u8; 8];
            if reader.read_exact(&mut header).is_err() {
                break;
            }

            let len = u32::from_le_bytes(header[0..4].try_into().unwrap()) as usize;
            let expected_crc = u32::from_le_bytes(header[4..8].try_into().unwrap());

            // Preallocation padding (see open()): clean end, not an error —
            // callers use the returned position to keep tailing.
            if is_zero_header(&header) {
                break;
            }

            let mut payload = vec![0u8; len];
            if reader.read_exact(&mut payload).is_err() {
                break;
            }

            if crc32fast::hash(&payload) == expected_crc {
                let decoded_payload = if let Some(enc) = &self.encryption {
                    enc.decrypt(&payload)?
                } else {
                    payload
                };
                ops.push(decode(&decoded_payload)?);
                current_pos += 8 + len as u64;
            } else {
                break; // Stop at corruption
            }
        }

        Ok((ops, current_pos))
    }
    
}

impl WalOp {
    /// Returns the document key associated with this operation.
    /// Returns an empty string for transaction markers (Begin/Commit).
    pub fn get_key(&self) -> &str {        match self {
            WalOp::Put { key, .. } => key,
            WalOp::Delete { key, .. } => key,
            WalOp::PutInlined { key, .. } => key,
            WalOp::PutBlob { key, .. } => key,
            WalOp::BeginTx { .. } | WalOp::CommitTx { .. } => "",
        }
    }
}

impl Drop for Wal {
    fn drop(&mut self) {
        // Final attempt to save data when the database handle is closed
        let _ = self.flush();
    }
}

fn filter_committed_ops(raw_ops: Vec<WalOp>) -> Vec<WalOp> {
    let mut output = Vec::new();
    let mut current_tx: Option<u64> = None;
    let mut tx_ops = Vec::new();

    for op in raw_ops {
        match op {
            WalOp::BeginTx { tx_id } => {
                current_tx = Some(tx_id);
                tx_ops.clear();
            }
            WalOp::CommitTx { tx_id } => {
                if current_tx == Some(tx_id) {
                    output.append(&mut tx_ops);
                }
                current_tx = None;
                tx_ops.clear();
            }
            WalOp::Put { .. } | WalOp::Delete { .. } | WalOp::PutInlined { .. } | WalOp::PutBlob { .. }  => {
                if current_tx.is_some() {
                    tx_ops.push(op);
                } else {
                    output.push(op);
                }
            }
        }
    }

    output
}

fn encode_into(buf: &mut Vec<u8>, op: &WalOp) {
    match op {
        WalOp::BeginTx { tx_id } => {
            buf.push(0);
            buf.extend_from_slice(&tx_id.to_le_bytes());
        }

        WalOp::Put {
            key,
            segment_id,
            segment_offset,
            len,
        } => {
            buf.push(1);

            buf.extend_from_slice(&(key.len() as u16).to_le_bytes());
            buf.extend_from_slice(key.as_bytes());

            buf.extend_from_slice(&segment_id.to_le_bytes());
            buf.extend_from_slice(&segment_offset.to_le_bytes());
            buf.extend_from_slice(&len.to_le_bytes());
        }

        WalOp::Delete { key, timestamp } => {
            buf.push(2);
            buf.extend_from_slice(&(key.len() as u16).to_le_bytes());
            buf.extend_from_slice(key.as_bytes());
            buf.extend_from_slice(&timestamp.to_le_bytes());
        }

        WalOp::CommitTx { tx_id } => {
            buf.push(3);
            buf.extend_from_slice(&tx_id.to_le_bytes());
        }

        WalOp::PutInlined { key, value } => {
            buf.push(4); // New Tag
            buf.extend_from_slice(&(key.len() as u16).to_le_bytes());
            buf.extend_from_slice(key.as_bytes());
            buf.extend_from_slice(&(value.len() as u32).to_le_bytes());
            buf.extend_from_slice(value);
        }

        WalOp::PutBlob { key, offset, len } => {
            buf.push(5);
            buf.extend_from_slice(&(key.len() as u16).to_le_bytes());
            buf.extend_from_slice(key.as_bytes());
            buf.extend_from_slice(&offset.to_le_bytes());
            buf.extend_from_slice(&len.to_le_bytes());
        }
    }
}

fn decode(payload: &[u8]) -> Result<WalOp> {
    let tag = *payload
        .first()
        .ok_or_else(|| HakoError::Corrupt("empty wal record".into()))?;
    let mut pos = 1;
    match tag {
        0 => {
            let tx_id = u64::from_le_bytes(
                payload[pos..pos + 8]
                    .try_into()
                    .map_err(|_| HakoError::Corrupt("bad begin tx id".into()))?,
            );
            Ok(WalOp::BeginTx { tx_id })
        }
        1 => {
            let key_len = u16::from_le_bytes(
                payload[pos..pos + 2]
                    .try_into()
                    .map_err(|_| HakoError::Corrupt("bad wal key len".into()))?,
            ) as usize;
            pos += 2;
            if pos + key_len > payload.len() {
                return Err(HakoError::Corrupt("wal put key overruns record".into()));
            }
            let key = String::from_utf8(payload[pos..pos + key_len].to_vec())
                .map_err(|_| HakoError::Corrupt("bad wal key".into()))?;
            pos += key_len;
            let segment_id = u64::from_le_bytes(
                payload[pos..pos + 8]
                    .try_into()
                    .map_err(|_| HakoError::Corrupt("bad wal segment id".into()))?,
            );
            pos += 8;
            let offset = u64::from_le_bytes(
                payload[pos..pos + 8]
                    .try_into()
                    .map_err(|_| HakoError::Corrupt("bad wal offset".into()))?,
            );
            pos += 8;
            let len = u32::from_le_bytes(
                payload[pos..pos + 4]
                    .try_into()
                    .map_err(|_| HakoError::Corrupt("bad wal len".into()))?,
            );
            Ok(WalOp::Put {
                key,
                segment_id,
                segment_offset: offset,
                len,
            })
        }
        2 => {
            let key_len = u16::from_le_bytes(
                payload[pos..pos + 2]
                    .try_into()
                    .map_err(|_| HakoError::Corrupt("bad wal key len".into()))?,
            ) as usize;
            pos += 2;
            if pos + key_len > payload.len() {
                return Err(HakoError::Corrupt("wal delete key overruns record".into()));
            }
            let key = String::from_utf8(payload[pos..pos + key_len].to_vec())
                .map_err(|_| HakoError::Corrupt("bad wal key".into()))?;
            pos += key_len;
            // FIX: was reading timestamp from key bytes (missing pos += key_len);
            // would silently misread timestamps for any key >= 8 bytes.
            let timestamp = i64::from_le_bytes(
                payload[pos..pos + 8]
                    .try_into()
                    .map_err(|_| HakoError::Corrupt("bad wal delete timestamp".into()))?,
            );
            Ok(WalOp::Delete { key, timestamp })
        }
        3 => {
            let tx_id = u64::from_le_bytes(
                payload[pos..pos + 8]
                    .try_into()
                    .map_err(|_| HakoError::Corrupt("bad commit tx id".into()))?,
            );
            Ok(WalOp::CommitTx { tx_id })
        }
        4 => {
            let key_len = u16::from_le_bytes(
                payload[pos..pos + 2]
                    .try_into()
                    .map_err(|_| HakoError::Corrupt("bad wal key len".into()))?,
            ) as usize;
            pos += 2;
            if pos + key_len > payload.len() {
                return Err(HakoError::Corrupt("wal putinlined key overruns record".into()));
            }
            let key = String::from_utf8(payload[pos..pos + key_len].to_vec())
                .map_err(|_| HakoError::Corrupt("bad key".into()))?;
            pos += key_len;
            let val_len = u32::from_le_bytes(
                payload[pos..pos + 4]
                    .try_into()
                    .map_err(|_| HakoError::Corrupt("bad wal putinlined val len".into()))?,
            ) as usize;
            pos += 4;
            if pos + val_len > payload.len() {
                return Err(HakoError::Corrupt("wal putinlined val overruns record".into()));
            }
            let value = payload[pos..pos + val_len].to_vec();
            Ok(WalOp::PutInlined { key, value })
        }
        5 => {
            let key_len = u16::from_le_bytes(
                payload[pos..pos + 2]
                    .try_into()
                    .map_err(|_| HakoError::Corrupt("bad wal key len".into()))?,
            ) as usize;
            pos += 2;
            if pos + key_len > payload.len() {
                return Err(HakoError::Corrupt("wal putblob key overruns record".into()));
            }
            let key = String::from_utf8(payload[pos..pos + key_len].to_vec())
                .map_err(|_| HakoError::Corrupt("bad key".into()))?;
            pos += key_len;
            let offset = u64::from_le_bytes(
                payload[pos..pos + 8]
                    .try_into()
                    .map_err(|_| HakoError::Corrupt("bad wal putblob offset".into()))?,
            );
            pos += 8;
            let len = u32::from_le_bytes(
                payload[pos..pos + 4]
                    .try_into()
                    .map_err(|_| HakoError::Corrupt("bad wal putblob len".into()))?,
            );
            Ok(WalOp::PutBlob { key, offset, len })
        }
        _ => Err(HakoError::Corrupt("unknown wal op".into())),
    }
}

#[cfg(test)]
mod tests {
    use std::fs;

    use crate::config::DurabilityMode;

    use super::{Wal, WalOp};

    #[test]
    fn reserve_does_not_stack_across_opens() {
        // Regression test (insiden-hako-wal-20261009): the open-time
        // reservation used to add `reserve_bytes` on EVERY open (the
        // `len < end + reserve` guard was vacuously true since end == len),
        // so each app launch grew every collection wal.log by 4MB of zeros.
        // Always still tops up once; Interval never reserves (size follows
        // data) — both stable across reopens.
        let reserve: u64 = 4 * 1024 * 1024;
        let stamp = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .expect("clock")
            .as_nanos();

        let path = std::env::temp_dir().join(format!("hako-wal-reserve-{stamp}.log"));
        for _ in 0..3 {
            let wal = Wal::open(&path, DurabilityMode::Always, 2, None, reserve)
                .expect("open");
            drop(wal);
        }
        let len = fs::metadata(&path).expect("meta").len();
        assert_eq!(len, reserve, "reservation must top-up once, not stack per open");
        fs::remove_file(&path).expect("cleanup");

        let path = std::env::temp_dir().join(format!("hako-wal-noreserve-{stamp}.log"));
        for _ in 0..3 {
            let wal = Wal::open(&path, DurabilityMode::Interval, 2, None, reserve)
                .expect("open");
            drop(wal);
        }
        let len = fs::metadata(&path).expect("meta").len();
        assert_eq!(len, 0, "Interval must not reserve: {len}");

        fs::remove_file(path).expect("cleanup");
    }

    #[test]
    fn replay_ignores_uncommitted_transaction() {
        let path = std::env::temp_dir().join(format!(
            "hako-wal-{}.log",
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .expect("clock")
                .as_nanos()
        ));

        let mut wal = Wal::open(&path, DurabilityMode::Always, 2, None, 0).expect("open");
        wal.append(&WalOp::BeginTx { tx_id: 1 }, false).expect("begin");
        wal.append(&WalOp::Put {
            key: "users:1".into(),
            segment_id: 0,
            segment_offset: 10,
            len: 3,
        }, false)
        .expect("put");

        let replayed = wal.replay().expect("replay");
        assert!(replayed.is_empty());

        wal.append(&WalOp::CommitTx { tx_id: 1 }, false).expect("commit");
        let replayed = wal.replay().expect("replay2");
        assert_eq!(replayed.len(), 1);

        fs::remove_file(path).expect("cleanup");
    }

    #[test]
    fn roundtrip_delete_via_replay() {
        // Regression test for the wal decode() bug: tag 2 (Delete) was missing
        // `pos += key_len` and silently misread the timestamp. We can't poke
        // private decode() directly, but we can replay a Delete through the
        // public Wal API and check the recovered timestamp matches what we
        // wrote.
        let path = std::env::temp_dir().join(format!(
            "hako-wal-rt-{}.log",
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .expect("clock")
                .as_nanos()
        ));

        let ts: i64 = 1_700_000_123;

        let mut wal = Wal::open(&path, DurabilityMode::Always, 2, None, 0).expect("open");
        wal.append(&WalOp::BeginTx { tx_id: 9 }, false)
            .expect("begin");
        wal.append(
            &WalOp::Delete {
                key: "doc-with-long-key".into(),
                timestamp: ts,
            },
            false,
        )
        .expect("delete");
        wal.append(&WalOp::CommitTx { tx_id: 9 }, false)
            .expect("commit");

        let replayed = wal.replay().expect("replay");
        assert_eq!(replayed.len(), 1, "expected the Delete op back");
        match &replayed[0] {
            WalOp::Delete { key, timestamp } => {
                assert_eq!(key, "doc-with-long-key");
                assert_eq!(
                    *timestamp, ts,
                    "timestamp round-trip (regression test for pos += key_len bug)"
                );
            }
            other => panic!("expected Delete, got {:?}", other),
        }

        fs::remove_file(path).expect("cleanup");
    }

    #[test]
    fn preallocation_survives_replay_and_appends() {
        // The 4MB reservation must be invisible to recovery: records written
        // into it replay fully, the padding is never truncated, and appends
        // after a reopen continue exactly at end-of-records (not EOF).
        let path = std::env::temp_dir().join(format!(
            "hako-wal-prealloc-{}.log",
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .expect("clock")
                .as_nanos()
        ));

        let mut wal = Wal::open(&path, DurabilityMode::OnCommit, 100, None, 4 * 1024 * 1024).expect("open");
        assert!(fs::metadata(&path).expect("meta").len() >= 4 * 1024 * 1024 - 1);

        for tx in 1..=3u64 {
            wal.append(&WalOp::BeginTx { tx_id: tx }, false).expect("begin");
            wal.append(&WalOp::PutInlined {
                key: format!("k{tx}"),
                value: vec![tx as u8; 64],
            }, false).expect("put");
            wal.append(&WalOp::CommitTx { tx_id: tx }, false).expect("commit");
        }
        drop(wal);

        // Reopen: reservation intact, all 3 puts recover, no truncation.
        let mut wal2 = Wal::open(&path, DurabilityMode::OnCommit, 100, None, 4 * 1024 * 1024).expect("reopen");
        let replayed = wal2.replay().expect("replay");
        assert_eq!(replayed.len(), 3, "all puts must survive, got {replayed:?}");
        assert!(fs::metadata(&path).expect("meta2").len() >= 4 * 1024 * 1024 - 1);

        // Append after reopen lands right after the records (position check:
        // file length must NOT jump — the reservation absorbs it).
        let len_before = fs::metadata(&path).expect("meta3").len();
        wal2.append(&WalOp::BeginTx { tx_id: 4 }, false).expect("begin2");
        wal2.append(&WalOp::PutInlined { key: "k4".into(), value: vec![4u8; 64] }, false).expect("put2");
        wal2.append(&WalOp::CommitTx { tx_id: 4 }, false).expect("commit2");
        assert_eq!(fs::metadata(&path).expect("meta4").len(), len_before);
        drop(wal2);

        let mut wal3 = Wal::open(&path, DurabilityMode::OnCommit, 100, None, 4 * 1024 * 1024).expect("reopen2");
        let replayed = wal3.replay().expect("replay2");
        assert_eq!(replayed.len(), 4, "post-reopen append must be reachable, got {replayed:?}");

        fs::remove_file(path).expect("cleanup");
    }

    /// 2-b: data_len tracks real records, never the sparse reservation.
    /// A 4MB-reserved file holding 3 small puts must report ~bytes, or
    /// size heuristics fire on phantom megabytes (ratchet trigger).
    #[test]
    fn data_len_ignores_reservation() {
        let path = std::env::temp_dir().join(format!(
            "hako-wal-dlen-{}.log",
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .expect("clock")
                .as_nanos()
        ));

        let mut wal = Wal::open(&path, DurabilityMode::Always, 100, None, 4 * 1024 * 1024).expect("open");
        wal.append(&WalOp::PutInlined { key: "k".into(), value: vec![9u8; 64] }, false).expect("put");
        // Always flushes per append: file is 4MB sparse, data is ~100B.
        assert!(fs::metadata(&path).expect("meta").len() >= 4 * 1024 * 1024);
        assert!(wal.data_len() < 1024, "data_len {}, must be bytes not megabytes", wal.data_len());
        assert!(!wal.has_pending(), "Always flushes: nothing pending");

        // Buffered-only append is pending but uncounted (safe direction).
        let mut wal2 = Wal::open(&path, DurabilityMode::Manual, 100, None, 0).expect("open2");
        wal2.append(&WalOp::PutInlined { key: "q".into(), value: vec![1u8; 64] }, false).expect("put2");
        assert!(wal2.has_pending(), "Manual buffers");
        let dlen = wal2.data_len();
        wal2.flush().expect("explicit flush");
        assert!(wal2.data_len() > dlen, "flush recounts end-of-records");

        drop(wal);
        drop(wal2);
        fs::remove_file(path).expect("cleanup");
    }

    /// #80: rewrite/reset leaves tailers with offsets from the old WAL. If
    /// preallocation keeps file_len large, seeking to that offset lands on
    /// zero padding and tail() returned empty forever.
    #[test]
    fn tail_resyncs_after_reset() {
        let path = std::env::temp_dir().join(format!(
            "hako-wal-tail-reset-{}.log",
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .expect("clock")
                .as_nanos()
        ));

        let reserve = 64 * 1024;
        let mut wal = Wal::open(&path, DurabilityMode::Always, 100, None, reserve).expect("open");
        wal.append(
            &WalOp::PutInlined {
                key: "before".into(),
                value: vec![1u8; 1024],
            },
            false,
        )
        .expect("before");
        let stale_offset = wal.data_len();
        assert!(wal.file_len() > stale_offset, "preallocation keeps EOF ahead");

        wal.reset().expect("reset");
        wal.append(
            &WalOp::PutInlined {
                key: "after".into(),
                value: vec![2u8; 8],
            },
            false,
        )
        .expect("after");
        let new_len = wal.data_len();
        assert!(
            stale_offset > new_len,
            "test must cross the rebuilt boundary ({stale_offset} vs {new_len})"
        );

        let (ops, new_pos) = wal.tail(stale_offset).expect("tail");
        assert_eq!(ops.len(), 1, "must replay the rebuilt WAL, got {ops:?}");
        assert!(
            matches!(&ops[0], WalOp::PutInlined { key, .. } if key == "after"),
            "got {:?}",
            ops[0]
        );
        assert_eq!(new_pos, new_len);

        drop(wal);
        fs::remove_file(path).expect("cleanup");
    }

    /// #80: remote ingest skips fsync but still advances the real-byte
    /// watermark used by tail()'s stale-offset clamp and snapshot staleness.
    #[test]
    fn remote_append_advances_data_len() {
        let path = std::env::temp_dir().join(format!(
            "hako-wal-remote-dlen-{}.log",
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .expect("clock")
                .as_nanos()
        ));

        let mut wal = Wal::open(&path, DurabilityMode::Manual, 100, None, 0).expect("open");
        assert_eq!(wal.data_len(), 0);
        wal.append_batch_fast(
            1,
            &[WalOp::PutInlined {
                key: "remote".into(),
                value: vec![7u8; 16],
            }],
            true,
        )
        .expect("remote batch");

        assert!(wal.data_len() > 0, "remote writes count as real bytes");
        assert_eq!(
            wal.data_len(),
            fs::metadata(&path).expect("meta").len(),
            "no reservation here, so data_len is the file length"
        );

        drop(wal);
        fs::remove_file(path).expect("cleanup");
    }
}