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    fn versioned(id: u32, version: u64) -> Page {
542        let mut page = Page::new(PageType::BTreeLeaf, id);
543        page.content_mut()[..8].copy_from_slice(&version.to_le_bytes());
544        page
545    }
546
547    fn version(page: &Page) -> u64 {
548        u64::from_le_bytes(page.content()[..8].try_into().expect("version"))
549    }
550
551    #[test]
552    fn a_miss_reads_the_published_page_while_another_thread_holds_the_epoch() {
553        let directory = tempfile::tempdir().expect("temporary directory");
554        let path = directory.path().join("data.rdb");
555        let writer = Pager::open(&path, Default::default()).expect("pager");
556        let id = writer
557            .allocate_page(PageType::BTreeLeaf)
558            .expect("allocate")
559            .page_id();
560        writer.write_page(id, versioned(id, 7)).expect("write");
561        writer.sync().expect("publish");
562        drop(writer);
563
564        // A fresh pager has nothing cached, so the read below is a miss.
565        let pager = Arc::new(
566            Pager::open(
567                &path,
568                PagerConfig {
569                    create: false,
570                    ..Default::default()
571                },
572            )
573            .expect("reopen"),
574        );
575        let epoch = pager.lock_ownership_mutations();
576        let (done_tx, done_rx) = std::sync::mpsc::channel();
577        let reader_pager = Arc::clone(&pager);
578        let reader = std::thread::spawn(move || {
579            done_tx
580                .send(reader_pager.read_page(id).map(|page| version(&page)))
581                .expect("signal read");
582        });
583        let read = done_rx
584            .recv_timeout(std::time::Duration::from_secs(10))
585            .expect("a reader waited for another thread's ownership epoch");
586        assert_eq!(read.expect("read"), 7);
587        drop(epoch);
588        reader.join().expect("reader");
589    }
590
591    #[test]
592    fn a_miss_outside_the_epoch_never_misses_a_finished_write() {
593        use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
594
595        let directory = tempfile::tempdir().expect("temporary directory");
596        let pager = Arc::new(
597            Pager::open(
598                directory.path().join("data.rdb"),
599                PagerConfig {
600                    cache_size: 1,
601                    ..Default::default()
602                },
603            )
604            .expect("pager"),
605        );
606        // Several cache generations, so every round of writes evicts dirty
607        // images whose only copy is then on its way to the file.
608        let ids: Vec<u32> = (0..pager.cache_capacity() * 4)
609            .map(|_| {
610                pager
611                    .allocate_page(PageType::BTreeLeaf)
612                    .expect("allocate")
613                    .page_id()
614            })
615            .collect();
616        for &id in &ids {
617            pager.write_page(id, versioned(id, 0)).expect("seed");
618        }
619        pager.sync().expect("publish");
620
621        let written: Arc<Vec<AtomicU64>> =
622            Arc::new(ids.iter().map(|_| AtomicU64::new(0)).collect());
623        let done = Arc::new(AtomicBool::new(false));
624        let reads = Arc::new(AtomicU64::new(0));
625        let readers: Vec<_> = (0..3)
626            .map(|reader| {
627                let (pager, ids, written, done, reads) = (
628                    Arc::clone(&pager),
629                    ids.clone(),
630                    Arc::clone(&written),
631                    Arc::clone(&done),
632                    Arc::clone(&reads),
633                );
634                std::thread::spawn(move || {
635                    let mut at = reader;
636                    while !done.load(Ordering::Acquire) {
637                        at = (at + 7) % ids.len();
638                        // A write that has returned is the least this read may see.
639                        let floor = written[at].load(Ordering::SeqCst);
640                        let page = pager.read_page(ids[at]).expect("read");
641                        assert!(
642                            version(&page) >= floor,
643                            "page {} read at version {} after version {floor} was written",
644                            ids[at],
645                            version(&page)
646                        );
647                        reads.fetch_add(1, Ordering::Relaxed);
648                    }
649                })
650            })
651            .collect();
652
653        // One epoch for every round, as a checkpoint holds it.
654        let epoch = pager.lock_ownership_mutations();
655        for round in 1..=40u64 {
656            for (at, &id) in ids.iter().enumerate() {
657                pager.write_page(id, versioned(id, round)).expect("write");
658                written[at].store(round, Ordering::SeqCst);
659            }
660        }
661        let during_epoch = reads.load(Ordering::Relaxed);
662        drop(epoch);
663        done.store(true, Ordering::Release);
664        for reader in readers {
665            reader.join().expect("reader saw a stale page");
666        }
667        assert!(
668            during_epoch > 0,
669            "no read finished while the epoch was held"
670        );
671    }
672
673    #[test]
674    fn ownership_scope_serializes_other_allocators_and_fences_errors() {
675        let directory = tempfile::tempdir().expect("temporary directory");
676        let pager = Arc::new(
677            Pager::open(directory.path().join("data.rdb"), Default::default()).expect("pager"),
678        );
679        let scope = pager.lock_ownership_mutations();
680        let (started_tx, started_rx) = std::sync::mpsc::channel();
681        let (done_tx, done_rx) = std::sync::mpsc::channel();
682        let other_pager = Arc::clone(&pager);
683        let worker = std::thread::spawn(move || {
684            started_tx.send(()).expect("signal worker started");
685            let page = other_pager.allocate_page(PageType::BTreeLeaf);
686            done_tx
687                .send(page.map(|page| page.page_id()))
688                .expect("signal allocation");
689        });
690        started_rx.recv().expect("worker started");
691        assert!(done_rx
692            .recv_timeout(std::time::Duration::from_millis(100))
693            .is_err());
694        let own = pager
695            .allocate_page(PageType::BTreeLeaf)
696            .expect("reentrant allocation");
697        drop(scope);
698        let other = done_rx
699            .recv()
700            .expect("worker result")
701            .expect("other allocation");
702        worker.join().expect("worker");
703        assert_ne!(own.page_id(), other);
704        pager.fence_interrupted_ownership();
705        assert!(pager.allocate_page(PageType::BTreeLeaf).is_err());
706    }
707
708    fn temp_db_path(name: &str) -> PathBuf {
709        std::env::temp_dir().join(format!(
710            "reddb-pager-{}-{}-{}.rdb",
711            name,
712            std::process::id(),
713            crate::utils::now_unix_nanos()
714        ))
715    }
716
717    fn cleanup(path: &Path) {
718        let _ = std::fs::remove_file(path);
719        let _ = std::fs::remove_file(Pager::dwb_path(path));
720    }
721
722    fn read_zone(path: &Path) -> Vec<u8> {
723        let mut zone = vec![0u8; SUPERBLOCK_ZONE_SIZE];
724        let mut file = File::open(path).expect("open() should succeed");
725        file.read_exact(&mut zone)
726            .expect("read_exact() should succeed");
727        zone
728    }
729
730    fn read_owned_zone(pager: &Pager) -> [u8; SUPERBLOCK_ZONE_SIZE] {
731        pager
732            .core
733            .with_file(reddb_engine::storage::pager_io::read_superblock_zone)
734            .expect("owned pager file")
735            .expect("superblock read")
736    }
737
738    #[test]
739    fn read_only_dwb_recovery_survives_cache_eviction_without_writing() {
740        let directory = tempfile::tempdir().expect("fixture");
741        let path = directory.path().join("data.rdb");
742        let writer = Pager::open_default(&path).expect("writer");
743        let mut pages = Vec::new();
744        for _ in 0..100 {
745            let mut page = writer.allocate_page(PageType::Overflow).expect("allocate");
746            page.update_checksum();
747            writer
748                .write_page(page.page_id(), page.clone())
749                .expect("page");
750            pages.push(page);
751        }
752        writer.sync().expect("checkpoint");
753        drop(writer);
754        let mut staged = pages.last().expect("tail page").clone();
755        staged.content_mut()[0] = 123;
756        staged.update_checksum();
757        let frame = reddb_file::encode_paged_dwb_frame([(staged.page_id(), staged.as_bytes())]);
758        let mut file = OpenOptions::new().write(true).open(&path).expect("fixture");
759        file.seek(SeekFrom::Start(
760            u64::from(reddb_engine::storage::pager_io::DWB_ZONE_START_PAGE) * PAGE_SIZE as u64,
761        ))
762        .expect("DWB offset");
763        file.write_all(&frame).expect("stage durable image");
764        // Simulate interruption before the staged tail page reached its home.
765        file.set_len(u64::from(staged.page_id()) * PAGE_SIZE as u64)
766            .expect("truncate tail");
767        file.sync_all().expect("fixture sync");
768        drop(file);
769        let before = std::fs::read(&path).expect("source bytes");
770        for _ in 0..2 {
771            let reader = Pager::open(
772                &path,
773                PagerConfig {
774                    read_only: true,
775                    create: false,
776                    cache_size: 2,
777                    ..Default::default()
778                },
779            )
780            .expect("read-only DWB recovery");
781            for page in &pages[..pages.len() - 1] {
782                reader
783                    .read_page(page.page_id())
784                    .expect("evict ordinary cache entries");
785            }
786            assert_eq!(
787                reader
788                    .read_page(staged.page_id())
789                    .expect("recovered tail")
790                    .as_bytes(),
791                staged.as_bytes()
792            );
793            assert!(reader.write_page(staged.page_id(), staged.clone()).is_err());
794            drop(reader);
795            assert_eq!(std::fs::read(&path).expect("unchanged source"), before);
796        }
797        let writer = Pager::open_default(&path).expect("ordinary DWB recovery");
798        assert_eq!(
799            writer
800                .read_page(staged.page_id())
801                .expect("durable tail")
802                .as_bytes(),
803            staged.as_bytes()
804        );
805    }
806
807    #[test]
808    fn read_only_dwb_retains_raw_pages_for_host_authentication() {
809        let directory = tempfile::tempdir().expect("fixture");
810        let path = directory.path().join("data.rdb");
811        let writer = Pager::open_default(&path).expect("writer");
812        let id = writer
813            .allocate_page(PageType::Overflow)
814            .expect("page")
815            .page_id();
816        writer.sync().expect("checkpoint");
817        drop(writer);
818        // Ciphertext does not carry a plaintext PageHeader or page checksum.
819        let raw = [91; PAGE_SIZE];
820        let frame = reddb_file::encode_paged_dwb_frame([(id, &raw)]);
821        let mut file = OpenOptions::new().write(true).open(&path).expect("fixture");
822        file.seek(SeekFrom::Start(
823            u64::from(DWB_ZONE_START_PAGE) * PAGE_SIZE as u64,
824        ))
825        .expect("DWB offset");
826        file.write_all(&frame).expect("staged raw frame");
827        file.sync_all().expect("fixture sync");
828        drop(file);
829        let before = std::fs::read(&path).expect("source");
830        let reader = Pager::open(
831            &path,
832            PagerConfig {
833                read_only: true,
834                create: false,
835                ..Default::default()
836            },
837        )
838        .expect("raw DWB recovery");
839        assert_eq!(
840            reader
841                .read_page_no_checksum(id)
842                .expect("raw image")
843                .as_bytes(),
844            &raw
845        );
846        assert!(
847            reader.read_page(id).is_err(),
848            "normal reads still require a page checksum"
849        );
850        drop(reader);
851        assert_eq!(std::fs::read(&path).expect("unchanged source"), before);
852    }
853
854    #[test]
855    fn read_only_recovery_refuses_excess_images_without_writing() {
856        let directory = tempfile::tempdir().expect("fixture");
857        let path = directory.path().join("data.rdb");
858        drop(Pager::open_default(&path).expect("writer"));
859        let before = std::fs::read(&path).expect("source");
860        let reader = Pager::open(
861            &path,
862            PagerConfig {
863                read_only: true,
864                create: false,
865                cache_size: 2,
866                ..Default::default()
867            },
868        )
869        .expect("reader");
870        let limit = reddb_engine::storage::pager_io::DWB_MAX_PAGES_PER_FRAME;
871        for index in 0..=limit {
872            let id = reddb_engine::storage::pager_io::FIRST_ALLOCATABLE_PAGE + index as u32;
873            let mut page = Page::new(PageType::Overflow, id);
874            page.update_checksum();
875            let result = reader.restore_read_only_page(id, page);
876            if index < limit {
877                result.expect("within recovery budget");
878            } else {
879                assert!(result
880                    .expect_err("bounded recovery")
881                    .to_string()
882                    .contains("budget"));
883            }
884        }
885        drop(reader);
886        assert_eq!(std::fs::read(&path).expect("unchanged source"), before);
887    }
888
889    /// Overwrite one superblock slot in place, leaving the sibling untouched.
890    fn poke_slot(path: &Path, copy_index: usize, bytes: &[u8]) {
891        let mut file = OpenOptions::new()
892            .write(true)
893            .open(path)
894            .expect("open() should succeed");
895        file.seek(SeekFrom::Start(reddb_file::paged_superblock_slot_offset(
896            copy_index,
897        )))
898        .expect("operation should succeed");
899        file.write_all(bytes).expect("write_all() should succeed");
900        file.sync_all().expect("sync_all() should succeed");
901    }
902
903    fn stamp_pre_phase3_layout(path: &Path, page_count: u32) {
904        let zone = read_zone(path);
905        for copy_index in 0..reddb_file::PAGED_SUPERBLOCK_SLOT_COUNT {
906            let start = copy_index * SUPERBLOCK_SLOT_SIZE;
907            let mut slot = zone[start..start + SUPERBLOCK_SLOT_SIZE].to_vec();
908            let generation = reddb_file::paged_superblock_slot_generation(&slot, copy_index)
909                .expect("fresh store should publish both slots");
910            reddb_file::set_database_header_version(
911                &mut slot,
912                reddb_file::PAGE_DWB_ZONE_FILE_VERSION - 1,
913            )
914            .expect("set_database_header_version() should succeed");
915            reddb_file::set_database_header_page_count(&mut slot, page_count)
916                .expect("set_database_header_page_count() should succeed");
917            reddb_file::seal_paged_superblock_slot(&mut slot, copy_index, generation)
918                .expect("seal_paged_superblock_slot() should succeed");
919            poke_slot(path, copy_index, &slot);
920        }
921    }
922
923    #[test]
924    fn open_refuses_future_database_version() {
925        let path = temp_db_path("future-version");
926        let pager = Pager::open_default(&path).expect("open_default() should succeed");
927        drop(pager);
928
929        // A *valid* superblock slot — correct magic, copy index and CRC — whose
930        // database header names a version we cannot read. The slot is intact;
931        // the header is from the future.
932        let selection = reddb_file::select_paged_superblock(&read_zone(&path))
933            .expect("operation should succeed");
934        let mut slot = vec![0u8; SUPERBLOCK_SLOT_SIZE];
935        reddb_file::init_database_header_page(&mut slot, 1)
936            .expect("init_database_header_page() should succeed");
937        reddb_file::set_database_header_version(&mut slot, reddb_file::PAGE_FILE_VERSION + 1)
938            .expect("operation should succeed");
939        reddb_file::seal_paged_superblock_slot(
940            &mut slot,
941            selection.copy_index,
942            selection.generation + 1,
943        )
944        .expect("operation should succeed");
945        poke_slot(&path, selection.copy_index, &slot);
946
947        let err = match Pager::open_default(&path) {
948            Ok(_) => panic!("future database version should be rejected"),
949            Err(err) => err,
950        };
951        match err {
952            PagerError::InvalidDatabase(msg) => {
953                assert!(msg.contains("newer than supported"), "{msg}");
954            }
955            other => panic!("expected InvalidDatabase, got {other:?}"),
956        }
957
958        cleanup(&path);
959    }
960
961    #[test]
962    fn a_fresh_store_publishes_both_superblock_copies() {
963        // The ping-pong invariant must hold from the very first update, which
964        // means creation cannot leave one copy blank.
965        let path = temp_db_path("fresh-pair");
966        let pager = Pager::open_default(&path).expect("open_default() should succeed");
967        drop(pager);
968
969        let zone = read_zone(&path);
970        for copy_index in 0..reddb_file::PAGED_SUPERBLOCK_SLOT_COUNT {
971            let start = copy_index * SUPERBLOCK_SLOT_SIZE;
972            assert!(
973                reddb_file::paged_superblock_slot_generation(
974                    &zone[start..start + SUPERBLOCK_SLOT_SIZE],
975                    copy_index
976                )
977                .is_some(),
978                "copy {copy_index} must be valid on a fresh store"
979            );
980        }
981        cleanup(&path);
982    }
983
984    #[test]
985    fn an_update_writes_the_stale_copy_and_leaves_the_newest_one_intact() {
986        let path = temp_db_path("ping-pong");
987        let pager = Pager::open_default(&path).expect("open_default() should succeed");
988        let before = reddb_file::select_paged_superblock(&read_owned_zone(&pager))
989            .expect("operation should succeed");
990
991        pager
992            .allocate_page(PageType::BTreeLeaf)
993            .expect("allocate_page() should succeed");
994        pager.sync().expect("sync() should succeed");
995
996        let zone = read_owned_zone(&pager);
997        let after = reddb_file::select_paged_superblock(&zone)
998            .expect("select_paged_superblock() should succeed");
999        assert_ne!(
1000            after.copy_index, before.copy_index,
1001            "an update must target the stale copy"
1002        );
1003        assert!(after.generation > before.generation);
1004
1005        // The copy that was newest before the update is still readable — this
1006        // is the byte-level statement of "a crash mid-write always leaves one
1007        // valid copy".
1008        let start = before.copy_index * SUPERBLOCK_SLOT_SIZE;
1009        assert_eq!(
1010            reddb_file::paged_superblock_slot_generation(
1011                &zone[start..start + SUPERBLOCK_SLOT_SIZE],
1012                before.copy_index
1013            ),
1014            Some(before.generation)
1015        );
1016
1017        drop(pager);
1018        cleanup(&path);
1019    }
1020
1021    #[test]
1022    fn failed_trunk_fence_is_completed_before_retrying_allocation() {
1023        let path = temp_db_path("retry-trunk-fence");
1024        let pager = Pager::open_default(&path).expect("pager");
1025        // An empty trunk is itself reusable, so consuming its last page must
1026        // still fence both superblocks even outside an ownership epoch.
1027        let page = pager.allocate_page(PageType::BTreeLeaf).unwrap().page_id();
1028        pager.sync().unwrap();
1029        pager.free_page(page).unwrap();
1030        pager.sync().unwrap();
1031        let trunk = pager.header().unwrap().freelist_head;
1032        assert_ne!(trunk, 0);
1033
1034        // A real write error after the trunk has been read must not turn a
1035        // subsequent allocation into an unfenced fast-path reuse.
1036        let writable = pager
1037            .core
1038            .with_file(|file| std::mem::replace(&mut file.0, File::open(&path).unwrap()))
1039            .unwrap();
1040        assert!(pager.allocate_page(PageType::BTreeLeaf).is_err());
1041        pager.core.with_file(|file| file.0 = writable).unwrap();
1042        pager.allocate_page(PageType::BTreeLeaf).unwrap();
1043
1044        let zone = read_owned_zone(&pager);
1045        for copy in 0..reddb_file::PAGED_SUPERBLOCK_SLOT_COUNT {
1046            let start = copy * SUPERBLOCK_SLOT_SIZE;
1047            let header =
1048                reddb_file::decode_database_header(&zone[start..start + SUPERBLOCK_SLOT_SIZE])
1049                    .unwrap();
1050            assert_ne!(
1051                header.freelist_head, trunk,
1052                "copy {copy} still owns consumed trunk"
1053            );
1054        }
1055        drop(pager);
1056        cleanup(&path);
1057    }
1058
1059    #[test]
1060    fn failed_unjournaled_trunk_write_requires_reopen_and_preserves_free_pages() {
1061        let path = temp_db_path("failed-trunk-rewrite");
1062        let pager = Pager::open_default(&path).expect("pager");
1063        let mut pages = std::collections::HashSet::new();
1064        for _ in 0..8 {
1065            pages.insert(
1066                pager
1067                    .allocate_page(PageType::BTreeLeaf)
1068                    .expect("seed page")
1069                    .page_id(),
1070            );
1071        }
1072        pager.sync().expect("persist seed");
1073        for &id in &pages {
1074            pager.free_page(id).expect("free seed page");
1075        }
1076        pager.sync().expect("persist free list");
1077        let baseline = pager.page_count().expect("page count");
1078        let writable = pager
1079            .core
1080            .with_file(|file| std::mem::replace(&mut file.0, File::open(&path).expect("read only")))
1081            .expect("inject write failure");
1082        assert!(pager.allocate_page(PageType::BTreeLeaf).is_err());
1083        pager
1084            .core
1085            .with_file(|file| file.0 = writable)
1086            .expect("restore file");
1087        let error = pager
1088            .allocate_page(PageType::BTreeLeaf)
1089            .expect_err("writeback must stay fenced");
1090        assert!(error.to_string().contains("reopen"), "{error}");
1091        drop(pager);
1092
1093        let recovered = Pager::open_default(&path).expect("recover protected write");
1094        let mut reused = std::collections::HashSet::new();
1095        for _ in 0..pages.len() {
1096            let id = recovered
1097                .allocate_page(PageType::BTreeLeaf)
1098                .expect("reuse after recovery")
1099                .page_id();
1100            if id >= baseline {
1101                break;
1102            }
1103            assert!(pages.contains(&id), "unexpected free page {id}");
1104            assert!(reused.insert(id), "duplicate reuse {id}");
1105        }
1106        // Only the single uncertain reservation may have been removed. The
1107        // protected write must never detach and lose the rest of the trunk.
1108        assert!(reused.len() >= pages.len() - 1, "lost free-page remainder");
1109        drop(recovered);
1110        cleanup(&path);
1111    }
1112
1113    #[test]
1114    fn sibling_superblock_recovery_does_not_reallocate_live_reused_pages() {
1115        let path = temp_db_path("reused-allocator-pair");
1116        let pager = Pager::open_default(&path).expect("pager");
1117        let mut pages = Vec::new();
1118        for _ in 0..32 {
1119            pages.push(
1120                pager
1121                    .allocate_page(PageType::BTreeLeaf)
1122                    .expect("allocate")
1123                    .page_id(),
1124            );
1125        }
1126        pager.sync().expect("seed");
1127        for id in pages {
1128            pager.free_page(id).expect("free");
1129        }
1130        pager.sync().expect("publish free list");
1131        let mut live = std::collections::HashSet::new();
1132        for _ in 0..8 {
1133            let page = pager.allocate_page(PageType::BTreeLeaf).expect("reuse");
1134            live.insert(page.page_id());
1135            pager
1136                .write_page(page.page_id(), page)
1137                .expect("write valid page");
1138        }
1139        pager.sync().expect("publish reused ownership");
1140        drop(pager);
1141        let selection = reddb_file::select_paged_superblock(&read_zone(&path)).expect("superblock");
1142        poke_slot(&path, selection.copy_index, &[0; SUPERBLOCK_SLOT_SIZE]);
1143        let recovered = Pager::open_default(&path).expect("sibling recovery");
1144        for _ in 0..64 {
1145            let id = recovered
1146                .allocate_page(PageType::BTreeLeaf)
1147                .expect("allocate after recovery")
1148                .page_id();
1149            assert!(
1150                !live.contains(&id),
1151                "sibling allocator still considers live page {id} free"
1152            );
1153        }
1154        drop(recovered);
1155        cleanup(&path);
1156    }
1157
1158    #[test]
1159    fn open_recovers_from_the_older_copy_when_the_newest_is_torn() {
1160        let path = temp_db_path("torn-newest");
1161        {
1162            let pager = Pager::open_default(&path).expect("open_default() should succeed");
1163            pager
1164                .allocate_page(PageType::BTreeLeaf)
1165                .expect("allocate_page() should succeed");
1166            pager.sync().expect("sync() should succeed");
1167        }
1168
1169        let newest = reddb_file::select_paged_superblock(&read_zone(&path))
1170            .expect("operation should succeed");
1171        // Tear the newest copy: a torn write leaves its CRC broken.
1172        let mut torn = vec![0u8; SUPERBLOCK_SLOT_SIZE];
1173        torn.copy_from_slice(
1174            &read_zone(&path)[newest.copy_index * SUPERBLOCK_SLOT_SIZE
1175                ..newest.copy_index * SUPERBLOCK_SLOT_SIZE + SUPERBLOCK_SLOT_SIZE],
1176        );
1177        torn[64] ^= 0xFF;
1178        poke_slot(&path, newest.copy_index, &torn);
1179
1180        let before = std::fs::read(&path).expect("torn source");
1181        let reader = Pager::open(
1182            &path,
1183            PagerConfig {
1184                read_only: true,
1185                create: false,
1186                ..Default::default()
1187            },
1188        )
1189        .expect("read-only fallback to older superblock");
1190        assert!(reader.page_count().expect("read-only page count") >= 3);
1191        drop(reader);
1192        assert_eq!(std::fs::read(&path).expect("preserved torn source"), before);
1193
1194        let pager = Pager::open_default(&path).expect("older copy must root the store");
1195        assert!(pager.page_count().expect("page_count() should succeed") >= 3);
1196        drop(pager);
1197        cleanup(&path);
1198    }
1199
1200    #[test]
1201    fn open_refuses_didactically_when_both_superblock_copies_are_invalid() {
1202        let path = temp_db_path("both-invalid");
1203        {
1204            let _ = Pager::open_default(&path).expect("open_default() should succeed");
1205        }
1206
1207        let zone = read_zone(&path);
1208        for copy_index in 0..reddb_file::PAGED_SUPERBLOCK_SLOT_COUNT {
1209            let start = copy_index * SUPERBLOCK_SLOT_SIZE;
1210            let mut slot = zone[start..start + SUPERBLOCK_SLOT_SIZE].to_vec();
1211            slot[64] ^= 0xFF;
1212            poke_slot(&path, copy_index, &slot);
1213        }
1214
1215        let err = match Pager::open_default(&path) {
1216            Ok(_) => panic!("a rootless store must not open"),
1217            Err(err) => err,
1218        };
1219        let rendered = err.to_string();
1220        assert!(matches!(err, PagerError::SuperblockZoneUnrecoverable(_)));
1221        assert!(rendered.contains("superblock zone"), "{rendered}");
1222        assert!(rendered.contains("Preserve the database"), "{rendered}");
1223        assert!(rendered.contains("verified backup"), "{rendered}");
1224        assert!(!rendered.contains("salvage"), "{rendered}");
1225
1226        cleanup(&path);
1227    }
1228
1229    #[test]
1230    fn open_refuses_a_legacy_sidecar_store_and_names_the_migration_tool() {
1231        let path = temp_db_path("legacy-sidecar");
1232        {
1233            let _ = Pager::open_default(&path).expect("open_default() should succeed");
1234        }
1235
1236        let sidecar = reddb_file::layout::retired::pager_header_path_v0(&path);
1237        std::fs::write(&sidecar, b"legacy header shadow").expect("write() should succeed");
1238
1239        let err = match Pager::open_default(&path) {
1240            Ok(_) => panic!("legacy stores need migration first"),
1241            Err(err) => err,
1242        };
1243        let rendered = err.to_string();
1244        assert!(matches!(err, PagerError::LegacySidecarStore { .. }));
1245        assert!(rendered.contains("migration tool"), "{rendered}");
1246
1247        let _ = std::fs::remove_file(&sidecar);
1248        cleanup(&path);
1249    }
1250
1251    #[test]
1252    fn pre_phase3_large_store_without_sidecar_routes_to_migration() {
1253        let path = temp_db_path("pre-phase3-large");
1254        {
1255            let _ = Pager::open_default(&path).expect("open_default() should succeed");
1256        }
1257        stamp_pre_phase3_layout(&path, FIRST_ALLOCATABLE_PAGE);
1258
1259        let err = match Pager::open_default(&path) {
1260            Ok(_) => panic!("pre-phase-3 stores need migration first"),
1261            Err(err) => err,
1262        };
1263        let rendered = err.to_string();
1264        assert!(matches!(err, PagerError::LegacyPagedStore { .. }));
1265        assert!(rendered.contains("migration tool"), "{rendered}");
1266
1267        cleanup(&path);
1268    }
1269
1270    #[test]
1271    fn pre_phase3_small_store_without_sidecar_routes_to_migration() {
1272        let path = temp_db_path("pre-phase3-small");
1273        {
1274            let _ = Pager::open_default(&path).expect("open_default() should succeed");
1275        }
1276        stamp_pre_phase3_layout(&path, 3);
1277        OpenOptions::new()
1278            .write(true)
1279            .open(&path)
1280            .expect("open() should succeed")
1281            .set_len(3 * PAGE_SIZE as u64)
1282            .expect("set_len() should succeed");
1283
1284        let err = match Pager::open_default(&path) {
1285            Ok(_) => panic!("pre-phase-3 stores need migration first"),
1286            Err(err) => err,
1287        };
1288        assert!(matches!(err, PagerError::LegacyPagedStore { .. }));
1289
1290        cleanup(&path);
1291    }
1292
1293    #[test]
1294    fn no_phase_one_sidecar_survives_a_create_write_reopen_cycle() {
1295        let path = temp_db_path("census");
1296        {
1297            let pager = Pager::open_default(&path).expect("open_default() should succeed");
1298            let page = pager
1299                .allocate_page(PageType::BTreeLeaf)
1300                .expect("allocate_page() should succeed");
1301            pager
1302                .write_page(page.page_id(), page)
1303                .expect("operation should succeed");
1304            pager.sync().expect("sync() should succeed");
1305        }
1306        {
1307            let pager = Pager::open_default(&path).expect("open_default() should succeed");
1308            pager.sync().expect("sync() should succeed");
1309        }
1310
1311        assert_eq!(
1312            reddb_file::layout::retired::first_present_phase1_sidecar(&path),
1313            None,
1314            "the pager must never create a retired phase-1 sidecar"
1315        );
1316        cleanup(&path);
1317    }
1318}