Skip to main content

reddb_server/storage/wal/
checkpoint.rs

1//! Checkpoint Manager
2//!
3//! Responsible for transferring committed transactions from the WAL to the main
4//! database file. Checkpointing ensures durability and allows WAL truncation.
5//!
6//! # Algorithm
7//!
8//! 1. Read all WAL records sequentially
9//! 2. Track transaction states (Begin, Commit, Rollback)
10//! 3. For committed transactions, collect PageWrite records
11//! 4. Apply committed pages to the Pager in LSN order
12//! 5. Sync Pager to disk
13//! 6. Update checkpoint LSN in database header
14//! 7. Truncate WAL
15//!
16//! # References
17//!
18//! - Turso `core/storage/wal.rs:checkpoint()` - Checkpoint logic
19//! - SQLite WAL documentation
20
21use std::collections::{HashMap, HashSet};
22use std::io;
23use std::path::Path;
24
25use super::reader::WalReader;
26use super::record::WalRecord;
27use super::writer::WalWriter;
28use crate::storage::engine::{Page, Pager, PAGE_SIZE};
29
30/// Checkpoint mode
31#[derive(Debug, Clone, Copy, PartialEq, Eq)]
32pub enum CheckpointMode {
33    /// Passive: Only checkpoint if no active writers
34    Passive,
35    /// Full: Wait for active writers to finish, then checkpoint all
36    Full,
37    /// Restart: Like Full, but also truncates the WAL
38    Restart,
39    /// Truncate: Checkpoint all and truncate WAL
40    Truncate,
41}
42
43/// Checkpoint result statistics
44#[derive(Debug, Clone, Default)]
45pub struct CheckpointResult {
46    /// Number of transactions processed
47    pub transactions_processed: u64,
48    /// Highest transaction id observed while scanning the WAL.
49    pub max_transaction_id: u64,
50    /// Number of pages checkpointed
51    pub pages_checkpointed: u64,
52    /// Number of records processed
53    pub records_processed: u64,
54    /// Final LSN after checkpoint
55    pub checkpoint_lsn: u64,
56    /// Whether WAL was truncated
57    pub wal_truncated: bool,
58}
59
60/// Checkpoint error types
61#[derive(Debug)]
62pub enum CheckpointError {
63    /// I/O error
64    Io(io::Error),
65    /// Pager error
66    Pager(String),
67    /// WAL is corrupted
68    CorruptedWal(String),
69    /// No WAL file found
70    NoWal,
71}
72
73impl std::fmt::Display for CheckpointError {
74    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
75        match self {
76            Self::Io(e) => write!(f, "I/O error: {}", e),
77            Self::Pager(msg) => write!(f, "Pager error: {}", msg),
78            Self::CorruptedWal(msg) => write!(f, "Corrupted WAL: {}", msg),
79            Self::NoWal => write!(f, "No WAL file found"),
80        }
81    }
82}
83
84impl std::error::Error for CheckpointError {}
85
86impl From<io::Error> for CheckpointError {
87    fn from(e: io::Error) -> Self {
88        Self::Io(e)
89    }
90}
91
92/// Transaction state during checkpoint
93#[derive(Debug, Clone, Copy, PartialEq, Eq)]
94enum TxState {
95    Active,
96    Committed,
97    Aborted,
98}
99
100/// Pending page write from a transaction
101#[derive(Debug)]
102struct PendingWrite {
103    tx_id: u64,
104    page_id: u32,
105    data: Vec<u8>,
106    lsn: u64,
107}
108
109fn result_observe_tx_id(max_transaction_id: &mut u64, tx_id: u64) {
110    *max_transaction_id = (*max_transaction_id).max(tx_id);
111}
112
113/// Checkpoint manager
114///
115/// Responsible for transferring committed transactions from the WAL to the main database file.
116pub struct Checkpointer {
117    /// Checkpoint mode
118    mode: CheckpointMode,
119}
120
121impl Checkpointer {
122    /// Create a new checkpointer with the given mode
123    pub fn new(mode: CheckpointMode) -> Self {
124        Self { mode }
125    }
126
127    /// Create a checkpointer with default mode (Full)
128    pub fn default_mode() -> Self {
129        Self::new(CheckpointMode::Full)
130    }
131
132    /// Perform a checkpoint
133    ///
134    /// Reads all records from the WAL and applies committed changes to the database.
135    ///
136    /// # Arguments
137    ///
138    /// * `pager` - The Pager to write committed pages to
139    /// * `wal_path` - Path to the WAL file
140    ///
141    /// # Returns
142    ///
143    /// Checkpoint statistics or error
144    pub fn checkpoint(
145        &self,
146        pager: &Pager,
147        wal_path: &Path,
148    ) -> Result<CheckpointResult, CheckpointError> {
149        // Open WAL for reading
150        let wal_reader = match WalReader::open(wal_path) {
151            Ok(r) => r,
152            Err(e) if e.kind() == io::ErrorKind::NotFound => {
153                // No WAL file - nothing to checkpoint
154                return Ok(CheckpointResult::default());
155            }
156            Err(e) => return Err(CheckpointError::Io(e)),
157        };
158
159        // Phase 1: Read and categorize all records
160        let mut tx_states: HashMap<u64, TxState> = HashMap::new();
161        let mut pending_writes: Vec<PendingWrite> = Vec::new();
162        let mut records_processed: u64 = 0;
163        let mut last_lsn: u64 = 0;
164        let mut max_transaction_id: u64 = 0;
165
166        for record_result in wal_reader.iter() {
167            let (lsn, record) = record_result.map_err(CheckpointError::Io)?;
168            records_processed += 1;
169            last_lsn = lsn;
170
171            match record {
172                WalRecord::PageOwnership { .. } => {
173                    return Err(CheckpointError::Io(io::Error::other(
174                        "page ownership journal requires recovery before checkpoint",
175                    )));
176                }
177                WalRecord::Begin { tx_id } => {
178                    result_observe_tx_id(&mut max_transaction_id, tx_id);
179                    tx_states.insert(tx_id, TxState::Active);
180                }
181                WalRecord::Commit { tx_id } => {
182                    result_observe_tx_id(&mut max_transaction_id, tx_id);
183                    tx_states.insert(tx_id, TxState::Committed);
184                }
185                WalRecord::Rollback { tx_id } => {
186                    result_observe_tx_id(&mut max_transaction_id, tx_id);
187                    tx_states.insert(tx_id, TxState::Aborted);
188                }
189                WalRecord::PageWrite {
190                    tx_id,
191                    page_id,
192                    data,
193                } => {
194                    result_observe_tx_id(&mut max_transaction_id, tx_id);
195                    pending_writes.push(PendingWrite {
196                        tx_id,
197                        page_id,
198                        data,
199                        lsn,
200                    });
201                }
202                WalRecord::Checkpoint {
203                    lsn: _checkpoint_lsn,
204                } => {
205                    // Checkpoint marker - we can skip records before this LSN
206                    // For now, we process everything
207                }
208                WalRecord::TxCommitBatch { tx_id, .. } => {
209                    result_observe_tx_id(&mut max_transaction_id, tx_id);
210                    // Store-level logical commit batches are replayed by
211                    // UnifiedStore, not by the pager page checkpoint path.
212                }
213                WalRecord::VectorInsert { .. } => {
214                    // Vector-turbo logical inserts are replayed by the
215                    // vector index layer, not by page checkpointing.
216                    // Issue #694 — named crash boundary for #673.
217                    crate::runtime::turbo_crash_inject::fire(
218                        crate::runtime::turbo_crash_inject::InjectionPoint::MidCheckpoint,
219                    );
220                }
221                WalRecord::ProbabilisticDelta { .. } => {
222                    // Probabilistic sidecar deltas are replayed by the
223                    // runtime after loading the latest full snapshot.
224                }
225                WalRecord::FullPageImage { tx_id, .. } => {
226                    result_observe_tx_id(&mut max_transaction_id, tx_id);
227                    // FPI records (gh-478) are consumed by the pager
228                    // recovery path before redo, not by checkpoint
229                    // accounting.
230                }
231            }
232        }
233
234        // Phase 2: Filter for committed transactions only
235        let committed_txs: HashSet<u64> = tx_states
236            .iter()
237            .filter(|(_, state)| **state == TxState::Committed)
238            .map(|(tx_id, _)| *tx_id)
239            .collect();
240
241        // Phase 3: Collect pages from committed transactions
242        // Keep only the latest write for each page (from committed txs)
243        let mut latest_writes: HashMap<u32, Vec<u8>> = HashMap::new();
244
245        for write in pending_writes {
246            if committed_txs.contains(&write.tx_id) {
247                // Always overwrite with later writes (they have higher LSN)
248                latest_writes.insert(write.page_id, write.data);
249            }
250        }
251
252        // Phase 4 (PREPARE): Mark checkpoint in progress in header
253        if !latest_writes.is_empty() {
254            pager
255                .set_checkpoint_in_progress(true, last_lsn)
256                .map_err(|e| CheckpointError::Pager(e.to_string()))?;
257        }
258
259        // Phase 5 (APPLY): Write committed pages to Pager
260        let mut pages_checkpointed: u64 = 0;
261
262        for (page_id, data) in &latest_writes {
263            // Reconstruct page from WAL data
264            if data.len() != PAGE_SIZE {
265                return Err(CheckpointError::CorruptedWal(format!(
266                    "Page {} has wrong size: {} (expected {})",
267                    page_id,
268                    data.len(),
269                    PAGE_SIZE
270                )));
271            }
272
273            let mut page_data = [0u8; PAGE_SIZE];
274            page_data.copy_from_slice(data);
275            let page = Page::from_bytes(page_data);
276
277            // Write to pager
278            pager
279                .write_page(*page_id, page)
280                .map_err(|e| CheckpointError::Pager(e.to_string()))?;
281
282            pages_checkpointed += 1;
283        }
284
285        // Phase 6: Sync Pager to disk
286        pager
287            .sync()
288            .map_err(|e| CheckpointError::Pager(e.to_string()))?;
289
290        // Phase 7 (COMPLETE): Clear in-progress flag and update checkpoint LSN
291        if !latest_writes.is_empty() {
292            pager
293                .complete_checkpoint(last_lsn)
294                .map_err(|e| CheckpointError::Pager(e.to_string()))?;
295        }
296
297        // Phase 8: Truncate WAL if requested
298        let wal_truncated = matches!(
299            self.mode,
300            CheckpointMode::Restart | CheckpointMode::Truncate
301        );
302
303        if wal_truncated {
304            let mut wal_writer = WalWriter::open(wal_path)?;
305            wal_writer.truncate()?;
306
307            // Write checkpoint marker with current LSN
308            let checkpoint_record = WalRecord::Checkpoint { lsn: last_lsn };
309            wal_writer.append(&checkpoint_record)?;
310            wal_writer.sync()?;
311        }
312
313        Ok(CheckpointResult {
314            transactions_processed: committed_txs.len() as u64,
315            max_transaction_id,
316            pages_checkpointed,
317            records_processed,
318            checkpoint_lsn: last_lsn,
319            wal_truncated,
320        })
321    }
322
323    /// Perform crash recovery
324    ///
325    /// Called on database open to apply any committed transactions from the WAL
326    /// that weren't checkpointed before the crash. If a checkpoint was interrupted
327    /// (checkpoint_in_progress flag set), re-applies all WAL records from scratch.
328    ///
329    /// # Arguments
330    ///
331    /// * `pager` - The Pager to recover into
332    /// * `wal_path` - Path to the WAL file
333    ///
334    /// # Returns
335    ///
336    /// Recovery statistics or error
337    pub fn recover(pager: &Pager, wal_path: &Path) -> Result<CheckpointResult, CheckpointError> {
338        // Check if a checkpoint was interrupted
339        if let Ok(header) = pager.header() {
340            if header.checkpoint_in_progress {
341                // Previous checkpoint was interrupted — re-apply everything from WAL
342                // This is safe because page writes are idempotent (last-write-wins)
343                let _ = pager.set_checkpoint_in_progress(false, 0);
344            }
345        }
346        let checkpointer = Self::new(CheckpointMode::Truncate);
347        checkpointer.checkpoint(pager, wal_path)
348    }
349}
350
351#[cfg(test)]
352mod tests {
353    use super::*;
354    use crate::storage::engine::{PageType, HEADER_SIZE};
355    use std::fs;
356    use std::time::{SystemTime, UNIX_EPOCH};
357
358    fn temp_dir() -> std::path::PathBuf {
359        let timestamp = SystemTime::now()
360            .duration_since(UNIX_EPOCH)
361            .unwrap()
362            .as_nanos();
363        std::env::temp_dir().join(format!("reddb_checkpoint_test_{}", timestamp))
364    }
365
366    fn cleanup(dir: &Path) {
367        let _ = fs::remove_dir_all(dir);
368    }
369
370    fn temp_wal_path(dir: &Path, name: &str) -> std::path::PathBuf {
371        reddb_file::layout::wal_component_temp_path(dir, "checkpoint", name, std::process::id())
372    }
373
374    fn page_image(page_id: u32, marker: u8) -> Vec<u8> {
375        let mut page = Page::new(PageType::BTreeLeaf, page_id);
376        page.as_bytes_mut()[HEADER_SIZE] = marker;
377        page.as_bytes().to_vec()
378    }
379
380    #[test]
381    fn test_checkpoint_empty_wal() {
382        let dir = temp_dir();
383        let _ = fs::create_dir_all(&dir);
384        let db_path = dir.join("test.db");
385        let wal_path = temp_wal_path(&dir, "empty");
386
387        // Create pager
388        let pager = Pager::open_default(&db_path).unwrap();
389
390        // No WAL file - should succeed with empty result
391        let checkpointer = Checkpointer::default_mode();
392        let result = checkpointer.checkpoint(&pager, &wal_path).unwrap();
393
394        assert_eq!(result.transactions_processed, 0);
395        assert_eq!(result.pages_checkpointed, 0);
396
397        cleanup(&dir);
398    }
399
400    #[test]
401    fn test_checkpoint_committed_transaction() {
402        let dir = temp_dir();
403        let _ = fs::create_dir_all(&dir);
404        let db_path = dir.join("test.db");
405        let wal_path = temp_wal_path(&dir, "committed");
406
407        // Create pager
408        let pager = Pager::open_default(&db_path).unwrap();
409
410        // Allocate a page to get its ID
411        let page = pager.allocate_page(PageType::BTreeLeaf).unwrap();
412        let page_id = page.page_id();
413
414        // Create WAL with a committed transaction
415        {
416            let mut wal_writer = WalWriter::open(&wal_path).unwrap();
417
418            // Begin transaction
419            wal_writer.append(&WalRecord::Begin { tx_id: 1 }).unwrap();
420
421            // Write a page
422            wal_writer
423                .append(&WalRecord::PageWrite {
424                    tx_id: 1,
425                    page_id,
426                    data: page_image(page_id, 0x42),
427                })
428                .unwrap();
429
430            // Commit transaction
431            wal_writer.append(&WalRecord::Commit { tx_id: 1 }).unwrap();
432
433            wal_writer.sync().unwrap();
434        }
435
436        // Checkpoint
437        let checkpointer = Checkpointer::new(CheckpointMode::Full);
438        let result = checkpointer.checkpoint(&pager, &wal_path).unwrap();
439
440        assert_eq!(result.transactions_processed, 1);
441        assert_eq!(result.pages_checkpointed, 1);
442        assert_eq!(result.records_processed, 3);
443
444        // Verify page was written
445        let read_page = pager.read_page(page_id).unwrap();
446        assert_eq!(read_page.as_bytes()[HEADER_SIZE], 0x42);
447
448        cleanup(&dir);
449    }
450
451    #[test]
452    fn test_checkpoint_aborted_transaction() {
453        let dir = temp_dir();
454        let _ = fs::create_dir_all(&dir);
455        let db_path = dir.join("test.db");
456        let wal_path = temp_wal_path(&dir, "aborted");
457
458        // Create pager
459        let pager = Pager::open_default(&db_path).unwrap();
460
461        // Allocate a page to get its ID
462        let page = pager.allocate_page(PageType::BTreeLeaf).unwrap();
463        let page_id = page.page_id();
464
465        // Create WAL with an aborted transaction
466        {
467            let mut wal_writer = WalWriter::open(&wal_path).unwrap();
468
469            // Begin transaction
470            wal_writer.append(&WalRecord::Begin { tx_id: 1 }).unwrap();
471
472            // Write a page
473            wal_writer
474                .append(&WalRecord::PageWrite {
475                    tx_id: 1,
476                    page_id,
477                    data: page_image(page_id, 0x42),
478                })
479                .unwrap();
480
481            // Rollback transaction
482            wal_writer
483                .append(&WalRecord::Rollback { tx_id: 1 })
484                .unwrap();
485
486            wal_writer.sync().unwrap();
487        }
488
489        // Checkpoint
490        let checkpointer = Checkpointer::new(CheckpointMode::Full);
491        let result = checkpointer.checkpoint(&pager, &wal_path).unwrap();
492
493        // Aborted transaction should not be checkpointed
494        assert_eq!(result.transactions_processed, 0);
495        assert_eq!(result.pages_checkpointed, 0);
496
497        // Verify page was NOT written (should still be zeros)
498        let read_page = pager.read_page(page_id).unwrap();
499        assert_ne!(read_page.as_bytes()[HEADER_SIZE], 0x42);
500
501        cleanup(&dir);
502    }
503
504    #[test]
505    fn test_checkpoint_mixed_transactions() {
506        let dir = temp_dir();
507        let _ = fs::create_dir_all(&dir);
508        let db_path = dir.join("test.db");
509        let wal_path = temp_wal_path(&dir, "truncate");
510
511        // Create pager
512        let pager = Pager::open_default(&db_path).unwrap();
513
514        // Allocate pages
515        let page1 = pager.allocate_page(PageType::BTreeLeaf).unwrap();
516        let page2 = pager.allocate_page(PageType::BTreeLeaf).unwrap();
517        let page1_id = page1.page_id();
518        let page2_id = page2.page_id();
519
520        // Create WAL with mixed transactions
521        {
522            let mut wal_writer = WalWriter::open(&wal_path).unwrap();
523
524            // Transaction 1: Committed
525            wal_writer.append(&WalRecord::Begin { tx_id: 1 }).unwrap();
526            wal_writer
527                .append(&WalRecord::PageWrite {
528                    tx_id: 1,
529                    page_id: page1_id,
530                    data: page_image(page1_id, 0x11),
531                })
532                .unwrap();
533            wal_writer.append(&WalRecord::Commit { tx_id: 1 }).unwrap();
534
535            // Transaction 2: Aborted
536            wal_writer.append(&WalRecord::Begin { tx_id: 2 }).unwrap();
537            wal_writer
538                .append(&WalRecord::PageWrite {
539                    tx_id: 2,
540                    page_id: page2_id,
541                    data: page_image(page2_id, 0x22),
542                })
543                .unwrap();
544            wal_writer
545                .append(&WalRecord::Rollback { tx_id: 2 })
546                .unwrap();
547
548            // Transaction 3: Committed
549            wal_writer.append(&WalRecord::Begin { tx_id: 3 }).unwrap();
550            wal_writer
551                .append(&WalRecord::PageWrite {
552                    tx_id: 3,
553                    page_id: page2_id,
554                    data: page_image(page2_id, 0x33),
555                })
556                .unwrap();
557            wal_writer.append(&WalRecord::Commit { tx_id: 3 }).unwrap();
558
559            wal_writer.sync().unwrap();
560        }
561
562        // Checkpoint
563        let checkpointer = Checkpointer::new(CheckpointMode::Full);
564        let result = checkpointer.checkpoint(&pager, &wal_path).unwrap();
565
566        // Only committed transactions (1 and 3) should be processed
567        assert_eq!(result.transactions_processed, 2);
568        assert_eq!(result.max_transaction_id, 3);
569        assert_eq!(result.pages_checkpointed, 2);
570
571        // Verify pages
572        let read_page1 = pager.read_page(page1_id).unwrap();
573        assert_eq!(read_page1.as_bytes()[HEADER_SIZE], 0x11);
574
575        let read_page2 = pager.read_page(page2_id).unwrap();
576        assert_eq!(read_page2.as_bytes()[HEADER_SIZE], 0x33); // From tx 3, not tx 2
577
578        cleanup(&dir);
579    }
580
581    #[test]
582    fn test_checkpoint_truncate() {
583        let dir = temp_dir();
584        let _ = fs::create_dir_all(&dir);
585        let db_path = dir.join("test.db");
586        let wal_path = temp_wal_path(&dir, "full-page-images");
587
588        // Create pager
589        let pager = Pager::open_default(&db_path).unwrap();
590
591        // Create WAL with a committed transaction
592        {
593            let mut wal_writer = WalWriter::open(&wal_path).unwrap();
594            wal_writer.append(&WalRecord::Begin { tx_id: 1 }).unwrap();
595            wal_writer.append(&WalRecord::Commit { tx_id: 1 }).unwrap();
596            wal_writer.sync().unwrap();
597        }
598
599        // Checkpoint with truncate
600        let checkpointer = Checkpointer::new(CheckpointMode::Truncate);
601        let result = checkpointer.checkpoint(&pager, &wal_path).unwrap();
602
603        assert!(result.wal_truncated);
604
605        let records: Vec<_> = WalReader::open(&wal_path)
606            .unwrap()
607            .iter()
608            .collect::<Result<Vec<_>, _>>()
609            .unwrap();
610        assert_eq!(records.len(), 1);
611        assert_eq!(
612            records[0].1,
613            WalRecord::Checkpoint {
614                lsn: result.checkpoint_lsn
615            }
616        );
617
618        cleanup(&dir);
619    }
620}