Skip to main content

reddb_server/storage/engine/pager/
impl.rs

1use super::*;
2
3pub(super) const BTRFS_SUPER_MAGIC: i64 = 0x9123_683e;
4pub(super) const ZFS_SUPER_MAGIC: i64 = 0x2fc1_2fc1;
5pub(super) const FS_NOCOW_FL: u64 = 0x0080_0000;
6
7/// The superblock zone occupies the head of page 0 (ADR 0038 §2 phase 1).
8pub(super) const SUPERBLOCK_SLOT_SIZE: usize = reddb_file::PAGED_SUPERBLOCK_SLOT_SIZE;
9pub(super) const SUPERBLOCK_ZONE_SIZE: usize = reddb_file::PAGED_SUPERBLOCK_ZONE_SIZE;
10pub(super) const PHASE3_DWB_ZONE_FILE_VERSION: u32 = reddb_file::PAGE_FILE_VERSION;
11
12/// The newest valid superblock copy together with its slot image.
13type NewestSuperblock = (
14    reddb_file::PagedSuperblockSelection,
15    [u8; SUPERBLOCK_SLOT_SIZE],
16);
17
18/// Take the first slot's worth of a freshly-built page-0 image. The database
19/// header and the encryption header both live well inside this prefix.
20fn superblock_slot_image(page: &[u8; PAGE_SIZE]) -> [u8; SUPERBLOCK_SLOT_SIZE] {
21    let mut image = [0u8; SUPERBLOCK_SLOT_SIZE];
22    image.copy_from_slice(&page[..SUPERBLOCK_SLOT_SIZE]);
23    image
24}
25
26#[derive(Debug, Clone, Copy, PartialEq, Eq)]
27pub(super) enum CowFilesystemKind {
28    Zfs,
29    BtrfsDataCow,
30    TestOverride,
31}
32
33pub(super) fn classify_cow_filesystem(
34    fs_type: i64,
35    mount_options: Option<&str>,
36    inode_flags: Option<u64>,
37) -> Option<CowFilesystemKind> {
38    match fs_type {
39        ZFS_SUPER_MAGIC => Some(CowFilesystemKind::Zfs),
40        BTRFS_SUPER_MAGIC => {
41            let mount_options = mount_options?;
42            if mount_options.split(',').any(|option| option == "nodatacow") {
43                return None;
44            }
45
46            let inode_flags = inode_flags?;
47            if inode_flags & FS_NOCOW_FL != 0 {
48                return None;
49            }
50
51            Some(CowFilesystemKind::BtrfsDataCow)
52        }
53        _ => None,
54    }
55}
56
57#[cfg(target_os = "linux")]
58fn linux_fstatfs_type(file: &File) -> Option<i64> {
59    use std::mem::MaybeUninit;
60    use std::os::fd::AsRawFd;
61
62    let mut stat = MaybeUninit::<libc::statfs>::uninit();
63    let rc = unsafe { libc::fstatfs(file.as_raw_fd(), stat.as_mut_ptr()) };
64    if rc != 0 {
65        return None;
66    }
67    let stat = unsafe { stat.assume_init() };
68    // `statfs.f_type` is i32 on 32-bit glibc targets (armv7) and i64 on
69    // 64-bit ones — widen explicitly so both compile.
70    #[allow(clippy::unnecessary_cast)]
71    Some(stat.f_type as i64)
72}
73
74#[cfg(target_os = "linux")]
75fn linux_inode_flags(file: &File) -> Option<u64> {
76    use std::os::fd::AsRawFd;
77
78    let mut flags: libc::c_long = 0;
79    let rc = unsafe { libc::ioctl(file.as_raw_fd(), libc::FS_IOC_GETFLAGS, &mut flags) };
80    if rc != 0 {
81        return None;
82    }
83    Some(flags as u64)
84}
85
86#[cfg(target_os = "linux")]
87fn linux_mount_options_for_path(path: &Path) -> Option<String> {
88    let path = path.canonicalize().ok()?;
89    let mountinfo = std::fs::read_to_string("/proc/self/mountinfo").ok()?;
90    parse_mountinfo_options_for_path(&mountinfo, &path)
91}
92
93#[cfg(target_os = "linux")]
94pub(super) fn parse_mountinfo_options_for_path(mountinfo: &str, path: &Path) -> Option<String> {
95    let mut best: Option<(usize, String)> = None;
96
97    for line in mountinfo.lines() {
98        let fields: Vec<&str> = line.split(' ').collect();
99        if fields.len() < 10 {
100            continue;
101        }
102
103        let Some(separator) = fields.iter().position(|field| *field == "-") else {
104            continue;
105        };
106        if separator + 3 >= fields.len() || separator < 6 {
107            continue;
108        }
109
110        let mount_point = mountinfo_unescape_path(fields[4]);
111        if !path.starts_with(&mount_point) {
112            continue;
113        }
114
115        let fs_type = fields[separator + 1];
116        if fs_type != "btrfs" && fs_type != "zfs" {
117            continue;
118        }
119
120        let mount_options = fields[5];
121        let super_options = fields[separator + 3];
122        let options = format!("{mount_options},{super_options}");
123        let depth = mount_point.components().count();
124        if best
125            .as_ref()
126            .map(|(best_depth, _)| depth > *best_depth)
127            .unwrap_or(true)
128        {
129            best = Some((depth, options));
130        }
131    }
132
133    best.map(|(_, options)| options)
134}
135
136#[cfg(target_os = "linux")]
137fn mountinfo_unescape_path(value: &str) -> PathBuf {
138    let bytes = value.as_bytes();
139    let mut out = Vec::with_capacity(bytes.len());
140    let mut i = 0;
141
142    while i < bytes.len() {
143        if bytes[i] == b'\\' && i + 3 < bytes.len() {
144            let octal = &value[i + 1..i + 4];
145            if let Ok(byte) = u8::from_str_radix(octal, 8) {
146                out.push(byte);
147                i += 4;
148                continue;
149            }
150        }
151        out.push(bytes[i]);
152        i += 1;
153    }
154
155    PathBuf::from(String::from_utf8_lossy(&out).into_owned())
156}
157
158impl Pager {
159    /// Open or create a database file
160    pub fn open<P: AsRef<Path>>(path: P, mut config: PagerConfig) -> Result<Self, PagerError> {
161        let path = path.as_ref().to_path_buf();
162        let exists = path.exists();
163
164        if !exists && !config.create {
165            return Err(PagerError::InvalidDatabase(
166                "Database does not exist".into(),
167            ));
168        }
169
170        // ADR 0038 §4 phase 1 is a clean break: a store still carrying the
171        // retired `rdb-hdr`/`rdb-meta` sidecars is never read by the engine.
172        // The offline migration tool is the only path forward.
173        if exists {
174            if let Some(sidecar) = reddb_file::layout::retired::first_present_phase1_sidecar(&path)
175            {
176                return Err(PagerError::LegacySidecarStore { sidecar });
177            }
178        }
179
180        if !exists && config.read_only {
181            return Err(PagerError::InvalidDatabase(
182                "Cannot create read-only database".into(),
183            ));
184        }
185
186        // Open file
187        // Note: create requires write access, so disable it for read-only mode
188        let file = OpenOptions::new()
189            .read(true)
190            .write(!config.read_only)
191            .create(config.create && !config.read_only)
192            .open(&path)?;
193
194        // gh-892: diagnostic probe of the filesystem block size. If the
195        // compile-time 16 KiB PAGE_SIZE is not a multiple of the FS block
196        // size, page writes straddle FS blocks and incur read-modify-write
197        // amplification. Pure diagnostic — emitted once per open, never
198        // mutates the page size. `blksize()` is the fstat `st_blksize`.
199        #[cfg(unix)]
200        {
201            use std::os::unix::fs::MetadataExt;
202            if let Ok(meta) = file.metadata() {
203                let fs_block_size = meta.blksize();
204                if Self::page_size_misaligned_with_block(PAGE_SIZE, fs_block_size) {
205                    tracing::warn!(
206                        page_size = PAGE_SIZE,
207                        fs_block_size,
208                        path = %path.display(),
209                        "database page size is not a multiple of the filesystem \
210                         block size; page writes will straddle FS blocks \
211                         (read-modify-write amplification). Diagnostic only — \
212                         the page size is unchanged."
213                    );
214                }
215            }
216        }
217
218        // Acquire file lock (exclusive for writes, shared for read-only)
219        let lock_file = if !config.read_only {
220            let lf = OpenOptions::new().read(true).write(true).open(&path)?;
221            lf.try_lock_exclusive().map_err(|_| PagerError::Locked)?;
222            Some(lf)
223        } else {
224            let lf = OpenOptions::new().read(true).open(&path)?;
225            match lf.try_lock_shared() {
226                Ok(_) => Some(lf),
227                Err(_) => None,
228            }
229        };
230
231        // ADR 0038 phase 3: the DWB sidecar is retired. When DWB is active,
232        // the recovery frame is written to a reserved zone inside the data
233        // file and fsynced before in-place page writes. A pre-existing sidecar
234        // marks a legacy store that must go through the offline migration tool.
235        //
236        // gh-895: an explicit `double_write = false` request is honored only
237        // when the already-open data file is proven to live on a filesystem
238        // with atomic CoW page writes. Unknown and non-CoW filesystems fail
239        // closed by keeping the in-file DWB zone enabled.
240        let fold_dwb = crate::physical::fold_dwb_into_wal_enabled();
241        if exists {
242            if let Some(sidecar) =
243                reddb_file::layout::retired::first_present_phase3_dwb_sidecar(&path)
244            {
245                return Err(PagerError::LegacySidecarStore { sidecar });
246            }
247        }
248        if !config.double_write && !config.read_only && !fold_dwb {
249            let skip_dwb_on_cow =
250                Self::cow_filesystem_has_atomic_page_writes(&path, &file).is_some();
251            if !skip_dwb_on_cow {
252                tracing::warn!(
253                    path = %path.display(),
254                    "double_write=false requested, but the data file is not proven to be on \
255                     ZFS or btrfs datacow; keeping the in-file double-write buffer enabled"
256                );
257                config.double_write = true;
258            }
259        }
260        let dwb_enabled = config.double_write && !config.read_only && !fold_dwb;
261
262        let mut pager = Self {
263            path,
264            file: Mutex::new(file),
265            _lock_file: lock_file,
266            dwb_enabled,
267            cache: PageCache::new(config.cache_size),
268            freelist: RwLock::new(FreeList::new()),
269            header: RwLock::new(DatabaseHeader::default()),
270            config,
271            header_dirty: Mutex::new(false),
272            wal: RwLock::new(None),
273            encryption: None,
274        };
275
276        if exists {
277            // Recover from the in-file double-write zone before loading the
278            // header or allowing WAL replay to read pages.
279            pager.ensure_phase3_dwb_zone_layout()?;
280            pager.recover_from_dwb()?;
281            // Load existing database (with header shadow fallback)
282            pager.load_header()?;
283            pager.bind_encryption_for_existing()?;
284        } else {
285            // Initialize new database
286            pager.initialize()?;
287            pager.bind_encryption_for_new()?;
288        }
289
290        Ok(pager)
291    }
292
293    /// gh-892 diagnostic predicate: returns `true` when the database
294    /// `page_size` is **not** an integer multiple of the filesystem's
295    /// reported block size (`st_blksize`), i.e. `page_size % fs_block_size
296    /// != 0`. A `fs_block_size` of `0` (probe unavailable / unknown) is
297    /// treated as aligned so a missing probe never produces a warning.
298    /// Pure function with no I/O so the warn decision is unit-testable.
299    pub(crate) fn page_size_misaligned_with_block(page_size: usize, fs_block_size: u64) -> bool {
300        fs_block_size != 0 && !(page_size as u64).is_multiple_of(fs_block_size)
301    }
302
303    #[cfg(test)]
304    fn cow_filesystem_test_override() -> Option<bool> {
305        match COW_ATOMIC_WRITE_TEST_OVERRIDE.load(Ordering::Relaxed) {
306            1 => Some(true),
307            2 => Some(false),
308            _ => None,
309        }
310    }
311
312    #[cfg(not(test))]
313    fn cow_filesystem_test_override() -> Option<bool> {
314        None
315    }
316
317    fn cow_filesystem_has_atomic_page_writes(
318        path: &Path,
319        file: &File,
320    ) -> Option<CowFilesystemKind> {
321        if let Some(allowed) = Self::cow_filesystem_test_override() {
322            return allowed.then_some(CowFilesystemKind::TestOverride);
323        }
324        Self::probe_cow_filesystem(path, file)
325    }
326
327    #[cfg(target_os = "linux")]
328    fn probe_cow_filesystem(path: &Path, file: &File) -> Option<CowFilesystemKind> {
329        let fs_type = linux_fstatfs_type(file)?;
330        match fs_type {
331            ZFS_SUPER_MAGIC => Some(CowFilesystemKind::Zfs),
332            BTRFS_SUPER_MAGIC => {
333                let mount_options = linux_mount_options_for_path(path)?;
334                let inode_flags = linux_inode_flags(file)?;
335                classify_cow_filesystem(fs_type, Some(&mount_options), Some(inode_flags))
336            }
337            _ => None,
338        }
339    }
340
341    #[cfg(not(target_os = "linux"))]
342    fn probe_cow_filesystem(_path: &Path, _file: &File) -> Option<CowFilesystemKind> {
343        None
344    }
345
346    /// Inspect page 0 for the `RDBE` encryption marker, then resolve
347    /// the (key, marker) matrix:
348    ///
349    /// | Marker | Key supplied | Result                              |
350    /// |--------|--------------|-------------------------------------|
351    /// | yes    | yes          | Bind encryptor; validate key        |
352    /// | yes    | no           | `EncryptionRequired` (fail closed)  |
353    /// | no     | yes          | `PlainDatabaseRefusesKey`           |
354    /// | no     | no           | Plain pager — no binding needed     |
355    fn bind_encryption_for_existing(&mut self) -> Result<(), PagerError> {
356        if self.page_count().unwrap_or(0) == 0 {
357            return self.bind_encryption_for_new();
358        }
359        let (_, image) = self.newest_superblock()?;
360        let data = &image[..];
361        let has_marker = reddb_file::paged_encryption_marker_present(data);
362
363        let key = self.config.encryption.clone();
364        match (has_marker, key) {
365            (true, Some(key)) => {
366                let header_bytes =
367                    reddb_file::paged_encryption_header_bytes(data).ok_or_else(|| {
368                        PagerError::InvalidDatabase("encryption header parse failed".to_string())
369                    })?;
370                let header = crate::storage::encryption::EncryptionHeader::from_bytes(header_bytes)
371                    .map_err(|e| {
372                        PagerError::InvalidDatabase(format!("encryption header parse failed: {e}"))
373                    })?;
374                if !header.validate(&key) {
375                    return Err(PagerError::InvalidKey);
376                }
377                let encryptor = crate::storage::encryption::PageEncryptor::new(key);
378                self.encryption = Some((encryptor, header));
379                Ok(())
380            }
381            (true, None) => Err(PagerError::EncryptionRequired),
382            (false, Some(_)) => Err(PagerError::PlainDatabaseRefusesKey),
383            (false, None) => Ok(()),
384        }
385    }
386
387    /// New DB: if a key is configured, write the marker + header to
388    /// page 0 so subsequent opens detect encryption.
389    fn bind_encryption_for_new(&mut self) -> Result<(), PagerError> {
390        let Some(key) = self.config.encryption.clone() else {
391            return Ok(());
392        };
393        let header = crate::storage::encryption::EncryptionHeader::new(&key);
394        let encryptor = crate::storage::encryption::PageEncryptor::new(key);
395
396        // Stamp the marker + header into the superblock zone if `initialize()`
397        // has already published it.
398        if self.page_count().unwrap_or(0) > 0 {
399            let header_bytes = header.to_bytes();
400            self.commit_superblock(|image| {
401                reddb_file::write_paged_encryption_marker_and_header(image, &header_bytes)
402                    .map_err(|err| PagerError::InvalidDatabase(err.to_string()))
403            })?;
404        }
405        self.encryption = Some((encryptor, header));
406        Ok(())
407    }
408
409    /// Open with default configuration
410    pub fn open_default<P: AsRef<Path>>(path: P) -> Result<Self, PagerError> {
411        Self::open(path, PagerConfig::default())
412    }
413
414    /// Initialize a new database
415    fn initialize(&self) -> Result<(), PagerError> {
416        if self.config.read_only {
417            return Err(PagerError::ReadOnly);
418        }
419
420        // Create header page. Page ids 1 and 2 are reserved for fixed
421        // metadata/vault pages. ADR 0038 phase 3 reserves the following DWB
422        // zone in-file so normal B-tree allocation starts after it.
423        let initial_page_count = FIRST_ALLOCATABLE_PAGE;
424        let header_page = Page::new_header_page(initial_page_count);
425        self.header_write()?.page_count = initial_page_count;
426
427        // Reserve page 0 (the superblock zone) plus the reserved pages so any
428        // scan over 0..page_count can read every allocated page in a brand-new
429        // database. The zone's own bytes are published below, one slot at a
430        // time; this first whole-page write only sizes the file.
431        self.write_page_raw(0, &header_page)?;
432        let mut metadata_page = Page::new(PageType::Header, 1);
433        metadata_page.update_checksum();
434        self.write_page_raw(1, &metadata_page)?;
435        let mut vault_page = Page::new(PageType::Vault, 2);
436        vault_page.update_checksum();
437        self.write_page_raw(2, &vault_page)?;
438        self.clear_dwb_zone()?;
439
440        // Publish both superblock copies so the ping-pong invariant — one
441        // valid copy always survives a crash — holds from the very first
442        // update onward, not just from the second.
443        let mut slot = superblock_slot_image(header_page.as_bytes());
444        self.write_superblock_slot(&mut slot, 0, 1)?;
445        self.write_superblock_slot(&mut slot, 1, 2)?;
446
447        // Sync to disk
448        self.sync()?;
449
450        Ok(())
451    }
452
453    /// Acquire a write lock on the header RwLock, mapping poison errors.
454    fn header_write(&self) -> Result<std::sync::RwLockWriteGuard<'_, DatabaseHeader>, PagerError> {
455        self.header.write().map_err(|_| PagerError::LockPoisoned)
456    }
457
458    /// Acquire a read lock on the header RwLock, mapping poison errors.
459    fn header_read(&self) -> Result<std::sync::RwLockReadGuard<'_, DatabaseHeader>, PagerError> {
460        self.header.read().map_err(|_| PagerError::LockPoisoned)
461    }
462
463    /// Acquire a write lock on the freelist RwLock, mapping poison errors.
464    fn freelist_write(&self) -> Result<std::sync::RwLockWriteGuard<'_, FreeList>, PagerError> {
465        self.freelist.write().map_err(|_| PagerError::LockPoisoned)
466    }
467
468    /// Acquire a lock on the file Mutex, mapping poison errors.
469    fn file_lock(&self) -> Result<std::sync::MutexGuard<'_, File>, PagerError> {
470        self.file.lock().map_err(|_| PagerError::LockPoisoned)
471    }
472
473    /// Acquire a lock on the header_dirty Mutex, mapping poison errors.
474    fn header_dirty_lock(&self) -> Result<std::sync::MutexGuard<'_, bool>, PagerError> {
475        self.header_dirty
476            .lock()
477            .map_err(|_| PagerError::LockPoisoned)
478    }
479
480    /// Read the whole superblock zone (both ping-pong copies) from the head of
481    /// the file. A file shorter than the zone yields zero-filled tail bytes,
482    /// which decode as "slot never written".
483    fn read_superblock_zone(&self) -> Result<[u8; SUPERBLOCK_ZONE_SIZE], PagerError> {
484        let mut file = self.file_lock()?;
485        let len = file.metadata().map(|meta| meta.len()).unwrap_or(0);
486        let mut zone = [0u8; SUPERBLOCK_ZONE_SIZE];
487        let readable = len.min(SUPERBLOCK_ZONE_SIZE as u64) as usize;
488        if readable > 0 {
489            file.seek(SeekFrom::Start(0))?;
490            file.read_exact(&mut zone[..readable])?;
491        }
492        Ok(zone)
493    }
494
495    /// The newest valid superblock copy, with its slot image.
496    ///
497    /// Both copies invalid is the one unrecoverable superblock state (ADR 0074
498    /// §2): the store does not open, and the error names the zone and points
499    /// at salvage rather than panicking or silently re-initialising.
500    fn newest_superblock(&self) -> Result<NewestSuperblock, PagerError> {
501        let zone = self.read_superblock_zone()?;
502        let selection = reddb_file::select_paged_superblock(&zone)
503            .ok_or_else(|| PagerError::SuperblockZoneUnrecoverable(self.path.clone()))?;
504
505        let start = selection.copy_index * SUPERBLOCK_SLOT_SIZE;
506        let mut image = [0u8; SUPERBLOCK_SLOT_SIZE];
507        image.copy_from_slice(&zone[start..start + SUPERBLOCK_SLOT_SIZE]);
508        Ok((selection, image))
509    }
510
511    fn ensure_phase3_dwb_zone_layout(&self) -> Result<(), PagerError> {
512        let (_, image) = self.newest_superblock()?;
513        let header = reddb_file::decode_database_header(&image)
514            .map_err(|err| PagerError::InvalidDatabase(err.to_string()))?;
515        if header.version < PHASE3_DWB_ZONE_FILE_VERSION {
516            return Err(PagerError::LegacyPagedStore {
517                path: self.path.clone(),
518            });
519        }
520        Ok(())
521    }
522
523    /// Seal `slot` for `copy_index`/`generation` and write exactly that slot,
524    /// then fsync. The caller guarantees `copy_index` is the stale copy.
525    fn write_superblock_slot(
526        &self,
527        slot: &mut [u8; SUPERBLOCK_SLOT_SIZE],
528        copy_index: usize,
529        generation: u64,
530    ) -> Result<(), PagerError> {
531        if self.config.read_only {
532            return Err(PagerError::ReadOnly);
533        }
534        reddb_file::seal_paged_superblock_slot(slot, copy_index, generation)
535            .map_err(|err| PagerError::InvalidDatabase(err.to_string()))?;
536
537        let mut file = self.file_lock()?;
538        file.seek(SeekFrom::Start(reddb_file::paged_superblock_slot_offset(
539            copy_index,
540        )))?;
541        file.write_all(slot)?;
542        file.sync_all()?;
543        Ok(())
544    }
545
546    /// Publish `mutate`'s edit of the newest slot image into the *stale* copy.
547    ///
548    /// Reading the newest image first means every byte the pager does not
549    /// explicitly rewrite — most importantly the encryption marker and header —
550    /// carries forward untouched.
551    fn commit_superblock(
552        &self,
553        mutate: impl FnOnce(&mut [u8; SUPERBLOCK_SLOT_SIZE]) -> Result<(), PagerError>,
554    ) -> Result<(), PagerError> {
555        if self.config.read_only {
556            return Err(PagerError::ReadOnly);
557        }
558        let (newest, mut image) = self.newest_superblock()?;
559        mutate(&mut image)?;
560        let next_copy = reddb_file::paged_superblock_next_copy(Some(newest));
561        self.write_superblock_slot(&mut image, next_copy, newest.generation.saturating_add(1))
562    }
563
564    /// Load the database header from the newest valid superblock copy.
565    fn load_header(&self) -> Result<(), PagerError> {
566        let (_, image) = self.newest_superblock()?;
567
568        let decoded_header = reddb_file::decode_database_header(&image)
569            .map_err(|err| PagerError::InvalidDatabase(err.to_string()))?;
570        let freelist_head = decoded_header.freelist_head;
571
572        {
573            let mut header = self.header_write()?;
574            *header = decoded_header;
575        }
576
577        // Initialize freelist
578        {
579            let mut freelist = self.freelist_write()?;
580            *freelist = FreeList::from_header(freelist_head, 0);
581        }
582
583        Ok(())
584    }
585
586    /// Publish the in-memory database header as a new superblock generation.
587    fn write_header(&self) -> Result<(), PagerError> {
588        if self.config.read_only {
589            return Err(PagerError::ReadOnly);
590        }
591
592        let header = self.header_read()?.clone();
593        self.commit_superblock(|image| {
594            reddb_file::encode_database_header(image, &header)
595                .map_err(|err| PagerError::InvalidDatabase(err.to_string()))
596        })?;
597        *self.header_dirty_lock()? = false;
598
599        Ok(())
600    }
601
602    /// Read a page from disk (bypassing cache)
603    fn read_page_raw(&self, page_id: u32) -> Result<Page, PagerError> {
604        let mut file = self.file_lock()?;
605        let offset = (page_id as u64) * (PAGE_SIZE as u64);
606
607        file.seek(SeekFrom::Start(offset))?;
608
609        let mut buf = [0u8; PAGE_SIZE];
610        file.read_exact(&mut buf)?;
611
612        let page = Page::from_bytes(buf);
613
614        // Page 0 is the superblock zone, not a checksummed page: its two slots
615        // are sealed independently, so no whole-page checksum can hold across
616        // a ping-pong write. Slot CRCs are its integrity contract.
617        if self.config.verify_checksums && page_id != 0 {
618            page.verify_checksum()?;
619        }
620
621        Ok(page)
622    }
623
624    /// Write a page to disk (bypassing cache)
625    fn write_page_raw(&self, page_id: u32, page: &Page) -> Result<(), PagerError> {
626        if self.config.read_only {
627            return Err(PagerError::ReadOnly);
628        }
629
630        let mut file = self.file_lock()?;
631        let offset = (page_id as u64) * (PAGE_SIZE as u64);
632
633        file.seek(SeekFrom::Start(offset))?;
634        file.write_all(page.as_bytes())?;
635
636        Ok(())
637    }
638
639    /// Read a page (cache-aware)
640    pub fn read_page(&self, page_id: u32) -> Result<Page, PagerError> {
641        // Check cache first
642        if let Some(page) = self.cache.get(page_id) {
643            return Ok(page);
644        }
645
646        // Cache miss - read from disk
647        let page = self.read_page_raw(page_id)?;
648
649        // Add to cache
650        if let Some(dirty_page) = self.cache.insert(page_id, page.clone()) {
651            // Evicted page was dirty, need to write it back
652            let evicted_id = dirty_page.page_id();
653            self.write_page_raw(evicted_id, &dirty_page)?;
654        }
655
656        Ok(page)
657    }
658
659    /// Read a page without verifying checksum (for encrypted pages)
660    ///
661    /// Use this when the page content has its own integrity protection
662    /// (e.g., AES-GCM authentication tag for encrypted pages).
663    pub fn read_page_no_checksum(&self, page_id: u32) -> Result<Page, PagerError> {
664        // Check cache first
665        if let Some(page) = self.cache.get(page_id) {
666            return Ok(page);
667        }
668
669        // Cache miss - read from disk (skip checksum verification)
670        let mut file = self.file_lock()?;
671        let offset = (page_id as u64) * (PAGE_SIZE as u64);
672
673        file.seek(SeekFrom::Start(offset))?;
674
675        let mut buf = [0u8; PAGE_SIZE];
676        file.read_exact(&mut buf)?;
677        drop(file);
678
679        let page = Page::from_bytes(buf);
680
681        // Add to cache (no checksum verification)
682        if let Some(dirty_page) = self.cache.insert(page_id, page.clone()) {
683            // Evicted page was dirty, need to write it back
684            let evicted_id = dirty_page.page_id();
685            self.write_page_raw(evicted_id, &dirty_page)?;
686        }
687
688        Ok(page)
689    }
690
691    /// Write a page (cache-aware)
692    pub fn write_page(&self, page_id: u32, mut page: Page) -> Result<(), PagerError> {
693        if self.config.read_only {
694            return Err(PagerError::ReadOnly);
695        }
696
697        // Update checksum
698        page.update_checksum();
699
700        // Add to cache and mark dirty. If the cache had to evict a
701        // dirty entry, write it through immediately — the evicted
702        // page will never be flushed otherwise (same bug fixed in
703        // `allocate_page`).
704        if let Some(dirty_page) = self.cache.insert(page_id, page) {
705            let evicted_id = dirty_page.page_id();
706            self.write_page_raw(evicted_id, &dirty_page)?;
707        }
708        self.cache.mark_dirty(page_id);
709
710        Ok(())
711    }
712
713    /// Read a page through the configured encryptor if any. Page 0
714    /// is always returned plaintext (it carries the encryption marker
715    /// + header). Callers that want raw cipher bytes can use
716    ///   `read_page_no_checksum` directly.
717    pub fn read_page_decrypted(&self, page_id: u32) -> Result<Page, PagerError> {
718        if page_id == 0 || self.encryption.is_none() {
719            return self.read_page(page_id);
720        }
721        let raw = self.read_page_no_checksum(page_id)?;
722        let (enc, _) = self
723            .encryption
724            .as_ref()
725            .expect("encryption presence checked above");
726        let plaintext = enc
727            .decrypt(page_id, raw.as_bytes())
728            .map_err(|e| PagerError::InvalidDatabase(format!("decrypt page {page_id}: {e}")))?;
729        let mut buf = [0u8; PAGE_SIZE];
730        let n = plaintext.len().min(PAGE_SIZE);
731        buf[..n].copy_from_slice(&plaintext[..n]);
732        Ok(Page::from_bytes(buf))
733    }
734
735    /// Write a page through the configured encryptor if any. Page 0
736    /// bypasses encryption and goes through the normal checksummed
737    /// path. Encrypted pages skip the checksum update because
738    /// AES-GCM's authentication tag is the integrity guarantee.
739    pub fn write_page_encrypted(&self, page_id: u32, page: Page) -> Result<(), PagerError> {
740        if page_id == 0 || self.encryption.is_none() {
741            return self.write_page(page_id, page);
742        }
743        // Canonical per-page envelope overhead (nonce + GCM tag),
744        // owned by reddb-io-crypto (#1053, ADR 0054).
745        const OVERHEAD: usize = crate::storage::encryption::page_encryptor::OVERHEAD;
746        let plaintext_len = PAGE_SIZE - OVERHEAD;
747        let plaintext = &page.as_bytes()[..plaintext_len];
748        let (enc, _) = self
749            .encryption
750            .as_ref()
751            .expect("encryption presence checked above");
752        let ciphertext = enc.encrypt(page_id, plaintext);
753        debug_assert_eq!(ciphertext.len(), PAGE_SIZE);
754        let mut buf = [0u8; PAGE_SIZE];
755        buf.copy_from_slice(&ciphertext);
756        let cipher_page = Page::from_bytes(buf);
757        self.write_page_no_checksum(page_id, cipher_page)
758    }
759
760    /// Write a page without updating checksum (for encrypted pages)
761    ///
762    /// Use this when the page content has its own integrity protection
763    /// (e.g., AES-GCM authentication tag for encrypted pages).
764    pub fn write_page_no_checksum(&self, page_id: u32, page: Page) -> Result<(), PagerError> {
765        if self.config.read_only {
766            return Err(PagerError::ReadOnly);
767        }
768
769        // Add to cache and mark dirty (no checksum update). Same
770        // eviction-write-through guard as `write_page`.
771        if let Some(dirty_page) = self.cache.insert(page_id, page) {
772            let evicted_id = dirty_page.page_id();
773            self.write_page_raw(evicted_id, &dirty_page)?;
774        }
775        self.cache.mark_dirty(page_id);
776
777        Ok(())
778    }
779
780    /// Allocate a new page
781    pub fn allocate_page(&self, page_type: PageType) -> Result<Page, PagerError> {
782        if self.config.read_only {
783            return Err(PagerError::ReadOnly);
784        }
785
786        // Try to get from freelist first
787        let page_id = {
788            let mut freelist = self.freelist_write()?;
789            if let Some(id) = freelist.allocate() {
790                id
791            } else if freelist.trunk_head() != 0 {
792                let trunk_id = freelist.trunk_head();
793                drop(freelist);
794
795                let trunk = self.read_page(trunk_id).map_err(|e| match e {
796                    PagerError::PageNotFound(_) => {
797                        PagerError::InvalidDatabase("Freelist trunk missing".to_string())
798                    }
799                    other => other,
800                })?;
801
802                let mut freelist = self.freelist_write()?;
803                freelist
804                    .load_from_trunk(&trunk)
805                    .map_err(|e| PagerError::InvalidDatabase(format!("Freelist: {}", e)))?;
806                let id = freelist.allocate().ok_or_else(|| {
807                    PagerError::InvalidDatabase("Freelist empty after trunk load".to_string())
808                })?;
809
810                let mut header = self.header_write()?;
811                header.freelist_head = freelist.trunk_head();
812                *self.header_dirty_lock()? = true;
813
814                id
815            } else {
816                // No free pages, extend file
817                let mut header = self.header_write()?;
818                let id = header.page_count;
819                header.page_count += 1;
820                *self.header_dirty_lock()? = true;
821                id
822            }
823        };
824
825        let page = Page::new(page_type, page_id);
826
827        // Write to cache. The evicted page (if any) is dirty by
828        // definition — `cache.insert` only returns `Some` when it
829        // had to evict a dirty entry to make room. The previous
830        // version dropped that return value, which silently lost
831        // writes whenever a freshly-allocated page caused an LRU
832        // eviction. This shows up under heavy ingest as
833        // "B-tree insert error: Pager error: I/O error: failed to
834        // fill whole buffer" later, when something tries to read
835        // back the never-flushed page. Mirror `read_page`'s
836        // handling: write the evicted page through immediately so
837        // the on-disk image stays consistent.
838        if let Some(dirty_page) = self.cache.insert(page_id, page.clone()) {
839            let evicted_id = dirty_page.page_id();
840            self.write_page_raw(evicted_id, &dirty_page)?;
841        }
842        self.cache.mark_dirty(page_id);
843
844        Ok(page)
845    }
846
847    /// Reserve a contiguous extent of vector pages.
848    pub fn reserve_contig_extent(&self, n_pages: u32) -> Result<super::ExtentId, PagerError> {
849        if self.config.read_only {
850            return Err(PagerError::ReadOnly);
851        }
852        if n_pages == 0 {
853            return Err(PagerError::InvalidDatabase(
854                "contiguous extent must reserve at least one page".to_string(),
855            ));
856        }
857
858        let start_page = {
859            let mut header = self.header_write()?;
860            let start = header.page_count;
861            header.page_count = header.page_count.checked_add(n_pages).ok_or_else(|| {
862                PagerError::InvalidDatabase("contiguous extent page count overflow".to_string())
863            })?;
864            *self.header_dirty_lock()? = true;
865            start
866        };
867
868        for page_id in start_page..start_page + n_pages {
869            let mut page = Page::new(PageType::Vector, page_id);
870            page.update_checksum();
871            if let Some(dirty_page) = self.cache.insert(page_id, page) {
872                let evicted_id = dirty_page.page_id();
873                self.write_page_raw(evicted_id, &dirty_page)?;
874            }
875            self.cache.mark_dirty(page_id);
876        }
877
878        Ok(super::ExtentId {
879            start_page,
880            n_pages,
881        })
882    }
883
884    /// Free a page (return to freelist)
885    pub fn free_page(&self, page_id: u32) -> Result<(), PagerError> {
886        if self.config.read_only {
887            return Err(PagerError::ReadOnly);
888        }
889
890        // Remove from cache
891        self.cache.remove(page_id);
892
893        // Add to freelist
894        let mut freelist = self.freelist_write()?;
895        freelist.free(page_id);
896
897        *self.header_dirty_lock()? = true;
898
899        Ok(())
900    }
901
902    /// Get database header
903    pub fn header(&self) -> Result<DatabaseHeader, PagerError> {
904        Ok(self.header_read()?.clone())
905    }
906
907    pub fn physical_header(&self) -> Result<PhysicalFileHeader, PagerError> {
908        Ok(self.header_read()?.physical)
909    }
910
911    pub fn update_physical_header(&self, physical: PhysicalFileHeader) -> Result<(), PagerError> {
912        if self.config.read_only {
913            return Err(PagerError::ReadOnly);
914        }
915
916        let mut header = self.header_write()?;
917        header.physical = physical;
918        *self.header_dirty_lock()? = true;
919        Ok(())
920    }
921
922    /// Get page count
923    pub fn page_count(&self) -> Result<u32, PagerError> {
924        Ok(self.header_read()?.page_count)
925    }
926
927    /// Attach a WAL writer to enforce WAL-first flush ordering.
928    ///
929    /// After this call, [`Pager::flush`] computes the maximum
930    /// `header.lsn` over all dirty pages and calls
931    /// `WalWriter::flush_until(max_lsn)` before any page is written
932    /// to the data file. This is the postgres rule: a page on disk
933    /// implies its WAL record is already durable on disk.
934    ///
935    /// Existing call sites that construct a Pager without a WAL
936    /// keep their previous behaviour (no LSN check) — wiring is
937    /// strictly opt-in.
938    pub fn set_wal_writer(&self, wal: Arc<Mutex<crate::storage::wal::writer::WalWriter>>) {
939        let mut slot = self.wal.write().unwrap_or_else(|p| p.into_inner());
940        *slot = Some(wal);
941    }
942
943    /// Detach the WAL writer (test / shutdown path).
944    pub fn clear_wal_writer(&self) {
945        let mut slot = self.wal.write().unwrap_or_else(|p| p.into_inner());
946        *slot = None;
947    }
948
949    /// Has a WAL writer been attached?
950    pub fn has_wal_writer(&self) -> bool {
951        self.wal.read().map(|s| s.is_some()).unwrap_or(false)
952    }
953
954    /// Flush all dirty pages to disk
955    pub fn flush(&self) -> Result<(), PagerError> {
956        if self.config.read_only {
957            return Ok(());
958        }
959
960        // Persist freelist to trunk pages when dirty
961        let trunks = {
962            let mut freelist = self.freelist_write()?;
963            if freelist.is_dirty() {
964                let mut header = self.header_write()?;
965                let trunks = freelist.flush_to_trunks(0, || {
966                    let id = header.page_count;
967                    header.page_count += 1;
968                    id
969                });
970                header.freelist_head = freelist.trunk_head();
971                *self.header_dirty_lock()? = true;
972                freelist.mark_clean();
973                trunks
974            } else {
975                Vec::new()
976            }
977        };
978
979        for trunk in trunks {
980            let page_id = trunk.page_id();
981            self.cache.insert(page_id, trunk);
982            self.cache.mark_dirty(page_id);
983        }
984
985        // Flush dirty pages from cache (through DWB if enabled)
986        let dirty_pages = self.cache.flush_dirty();
987        if !dirty_pages.is_empty() {
988            // WAL-FIRST: ensure every WAL record describing a dirty
989            // page is durable BEFORE the page itself reaches disk.
990            // Pages with `lsn == 0` are exempt (freelist trunks, header
991            // shadow pages, anything not produced by a WAL append).
992            let max_lsn = dirty_pages
993                .iter()
994                .filter_map(|(_, page)| page.header().ok().map(|h| h.lsn))
995                .max()
996                .unwrap_or(0);
997            if max_lsn > 0 {
998                if let Ok(slot) = self.wal.read() {
999                    if let Some(wal) = slot.as_ref() {
1000                        let wal = Arc::clone(wal);
1001                        // Drop the read lock before taking the WAL
1002                        // mutex so an unrelated reader cannot block
1003                        // the flush path.
1004                        drop(slot);
1005                        let mut wal_guard = wal.lock().unwrap_or_else(|p| p.into_inner());
1006                        wal_guard.flush_until(max_lsn).map_err(PagerError::Io)?;
1007                    }
1008                }
1009            }
1010            self.write_pages_through_dwb(&dirty_pages)?;
1011        }
1012
1013        // Write header if dirty
1014        if *self.header_dirty_lock()? {
1015            self.write_header()?;
1016        }
1017
1018        Ok(())
1019    }
1020
1021    /// Sync file to disk (fsync)
1022    pub fn sync(&self) -> Result<(), PagerError> {
1023        self.flush()?;
1024
1025        let file = self.file_lock()?;
1026        file.sync_all()?;
1027
1028        Ok(())
1029    }
1030
1031    /// Get cache statistics
1032    pub fn cache_stats(&self) -> crate::storage::engine::page_cache::CacheStats {
1033        self.cache.stats()
1034    }
1035
1036    /// Pages currently resident in the page cache. Slots are fixed size, so
1037    /// this times the page size is the cache's memory footprint (ADR 0073 §2).
1038    pub fn cache_len(&self) -> usize {
1039        self.cache.len()
1040    }
1041
1042    /// Preallocated page-cache slots — the sizing this process derived from
1043    /// its page-cache budget share.
1044    pub fn cache_capacity(&self) -> usize {
1045        self.cache.capacity()
1046    }
1047
1048    /// Count dirty pages currently in the page cache.
1049    pub fn dirty_page_count(&self) -> usize {
1050        self.cache.dirty_count()
1051    }
1052
1053    /// Estimated fraction of the page cache holding dirty pages.
1054    /// Returned in `[0, 1]`. Used by the background writer to
1055    /// decide when to kick in aggressive flushing.
1056    pub fn dirty_fraction(&self) -> f64 {
1057        let capacity = self.cache.capacity().max(1) as f64;
1058        self.cache.dirty_count() as f64 / capacity
1059    }
1060
1061    /// Flush up to `max` dirty pages from the cache. Returns the
1062    /// number actually written. Background-writer entry point —
1063    /// reuses the same persistence path as `flush()` but bounded.
1064    pub fn flush_some_dirty(&self, max: usize) -> Result<usize, PagerError> {
1065        if self.config.read_only || max == 0 {
1066            return Ok(0);
1067        }
1068        let dirty_pages = self.cache.flush_some_dirty(max);
1069        if dirty_pages.is_empty() {
1070            return Ok(0);
1071        }
1072        let count = dirty_pages.len();
1073        // WAL-first: every cached dirty page carries an LSN that the
1074        // WAL must have already persisted. The full `flush()` path
1075        // enforces this with `wal.flush(max_lsn)`; here we simply
1076        // write through the pager — safe because callers only reach
1077        // this path via the bgwriter, which runs asynchronously
1078        // alongside normal commits that already respect WAL-first.
1079        for (page_id, page) in dirty_pages {
1080            self.write_page(page_id, page)?;
1081        }
1082        Ok(count)
1083    }
1084
1085    /// Get database file path
1086    pub fn path(&self) -> &Path {
1087        &self.path
1088    }
1089
1090    /// Check if database is read-only
1091    pub fn is_read_only(&self) -> bool {
1092        self.config.read_only
1093    }
1094
1095    /// Get file size in bytes
1096    pub fn file_size(&self) -> Result<u64, PagerError> {
1097        let file = self.file_lock()?;
1098        Ok(file.metadata()?.len())
1099    }
1100
1101    /// Issue an OS-level read-ahead hint for `page_id`.
1102    ///
1103    /// A6 prefetch wire: called from `BTreeCursor::next` when the
1104    /// cursor passes 50% of the current leaf, so the kernel fetches
1105    /// the next leaf page while CPU processes the remaining half of
1106    /// the current one. Failures are silent — a missed prefetch is a
1107    /// performance miss, never a correctness bug.
1108    pub fn prefetch_hint(&self, page_id: u32) {
1109        if let Ok(file) = self.file_lock() {
1110            let _ = super::super::prefetch::prefetch_page(&file, page_id as u64, PAGE_SIZE as u32);
1111        }
1112    }
1113
1114    // ── Corruption defense helpers ──────────────────────────────────
1115
1116    /// Path for the double-write buffer file
1117    fn dwb_path(db_path: &Path) -> PathBuf {
1118        reddb_file::layout::pager_dwb_shadow_path(db_path)
1119    }
1120
1121    fn dwb_zone_offset() -> u64 {
1122        DWB_ZONE_START_PAGE as u64 * PAGE_SIZE as u64
1123    }
1124
1125    fn write_dwb_zone_frame(&self, buf: &[u8]) -> Result<(), PagerError> {
1126        if buf.len() > DWB_ZONE_BYTES {
1127            return Err(PagerError::InvalidDatabase(
1128                "DWB frame exceeds the reserved in-file zone".to_string(),
1129            ));
1130        }
1131        let mut file = self.file_lock()?;
1132        file.seek(SeekFrom::Start(Self::dwb_zone_offset()))?;
1133        file.write_all(buf)?;
1134        file.sync_all()?;
1135        Ok(())
1136    }
1137
1138    /// Clear the in-file DWB zone with valid reserved pages.
1139    fn clear_dwb_zone(&self) -> Result<(), PagerError> {
1140        let mut file = self.file_lock()?;
1141        for page_id in DWB_ZONE_START_PAGE..FIRST_ALLOCATABLE_PAGE {
1142            let mut page = Page::new(PageType::Header, page_id);
1143            page.update_checksum();
1144            file.seek(SeekFrom::Start(page_id as u64 * PAGE_SIZE as u64))?;
1145            file.write_all(page.as_bytes())?;
1146        }
1147        file.sync_all()?;
1148        Ok(())
1149    }
1150
1151    fn dwb_zone_is_clear(buf: &[u8]) -> bool {
1152        if buf.len() != DWB_ZONE_BYTES {
1153            return false;
1154        }
1155        for (idx, chunk) in buf.chunks_exact(PAGE_SIZE).enumerate() {
1156            let Ok(page) = Page::from_slice(chunk) else {
1157                return false;
1158            };
1159            if page.verify_checksum().is_err() {
1160                return false;
1161            }
1162            if page.page_id() != DWB_ZONE_START_PAGE + idx as u32 {
1163                return false;
1164            }
1165            if page.page_type().ok() != Some(PageType::Header) {
1166                return false;
1167            }
1168        }
1169        true
1170    }
1171
1172    /// Read the internal manifest page (page 1), the zone the superblock roots.
1173    ///
1174    /// ADR 0074 §2: manifest corruption fails the open didactically, naming the
1175    /// zone — it never falls back to a sidecar and never returns garbage.
1176    pub fn read_manifest_page(&self) -> Result<Page, PagerError> {
1177        self.read_page(1)
1178            .map_err(|_| PagerError::ManifestZoneCorrupt(self.path.clone()))
1179    }
1180
1181    /// Write pages through the double-write buffer for torn page protection.
1182    ///
1183    /// 1. Write pages to the in-file DWB zone with a header (magic + count + checksum)
1184    /// 2. fsync the DWB zone
1185    /// 3. Write all pages to their final locations in the .rdb file
1186    /// 4. Clear the DWB zone (marks as consumed)
1187    fn write_pages_through_dwb(&self, pages: &[(u32, Page)]) -> Result<(), PagerError> {
1188        if self.dwb_enabled {
1189            for chunk in pages.chunks(DWB_MAX_PAGES_PER_FRAME.max(1)) {
1190                let buf = reddb_file::encode_paged_dwb_frame(
1191                    chunk
1192                        .iter()
1193                        .map(|(page_id, page)| (*page_id, page.as_bytes())),
1194                );
1195
1196                // Write DWB zone and fsync
1197                self.write_dwb_zone_frame(&buf)?;
1198
1199                // Now write pages to their final locations
1200                for (page_id, page) in chunk {
1201                    self.write_page_raw(*page_id, page)?;
1202                }
1203                {
1204                    let file = self.file_lock()?;
1205                    file.sync_all()?;
1206                }
1207
1208                // Reset the zone to its inactive page images.
1209                self.clear_dwb_zone()?;
1210            }
1211
1212            Ok(())
1213        } else {
1214            // DWB disabled — write directly
1215            for (page_id, page) in pages {
1216                self.write_page_raw(*page_id, page)?;
1217            }
1218            Ok(())
1219        }
1220    }
1221
1222    /// Recover from double-write buffer after a crash.
1223    ///
1224    /// If the DWB zone contains valid pages, they were written before the crash
1225    /// interrupted writing to their home locations. Re-apply them.
1226    fn recover_from_dwb(&self) -> Result<(), PagerError> {
1227        let len = {
1228            let file = self.file_lock()?;
1229            file.metadata()?.len()
1230        };
1231        let zone_end = Self::dwb_zone_offset() + DWB_ZONE_BYTES as u64;
1232        if len < zone_end {
1233            return Ok(());
1234        }
1235
1236        let mut buf = vec![0u8; DWB_ZONE_BYTES];
1237        {
1238            let mut file = self.file_lock()?;
1239            file.seek(SeekFrom::Start(Self::dwb_zone_offset()))?;
1240            file.read_exact(&mut buf)?;
1241        }
1242        if buf.get(0..4) != Some(reddb_file::DWB_MAGIC.as_slice()) {
1243            if Self::dwb_zone_is_clear(&buf) {
1244                return Ok(());
1245            }
1246            self.clear_dwb_zone()?;
1247            return Ok(());
1248        }
1249
1250        let entries = match reddb_file::decode_paged_dwb_frame(&buf) {
1251            Ok(entries) => entries,
1252            Err(_) => {
1253                self.clear_dwb_zone()?;
1254                return Ok(());
1255            }
1256        };
1257
1258        // DWB is valid — re-apply pages to main file
1259        for entry in entries {
1260            let page = Page::from_bytes(entry.page);
1261            self.write_page_raw(entry.page_id, &page)?;
1262        }
1263
1264        // Sync and clean up
1265        {
1266            let file = self.file_lock()?;
1267            file.sync_all()?;
1268        }
1269
1270        self.clear_dwb_zone()
1271    }
1272
1273    /// Write header and sync to disk (public for checkpointer).
1274    pub fn write_header_and_sync(&self) -> Result<(), PagerError> {
1275        self.write_header()?;
1276        let file = self.file_lock()?;
1277        file.sync_all()?;
1278        Ok(())
1279    }
1280
1281    /// Set the checkpoint_in_progress flag in the header.
1282    pub fn set_checkpoint_in_progress(
1283        &self,
1284        in_progress: bool,
1285        target_lsn: u64,
1286    ) -> Result<(), PagerError> {
1287        let mut header = self.header_write()?;
1288        header.checkpoint_in_progress = in_progress;
1289        header.checkpoint_target_lsn = target_lsn;
1290        *self.header_dirty_lock()? = true;
1291        drop(header);
1292        self.write_header_and_sync()
1293    }
1294
1295    /// Update the checkpoint LSN and clear the in-progress flag.
1296    pub fn complete_checkpoint(&self, lsn: u64) -> Result<(), PagerError> {
1297        let mut header = self.header_write()?;
1298        header.checkpoint_lsn = lsn;
1299        header.checkpoint_in_progress = false;
1300        header.checkpoint_target_lsn = 0;
1301        *self.header_dirty_lock()? = true;
1302        drop(header);
1303        self.write_header_and_sync()
1304    }
1305}
1306
1307#[cfg(test)]
1308mod tests {
1309    use super::*;
1310
1311    fn temp_db_path(name: &str) -> PathBuf {
1312        std::env::temp_dir().join(format!(
1313            "reddb-pager-{}-{}-{}.rdb",
1314            name,
1315            std::process::id(),
1316            crate::utils::now_unix_nanos()
1317        ))
1318    }
1319
1320    fn cleanup(path: &Path) {
1321        let _ = std::fs::remove_file(path);
1322        let _ = std::fs::remove_file(Pager::dwb_path(path));
1323    }
1324
1325    fn read_zone(path: &Path) -> Vec<u8> {
1326        let mut zone = vec![0u8; SUPERBLOCK_ZONE_SIZE];
1327        let mut file = File::open(path).expect("open() should succeed");
1328        file.read_exact(&mut zone)
1329            .expect("read_exact() should succeed");
1330        zone
1331    }
1332
1333    /// Overwrite one superblock slot in place, leaving the sibling untouched.
1334    fn poke_slot(path: &Path, copy_index: usize, bytes: &[u8]) {
1335        let mut file = OpenOptions::new()
1336            .write(true)
1337            .open(path)
1338            .expect("open() should succeed");
1339        file.seek(SeekFrom::Start(reddb_file::paged_superblock_slot_offset(
1340            copy_index,
1341        )))
1342        .expect("operation should succeed");
1343        file.write_all(bytes).expect("write_all() should succeed");
1344        file.sync_all().expect("sync_all() should succeed");
1345    }
1346
1347    fn stamp_pre_phase3_layout(path: &Path, page_count: u32) {
1348        let zone = read_zone(path);
1349        for copy_index in 0..reddb_file::PAGED_SUPERBLOCK_SLOT_COUNT {
1350            let start = copy_index * SUPERBLOCK_SLOT_SIZE;
1351            let mut slot = zone[start..start + SUPERBLOCK_SLOT_SIZE].to_vec();
1352            let generation = reddb_file::paged_superblock_slot_generation(&slot, copy_index)
1353                .expect("fresh store should publish both slots");
1354            reddb_file::set_database_header_version(&mut slot, PHASE3_DWB_ZONE_FILE_VERSION - 1)
1355                .expect("set_database_header_version() should succeed");
1356            reddb_file::set_database_header_page_count(&mut slot, page_count)
1357                .expect("set_database_header_page_count() should succeed");
1358            reddb_file::seal_paged_superblock_slot(&mut slot, copy_index, generation)
1359                .expect("seal_paged_superblock_slot() should succeed");
1360            poke_slot(path, copy_index, &slot);
1361        }
1362    }
1363
1364    #[test]
1365    fn open_refuses_future_database_version() {
1366        let path = temp_db_path("future-version");
1367        let pager = Pager::open_default(&path).expect("open_default() should succeed");
1368        drop(pager);
1369
1370        // A *valid* superblock slot — correct magic, copy index and CRC — whose
1371        // database header names a version we cannot read. The slot is intact;
1372        // the header is from the future.
1373        let selection = reddb_file::select_paged_superblock(&read_zone(&path))
1374            .expect("operation should succeed");
1375        let mut slot = vec![0u8; SUPERBLOCK_SLOT_SIZE];
1376        reddb_file::init_database_header_page(&mut slot, 1)
1377            .expect("init_database_header_page() should succeed");
1378        reddb_file::set_database_header_version(&mut slot, reddb_file::PAGE_FILE_VERSION + 1)
1379            .expect("operation should succeed");
1380        reddb_file::seal_paged_superblock_slot(
1381            &mut slot,
1382            selection.copy_index,
1383            selection.generation + 1,
1384        )
1385        .expect("operation should succeed");
1386        poke_slot(&path, selection.copy_index, &slot);
1387
1388        let err = match Pager::open_default(&path) {
1389            Ok(_) => panic!("future database version should be rejected"),
1390            Err(err) => err,
1391        };
1392        match err {
1393            PagerError::InvalidDatabase(msg) => {
1394                assert!(msg.contains("newer than supported"), "{msg}");
1395            }
1396            other => panic!("expected InvalidDatabase, got {other:?}"),
1397        }
1398
1399        cleanup(&path);
1400    }
1401
1402    #[test]
1403    fn a_fresh_store_publishes_both_superblock_copies() {
1404        // The ping-pong invariant must hold from the very first update, which
1405        // means creation cannot leave one copy blank.
1406        let path = temp_db_path("fresh-pair");
1407        let pager = Pager::open_default(&path).expect("open_default() should succeed");
1408        drop(pager);
1409
1410        let zone = read_zone(&path);
1411        for copy_index in 0..reddb_file::PAGED_SUPERBLOCK_SLOT_COUNT {
1412            let start = copy_index * SUPERBLOCK_SLOT_SIZE;
1413            assert!(
1414                reddb_file::paged_superblock_slot_generation(
1415                    &zone[start..start + SUPERBLOCK_SLOT_SIZE],
1416                    copy_index
1417                )
1418                .is_some(),
1419                "copy {copy_index} must be valid on a fresh store"
1420            );
1421        }
1422        cleanup(&path);
1423    }
1424
1425    #[test]
1426    fn an_update_writes_the_stale_copy_and_leaves_the_newest_one_intact() {
1427        let path = temp_db_path("ping-pong");
1428        let pager = Pager::open_default(&path).expect("open_default() should succeed");
1429        let before = reddb_file::select_paged_superblock(&read_zone(&path))
1430            .expect("operation should succeed");
1431
1432        pager
1433            .allocate_page(PageType::BTreeLeaf)
1434            .expect("allocate_page() should succeed");
1435        pager.sync().expect("sync() should succeed");
1436
1437        let zone = read_zone(&path);
1438        let after = reddb_file::select_paged_superblock(&zone)
1439            .expect("select_paged_superblock() should succeed");
1440        assert_ne!(
1441            after.copy_index, before.copy_index,
1442            "an update must target the stale copy"
1443        );
1444        assert!(after.generation > before.generation);
1445
1446        // The copy that was newest before the update is still readable — this
1447        // is the byte-level statement of "a crash mid-write always leaves one
1448        // valid copy".
1449        let start = before.copy_index * SUPERBLOCK_SLOT_SIZE;
1450        assert_eq!(
1451            reddb_file::paged_superblock_slot_generation(
1452                &zone[start..start + SUPERBLOCK_SLOT_SIZE],
1453                before.copy_index
1454            ),
1455            Some(before.generation)
1456        );
1457
1458        drop(pager);
1459        cleanup(&path);
1460    }
1461
1462    #[test]
1463    fn open_recovers_from_the_older_copy_when_the_newest_is_torn() {
1464        let path = temp_db_path("torn-newest");
1465        {
1466            let pager = Pager::open_default(&path).expect("open_default() should succeed");
1467            pager
1468                .allocate_page(PageType::BTreeLeaf)
1469                .expect("allocate_page() should succeed");
1470            pager.sync().expect("sync() should succeed");
1471        }
1472
1473        let newest = reddb_file::select_paged_superblock(&read_zone(&path))
1474            .expect("operation should succeed");
1475        // Tear the newest copy: a torn write leaves its CRC broken.
1476        let mut torn = vec![0u8; SUPERBLOCK_SLOT_SIZE];
1477        torn.copy_from_slice(
1478            &read_zone(&path)[newest.copy_index * SUPERBLOCK_SLOT_SIZE
1479                ..newest.copy_index * SUPERBLOCK_SLOT_SIZE + SUPERBLOCK_SLOT_SIZE],
1480        );
1481        torn[64] ^= 0xFF;
1482        poke_slot(&path, newest.copy_index, &torn);
1483
1484        let pager = Pager::open_default(&path).expect("older copy must root the store");
1485        assert!(pager.page_count().expect("page_count() should succeed") >= 3);
1486        drop(pager);
1487        cleanup(&path);
1488    }
1489
1490    #[test]
1491    fn open_refuses_didactically_when_both_superblock_copies_are_invalid() {
1492        let path = temp_db_path("both-invalid");
1493        {
1494            let _ = Pager::open_default(&path).expect("open_default() should succeed");
1495        }
1496
1497        let zone = read_zone(&path);
1498        for copy_index in 0..reddb_file::PAGED_SUPERBLOCK_SLOT_COUNT {
1499            let start = copy_index * SUPERBLOCK_SLOT_SIZE;
1500            let mut slot = zone[start..start + SUPERBLOCK_SLOT_SIZE].to_vec();
1501            slot[64] ^= 0xFF;
1502            poke_slot(&path, copy_index, &slot);
1503        }
1504
1505        let err = match Pager::open_default(&path) {
1506            Ok(_) => panic!("a rootless store must not open"),
1507            Err(err) => err,
1508        };
1509        let rendered = err.to_string();
1510        assert!(matches!(err, PagerError::SuperblockZoneUnrecoverable(_)));
1511        assert!(rendered.contains("superblock zone"), "{rendered}");
1512        assert!(rendered.contains("salvage"), "{rendered}");
1513
1514        cleanup(&path);
1515    }
1516
1517    #[test]
1518    fn open_refuses_a_legacy_sidecar_store_and_names_the_migration_tool() {
1519        let path = temp_db_path("legacy-sidecar");
1520        {
1521            let _ = Pager::open_default(&path).expect("open_default() should succeed");
1522        }
1523
1524        let sidecar = reddb_file::layout::retired::pager_header_path_v0(&path);
1525        std::fs::write(&sidecar, b"legacy header shadow").expect("write() should succeed");
1526
1527        let err = match Pager::open_default(&path) {
1528            Ok(_) => panic!("legacy stores need migration first"),
1529            Err(err) => err,
1530        };
1531        let rendered = err.to_string();
1532        assert!(matches!(err, PagerError::LegacySidecarStore { .. }));
1533        assert!(rendered.contains("migration tool"), "{rendered}");
1534
1535        let _ = std::fs::remove_file(&sidecar);
1536        cleanup(&path);
1537    }
1538
1539    #[test]
1540    fn pre_phase3_large_store_without_sidecar_routes_to_migration() {
1541        let path = temp_db_path("pre-phase3-large");
1542        {
1543            let _ = Pager::open_default(&path).expect("open_default() should succeed");
1544        }
1545        stamp_pre_phase3_layout(&path, FIRST_ALLOCATABLE_PAGE);
1546
1547        let err = match Pager::open_default(&path) {
1548            Ok(_) => panic!("pre-phase-3 stores need migration first"),
1549            Err(err) => err,
1550        };
1551        let rendered = err.to_string();
1552        assert!(matches!(err, PagerError::LegacyPagedStore { .. }));
1553        assert!(rendered.contains("migration tool"), "{rendered}");
1554
1555        cleanup(&path);
1556    }
1557
1558    #[test]
1559    fn pre_phase3_small_store_without_sidecar_routes_to_migration() {
1560        let path = temp_db_path("pre-phase3-small");
1561        {
1562            let _ = Pager::open_default(&path).expect("open_default() should succeed");
1563        }
1564        stamp_pre_phase3_layout(&path, 3);
1565        OpenOptions::new()
1566            .write(true)
1567            .open(&path)
1568            .expect("open() should succeed")
1569            .set_len(3 * PAGE_SIZE as u64)
1570            .expect("set_len() should succeed");
1571
1572        let err = match Pager::open_default(&path) {
1573            Ok(_) => panic!("pre-phase-3 stores need migration first"),
1574            Err(err) => err,
1575        };
1576        assert!(matches!(err, PagerError::LegacyPagedStore { .. }));
1577
1578        cleanup(&path);
1579    }
1580
1581    #[test]
1582    fn no_phase_one_sidecar_survives_a_create_write_reopen_cycle() {
1583        let path = temp_db_path("census");
1584        {
1585            let pager = Pager::open_default(&path).expect("open_default() should succeed");
1586            let page = pager
1587                .allocate_page(PageType::BTreeLeaf)
1588                .expect("allocate_page() should succeed");
1589            pager
1590                .write_page(page.page_id(), page)
1591                .expect("operation should succeed");
1592            pager.sync().expect("sync() should succeed");
1593        }
1594        {
1595            let pager = Pager::open_default(&path).expect("open_default() should succeed");
1596            pager.sync().expect("sync() should succeed");
1597        }
1598
1599        assert_eq!(
1600            reddb_file::layout::retired::first_present_phase1_sidecar(&path),
1601            None,
1602            "the pager must never create a retired phase-1 sidecar"
1603        );
1604        cleanup(&path);
1605    }
1606}