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#[cfg(test)]
8pub(super) const SUPERBLOCK_SLOT_SIZE: usize = reddb_file::PAGED_SUPERBLOCK_SLOT_SIZE;
9#[cfg(test)]
10pub(super) const SUPERBLOCK_ZONE_SIZE: usize = reddb_file::PAGED_SUPERBLOCK_ZONE_SIZE;
11
12#[derive(Debug, Clone, Copy, PartialEq, Eq)]
13pub(super) enum CowFilesystemKind {
14    Zfs,
15    BtrfsDataCow,
16    TestOverride,
17}
18
19pub(super) fn classify_cow_filesystem(
20    fs_type: i64,
21    mount_options: Option<&str>,
22    inode_flags: Option<u64>,
23) -> Option<CowFilesystemKind> {
24    match fs_type {
25        ZFS_SUPER_MAGIC => Some(CowFilesystemKind::Zfs),
26        BTRFS_SUPER_MAGIC => {
27            let mount_options = mount_options?;
28            if mount_options.split(',').any(|option| option == "nodatacow") {
29                return None;
30            }
31
32            let inode_flags = inode_flags?;
33            if inode_flags & FS_NOCOW_FL != 0 {
34                return None;
35            }
36
37            Some(CowFilesystemKind::BtrfsDataCow)
38        }
39        _ => None,
40    }
41}
42
43#[cfg(target_os = "linux")]
44fn linux_fstatfs_type(file: &File) -> Option<i64> {
45    use std::mem::MaybeUninit;
46    use std::os::fd::AsRawFd;
47
48    let mut stat = MaybeUninit::<libc::statfs>::uninit();
49    let rc = unsafe { libc::fstatfs(file.as_raw_fd(), stat.as_mut_ptr()) };
50    if rc != 0 {
51        return None;
52    }
53    let stat = unsafe { stat.assume_init() };
54    // `statfs.f_type` is i32 on 32-bit glibc targets (armv7) and i64 on
55    // 64-bit ones — widen explicitly so both compile.
56    #[allow(clippy::unnecessary_cast)]
57    Some(stat.f_type as i64)
58}
59
60#[cfg(target_os = "linux")]
61fn linux_inode_flags(file: &File) -> Option<u64> {
62    use std::os::fd::AsRawFd;
63
64    let mut flags: libc::c_long = 0;
65    let rc = unsafe { libc::ioctl(file.as_raw_fd(), libc::FS_IOC_GETFLAGS, &mut flags) };
66    if rc != 0 {
67        return None;
68    }
69    Some(flags as u64)
70}
71
72#[cfg(target_os = "linux")]
73fn linux_mount_options_for_path(path: &Path) -> Option<String> {
74    let path = path.canonicalize().ok()?;
75    let mountinfo = std::fs::read_to_string("/proc/self/mountinfo").ok()?;
76    parse_mountinfo_options_for_path(&mountinfo, &path)
77}
78
79#[cfg(target_os = "linux")]
80pub(super) fn parse_mountinfo_options_for_path(mountinfo: &str, path: &Path) -> Option<String> {
81    let mut best: Option<(usize, String)> = None;
82
83    for line in mountinfo.lines() {
84        let fields: Vec<&str> = line.split(' ').collect();
85        if fields.len() < 10 {
86            continue;
87        }
88
89        let Some(separator) = fields.iter().position(|field| *field == "-") else {
90            continue;
91        };
92        if separator + 3 >= fields.len() || separator < 6 {
93            continue;
94        }
95
96        let mount_point = mountinfo_unescape_path(fields[4]);
97        if !path.starts_with(&mount_point) {
98            continue;
99        }
100
101        let fs_type = fields[separator + 1];
102        if fs_type != "btrfs" && fs_type != "zfs" {
103            continue;
104        }
105
106        let mount_options = fields[5];
107        let super_options = fields[separator + 3];
108        let options = format!("{mount_options},{super_options}");
109        let depth = mount_point.components().count();
110        if best
111            .as_ref()
112            .map(|(best_depth, _)| depth > *best_depth)
113            .unwrap_or(true)
114        {
115            best = Some((depth, options));
116        }
117    }
118
119    best.map(|(_, options)| options)
120}
121
122#[cfg(target_os = "linux")]
123fn mountinfo_unescape_path(value: &str) -> PathBuf {
124    let bytes = value.as_bytes();
125    let mut out = Vec::with_capacity(bytes.len());
126    let mut i = 0;
127
128    while i < bytes.len() {
129        if bytes[i] == b'\\' && i + 3 < bytes.len() {
130            let octal = &value[i + 1..i + 4];
131            if let Ok(byte) = u8::from_str_radix(octal, 8) {
132                out.push(byte);
133                i += 4;
134                continue;
135            }
136        }
137        out.push(bytes[i]);
138        i += 1;
139    }
140
141    PathBuf::from(String::from_utf8_lossy(&out).into_owned())
142}
143
144impl Pager {
145    /// Open or create a database file
146    pub fn open<P: AsRef<Path>>(path: P, mut config: PagerConfig) -> Result<Self, PagerError> {
147        let path = path.as_ref().to_path_buf();
148        let exists = path.exists();
149
150        if !exists && !config.create {
151            return Err(PagerError::InvalidDatabase(
152                "Database does not exist".into(),
153            ));
154        }
155
156        // ADR 0038 §4 phase 1 is a clean break: a store still carrying the
157        // retired `rdb-hdr`/`rdb-meta` sidecars is never read by the engine.
158        // The offline migration tool is the only path forward.
159        if exists {
160            if let Some(sidecar) = reddb_file::layout::retired::first_present_phase1_sidecar(&path)
161            {
162                return Err(PagerError::LegacySidecarStore { sidecar });
163            }
164        }
165
166        if !exists && config.read_only {
167            return Err(PagerError::InvalidDatabase(
168                "Cannot create read-only database".into(),
169            ));
170        }
171
172        // Open file
173        // Note: create requires write access, so disable it for read-only mode
174        let file = OpenOptions::new()
175            .read(true)
176            .write(!config.read_only)
177            .create(config.create && !config.read_only)
178            .open(&path)?;
179
180        // gh-892: diagnostic probe of the filesystem block size. If the
181        // compile-time 16 KiB PAGE_SIZE is not a multiple of the FS block
182        // size, page writes straddle FS blocks and incur read-modify-write
183        // amplification. Pure diagnostic — emitted once per open, never
184        // mutates the page size. `blksize()` is the fstat `st_blksize`.
185        #[cfg(unix)]
186        {
187            use std::os::unix::fs::MetadataExt;
188            if let Ok(meta) = file.metadata() {
189                let fs_block_size = meta.blksize();
190                if Self::page_size_misaligned_with_block(PAGE_SIZE, fs_block_size) {
191                    tracing::warn!(
192                        page_size = PAGE_SIZE,
193                        fs_block_size,
194                        path = %path.display(),
195                        "database page size is not a multiple of the filesystem \
196                         block size; page writes will straddle FS blocks \
197                         (read-modify-write amplification). Diagnostic only — \
198                         the page size is unchanged."
199                    );
200                }
201            }
202        }
203
204        // Lock the same handle that performs page I/O. Windows byte-range
205        // locks deny reads/writes through a separately opened handle even in
206        // this process. The owned VFS handle holds the fence until it closes.
207        if !config.read_only {
208            file.try_lock_exclusive().map_err(|_| PagerError::Locked)?;
209        } else {
210            FileExt::try_lock_shared(&file).map_err(|_| PagerError::Locked)?;
211        }
212        // Own lock release across both ordinary close and later open failures.
213        let file = NativePagerFile(file);
214
215        // ADR 0038 phase 3: the DWB sidecar is retired. When DWB is active,
216        // the recovery frame is written to a reserved zone inside the data
217        // file and fsynced before in-place page writes. A pre-existing sidecar
218        // marks a legacy store that must go through the offline migration tool.
219        //
220        // gh-895: an explicit `double_write = false` request is honored only
221        // when the already-open data file is proven to live on a filesystem
222        // with atomic CoW page writes. Unknown and non-CoW filesystems fail
223        // closed by keeping the in-file DWB zone enabled.
224        let fold_dwb = crate::physical::fold_dwb_into_wal_enabled();
225        if exists {
226            if let Some(sidecar) =
227                reddb_file::layout::retired::first_present_phase3_dwb_sidecar(&path)
228            {
229                return Err(PagerError::LegacySidecarStore { sidecar });
230            }
231        }
232        if !config.double_write && !config.read_only && !fold_dwb {
233            let skip_dwb_on_cow =
234                Self::cow_filesystem_has_atomic_page_writes(&path, &file.0).is_some();
235            if !skip_dwb_on_cow {
236                tracing::warn!(
237                    path = %path.display(),
238                    "double_write=false requested, but the data file is not proven to be on \
239                     ZFS or btrfs datacow; keeping the in-file double-write buffer enabled"
240                );
241                config.double_write = true;
242            }
243        }
244        let dwb_enabled = config.double_write && !config.read_only && !fold_dwb;
245
246        let core = SharedPager::open_owned(
247            file,
248            path,
249            SharedPagerConfig {
250                disk_residency: config.disk_residency,
251                cache_size: config.cache_size,
252                read_only: config.read_only,
253                verify_checksums: config.verify_checksums,
254                double_write: dwb_enabled,
255            },
256            NativeWalBarrier::default(),
257            !exists,
258        )?;
259        let mut pager = Self {
260            core,
261            config,
262            encryption: None,
263        };
264
265        if exists {
266            pager.bind_encryption_for_existing()?;
267        } else {
268            // Initialize new database
269            pager.bind_encryption_for_new()?;
270        }
271
272        Ok(pager)
273    }
274
275    /// gh-892 diagnostic predicate: returns `true` when the database
276    /// `page_size` is **not** an integer multiple of the filesystem's
277    /// reported block size (`st_blksize`), i.e. `page_size % fs_block_size
278    /// != 0`. A `fs_block_size` of `0` (probe unavailable / unknown) is
279    /// treated as aligned so a missing probe never produces a warning.
280    /// Pure function with no I/O so the warn decision is unit-testable.
281    pub(crate) fn page_size_misaligned_with_block(page_size: usize, fs_block_size: u64) -> bool {
282        fs_block_size != 0 && !(page_size as u64).is_multiple_of(fs_block_size)
283    }
284
285    #[cfg(test)]
286    fn cow_filesystem_test_override() -> Option<bool> {
287        match COW_ATOMIC_WRITE_TEST_OVERRIDE.load(Ordering::Relaxed) {
288            1 => Some(true),
289            2 => Some(false),
290            _ => None,
291        }
292    }
293
294    #[cfg(not(test))]
295    fn cow_filesystem_test_override() -> Option<bool> {
296        None
297    }
298
299    fn cow_filesystem_has_atomic_page_writes(
300        path: &Path,
301        file: &File,
302    ) -> Option<CowFilesystemKind> {
303        if let Some(allowed) = Self::cow_filesystem_test_override() {
304            return allowed.then_some(CowFilesystemKind::TestOverride);
305        }
306        Self::probe_cow_filesystem(path, file)
307    }
308
309    #[cfg(target_os = "linux")]
310    fn probe_cow_filesystem(path: &Path, file: &File) -> Option<CowFilesystemKind> {
311        let fs_type = linux_fstatfs_type(file)?;
312        match fs_type {
313            ZFS_SUPER_MAGIC => Some(CowFilesystemKind::Zfs),
314            BTRFS_SUPER_MAGIC => {
315                let mount_options = linux_mount_options_for_path(path)?;
316                let inode_flags = linux_inode_flags(file)?;
317                classify_cow_filesystem(fs_type, Some(&mount_options), Some(inode_flags))
318            }
319            _ => None,
320        }
321    }
322
323    #[cfg(not(target_os = "linux"))]
324    fn probe_cow_filesystem(_path: &Path, _file: &File) -> Option<CowFilesystemKind> {
325        None
326    }
327
328    /// Inspect page 0 for the `RDBE` encryption marker, then resolve
329    /// the (key, marker) matrix:
330    ///
331    /// | Marker | Key supplied | Result                              |
332    /// |--------|--------------|-------------------------------------|
333    /// | yes    | yes          | Bind encryptor; validate key        |
334    /// | yes    | no           | `EncryptionRequired` (fail closed)  |
335    /// | no     | yes          | `PlainDatabaseRefusesKey`           |
336    /// | no     | no           | Plain pager — no binding needed     |
337    fn bind_encryption_for_existing(&mut self) -> Result<(), PagerError> {
338        if self.page_count().unwrap_or(0) == 0 {
339            return self.bind_encryption_for_new();
340        }
341        let (_, image) = self.newest_superblock()?;
342        let data = &image[..];
343        let has_marker = reddb_file::paged_encryption_marker_present(data);
344
345        let key = self.config.encryption.clone();
346        match (has_marker, key) {
347            (true, Some(key)) => {
348                let header_bytes =
349                    reddb_file::paged_encryption_header_bytes(data).ok_or_else(|| {
350                        PagerError::InvalidDatabase("encryption header parse failed".to_string())
351                    })?;
352                let header = crate::storage::encryption::EncryptionHeader::from_bytes(header_bytes)
353                    .map_err(|e| {
354                        PagerError::InvalidDatabase(format!("encryption header parse failed: {e}"))
355                    })?;
356                if !header.validate(&key) {
357                    return Err(PagerError::InvalidKey);
358                }
359                let encryptor = crate::storage::encryption::PageEncryptor::new(key);
360                self.encryption = Some((encryptor, header));
361                Ok(())
362            }
363            (true, None) => Err(PagerError::EncryptionRequired),
364            (false, Some(_)) => Err(PagerError::PlainDatabaseRefusesKey),
365            (false, None) => Ok(()),
366        }
367    }
368
369    /// New DB: if a key is configured, write the marker + header to
370    /// page 0 so subsequent opens detect encryption.
371    fn bind_encryption_for_new(&mut self) -> Result<(), PagerError> {
372        let Some(key) = self.config.encryption.clone() else {
373            return Ok(());
374        };
375        let header = crate::storage::encryption::EncryptionHeader::new(&key);
376        let encryptor = crate::storage::encryption::PageEncryptor::new(key);
377
378        // Stamp the marker + header into the superblock zone if `initialize()`
379        // has already published it.
380        if self.page_count().unwrap_or(0) > 0 {
381            let header_bytes = header.to_bytes();
382            self.commit_superblock(|image| {
383                reddb_file::write_paged_encryption_marker_and_header(image, &header_bytes)
384                    .map_err(|err| PagerError::InvalidDatabase(err.to_string()))
385            })?;
386        }
387        self.encryption = Some((encryptor, header));
388        Ok(())
389    }
390
391    /// Open with default configuration
392    pub fn open_default<P: AsRef<Path>>(path: P) -> Result<Self, PagerError> {
393        Self::open(path, PagerConfig::default())
394    }
395
396    /// Read a page through the configured encryptor if any. Page 0
397    /// is always returned plaintext (it carries the encryption marker
398    /// + header). Callers that want raw cipher bytes can use
399    ///   `read_page_no_checksum` directly.
400    pub fn read_page_decrypted(&self, page_id: u32) -> Result<Page, PagerError> {
401        if page_id == 0 || self.encryption.is_none() {
402            return self.read_page(page_id);
403        }
404        let raw = self.read_page_no_checksum(page_id)?;
405        let (enc, _) = self
406            .encryption
407            .as_ref()
408            .expect("encryption presence checked above");
409        let plaintext = enc
410            .decrypt(page_id, raw.as_bytes())
411            .map_err(|e| PagerError::InvalidDatabase(format!("decrypt page {page_id}: {e}")))?;
412        let mut buf = [0u8; PAGE_SIZE];
413        let n = plaintext.len().min(PAGE_SIZE);
414        buf[..n].copy_from_slice(&plaintext[..n]);
415        let page = Page::from_bytes(buf);
416        reddb_engine::storage::pager_io::check_page_identity(&page, page_id)?;
417        Ok(page)
418    }
419
420    /// Write a page through the configured encryptor if any. Page 0
421    /// bypasses encryption and goes through the normal checksummed
422    /// path. Encrypted pages skip the checksum update because
423    /// AES-GCM's authentication tag is the integrity guarantee.
424    pub fn write_page_encrypted(&self, page_id: u32, page: Page) -> Result<(), PagerError> {
425        if page_id == 0 || self.encryption.is_none() {
426            return self.write_page(page_id, page);
427        }
428        reddb_engine::storage::pager_io::check_page_identity(&page, page_id)?;
429        // Canonical per-page envelope overhead (nonce + GCM tag),
430        // owned by reddb-io-crypto (#1053, ADR 0054).
431        const OVERHEAD: usize = crate::storage::encryption::page_encryptor::OVERHEAD;
432        let plaintext_len = PAGE_SIZE - OVERHEAD;
433        let plaintext = &page.as_bytes()[..plaintext_len];
434        let (enc, _) = self
435            .encryption
436            .as_ref()
437            .expect("encryption presence checked above");
438        let ciphertext = enc.encrypt(page_id, plaintext);
439        debug_assert_eq!(ciphertext.len(), PAGE_SIZE);
440        let mut buf = [0u8; PAGE_SIZE];
441        buf.copy_from_slice(&ciphertext);
442        let cipher_page = Page::from_bytes(buf);
443        self.write_page_no_checksum(page_id, cipher_page)
444    }
445
446    /// Attach a WAL writer to enforce WAL-first flush ordering.
447    ///
448    /// After this call, [`Pager::flush`] computes the maximum
449    /// `header.lsn` over all dirty pages and calls
450    /// `WalWriter::flush_until(max_lsn)` before any page is written
451    /// to the data file. This is the postgres rule: a page on disk
452    /// implies its WAL record is already durable on disk.
453    ///
454    /// Cold checksummed reads with a nonzero page LSN beyond the completed
455    /// checkpoint also require this durable WAL authority. LSN-zero pages
456    /// remain protected by DWB and do not need an attached writer.
457    pub fn set_wal_writer(&self, wal: Arc<Mutex<crate::storage::wal::writer::WalWriter>>) {
458        let mut slot = self
459            .core
460            .wal_barrier()
461            .0
462            .write()
463            .unwrap_or_else(|p| p.into_inner());
464        *slot = Some(wal);
465    }
466
467    /// Detach the WAL writer (test / shutdown path).
468    pub fn clear_wal_writer(&self) {
469        let mut slot = self
470            .core
471            .wal_barrier()
472            .0
473            .write()
474            .unwrap_or_else(|p| p.into_inner());
475        *slot = None;
476    }
477
478    /// Has a WAL writer been attached?
479    pub fn has_wal_writer(&self) -> bool {
480        self.core
481            .wal_barrier()
482            .0
483            .read()
484            .map(|s| s.is_some())
485            .unwrap_or(false)
486    }
487
488    /// Install an ownership recorder while all other mutators are fenced.
489    #[allow(dead_code)] // Used when ownership recovery is activated.
490    pub(crate) fn install_ownership_recorder(
491        &self,
492        recorder: Arc<dyn super::PageOwnershipRecorder>,
493    ) -> std::io::Result<()> {
494        let mut slot = self
495            .core
496            .wal_barrier()
497            .1
498            .write()
499            .map_err(|_| std::io::Error::other("ownership recorder lock poisoned"))?;
500        if slot.is_some() {
501            return Err(std::io::Error::other(
502                "ownership recorder already installed",
503            ));
504        }
505        *slot = Some(recorder);
506        Ok(())
507    }
508
509    /// Remove the recorder after allocator copies and journal completion are
510    /// durable, while other mutators remain fenced.
511    pub(crate) fn clear_ownership_recorder(&self) -> std::io::Result<()> {
512        let mut slot = self
513            .core
514            .wal_barrier()
515            .1
516            .write()
517            .map_err(|_| std::io::Error::other("ownership recorder lock poisoned"))?;
518        if slot.take().is_none() {
519            return Err(std::io::Error::other("ownership recorder is not installed"));
520        }
521        Ok(())
522    }
523
524    /// Issue a best-effort OS read-ahead hint under the page-I/O lock.
525    pub fn prefetch_hint(&self, page_id: u32) {
526        let _ = self.core.with_file(|file| {
527            super::super::prefetch::prefetch_page(&file.0, u64::from(page_id), PAGE_SIZE as u32)
528        });
529    }
530
531    #[cfg(test)]
532    fn dwb_path(path: &Path) -> PathBuf {
533        reddb_file::layout::pager_dwb_shadow_path(path)
534    }
535}
536
537#[cfg(test)]
538mod tests {
539    use super::*;
540
541    #[test]
542    fn ownership_scope_serializes_other_allocators_and_fences_errors() {
543        let directory = tempfile::tempdir().expect("temporary directory");
544        let pager = Arc::new(
545            Pager::open(directory.path().join("data.rdb"), Default::default()).expect("pager"),
546        );
547        let scope = pager.lock_ownership_mutations();
548        let (started_tx, started_rx) = std::sync::mpsc::channel();
549        let (done_tx, done_rx) = std::sync::mpsc::channel();
550        let other_pager = Arc::clone(&pager);
551        let worker = std::thread::spawn(move || {
552            started_tx.send(()).expect("signal worker started");
553            let page = other_pager.allocate_page(PageType::BTreeLeaf);
554            done_tx
555                .send(page.map(|page| page.page_id()))
556                .expect("signal allocation");
557        });
558        started_rx.recv().expect("worker started");
559        assert!(done_rx
560            .recv_timeout(std::time::Duration::from_millis(100))
561            .is_err());
562        let own = pager
563            .allocate_page(PageType::BTreeLeaf)
564            .expect("reentrant allocation");
565        drop(scope);
566        let other = done_rx
567            .recv()
568            .expect("worker result")
569            .expect("other allocation");
570        worker.join().expect("worker");
571        assert_ne!(own.page_id(), other);
572        pager.fence_interrupted_ownership();
573        assert!(pager.allocate_page(PageType::BTreeLeaf).is_err());
574    }
575
576    fn temp_db_path(name: &str) -> PathBuf {
577        std::env::temp_dir().join(format!(
578            "reddb-pager-{}-{}-{}.rdb",
579            name,
580            std::process::id(),
581            crate::utils::now_unix_nanos()
582        ))
583    }
584
585    fn cleanup(path: &Path) {
586        let _ = std::fs::remove_file(path);
587        let _ = std::fs::remove_file(Pager::dwb_path(path));
588    }
589
590    fn read_zone(path: &Path) -> Vec<u8> {
591        let mut zone = vec![0u8; SUPERBLOCK_ZONE_SIZE];
592        let mut file = File::open(path).expect("open() should succeed");
593        file.read_exact(&mut zone)
594            .expect("read_exact() should succeed");
595        zone
596    }
597
598    fn read_owned_zone(pager: &Pager) -> [u8; SUPERBLOCK_ZONE_SIZE] {
599        pager
600            .core
601            .with_file(reddb_engine::storage::pager_io::read_superblock_zone)
602            .expect("owned pager file")
603            .expect("superblock read")
604    }
605
606    #[test]
607    fn read_only_dwb_recovery_survives_cache_eviction_without_writing() {
608        let directory = tempfile::tempdir().expect("fixture");
609        let path = directory.path().join("data.rdb");
610        let writer = Pager::open_default(&path).expect("writer");
611        let mut pages = Vec::new();
612        for _ in 0..100 {
613            let mut page = writer.allocate_page(PageType::Overflow).expect("allocate");
614            page.update_checksum();
615            writer
616                .write_page(page.page_id(), page.clone())
617                .expect("page");
618            pages.push(page);
619        }
620        writer.sync().expect("checkpoint");
621        drop(writer);
622        let mut staged = pages.last().expect("tail page").clone();
623        staged.content_mut()[0] = 123;
624        staged.update_checksum();
625        let frame = reddb_file::encode_paged_dwb_frame([(staged.page_id(), staged.as_bytes())]);
626        let mut file = OpenOptions::new().write(true).open(&path).expect("fixture");
627        file.seek(SeekFrom::Start(
628            u64::from(reddb_engine::storage::pager_io::DWB_ZONE_START_PAGE) * PAGE_SIZE as u64,
629        ))
630        .expect("DWB offset");
631        file.write_all(&frame).expect("stage durable image");
632        // Simulate interruption before the staged tail page reached its home.
633        file.set_len(u64::from(staged.page_id()) * PAGE_SIZE as u64)
634            .expect("truncate tail");
635        file.sync_all().expect("fixture sync");
636        drop(file);
637        let before = std::fs::read(&path).expect("source bytes");
638        for _ in 0..2 {
639            let reader = Pager::open(
640                &path,
641                PagerConfig {
642                    read_only: true,
643                    create: false,
644                    cache_size: 2,
645                    ..Default::default()
646                },
647            )
648            .expect("read-only DWB recovery");
649            for page in &pages[..pages.len() - 1] {
650                reader
651                    .read_page(page.page_id())
652                    .expect("evict ordinary cache entries");
653            }
654            assert_eq!(
655                reader
656                    .read_page(staged.page_id())
657                    .expect("recovered tail")
658                    .as_bytes(),
659                staged.as_bytes()
660            );
661            assert!(reader.write_page(staged.page_id(), staged.clone()).is_err());
662            drop(reader);
663            assert_eq!(std::fs::read(&path).expect("unchanged source"), before);
664        }
665        let writer = Pager::open_default(&path).expect("ordinary DWB recovery");
666        assert_eq!(
667            writer
668                .read_page(staged.page_id())
669                .expect("durable tail")
670                .as_bytes(),
671            staged.as_bytes()
672        );
673    }
674
675    #[test]
676    fn read_only_dwb_retains_raw_pages_for_host_authentication() {
677        let directory = tempfile::tempdir().expect("fixture");
678        let path = directory.path().join("data.rdb");
679        let writer = Pager::open_default(&path).expect("writer");
680        let id = writer
681            .allocate_page(PageType::Overflow)
682            .expect("page")
683            .page_id();
684        writer.sync().expect("checkpoint");
685        drop(writer);
686        // Ciphertext does not carry a plaintext PageHeader or page checksum.
687        let raw = [91; PAGE_SIZE];
688        let frame = reddb_file::encode_paged_dwb_frame([(id, &raw)]);
689        let mut file = OpenOptions::new().write(true).open(&path).expect("fixture");
690        file.seek(SeekFrom::Start(
691            u64::from(DWB_ZONE_START_PAGE) * PAGE_SIZE as u64,
692        ))
693        .expect("DWB offset");
694        file.write_all(&frame).expect("staged raw frame");
695        file.sync_all().expect("fixture sync");
696        drop(file);
697        let before = std::fs::read(&path).expect("source");
698        let reader = Pager::open(
699            &path,
700            PagerConfig {
701                read_only: true,
702                create: false,
703                ..Default::default()
704            },
705        )
706        .expect("raw DWB recovery");
707        assert_eq!(
708            reader
709                .read_page_no_checksum(id)
710                .expect("raw image")
711                .as_bytes(),
712            &raw
713        );
714        assert!(
715            reader.read_page(id).is_err(),
716            "normal reads still require a page checksum"
717        );
718        drop(reader);
719        assert_eq!(std::fs::read(&path).expect("unchanged source"), before);
720    }
721
722    #[test]
723    fn read_only_recovery_refuses_excess_images_without_writing() {
724        let directory = tempfile::tempdir().expect("fixture");
725        let path = directory.path().join("data.rdb");
726        drop(Pager::open_default(&path).expect("writer"));
727        let before = std::fs::read(&path).expect("source");
728        let reader = Pager::open(
729            &path,
730            PagerConfig {
731                read_only: true,
732                create: false,
733                cache_size: 2,
734                ..Default::default()
735            },
736        )
737        .expect("reader");
738        let limit = reddb_engine::storage::pager_io::DWB_MAX_PAGES_PER_FRAME;
739        for index in 0..=limit {
740            let id = reddb_engine::storage::pager_io::FIRST_ALLOCATABLE_PAGE + index as u32;
741            let mut page = Page::new(PageType::Overflow, id);
742            page.update_checksum();
743            let result = reader.restore_read_only_page(id, page);
744            if index < limit {
745                result.expect("within recovery budget");
746            } else {
747                assert!(result
748                    .expect_err("bounded recovery")
749                    .to_string()
750                    .contains("budget"));
751            }
752        }
753        drop(reader);
754        assert_eq!(std::fs::read(&path).expect("unchanged source"), before);
755    }
756
757    /// Overwrite one superblock slot in place, leaving the sibling untouched.
758    fn poke_slot(path: &Path, copy_index: usize, bytes: &[u8]) {
759        let mut file = OpenOptions::new()
760            .write(true)
761            .open(path)
762            .expect("open() should succeed");
763        file.seek(SeekFrom::Start(reddb_file::paged_superblock_slot_offset(
764            copy_index,
765        )))
766        .expect("operation should succeed");
767        file.write_all(bytes).expect("write_all() should succeed");
768        file.sync_all().expect("sync_all() should succeed");
769    }
770
771    fn stamp_pre_phase3_layout(path: &Path, page_count: u32) {
772        let zone = read_zone(path);
773        for copy_index in 0..reddb_file::PAGED_SUPERBLOCK_SLOT_COUNT {
774            let start = copy_index * SUPERBLOCK_SLOT_SIZE;
775            let mut slot = zone[start..start + SUPERBLOCK_SLOT_SIZE].to_vec();
776            let generation = reddb_file::paged_superblock_slot_generation(&slot, copy_index)
777                .expect("fresh store should publish both slots");
778            reddb_file::set_database_header_version(
779                &mut slot,
780                reddb_file::PAGE_DWB_ZONE_FILE_VERSION - 1,
781            )
782            .expect("set_database_header_version() should succeed");
783            reddb_file::set_database_header_page_count(&mut slot, page_count)
784                .expect("set_database_header_page_count() should succeed");
785            reddb_file::seal_paged_superblock_slot(&mut slot, copy_index, generation)
786                .expect("seal_paged_superblock_slot() should succeed");
787            poke_slot(path, copy_index, &slot);
788        }
789    }
790
791    #[test]
792    fn open_refuses_future_database_version() {
793        let path = temp_db_path("future-version");
794        let pager = Pager::open_default(&path).expect("open_default() should succeed");
795        drop(pager);
796
797        // A *valid* superblock slot — correct magic, copy index and CRC — whose
798        // database header names a version we cannot read. The slot is intact;
799        // the header is from the future.
800        let selection = reddb_file::select_paged_superblock(&read_zone(&path))
801            .expect("operation should succeed");
802        let mut slot = vec![0u8; SUPERBLOCK_SLOT_SIZE];
803        reddb_file::init_database_header_page(&mut slot, 1)
804            .expect("init_database_header_page() should succeed");
805        reddb_file::set_database_header_version(&mut slot, reddb_file::PAGE_FILE_VERSION + 1)
806            .expect("operation should succeed");
807        reddb_file::seal_paged_superblock_slot(
808            &mut slot,
809            selection.copy_index,
810            selection.generation + 1,
811        )
812        .expect("operation should succeed");
813        poke_slot(&path, selection.copy_index, &slot);
814
815        let err = match Pager::open_default(&path) {
816            Ok(_) => panic!("future database version should be rejected"),
817            Err(err) => err,
818        };
819        match err {
820            PagerError::InvalidDatabase(msg) => {
821                assert!(msg.contains("newer than supported"), "{msg}");
822            }
823            other => panic!("expected InvalidDatabase, got {other:?}"),
824        }
825
826        cleanup(&path);
827    }
828
829    #[test]
830    fn a_fresh_store_publishes_both_superblock_copies() {
831        // The ping-pong invariant must hold from the very first update, which
832        // means creation cannot leave one copy blank.
833        let path = temp_db_path("fresh-pair");
834        let pager = Pager::open_default(&path).expect("open_default() should succeed");
835        drop(pager);
836
837        let zone = read_zone(&path);
838        for copy_index in 0..reddb_file::PAGED_SUPERBLOCK_SLOT_COUNT {
839            let start = copy_index * SUPERBLOCK_SLOT_SIZE;
840            assert!(
841                reddb_file::paged_superblock_slot_generation(
842                    &zone[start..start + SUPERBLOCK_SLOT_SIZE],
843                    copy_index
844                )
845                .is_some(),
846                "copy {copy_index} must be valid on a fresh store"
847            );
848        }
849        cleanup(&path);
850    }
851
852    #[test]
853    fn an_update_writes_the_stale_copy_and_leaves_the_newest_one_intact() {
854        let path = temp_db_path("ping-pong");
855        let pager = Pager::open_default(&path).expect("open_default() should succeed");
856        let before = reddb_file::select_paged_superblock(&read_owned_zone(&pager))
857            .expect("operation should succeed");
858
859        pager
860            .allocate_page(PageType::BTreeLeaf)
861            .expect("allocate_page() should succeed");
862        pager.sync().expect("sync() should succeed");
863
864        let zone = read_owned_zone(&pager);
865        let after = reddb_file::select_paged_superblock(&zone)
866            .expect("select_paged_superblock() should succeed");
867        assert_ne!(
868            after.copy_index, before.copy_index,
869            "an update must target the stale copy"
870        );
871        assert!(after.generation > before.generation);
872
873        // The copy that was newest before the update is still readable — this
874        // is the byte-level statement of "a crash mid-write always leaves one
875        // valid copy".
876        let start = before.copy_index * SUPERBLOCK_SLOT_SIZE;
877        assert_eq!(
878            reddb_file::paged_superblock_slot_generation(
879                &zone[start..start + SUPERBLOCK_SLOT_SIZE],
880                before.copy_index
881            ),
882            Some(before.generation)
883        );
884
885        drop(pager);
886        cleanup(&path);
887    }
888
889    #[test]
890    fn failed_trunk_fence_is_completed_before_retrying_allocation() {
891        let path = temp_db_path("retry-trunk-fence");
892        let pager = Pager::open_default(&path).expect("pager");
893        // An empty trunk is itself reusable, so consuming its last page must
894        // still fence both superblocks even outside an ownership epoch.
895        let page = pager.allocate_page(PageType::BTreeLeaf).unwrap().page_id();
896        pager.sync().unwrap();
897        pager.free_page(page).unwrap();
898        pager.sync().unwrap();
899        let trunk = pager.header().unwrap().freelist_head;
900        assert_ne!(trunk, 0);
901
902        // A real write error after the trunk has been read must not turn a
903        // subsequent allocation into an unfenced fast-path reuse.
904        let writable = pager
905            .core
906            .with_file(|file| std::mem::replace(&mut file.0, File::open(&path).unwrap()))
907            .unwrap();
908        assert!(pager.allocate_page(PageType::BTreeLeaf).is_err());
909        pager.core.with_file(|file| file.0 = writable).unwrap();
910        pager.allocate_page(PageType::BTreeLeaf).unwrap();
911
912        let zone = read_owned_zone(&pager);
913        for copy in 0..reddb_file::PAGED_SUPERBLOCK_SLOT_COUNT {
914            let start = copy * SUPERBLOCK_SLOT_SIZE;
915            let header =
916                reddb_file::decode_database_header(&zone[start..start + SUPERBLOCK_SLOT_SIZE])
917                    .unwrap();
918            assert_ne!(
919                header.freelist_head, trunk,
920                "copy {copy} still owns consumed trunk"
921            );
922        }
923        drop(pager);
924        cleanup(&path);
925    }
926
927    #[test]
928    fn failed_unjournaled_trunk_write_requires_reopen_and_preserves_free_pages() {
929        let path = temp_db_path("failed-trunk-rewrite");
930        let pager = Pager::open_default(&path).expect("pager");
931        let mut pages = std::collections::HashSet::new();
932        for _ in 0..8 {
933            pages.insert(
934                pager
935                    .allocate_page(PageType::BTreeLeaf)
936                    .expect("seed page")
937                    .page_id(),
938            );
939        }
940        pager.sync().expect("persist seed");
941        for &id in &pages {
942            pager.free_page(id).expect("free seed page");
943        }
944        pager.sync().expect("persist free list");
945        let baseline = pager.page_count().expect("page count");
946        let writable = pager
947            .core
948            .with_file(|file| std::mem::replace(&mut file.0, File::open(&path).expect("read only")))
949            .expect("inject write failure");
950        assert!(pager.allocate_page(PageType::BTreeLeaf).is_err());
951        pager
952            .core
953            .with_file(|file| file.0 = writable)
954            .expect("restore file");
955        let error = pager
956            .allocate_page(PageType::BTreeLeaf)
957            .expect_err("writeback must stay fenced");
958        assert!(error.to_string().contains("reopen"), "{error}");
959        drop(pager);
960
961        let recovered = Pager::open_default(&path).expect("recover protected write");
962        let mut reused = std::collections::HashSet::new();
963        for _ in 0..pages.len() {
964            let id = recovered
965                .allocate_page(PageType::BTreeLeaf)
966                .expect("reuse after recovery")
967                .page_id();
968            if id >= baseline {
969                break;
970            }
971            assert!(pages.contains(&id), "unexpected free page {id}");
972            assert!(reused.insert(id), "duplicate reuse {id}");
973        }
974        // Only the single uncertain reservation may have been removed. The
975        // protected write must never detach and lose the rest of the trunk.
976        assert!(reused.len() >= pages.len() - 1, "lost free-page remainder");
977        drop(recovered);
978        cleanup(&path);
979    }
980
981    #[test]
982    fn sibling_superblock_recovery_does_not_reallocate_live_reused_pages() {
983        let path = temp_db_path("reused-allocator-pair");
984        let pager = Pager::open_default(&path).expect("pager");
985        let mut pages = Vec::new();
986        for _ in 0..32 {
987            pages.push(
988                pager
989                    .allocate_page(PageType::BTreeLeaf)
990                    .expect("allocate")
991                    .page_id(),
992            );
993        }
994        pager.sync().expect("seed");
995        for id in pages {
996            pager.free_page(id).expect("free");
997        }
998        pager.sync().expect("publish free list");
999        let mut live = std::collections::HashSet::new();
1000        for _ in 0..8 {
1001            let page = pager.allocate_page(PageType::BTreeLeaf).expect("reuse");
1002            live.insert(page.page_id());
1003            pager
1004                .write_page(page.page_id(), page)
1005                .expect("write valid page");
1006        }
1007        pager.sync().expect("publish reused ownership");
1008        drop(pager);
1009        let selection = reddb_file::select_paged_superblock(&read_zone(&path)).expect("superblock");
1010        poke_slot(&path, selection.copy_index, &[0; SUPERBLOCK_SLOT_SIZE]);
1011        let recovered = Pager::open_default(&path).expect("sibling recovery");
1012        for _ in 0..64 {
1013            let id = recovered
1014                .allocate_page(PageType::BTreeLeaf)
1015                .expect("allocate after recovery")
1016                .page_id();
1017            assert!(
1018                !live.contains(&id),
1019                "sibling allocator still considers live page {id} free"
1020            );
1021        }
1022        drop(recovered);
1023        cleanup(&path);
1024    }
1025
1026    #[test]
1027    fn open_recovers_from_the_older_copy_when_the_newest_is_torn() {
1028        let path = temp_db_path("torn-newest");
1029        {
1030            let pager = Pager::open_default(&path).expect("open_default() should succeed");
1031            pager
1032                .allocate_page(PageType::BTreeLeaf)
1033                .expect("allocate_page() should succeed");
1034            pager.sync().expect("sync() should succeed");
1035        }
1036
1037        let newest = reddb_file::select_paged_superblock(&read_zone(&path))
1038            .expect("operation should succeed");
1039        // Tear the newest copy: a torn write leaves its CRC broken.
1040        let mut torn = vec![0u8; SUPERBLOCK_SLOT_SIZE];
1041        torn.copy_from_slice(
1042            &read_zone(&path)[newest.copy_index * SUPERBLOCK_SLOT_SIZE
1043                ..newest.copy_index * SUPERBLOCK_SLOT_SIZE + SUPERBLOCK_SLOT_SIZE],
1044        );
1045        torn[64] ^= 0xFF;
1046        poke_slot(&path, newest.copy_index, &torn);
1047
1048        let before = std::fs::read(&path).expect("torn source");
1049        let reader = Pager::open(
1050            &path,
1051            PagerConfig {
1052                read_only: true,
1053                create: false,
1054                ..Default::default()
1055            },
1056        )
1057        .expect("read-only fallback to older superblock");
1058        assert!(reader.page_count().expect("read-only page count") >= 3);
1059        drop(reader);
1060        assert_eq!(std::fs::read(&path).expect("preserved torn source"), before);
1061
1062        let pager = Pager::open_default(&path).expect("older copy must root the store");
1063        assert!(pager.page_count().expect("page_count() should succeed") >= 3);
1064        drop(pager);
1065        cleanup(&path);
1066    }
1067
1068    #[test]
1069    fn open_refuses_didactically_when_both_superblock_copies_are_invalid() {
1070        let path = temp_db_path("both-invalid");
1071        {
1072            let _ = Pager::open_default(&path).expect("open_default() should succeed");
1073        }
1074
1075        let zone = read_zone(&path);
1076        for copy_index in 0..reddb_file::PAGED_SUPERBLOCK_SLOT_COUNT {
1077            let start = copy_index * SUPERBLOCK_SLOT_SIZE;
1078            let mut slot = zone[start..start + SUPERBLOCK_SLOT_SIZE].to_vec();
1079            slot[64] ^= 0xFF;
1080            poke_slot(&path, copy_index, &slot);
1081        }
1082
1083        let err = match Pager::open_default(&path) {
1084            Ok(_) => panic!("a rootless store must not open"),
1085            Err(err) => err,
1086        };
1087        let rendered = err.to_string();
1088        assert!(matches!(err, PagerError::SuperblockZoneUnrecoverable(_)));
1089        assert!(rendered.contains("superblock zone"), "{rendered}");
1090        assert!(rendered.contains("Preserve the database"), "{rendered}");
1091        assert!(rendered.contains("verified backup"), "{rendered}");
1092        assert!(!rendered.contains("salvage"), "{rendered}");
1093
1094        cleanup(&path);
1095    }
1096
1097    #[test]
1098    fn open_refuses_a_legacy_sidecar_store_and_names_the_migration_tool() {
1099        let path = temp_db_path("legacy-sidecar");
1100        {
1101            let _ = Pager::open_default(&path).expect("open_default() should succeed");
1102        }
1103
1104        let sidecar = reddb_file::layout::retired::pager_header_path_v0(&path);
1105        std::fs::write(&sidecar, b"legacy header shadow").expect("write() should succeed");
1106
1107        let err = match Pager::open_default(&path) {
1108            Ok(_) => panic!("legacy stores need migration first"),
1109            Err(err) => err,
1110        };
1111        let rendered = err.to_string();
1112        assert!(matches!(err, PagerError::LegacySidecarStore { .. }));
1113        assert!(rendered.contains("migration tool"), "{rendered}");
1114
1115        let _ = std::fs::remove_file(&sidecar);
1116        cleanup(&path);
1117    }
1118
1119    #[test]
1120    fn pre_phase3_large_store_without_sidecar_routes_to_migration() {
1121        let path = temp_db_path("pre-phase3-large");
1122        {
1123            let _ = Pager::open_default(&path).expect("open_default() should succeed");
1124        }
1125        stamp_pre_phase3_layout(&path, FIRST_ALLOCATABLE_PAGE);
1126
1127        let err = match Pager::open_default(&path) {
1128            Ok(_) => panic!("pre-phase-3 stores need migration first"),
1129            Err(err) => err,
1130        };
1131        let rendered = err.to_string();
1132        assert!(matches!(err, PagerError::LegacyPagedStore { .. }));
1133        assert!(rendered.contains("migration tool"), "{rendered}");
1134
1135        cleanup(&path);
1136    }
1137
1138    #[test]
1139    fn pre_phase3_small_store_without_sidecar_routes_to_migration() {
1140        let path = temp_db_path("pre-phase3-small");
1141        {
1142            let _ = Pager::open_default(&path).expect("open_default() should succeed");
1143        }
1144        stamp_pre_phase3_layout(&path, 3);
1145        OpenOptions::new()
1146            .write(true)
1147            .open(&path)
1148            .expect("open() should succeed")
1149            .set_len(3 * PAGE_SIZE as u64)
1150            .expect("set_len() should succeed");
1151
1152        let err = match Pager::open_default(&path) {
1153            Ok(_) => panic!("pre-phase-3 stores need migration first"),
1154            Err(err) => err,
1155        };
1156        assert!(matches!(err, PagerError::LegacyPagedStore { .. }));
1157
1158        cleanup(&path);
1159    }
1160
1161    #[test]
1162    fn no_phase_one_sidecar_survives_a_create_write_reopen_cycle() {
1163        let path = temp_db_path("census");
1164        {
1165            let pager = Pager::open_default(&path).expect("open_default() should succeed");
1166            let page = pager
1167                .allocate_page(PageType::BTreeLeaf)
1168                .expect("allocate_page() should succeed");
1169            pager
1170                .write_page(page.page_id(), page)
1171                .expect("operation should succeed");
1172            pager.sync().expect("sync() should succeed");
1173        }
1174        {
1175            let pager = Pager::open_default(&path).expect("open_default() should succeed");
1176            pager.sync().expect("sync() should succeed");
1177        }
1178
1179        assert_eq!(
1180            reddb_file::layout::retired::first_present_phase1_sidecar(&path),
1181            None,
1182            "the pager must never create a retired phase-1 sidecar"
1183        );
1184        cleanup(&path);
1185    }
1186}