fsqlite-wal 0.1.3

Write-ahead logging
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
//! Cell-Delta WAL Frame Format (C4-WAL: bd-l9k8e.10)
//!
//! This module implements the WAL record format for cell-level deltas, enabling
//! crash-recoverable cell-level MVCC without writing full 4KB page images.
//!
//! # Design Overview
//!
//! Cell-delta frames are distinguished from full-page frames by a dedicated
//! marker word in the first 4 bytes. Older experimental encodings also packed
//! the page number into the lower 31 bits of that word. Current recovery
//! intentionally rejects those legacy frames so high-bit page numbers remain
//! unambiguously valid full-page frames; only the marker helper below decodes
//! the old word shape for diagnostics.
//!
//! ## Frame Format
//!
//! ```text
//! ┌─────────────────────────────────────────────────────────────────┐
//! │ frame_marker = 0x00000000  (4 bytes, BE) — cell-delta indicator │
//! ├─────────────────────────────────────────────────────────────────┤
//! │ actual_page_number          (4 bytes, BE)                      │
//! ├─────────────────────────────────────────────────────────────────┤
//! │ cell_key_digest             (16 bytes)                         │
//! ├─────────────────────────────────────────────────────────────────┤
//! │ op                          (1 byte: 1=Insert, 2=Update, 3=Del)│
//! ├─────────────────────────────────────────────────────────────────┤
//! │ commit_seq                  (8 bytes, BE)                      │
//! ├─────────────────────────────────────────────────────────────────┤
//! │ txn_id                      (8 bytes, BE)                      │
//! ├─────────────────────────────────────────────────────────────────┤
//! │ cell_data_len               (4 bytes, BE; 0 for Delete)        │
//! ├─────────────────────────────────────────────────────────────────┤
//! │ cell_data                   (cell_data_len bytes)              │
//! ├─────────────────────────────────────────────────────────────────┤
//! │ checksum                    (4 bytes, CRC32C)                  │
//! └─────────────────────────────────────────────────────────────────┘
//! ```
//!
//! Fixed header: 45 bytes. Total: 45 + cell_data_len + 4 (checksum) = 49 + cell_data_len.
//!
//! ## Comparison with Full-Page Frames
//!
//! | Frame Type | Typical Size | Use Case |
//! |------------|--------------|----------|
//! | Full-page  | 4096+ bytes  | Structural changes (splits, merges) |
//! | Cell-delta | ~100-200 bytes | Logical row ops (INSERT, UPDATE, DELETE) |
//!
//! A typical 100-byte INSERT: 149 bytes vs 4096 bytes = **27x smaller**.
//!
//! # Recovery
//!
//! During crash recovery:
//! 1. Read WAL frames sequentially
//! 2. Check the frame envelope for the exact cell-delta marker and checksum
//! 3. Full-page frames: apply directly to page cache
//! 4. Cell-delta frames: reconstruct into CellVisibilityLog
//! 5. Materialize affected pages from CellVisibilityLog

use fsqlite_error::{FrankenError, Result};
use fsqlite_types::{CommitSeq, PageNumber, TxnId};
use tracing::debug;

/// Marker word that indicates a cell-delta frame.
///
/// This must stay outside the valid page-number domain because mixed WAL
/// recovery uses the first word to distinguish cell-delta records from ordinary
/// full-page frames. Page number 0 is invalid in SQLite, so it is a safe
/// in-band type word.
pub const CELL_DELTA_FRAME_MARKER: u32 = 0;

/// Legacy experimental frames used the high bit of the page-number word as a
/// marker. Keep the helper below able to decode that shape, but never use it as
/// the current discriminator because high-bit page numbers are valid.
const LEGACY_CELL_DELTA_FRAME_MARKER: u32 = 0x8000_0000;

/// Fixed header size for cell-delta frames (excluding variable cell_data).
pub const CELL_DELTA_HEADER_SIZE: usize = 45;

/// Checksum size (CRC32C).
pub const CELL_DELTA_CHECKSUM_SIZE: usize = 4;

/// Minimum frame size (header + checksum, no cell data).
pub const CELL_DELTA_MIN_FRAME_SIZE: usize = CELL_DELTA_HEADER_SIZE + CELL_DELTA_CHECKSUM_SIZE;

/// Maximum cell data size (same as max page size minus overhead).
pub const CELL_DELTA_MAX_DATA_SIZE: usize = 65536;

// ---------------------------------------------------------------------------
// CellOp — Operation type (§C4-WAL.1)
// ---------------------------------------------------------------------------

/// Cell operation type encoded in WAL frame.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(u8)]
pub enum CellOp {
    /// Insert a new cell.
    Insert = 1,
    /// Update an existing cell.
    Update = 2,
    /// Delete a cell.
    Delete = 3,
}

impl CellOp {
    /// Decode from byte, returning None for invalid values.
    #[must_use]
    pub const fn from_byte(b: u8) -> Option<Self> {
        match b {
            1 => Some(Self::Insert),
            2 => Some(Self::Update),
            3 => Some(Self::Delete),
            _ => None,
        }
    }

    /// Encode as byte.
    #[must_use]
    pub const fn as_byte(self) -> u8 {
        self as u8
    }
}

// ---------------------------------------------------------------------------
// CellDeltaWalFrame — WAL frame for cell-level deltas (§C4-WAL.2)
// ---------------------------------------------------------------------------

/// A cell-delta WAL frame for crash recovery.
///
/// This is a lightweight alternative to full-page WAL frames for logical
/// row operations (INSERT, UPDATE, DELETE) that don't change page structure.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CellDeltaWalFrame {
    /// Database page number containing this cell.
    pub page_number: PageNumber,
    /// Cell key digest (BLAKE3-based, 16 bytes) for stable identity.
    pub cell_key_digest: [u8; 16],
    /// Operation type.
    pub op: CellOp,
    /// Commit sequence number (0 = uncommitted).
    pub commit_seq: CommitSeq,
    /// Transaction ID that created this delta.
    pub txn_id: TxnId,
    /// Cell content (empty for Delete operations).
    pub cell_data: Vec<u8>,
}

impl CellDeltaWalFrame {
    /// Create a new cell-delta frame.
    #[must_use]
    pub fn new(
        page_number: PageNumber,
        cell_key_digest: [u8; 16],
        op: CellOp,
        commit_seq: CommitSeq,
        txn_id: TxnId,
        cell_data: Vec<u8>,
    ) -> Self {
        Self {
            page_number,
            cell_key_digest,
            op,
            commit_seq,
            txn_id,
            cell_data,
        }
    }

    /// Compute the serialized size of this frame.
    #[must_use]
    pub fn serialized_size(&self) -> usize {
        CELL_DELTA_HEADER_SIZE + self.cell_data.len() + CELL_DELTA_CHECKSUM_SIZE
    }

    /// Serialize this frame to bytes.
    ///
    /// Returns a `Vec` containing the complete frame with checksum.
    pub fn serialize(&self) -> Result<Vec<u8>> {
        if self.cell_data.len() > CELL_DELTA_MAX_DATA_SIZE {
            return Err(FrankenError::WalCorrupt {
                detail: format!(
                    "cell-delta payload too large: {} bytes exceeds max {CELL_DELTA_MAX_DATA_SIZE}",
                    self.cell_data.len()
                ),
            });
        }
        if self.op == CellOp::Delete && !self.cell_data.is_empty() {
            return Err(FrankenError::WalCorrupt {
                detail: "delete cell-delta frame cannot carry cell data".to_owned(),
            });
        }

        let mut buf = Vec::with_capacity(self.serialized_size());

        // Frame marker + actual page number (4 bytes each).
        // Keep the first word as a pure type tag so page numbers can use the
        // full non-zero u32 range accepted by PageNumber.
        buf.extend_from_slice(&CELL_DELTA_FRAME_MARKER.to_be_bytes());
        buf.extend_from_slice(&self.page_number.get().to_be_bytes());

        // Cell key digest (16 bytes)
        buf.extend_from_slice(&self.cell_key_digest);

        // Op (1 byte)
        buf.push(self.op.as_byte());

        // Commit seq (8 bytes)
        buf.extend_from_slice(&self.commit_seq.get().to_be_bytes());

        // Txn ID (8 bytes)
        buf.extend_from_slice(&self.txn_id.get().to_be_bytes());

        // Cell data length (4 bytes). The payload-size guard above keeps this
        // conversion infallible without silent narrowing.
        let data_len =
            u32::try_from(self.cell_data.len()).map_err(|_| FrankenError::WalCorrupt {
                detail: format!(
                    "cell-delta payload length {} does not fit in u32",
                    self.cell_data.len()
                ),
            })?;
        buf.extend_from_slice(&data_len.to_be_bytes());

        // Cell data (variable)
        buf.extend_from_slice(&self.cell_data);

        // CRC32C checksum (4 bytes) over everything before checksum
        let checksum = crc32c::crc32c(&buf);
        buf.extend_from_slice(&checksum.to_be_bytes());

        debug!(
            frame_type = "cell_delta",
            pgno = self.page_number.get(),
            cell_key = ?&self.cell_key_digest[..4],
            op = ?self.op,
            commit_seq = self.commit_seq.get(),
            data_len = self.cell_data.len(),
            "wal_frame_written"
        );

        Ok(buf)
    }

    /// Deserialize a cell-delta frame from bytes.
    ///
    /// Returns an error if the frame is too short, has an invalid marker,
    /// or fails checksum verification.
    pub fn deserialize(data: &[u8]) -> Result<Self> {
        if data.len() < CELL_DELTA_MIN_FRAME_SIZE {
            return Err(FrankenError::WalCorrupt {
                detail: format!(
                    "cell-delta frame too short: {} bytes, need at least {}",
                    data.len(),
                    CELL_DELTA_MIN_FRAME_SIZE
                ),
            });
        }

        // Verify marker. New frames use an invalid page-number word as a pure
        // type tag, so full-page frames cannot collide with cell-delta frames.
        let marker_and_pgno = u32::from_be_bytes([data[0], data[1], data[2], data[3]]);
        if marker_and_pgno != CELL_DELTA_FRAME_MARKER {
            return Err(FrankenError::WalCorrupt {
                detail: format!("cell-delta frame has invalid marker word: {marker_and_pgno:#x}"),
            });
        }

        // Parse fixed header fields
        let actual_pgno = u32::from_be_bytes([data[4], data[5], data[6], data[7]]);
        let page_number = PageNumber::new(actual_pgno).ok_or_else(|| FrankenError::WalCorrupt {
            detail: "cell-delta frame has invalid page number 0".to_owned(),
        })?;
        let mut cell_key_digest = [0u8; 16];
        cell_key_digest.copy_from_slice(&data[8..24]);

        let op = CellOp::from_byte(data[24]).ok_or_else(|| FrankenError::WalCorrupt {
            detail: format!("cell-delta frame has invalid op byte: {}", data[24]),
        })?;

        let commit_seq = CommitSeq::new(u64::from_be_bytes([
            data[25], data[26], data[27], data[28], data[29], data[30], data[31], data[32],
        ]));

        let txn_id_raw = u64::from_be_bytes([
            data[33], data[34], data[35], data[36], data[37], data[38], data[39], data[40],
        ]);
        let txn_id = TxnId::new(txn_id_raw).ok_or_else(|| FrankenError::WalCorrupt {
            detail: format!("cell-delta frame has invalid txn_id: {}", txn_id_raw),
        })?;

        let cell_data_len = u32::from_be_bytes([data[41], data[42], data[43], data[44]]) as usize;
        if cell_data_len > CELL_DELTA_MAX_DATA_SIZE {
            return Err(FrankenError::WalCorrupt {
                detail: format!(
                    "cell-delta frame data too large: {} bytes, max {}",
                    cell_data_len, CELL_DELTA_MAX_DATA_SIZE
                ),
            });
        }
        if op == CellOp::Delete && cell_data_len != 0 {
            return Err(FrankenError::WalCorrupt {
                detail: format!(
                    "cell-delta delete frame has non-empty payload: {} bytes",
                    cell_data_len
                ),
            });
        }

        // Validate total length
        let expected_len = CELL_DELTA_HEADER_SIZE
            .checked_add(cell_data_len)
            .and_then(|len| len.checked_add(CELL_DELTA_CHECKSUM_SIZE))
            .ok_or_else(|| FrankenError::WalCorrupt {
                detail: "cell-delta frame length overflow".to_owned(),
            })?;
        if data.len() < expected_len {
            return Err(FrankenError::WalCorrupt {
                detail: format!(
                    "cell-delta frame truncated: {} bytes, need {} (data_len={})",
                    data.len(),
                    expected_len,
                    cell_data_len
                ),
            });
        }
        if data.len() > expected_len {
            return Err(FrankenError::WalCorrupt {
                detail: format!(
                    "cell-delta frame has {} trailing bytes after checksum",
                    data.len() - expected_len
                ),
            });
        }

        // Extract cell data
        let cell_data =
            data[CELL_DELTA_HEADER_SIZE..CELL_DELTA_HEADER_SIZE + cell_data_len].to_vec();

        // Verify checksum
        let checksum_offset = CELL_DELTA_HEADER_SIZE + cell_data_len;
        let stored_checksum = u32::from_be_bytes([
            data[checksum_offset],
            data[checksum_offset + 1],
            data[checksum_offset + 2],
            data[checksum_offset + 3],
        ]);
        let computed_checksum = crc32c::crc32c(&data[..checksum_offset]);

        if stored_checksum != computed_checksum {
            return Err(FrankenError::WalCorrupt {
                detail: format!(
                    "cell-delta frame checksum mismatch: stored {:08x}, computed {:08x}",
                    stored_checksum, computed_checksum
                ),
            });
        }

        Ok(Self {
            page_number,
            cell_key_digest,
            op,
            commit_seq,
            txn_id,
            cell_data,
        })
    }
}

// ---------------------------------------------------------------------------
// Frame Type Detection (§C4-WAL.3)
// ---------------------------------------------------------------------------

/// Check if a WAL frame is a structurally valid cell-delta frame.
///
/// Full-page WAL frames also start with a page number. The marker word is page
/// 0, which is invalid, and the remaining envelope is still verified before a
/// frame is accepted.
#[must_use]
pub fn is_cell_delta_frame(frame_data: &[u8]) -> bool {
    if frame_data.len() < CELL_DELTA_MIN_FRAME_SIZE {
        return false;
    }
    let marker_and_pgno =
        u32::from_be_bytes([frame_data[0], frame_data[1], frame_data[2], frame_data[3]]);
    if marker_and_pgno != CELL_DELTA_FRAME_MARKER {
        return false;
    }
    let actual_pgno =
        u32::from_be_bytes([frame_data[4], frame_data[5], frame_data[6], frame_data[7]]);
    if PageNumber::new(actual_pgno).is_none() {
        return false;
    }
    let Some(op) = CellOp::from_byte(frame_data[24]) else {
        return false;
    };
    let txn_id_raw = u64::from_be_bytes([
        frame_data[33],
        frame_data[34],
        frame_data[35],
        frame_data[36],
        frame_data[37],
        frame_data[38],
        frame_data[39],
        frame_data[40],
    ]);
    if TxnId::new(txn_id_raw).is_none() {
        return false;
    }
    let cell_data_len = u32::from_be_bytes([
        frame_data[41],
        frame_data[42],
        frame_data[43],
        frame_data[44],
    ]) as usize;
    if cell_data_len > CELL_DELTA_MAX_DATA_SIZE || (op == CellOp::Delete && cell_data_len != 0) {
        return false;
    }
    let Some(expected_len) = CELL_DELTA_HEADER_SIZE
        .checked_add(cell_data_len)
        .and_then(|len| len.checked_add(CELL_DELTA_CHECKSUM_SIZE))
    else {
        return false;
    };
    if frame_data.len() != expected_len {
        return false;
    }

    let checksum_offset = CELL_DELTA_HEADER_SIZE + cell_data_len;
    let stored_checksum = u32::from_be_bytes([
        frame_data[checksum_offset],
        frame_data[checksum_offset + 1],
        frame_data[checksum_offset + 2],
        frame_data[checksum_offset + 3],
    ]);
    stored_checksum == crc32c::crc32c(&frame_data[..checksum_offset])
}

/// Extract the legacy embedded page number from a cell-delta frame marker.
///
/// New frames use an invalid page-number word as a pure type marker and store
/// the real page number in the second word, so this returns `None` for the
/// current encoding.
#[must_use]
pub fn extract_page_number_from_marker(marker_and_pgno: u32) -> Option<PageNumber> {
    if marker_and_pgno & LEGACY_CELL_DELTA_FRAME_MARKER == 0 {
        return None; // Not a cell-delta frame
    }
    let embedded_page = marker_and_pgno & !LEGACY_CELL_DELTA_FRAME_MARKER;
    if embedded_page == 0 {
        return None;
    }
    PageNumber::new(embedded_page)
}

// ---------------------------------------------------------------------------
// Recovery Helpers (§C4-WAL.4)
// ---------------------------------------------------------------------------

/// Summary statistics from WAL recovery.
#[derive(Debug, Clone, Default)]
pub struct WalRecoverySummary {
    /// Number of full-page frames processed.
    pub full_page_frames: u64,
    /// Number of cell-delta frames processed.
    pub cell_delta_frames: u64,
    /// Number of cell-delta frames skipped (uncommitted).
    pub cell_delta_uncommitted: u64,
    /// Number of checksum errors encountered.
    pub checksum_errors: u64,
    /// Total bytes of cell data recovered.
    pub cell_data_bytes: u64,
}

impl WalRecoverySummary {
    /// Log summary statistics.
    pub fn log_summary(&self) {
        tracing::info!(
            full_page_frames = self.full_page_frames,
            cell_delta_frames = self.cell_delta_frames,
            cell_delta_uncommitted = self.cell_delta_uncommitted,
            checksum_errors = self.checksum_errors,
            cell_data_bytes = self.cell_data_bytes,
            "wal_recovery_summary"
        );
    }
}

// ---------------------------------------------------------------------------
// Tests (§C4-WAL.5)
// ---------------------------------------------------------------------------

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

    fn test_page_number() -> PageNumber {
        PageNumber::new(42).unwrap()
    }

    fn test_cell_key_digest() -> [u8; 16] {
        [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]
    }

    fn test_txn_id(id: u64) -> TxnId {
        TxnId::new(id).unwrap()
    }

    fn high_bit_page_number() -> PageNumber {
        PageNumber::new(0x8000_0042).unwrap()
    }

    #[test]
    fn test_cell_delta_frame_round_trip() {
        let frame = CellDeltaWalFrame::new(
            test_page_number(),
            test_cell_key_digest(),
            CellOp::Insert,
            CommitSeq::new(100),
            test_txn_id(42),
            vec![1, 2, 3, 4, 5],
        );

        let serialized = frame.serialize().unwrap();
        let deserialized = CellDeltaWalFrame::deserialize(&serialized).unwrap();

        assert_eq!(frame, deserialized);
    }

    #[test]
    fn test_cell_delta_frame_checksum() {
        let frame = CellDeltaWalFrame::new(
            test_page_number(),
            test_cell_key_digest(),
            CellOp::Update,
            CommitSeq::new(200),
            test_txn_id(99),
            vec![10, 20, 30],
        );

        let mut serialized = frame.serialize().unwrap();

        // Corrupt one byte in the middle
        serialized[20] ^= 0xFF;

        let result = CellDeltaWalFrame::deserialize(&serialized);
        assert!(result.is_err());
        assert!(
            result
                .unwrap_err()
                .to_string()
                .contains("checksum mismatch")
        );
    }

    #[test]
    fn test_cell_delta_frame_variable_length() {
        // Test empty cell data (Delete)
        let frame_empty = CellDeltaWalFrame::new(
            test_page_number(),
            test_cell_key_digest(),
            CellOp::Delete,
            CommitSeq::new(50),
            test_txn_id(1),
            vec![],
        );
        let serialized = frame_empty.serialize().unwrap();
        let deserialized = CellDeltaWalFrame::deserialize(&serialized).unwrap();
        assert_eq!(frame_empty, deserialized);
        assert!(deserialized.cell_data.is_empty());

        // Test 100 bytes
        let frame_100 = CellDeltaWalFrame::new(
            test_page_number(),
            test_cell_key_digest(),
            CellOp::Insert,
            CommitSeq::new(51),
            test_txn_id(2),
            vec![0xAB; 100],
        );
        let serialized = frame_100.serialize().unwrap();
        let deserialized = CellDeltaWalFrame::deserialize(&serialized).unwrap();
        assert_eq!(frame_100, deserialized);
        assert_eq!(deserialized.cell_data.len(), 100);

        // Test 4000 bytes
        let frame_4000 = CellDeltaWalFrame::new(
            test_page_number(),
            test_cell_key_digest(),
            CellOp::Update,
            CommitSeq::new(52),
            test_txn_id(3),
            vec![0xCD; 4000],
        );
        let serialized = frame_4000.serialize().unwrap();
        let deserialized = CellDeltaWalFrame::deserialize(&serialized).unwrap();
        assert_eq!(frame_4000, deserialized);
        assert_eq!(deserialized.cell_data.len(), 4000);
    }

    #[test]
    fn test_cell_delta_frame_type_byte() {
        let frame = CellDeltaWalFrame::new(
            test_page_number(),
            test_cell_key_digest(),
            CellOp::Insert,
            CommitSeq::new(100),
            test_txn_id(42),
            vec![1, 2, 3],
        );

        let serialized = frame.serialize().unwrap();

        // Verify exact cell-delta marker.
        assert!(is_cell_delta_frame(&serialized));

        // Verify first 4 bytes are the pure marker word.
        let marker_and_pgno =
            u32::from_be_bytes([serialized[0], serialized[1], serialized[2], serialized[3]]);
        assert_eq!(marker_and_pgno, CELL_DELTA_FRAME_MARKER);

        // New frames use a pure marker word; there is no embedded page number.
        assert_eq!(extract_page_number_from_marker(marker_and_pgno), None);

        // Legacy experimental markers may still embed the page number in the
        // lower 31 bits.
        let legacy_marker = LEGACY_CELL_DELTA_FRAME_MARKER | test_page_number().get();
        assert_eq!(
            extract_page_number_from_marker(legacy_marker),
            Some(test_page_number())
        );
    }

    #[test]
    fn test_cell_op_encoding() {
        assert_eq!(CellOp::from_byte(1), Some(CellOp::Insert));
        assert_eq!(CellOp::from_byte(2), Some(CellOp::Update));
        assert_eq!(CellOp::from_byte(3), Some(CellOp::Delete));
        assert_eq!(CellOp::from_byte(0), None);
        assert_eq!(CellOp::from_byte(4), None);

        assert_eq!(CellOp::Insert.as_byte(), 1);
        assert_eq!(CellOp::Update.as_byte(), 2);
        assert_eq!(CellOp::Delete.as_byte(), 3);
    }

    #[test]
    fn test_is_cell_delta_frame_detection() {
        // Cell-delta frame
        let frame = CellDeltaWalFrame::new(
            test_page_number(),
            test_cell_key_digest(),
            CellOp::Insert,
            CommitSeq::new(100),
            test_txn_id(42),
            vec![1, 2, 3],
        );
        let serialized = frame.serialize().unwrap();
        assert!(is_cell_delta_frame(&serialized));

        let mut invalid_txn_id = serialized.clone();
        invalid_txn_id[33..41].copy_from_slice(&0u64.to_be_bytes());
        let checksum_offset = invalid_txn_id.len() - CELL_DELTA_CHECKSUM_SIZE;
        let checksum = crc32c::crc32c(&invalid_txn_id[..checksum_offset]);
        invalid_txn_id[checksum_offset..].copy_from_slice(&checksum.to_be_bytes());
        assert!(
            !is_cell_delta_frame(&invalid_txn_id),
            "frame detector should reject envelopes with invalid transaction ids"
        );
        assert!(CellDeltaWalFrame::deserialize(&invalid_txn_id).is_err());

        // Too short to be a structurally valid cell-delta frame.
        let fake_page_frame = [0x00, 0x00, 0x00, 0x2A];
        assert!(!is_cell_delta_frame(&fake_page_frame));

        // High-bit page numbers are valid full-page frame page numbers. The
        // discriminator must not classify them as cell-delta frames just
        // because they share the legacy marker bit.
        let high_bit_full_page_frame = 0x8000_0042_u32.to_be_bytes();
        assert!(!is_cell_delta_frame(&high_bit_full_page_frame));

        let mut exact_marker_full_page_frame = vec![0u8; 24 + 4096];
        exact_marker_full_page_frame[..4].copy_from_slice(&CELL_DELTA_FRAME_MARKER.to_be_bytes());
        assert!(
            !is_cell_delta_frame(&exact_marker_full_page_frame),
            "page-zero marker must not classify a malformed envelope as cell-delta"
        );

        // Too short
        assert!(!is_cell_delta_frame(&[0x80]));
        assert!(!is_cell_delta_frame(&[]));
    }

    #[test]
    fn test_serialized_size() {
        let frame = CellDeltaWalFrame::new(
            test_page_number(),
            test_cell_key_digest(),
            CellOp::Insert,
            CommitSeq::new(100),
            test_txn_id(42),
            vec![0xAB; 50],
        );

        // Header (45) + data (50) + checksum (4) = 99
        assert_eq!(frame.serialized_size(), 99);
        assert_eq!(frame.serialize().unwrap().len(), 99);
    }

    #[test]
    fn test_deserialize_truncated() {
        let frame = CellDeltaWalFrame::new(
            test_page_number(),
            test_cell_key_digest(),
            CellOp::Insert,
            CommitSeq::new(100),
            test_txn_id(42),
            vec![1, 2, 3, 4, 5],
        );

        let serialized = frame.serialize().unwrap();

        // Truncate to various lengths
        assert!(CellDeltaWalFrame::deserialize(&serialized[..10]).is_err());
        assert!(
            CellDeltaWalFrame::deserialize(&serialized[..CELL_DELTA_MIN_FRAME_SIZE - 1]).is_err()
        );

        // Truncate cell data
        let truncated = &serialized[..serialized.len() - 3];
        let result = CellDeltaWalFrame::deserialize(truncated);
        assert!(result.is_err());
    }

    #[test]
    fn test_deserialize_rejects_trailing_bytes() {
        let frame = CellDeltaWalFrame::new(
            test_page_number(),
            test_cell_key_digest(),
            CellOp::Insert,
            CommitSeq::new(100),
            test_txn_id(42),
            vec![1, 2, 3],
        );

        let mut serialized = frame.serialize().unwrap();
        serialized.extend_from_slice(b"junk");

        let result = CellDeltaWalFrame::deserialize(&serialized);
        assert!(result.is_err());
        assert!(
            result.unwrap_err().to_string().contains("trailing bytes"),
            "decoder should reject bytes not covered by the frame checksum"
        );
    }

    #[test]
    fn test_deserialize_rejects_oversized_cell_data_len() {
        let mut serialized = CellDeltaWalFrame::new(
            test_page_number(),
            test_cell_key_digest(),
            CellOp::Insert,
            CommitSeq::new(100),
            test_txn_id(42),
            Vec::new(),
        )
        .serialize()
        .unwrap();
        let too_large = u32::try_from(CELL_DELTA_MAX_DATA_SIZE + 1)
            .expect("test max cell delta size should fit u32");
        serialized[41..45].copy_from_slice(&too_large.to_be_bytes());

        let result = CellDeltaWalFrame::deserialize(&serialized);
        assert!(result.is_err());
        assert!(
            result.unwrap_err().to_string().contains("data too large"),
            "decoder should reject impossible allocation sizes before checksum work"
        );
    }

    #[test]
    fn test_deserialize_rejects_delete_payload() {
        let mut serialized = CellDeltaWalFrame::new(
            test_page_number(),
            test_cell_key_digest(),
            CellOp::Update,
            CommitSeq::new(100),
            test_txn_id(42),
            vec![1, 2, 3],
        )
        .serialize()
        .unwrap();
        serialized[24] = CellOp::Delete.as_byte();

        let result = CellDeltaWalFrame::deserialize(&serialized);
        assert!(result.is_err());
        assert!(
            result
                .unwrap_err()
                .to_string()
                .contains("delete frame has non-empty payload"),
            "decoder should reject delete frames with unreachable payload bytes"
        );
    }

    #[test]
    fn test_serialize_rejects_oversized_cell_data() {
        let frame = CellDeltaWalFrame::new(
            test_page_number(),
            test_cell_key_digest(),
            CellOp::Insert,
            CommitSeq::new(100),
            test_txn_id(42),
            vec![0; CELL_DELTA_MAX_DATA_SIZE + 1],
        );

        let err = frame
            .serialize()
            .expect_err("serializer should reject payloads larger than the frame limit");
        assert!(
            err.to_string().contains("payload too large"),
            "unexpected serializer error: {err}"
        );
    }

    #[test]
    fn test_serialize_rejects_delete_payload() {
        let frame = CellDeltaWalFrame::new(
            test_page_number(),
            test_cell_key_digest(),
            CellOp::Delete,
            CommitSeq::new(100),
            test_txn_id(42),
            vec![1],
        );

        let err = frame
            .serialize()
            .expect_err("serializer should reject DELETE frames with a payload");
        assert!(
            err.to_string().contains("cannot carry cell data"),
            "unexpected serializer error: {err}"
        );
    }

    #[test]
    fn test_recovery_summary() {
        let summary = WalRecoverySummary {
            full_page_frames: 100,
            cell_delta_frames: 500,
            cell_delta_uncommitted: 10,
            cell_data_bytes: 50_000,
            ..Default::default()
        };

        // Just verify it compiles and logs without panic
        summary.log_summary();
    }

    #[test]
    fn test_all_ops_round_trip() {
        for op in [CellOp::Insert, CellOp::Update, CellOp::Delete] {
            let cell_data = if op == CellOp::Delete {
                vec![]
            } else {
                vec![1, 2, 3, 4, 5]
            };

            let frame = CellDeltaWalFrame::new(
                test_page_number(),
                test_cell_key_digest(),
                op,
                CommitSeq::new(100),
                test_txn_id(42),
                cell_data,
            );

            let serialized = frame.serialize().unwrap();
            let deserialized = CellDeltaWalFrame::deserialize(&serialized).unwrap();
            assert_eq!(frame, deserialized);
        }
    }

    #[test]
    fn test_high_bit_page_number_round_trips() {
        let frame = CellDeltaWalFrame::new(
            high_bit_page_number(),
            test_cell_key_digest(),
            CellOp::Insert,
            CommitSeq::new(100),
            test_txn_id(42),
            vec![1, 2, 3],
        );

        let serialized = frame.serialize().unwrap();
        let deserialized = CellDeltaWalFrame::deserialize(&serialized).unwrap();
        assert_eq!(deserialized.page_number, high_bit_page_number());
    }

    #[test]
    fn test_deserialize_rejects_legacy_marker_word() {
        let frame = CellDeltaWalFrame::new(
            test_page_number(),
            test_cell_key_digest(),
            CellOp::Insert,
            CommitSeq::new(100),
            test_txn_id(42),
            vec![1, 2, 3],
        );

        let mut serialized = frame.serialize().unwrap();
        let legacy_marker = LEGACY_CELL_DELTA_FRAME_MARKER | test_page_number().get();
        serialized[..4].copy_from_slice(&legacy_marker.to_be_bytes());

        let result = CellDeltaWalFrame::deserialize(&serialized);
        assert!(result.is_err());
        assert!(
            result
                .unwrap_err()
                .to_string()
                .contains("invalid marker word")
        );
    }
}