Skip to main content

reddb_engine/storage/
pager.rs

1//! Shared pager orchestration over an exclusively owned VFS file.
2//!
3//! Native and browser use the same cache, allocation fences, freelist, DWB,
4//! superblock publication and checkpoint algorithms. Opening/locking files,
5//! scheduling, WAL implementation and encryption remain host policy.
6//! The owner explicitly calls `sync` before teardown; this low-level pager
7//! does not hide I/O failures in a destructor. It is not a transaction API.
8use super::freelist::FreeList;
9use super::page::{Page, PageError, PageType, PAGE_SIZE};
10use super::page_cache::PageCache;
11use super::pager_io::{self, FIRST_ALLOCATABLE_PAGE};
12use reddb_file::VfsFile;
13pub use reddb_file::{DatabaseHeader, PhysicalFileHeader};
14use std::path::{Path, PathBuf};
15use std::sync::{Mutex, RwLock};
16
17mod batch;
18
19/// Pager error types
20#[derive(Debug)]
21pub enum PagerError {
22    /// I/O error
23    Io(std::io::Error),
24    /// Page error
25    Page(PageError),
26    /// Invalid database file
27    InvalidDatabase(String),
28    /// Database is read-only
29    ReadOnly,
30    /// Page not found
31    PageNotFound(u32),
32    /// Database is locked
33    Locked,
34    /// A Mutex or RwLock was poisoned (another thread panicked while holding it)
35    LockPoisoned,
36    /// Database is encrypted but no key was supplied.
37    EncryptionRequired,
38    /// Plain (unencrypted) database opened with an encryption key.
39    PlainDatabaseRefusesKey,
40    /// Encryption key validation failed for an encrypted database.
41    InvalidKey,
42    /// Both superblock copies failed validation (ADR 0074 §2).
43    SuperblockZoneUnrecoverable(PathBuf),
44    /// The internal manifest zone failed its checksum (ADR 0074 §2).
45    ManifestZoneCorrupt(PathBuf),
46    /// The in-file double-write zone failed validation (ADR 0074 §2).
47    DwbZoneCorrupt(PathBuf),
48    /// The store still carries a retired phase-1 pager sidecar (ADR 0038 §4).
49    LegacySidecarStore { sidecar: PathBuf },
50    /// The store predates the phase-3 in-file DWB layout marker (ADR 0038 §4).
51    LegacyPagedStore { path: PathBuf },
52}
53
54/// A contiguous run of database pages reserved for vector-turbo payloads.
55#[derive(Debug, Clone, Copy, PartialEq, Eq)]
56pub struct ExtentId {
57    pub start_page: u32,
58    pub n_pages: u32,
59}
60
61impl std::fmt::Display for PagerError {
62    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
63        match self {
64            Self::Io(e) => write!(f, "I/O error: {}", e),
65            Self::Page(e) => write!(f, "Page error: {}", e),
66            Self::InvalidDatabase(msg) => write!(f, "Invalid database: {}", msg),
67            Self::ReadOnly => write!(f, "Database is read-only"),
68            Self::PageNotFound(id) => write!(f, "Page {} not found", id),
69            Self::Locked => write!(f, "Database is locked"),
70            Self::LockPoisoned => write!(f, "Internal lock poisoned (concurrent thread panicked)"),
71            Self::EncryptionRequired => write!(
72                f,
73                "Database is encrypted but no key was supplied (set PagerConfig::encryption)"
74            ),
75            Self::PlainDatabaseRefusesKey => write!(
76                f,
77                "Plain (unencrypted) database opened with an encryption key — refusing"
78            ),
79            Self::InvalidKey => write!(f, "Encryption key validation failed for this database"),
80            Self::SuperblockZoneUnrecoverable(path) => write!(
81                f,
82                "superblock zone of {} is unrecoverable: both ping-pong copies failed \
83                 validation, so no generation can be trusted to root the store. The store \
84                 will not be opened. Preserve the database and its recovery files; \
85                 restore from a verified backup.",
86                path.display()
87            ),
88            Self::ManifestZoneCorrupt(path) => write!(
89                f,
90                "internal manifest zone of {} failed its checksum: the zone that names \
91                 collections, indexes and the checkpoint boundary cannot be trusted, so no \
92                 rows are returned. Preserve the database and its recovery files; \
93                 restore from a verified backup.",
94                path.display()
95            ),
96            Self::DwbZoneCorrupt(path) => write!(
97                f,
98                "double-write zone of {} failed validation: page recovery cannot prove \
99                 whether the protected in-place write completed. The store will not be opened \
100                 silently. Preserve the database and its recovery files; restore from \
101                 a verified backup.",
102                path.display()
103            ),
104            Self::LegacySidecarStore { sidecar } => write!(
105                f,
106                "refusing to open a legacy sidecar-backed store: found {}. The superblock \
107                 pair, internal manifest, and double-write recovery state now live inside the \
108                 .rdb file (ADR 0038 §2/§4), \
109                 and the engine never reads the retired sidecars silently. Convert the store \
110                 first with the offline migration tool \
111                 (`reddb_server::pager_zone_migration::migrate_to_zoned`); it is reversible.",
112                sidecar.display()
113            ),
114            Self::LegacyPagedStore { path } => write!(
115                f,
116                "refusing to open a pre-phase-3 paged store: {} does not carry the layout marker \
117                 for the in-file double-write zone. Convert the store first with the offline \
118                 migration tool (`reddb_server::pager_zone_migration::migrate_to_zoned`); it is \
119                 reversible.",
120                path.display()
121            ),
122        }
123    }
124}
125
126impl std::error::Error for PagerError {
127    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
128        match self {
129            Self::Io(e) => Some(e),
130            Self::Page(e) => Some(e),
131            _ => None,
132        }
133    }
134}
135
136impl From<std::io::Error> for PagerError {
137    fn from(e: std::io::Error) -> Self {
138        Self::Io(e)
139    }
140}
141
142impl From<PageError> for PagerError {
143    fn from(e: PageError) -> Self {
144        Self::Page(e)
145    }
146}
147
148impl From<pager_io::PagerIoError> for PagerError {
149    fn from(error: pager_io::PagerIoError) -> Self {
150        match error {
151            pager_io::PagerIoError::Io(error) => Self::Io(error),
152            pager_io::PagerIoError::Page(error) => Self::Page(error),
153            pager_io::PagerIoError::InvalidDatabase(message) => Self::InvalidDatabase(message),
154        }
155    }
156}
157
158/// How long a miss lets an eviction write of another thread's epoch finish
159/// before it looks again.
160const EVICTION_WRITE_POLL: std::time::Duration = std::time::Duration::from_micros(500);
161
162/// Host-independent pager configuration. File creation and ownership are host policy.
163#[derive(Debug, Clone)]
164pub struct PagerConfig {
165    /// Host guarantees immutable published trees and generation-bound resume counters.
166    pub disk_residency: bool,
167    pub cache_size: usize,
168    pub read_only: bool,
169    pub verify_checksums: bool,
170    pub double_write: bool,
171}
172
173impl Default for PagerConfig {
174    fn default() -> Self {
175        Self {
176            disk_residency: false,
177            cache_size: 10_000,
178            read_only: false,
179            verify_checksums: true,
180            double_write: true,
181        }
182    }
183}
184
185/// The host's WAL durability barrier, called before publishing dirty page batches.
186/// Implementations must make all records through `lsn` durable or return an error.
187pub trait WalBarrier {
188    fn flush_until(&self, lsn: u64) -> std::io::Result<()>;
189
190    /// A cold page must not claim changes beyond the host's durable WAL.
191    /// LSN zero and the completed physical checkpoint need no live WAL handle.
192    fn validate_page_lsn(&self, lsn: u64, checkpoint_lsn: u64) -> std::io::Result<()> {
193        if lsn <= checkpoint_lsn {
194            return Ok(());
195        }
196        Err(std::io::Error::new(
197            std::io::ErrorKind::InvalidData,
198            "page LSN has no durable WAL authority",
199        ))
200    }
201
202    /// A checkpoint host can preserve the first image of an existing page
203    /// before the cache accepts an overwrite. Newly reserved pages need no undo.
204    fn needs_page_image(&self, _page_id: u32) -> std::io::Result<bool> {
205        Ok(false)
206    }
207
208    /// Must make the image durable before returning. The pager may evict the
209    /// replacement immediately; recording only at flush time is too late.
210    fn capture_page_image(&self, _page: &Page) -> std::io::Result<()> {
211        Ok(())
212    }
213
214    /// Called before pages are removed from allocator ownership. A host may
215    /// only queue the record here: `flush_page_ownership` is its durability
216    /// point.
217    fn reserve_pages(&self, _start: u32, _count: u32) -> std::io::Result<()> {
218        Ok(())
219    }
220
221    /// Called before any page image or allocator state reaches the file. Must
222    /// make every reservation and captured page image recorded so far durable
223    /// or return an error, so a page is never written, and the header never
224    /// names it, ahead of the record that lets recovery undo it.
225    fn flush_page_ownership(&self) -> std::io::Result<()> {
226        Ok(())
227    }
228
229    /// Called before a persisted free-list trunk is detached from its head.
230    fn detach_free_pages(&self, _pages: &[u32]) -> std::io::Result<()> {
231        Ok(())
232    }
233
234    /// True only while detached free IDs have durable recovery ownership.
235    /// No-op callbacks must not authorize moving a whole trunk into RAM.
236    fn has_page_ownership_journal(&self) -> std::io::Result<bool> {
237        Ok(false)
238    }
239
240    /// Called before retired pages enter the free list.
241    fn retire_pages(&self, _pages: &[u32]) -> std::io::Result<()> {
242        Ok(())
243    }
244}
245
246/// A pager without a WAL may only publish pages whose LSN is zero.
247pub struct NoWal;
248impl WalBarrier for NoWal {
249    fn flush_until(&self, _lsn: u64) -> std::io::Result<()> {
250        Err(std::io::Error::other(
251            "nonzero page LSN requires a WAL durability barrier",
252        ))
253    }
254}
255pub struct Pager<F: VfsFile, W: WalBarrier> {
256    /// Database file path
257    path: PathBuf,
258    /// File handle
259    file: Mutex<F>,
260    /// Whether mutable pages are protected by the in-file DWB zone.
261    dwb_enabled: bool,
262    staged_pages: Mutex<Option<pager_io::StagedPageBatch>>,
263    /// A failed writeback may leave the only complete image in the DWB.
264    /// Refuse further writes until reopen has recovered that image.
265    writeback_failed: std::sync::atomic::AtomicBool,
266    /// Page cache
267    cache: PageCache,
268    /// Recovery images must survive cache eviction without writing the source.
269    read_only_recovery: RwLock<std::collections::HashMap<u32, Page>>,
270    /// Free page list
271    freelist: RwLock<FreeList>,
272    /// Store-managed frees stay unavailable until their removal from the
273    /// durable catalog has crossed a publication boundary.
274    deferred_reclamation: Mutex<DeferredPageReclamation>,
275    /// Evicted dirty images that have reached the file. Equal to the cache's
276    /// count of dirty evictions when none is between the cache and the file.
277    evictions_written: std::sync::atomic::AtomicU64,
278    /// Excludes page ownership changes while a host publishes an epoch.
279    /// Reentrant so the publishing thread can use ordinary pager methods.
280    ownership_mutations: parking_lot::ReentrantMutex<()>,
281    /// Reused page ownership must reach both superblock copies before a
282    /// manifest can refer to those pages, including single-slot recovery.
283    allocation_reused: std::sync::atomic::AtomicBool,
284    /// A consumed trunk cannot be reused until both header fences succeed.
285    allocation_fence_pending: std::sync::atomic::AtomicBool,
286    /// Database header
287    header: RwLock<DatabaseHeader>,
288    /// Serialize read-select-write sequences for the superblock pair.
289    superblock_publication: Mutex<()>,
290    /// Configuration
291    config: PagerConfig,
292    /// Dirty flag for header
293    header_dirty: Mutex<bool>,
294    wal: W,
295}
296
297#[derive(Default)]
298struct DeferredPageReclamation {
299    enabled: bool,
300    pending: std::collections::BTreeSet<u32>,
301    published: std::collections::BTreeSet<u32>,
302}
303
304/// The superblock zone occupies the head of page 0 (ADR 0038 §2 phase 1).
305const SUPERBLOCK_SLOT_SIZE: usize = reddb_file::PAGED_SUPERBLOCK_SLOT_SIZE;
306const SUPERBLOCK_ZONE_SIZE: usize = reddb_file::PAGED_SUPERBLOCK_ZONE_SIZE;
307// The phase-3 layout was introduced in 1.0.1. Later file format versions
308// must not make existing phase-3 stores look like legacy sidecar stores.
309const PHASE3_DWB_ZONE_FILE_VERSION: u32 = 0x0001_0001;
310
311/// The newest valid superblock copy together with its slot image.
312pub type NewestSuperblock = (
313    reddb_file::PagedSuperblockSelection,
314    [u8; SUPERBLOCK_SLOT_SIZE],
315);
316
317/// Take the first slot's worth of a freshly-built page-0 image. The database
318/// header and the encryption header both live well inside this prefix.
319fn superblock_slot_image(page: &[u8; PAGE_SIZE]) -> [u8; SUPERBLOCK_SLOT_SIZE] {
320    let mut image = [0u8; SUPERBLOCK_SLOT_SIZE];
321    image.copy_from_slice(&page[..SUPERBLOCK_SLOT_SIZE]);
322    image
323}
324
325impl<F: VfsFile, W: WalBarrier> Pager<F, W> {
326    /// Use an already-owned file. The host retains exclusive ownership until
327    /// this pager is dropped, and supplies the native WAL/encryption policy.
328    /// `create` is explicit: a corrupt or empty existing file is never recreated.
329    pub fn open_owned(
330        file: F,
331        path: PathBuf,
332        config: PagerConfig,
333        wal: W,
334        create: bool,
335    ) -> Result<Self, PagerError> {
336        if create && file.file_len()? != 0 {
337            return Err(PagerError::InvalidDatabase(
338                "new pager file is not empty".into(),
339            ));
340        }
341        let pager = Self {
342            path,
343            file: Mutex::new(file),
344            dwb_enabled: config.double_write && !config.read_only,
345            staged_pages: Mutex::new(None),
346            writeback_failed: std::sync::atomic::AtomicBool::new(false),
347            cache: PageCache::new(config.cache_size),
348            read_only_recovery: RwLock::new(std::collections::HashMap::new()),
349            freelist: RwLock::new(FreeList::new()),
350            deferred_reclamation: Mutex::new(DeferredPageReclamation::default()),
351            evictions_written: std::sync::atomic::AtomicU64::new(0),
352            ownership_mutations: parking_lot::ReentrantMutex::new(()),
353            allocation_reused: std::sync::atomic::AtomicBool::new(false),
354            allocation_fence_pending: std::sync::atomic::AtomicBool::new(false),
355            header: RwLock::new(DatabaseHeader::default()),
356            superblock_publication: Mutex::new(()),
357            config,
358            header_dirty: Mutex::new(false),
359            wal,
360        };
361        if create {
362            pager.initialize()?;
363        } else {
364            pager.ensure_phase3_dwb_zone_layout()?;
365            pager.recover_from_dwb()?;
366            pager.load_header()?;
367        }
368        Ok(pager)
369    }
370
371    pub fn wal_barrier(&self) -> &W {
372        &self.wal
373    }
374
375    /// Hold across an entire ownership publication, not just individual
376    /// allocation calls. Readers may continue accessing already-published pages.
377    pub fn lock_ownership_mutations(&self) -> parking_lot::ReentrantMutexGuard<'_, ()> {
378        self.ownership_mutations.lock()
379    }
380
381    /// [`Self::read_page`] that never waits: `None` only while a dirty image
382    /// another thread's ownership epoch evicted is on its way to the file.
383    pub fn try_read_page(&self, page_id: u32) -> Result<Option<Page>, PagerError> {
384        self.read_page_now(page_id, true)
385    }
386
387    /// Between two [`Self::try_read_page`] calls that declined. An eviction
388    /// write is a few file syncs.
389    pub fn wait_to_retry_read(&self) {
390        std::thread::sleep(EVICTION_WRITE_POLL);
391    }
392
393    /// A miss while another thread holds the ownership epoch.
394    ///
395    /// An epoch can last a whole checkpoint, and a reader that waits for it
396    /// keeps what it holds until then. A collection whose base that reader
397    /// holds is then published again in full, because its delta needs the
398    /// base to itself. The reader has no reason to wait: the file holds the
399    /// newest image of every page the cache does not, except a page the cache
400    /// evicted dirty and whose write has not finished. The cache counts those
401    /// as they leave and this pager as they land, so the two counts say
402    /// whether one was in between while this read ran.
403    ///
404    /// Nothing is admitted to the cache. Admission can evict, and an eviction
405    /// write belongs to the epoch.
406    fn read_outside_epoch(
407        &self,
408        page_id: u32,
409        read: impl FnOnce() -> Result<Page, PagerError>,
410    ) -> Result<Option<Page>, PagerError> {
411        use std::sync::atomic::Ordering;
412        let evicted = self.cache.dirty_evictions();
413        // After a failed writeback the evicted image is lost and the file is
414        // all any reader will get, inside the epoch or not.
415        if self.evictions_written.load(Ordering::SeqCst) != evicted
416            && !self.writeback_failed.load(Ordering::Acquire)
417        {
418            return Ok(None);
419        }
420        if let Some(page) = self.cache.get(page_id) {
421            return Ok(Some(page));
422        }
423        let page = read();
424        if self.cache.dirty_evictions() != evicted {
425            return Ok(None);
426        }
427        page.map(Some)
428    }
429
430    /// An interrupted publication must be recovered before any more writes.
431    pub fn fence_interrupted_ownership(&self) {
432        self.writeback_failed
433            .store(true, std::sync::atomic::Ordering::Release);
434    }
435
436    /// Run a host operation while holding the same lock as protected page I/O.
437    /// This is used only for native prefetch and fault-injection tests.
438    #[doc(hidden)]
439    pub fn with_file<T>(&self, operation: impl FnOnce(&mut F) -> T) -> Result<T, PagerError> {
440        Ok(operation(&mut *self.file_lock()?))
441    }
442
443    /// Initialize a new database
444    fn initialize(&self) -> Result<(), PagerError> {
445        if self.config.read_only {
446            return Err(PagerError::ReadOnly);
447        }
448
449        // Create header page. Page ids 1 and 2 are reserved for fixed
450        // metadata/vault pages. ADR 0038 phase 3 reserves the following DWB
451        // zone in-file so normal B-tree allocation starts after it.
452        let initial_page_count = FIRST_ALLOCATABLE_PAGE;
453        let header_page = Page::new_header_page(initial_page_count);
454        self.header_write()?.page_count = initial_page_count;
455
456        // Reserve page 0 (the superblock zone) plus the reserved pages so any
457        // scan over 0..page_count can read every allocated page in a brand-new
458        // database. The zone's own bytes are published below, one slot at a
459        // time; this first whole-page write only sizes the file.
460        self.write_page_raw(0, &header_page)?;
461        let mut metadata_page = Page::new(PageType::Header, 1);
462        metadata_page.update_checksum();
463        self.write_page_raw(1, &metadata_page)?;
464        let mut vault_page = Page::new(PageType::Vault, 2);
465        vault_page.update_checksum();
466        self.write_page_raw(2, &vault_page)?;
467        self.clear_dwb_zone()?;
468
469        // Publish both superblock copies so the ping-pong invariant — one
470        // valid copy always survives a crash — holds from the very first
471        // update onward, not just from the second.
472        let mut slot = superblock_slot_image(header_page.as_bytes());
473        self.write_superblock_slot(&mut slot, 0, 1)?;
474        self.write_superblock_slot(&mut slot, 1, 2)?;
475
476        // Sync to disk
477        self.sync()?;
478
479        Ok(())
480    }
481
482    /// Acquire a write lock on the header RwLock, mapping poison errors.
483    fn header_write(&self) -> Result<std::sync::RwLockWriteGuard<'_, DatabaseHeader>, PagerError> {
484        self.header.write().map_err(|_| PagerError::LockPoisoned)
485    }
486
487    /// Acquire a read lock on the header RwLock, mapping poison errors.
488    fn header_read(&self) -> Result<std::sync::RwLockReadGuard<'_, DatabaseHeader>, PagerError> {
489        self.header.read().map_err(|_| PagerError::LockPoisoned)
490    }
491
492    /// Acquire a write lock on the freelist RwLock, mapping poison errors.
493    fn freelist_write(&self) -> Result<std::sync::RwLockWriteGuard<'_, FreeList>, PagerError> {
494        self.freelist.write().map_err(|_| PagerError::LockPoisoned)
495    }
496
497    /// Acquire a lock on the file Mutex, mapping poison errors.
498    fn file_lock(&self) -> Result<std::sync::MutexGuard<'_, F>, PagerError> {
499        self.file.lock().map_err(|_| PagerError::LockPoisoned)
500    }
501
502    /// Acquire a lock on the header_dirty Mutex, mapping poison errors.
503    fn header_dirty_lock(&self) -> Result<std::sync::MutexGuard<'_, bool>, PagerError> {
504        self.header_dirty
505            .lock()
506            .map_err(|_| PagerError::LockPoisoned)
507    }
508
509    /// Read the whole superblock zone (both ping-pong copies) from the head of
510    /// the file. A file shorter than the zone yields zero-filled tail bytes,
511    /// which decode as "slot never written".
512    fn read_superblock_zone(&self) -> Result<[u8; SUPERBLOCK_ZONE_SIZE], PagerError> {
513        let mut file = self.file_lock()?;
514        Ok(pager_io::read_superblock_zone(&mut *file)?)
515    }
516
517    /// The newest valid superblock copy, with its slot image.
518    ///
519    /// Both copies invalid is the one unrecoverable superblock state (ADR 0074
520    /// §2): the store does not open, and the error names the zone rather
521    /// than panicking or silently re-initialising.
522    #[doc(hidden)]
523    pub fn newest_superblock(&self) -> Result<NewestSuperblock, PagerError> {
524        let zone = self.read_superblock_zone()?;
525        let selection = reddb_file::select_paged_superblock(&zone)
526            .ok_or_else(|| PagerError::SuperblockZoneUnrecoverable(self.path.clone()))?;
527
528        let start = selection.copy_index * SUPERBLOCK_SLOT_SIZE;
529        let mut image = [0u8; SUPERBLOCK_SLOT_SIZE];
530        image.copy_from_slice(&zone[start..start + SUPERBLOCK_SLOT_SIZE]);
531        Ok((selection, image))
532    }
533
534    fn ensure_phase3_dwb_zone_layout(&self) -> Result<(), PagerError> {
535        let (_, image) = self.newest_superblock()?;
536        let header = reddb_file::decode_published_database_header(&image)
537            .map_err(|err| PagerError::InvalidDatabase(err.to_string()))?;
538        if header.is_recovery_read_only() && !self.config.read_only {
539            return Err(PagerError::InvalidDatabase(
540                "recovered database is read-only; export verified data into a new store".into(),
541            ));
542        }
543        if header.requires_disk_residency() && !self.config.disk_residency && !self.config.read_only
544        {
545            return Err(PagerError::InvalidDatabase(
546                "prepared disk-resident database requires a disk-resident writer".into(),
547            ));
548        }
549        if header.version < PHASE3_DWB_ZONE_FILE_VERSION {
550            return Err(PagerError::LegacyPagedStore {
551                path: self.path.clone(),
552            });
553        }
554        Ok(())
555    }
556
557    /// Seal `slot` for `copy_index`/`generation` and write exactly that slot,
558    /// then fsync. The caller guarantees `copy_index` is the stale copy.
559    fn write_superblock_slot(
560        &self,
561        slot: &mut [u8; SUPERBLOCK_SLOT_SIZE],
562        copy_index: usize,
563        generation: u64,
564    ) -> Result<(), PagerError> {
565        self.ensure_writeback_available()?;
566        if self.config.read_only {
567            return Err(PagerError::ReadOnly);
568        }
569        self.record_ownership(|wal| wal.flush_page_ownership())?;
570        let mut file = self.file_lock()?;
571        self.ensure_writeback_available()?;
572        Ok(pager_io::write_superblock_slot(
573            &mut *file, slot, copy_index, generation,
574        )?)
575    }
576
577    /// Publish `mutate`'s edit of the newest slot image into the *stale* copy.
578    ///
579    /// Reading the newest image first means every byte the pager does not
580    /// explicitly rewrite — most importantly the encryption marker and header —
581    /// carries forward untouched.
582    #[doc(hidden)]
583    pub fn commit_superblock(
584        &self,
585        mutate: impl FnOnce(&mut [u8; SUPERBLOCK_SLOT_SIZE]) -> Result<(), PagerError>,
586    ) -> Result<(), PagerError> {
587        let _ownership = self.lock_ownership_mutations();
588        let _publication = self
589            .superblock_publication
590            .lock()
591            .map_err(|_| PagerError::LockPoisoned)?;
592        self.commit_superblock_locked(mutate)
593    }
594
595    fn commit_superblock_locked(
596        &self,
597        mutate: impl FnOnce(&mut [u8; SUPERBLOCK_SLOT_SIZE]) -> Result<(), PagerError>,
598    ) -> Result<(), PagerError> {
599        if self.config.read_only {
600            return Err(PagerError::ReadOnly);
601        }
602        let (newest, mut image) = self.newest_superblock()?;
603        mutate(&mut image)?;
604        let next_copy = reddb_file::paged_superblock_next_copy(Some(newest));
605        self.write_superblock_slot(&mut image, next_copy, newest.generation.saturating_add(1))
606    }
607
608    /// Fence a file-format upgrade in both recoverable superblock copies.
609    ///
610    /// The caller must exclude other mutators while the fence is in progress
611    /// and may publish a new mandatory format only after this succeeds. A
612    /// failed write fences subsequent mutation until reopen and recovery.
613    pub fn fence_file_format_version(&self, version: u32) -> Result<(), PagerError> {
614        let _ownership = self.lock_ownership_mutations();
615        self.ensure_writeback_available()?;
616        if self.config.read_only {
617            return Err(PagerError::ReadOnly);
618        }
619        if version == reddb_file::file_format::PAGE_RECOVERY_READ_ONLY_FILE_VERSION {
620            return Err(PagerError::InvalidDatabase(
621                "recovery read-only format is reserved".into(),
622            ));
623        }
624        if !(PHASE3_DWB_ZONE_FILE_VERSION..=reddb_file::PAGE_FILE_VERSION).contains(&version) {
625            return Err(PagerError::InvalidDatabase(
626                "unsupported file format fence".into(),
627            ));
628        }
629        let current = self.header_read()?.clone();
630        if version < current.version {
631            return Err(PagerError::InvalidDatabase(
632                "file format downgrade is not supported".into(),
633            ));
634        }
635        let legacy_disk_residency =
636            reddb_file::file_format::page_format_is_disk_resident(current.version);
637        let required_capabilities = current.required_capabilities
638            | if version >= reddb_file::PAGE_REQUIRED_CAPABILITIES_FILE_VERSION
639                && legacy_disk_residency
640            {
641                reddb_file::FILE_CAPABILITY_DISK_RESIDENCY
642            } else {
643                0
644            };
645        let requires_disk_residency =
646            if version < reddb_file::PAGE_REQUIRED_CAPABILITIES_FILE_VERSION {
647                reddb_file::file_format::page_format_is_disk_resident(version)
648            } else {
649                required_capabilities & reddb_file::FILE_CAPABILITY_DISK_RESIDENCY != 0
650            };
651        if requires_disk_residency && !self.config.disk_residency {
652            return Err(PagerError::InvalidDatabase(
653                "disk-residency format requires a disk-resident writer".into(),
654            ));
655        }
656        let _publication = self
657            .superblock_publication
658            .lock()
659            .map_err(|_| PagerError::LockPoisoned)?;
660        let result = (|| {
661            for _ in 0..reddb_file::PAGED_SUPERBLOCK_SLOT_COUNT {
662                self.commit_superblock_locked(|image| {
663                    reddb_file::set_database_header_version(image, version)
664                        .map_err(|error| PagerError::InvalidDatabase(error.to_string()))?;
665                    if version >= reddb_file::PAGE_REQUIRED_CAPABILITIES_FILE_VERSION {
666                        reddb_file::set_database_header_required_capabilities(
667                            image,
668                            required_capabilities,
669                        )
670                        .map_err(|error| PagerError::InvalidDatabase(error.to_string()))?;
671                    }
672                    Ok(())
673                })?;
674            }
675            let mut header = self.header_write()?;
676            header.version = version;
677            if version >= reddb_file::PAGE_REQUIRED_CAPABILITIES_FILE_VERSION {
678                header.required_capabilities = required_capabilities;
679            }
680            Ok(())
681        })();
682        if result.is_err() {
683            self.writeback_failed
684                .store(true, std::sync::atomic::Ordering::Release);
685        }
686        result
687    }
688
689    /// Durably enable mandatory reader capabilities before dependent pages exist.
690    ///
691    /// The set only grows. Both superblock copies cross the fence before this
692    /// returns, so a crash can leave a conservatively declared unused feature,
693    /// never reachable bytes whose decoder requirement was not published.
694    pub fn fence_required_capabilities(&self, capabilities: u64) -> Result<(), PagerError> {
695        let _ownership = self.lock_ownership_mutations();
696        self.ensure_writeback_available()?;
697        if self.config.read_only {
698            return Err(PagerError::ReadOnly);
699        }
700        let unsupported = capabilities & !reddb_file::FILE_CAPABILITIES_SUPPORTED;
701        if unsupported != 0 {
702            return Err(PagerError::InvalidDatabase(format!(
703                "unsupported required database capabilities: {unsupported:#018x}"
704            )));
705        }
706
707        let current = self.header_read()?.clone();
708        if current.is_recovery_read_only() {
709            return Err(PagerError::InvalidDatabase(
710                "recovery read-only format cannot enable capabilities".into(),
711            ));
712        }
713        let legacy_disk_residency =
714            reddb_file::file_format::page_format_is_disk_resident(current.version);
715        let required = current.required_capabilities
716            | capabilities
717            | if legacy_disk_residency {
718                reddb_file::FILE_CAPABILITY_DISK_RESIDENCY
719            } else {
720                0
721            };
722        let version = current
723            .version
724            .max(reddb_file::PAGE_REQUIRED_CAPABILITIES_FILE_VERSION);
725        if required == current.required_capabilities && version == current.version {
726            return Ok(());
727        }
728        if required & reddb_file::FILE_CAPABILITY_DISK_RESIDENCY != 0 && !self.config.disk_residency
729        {
730            return Err(PagerError::InvalidDatabase(
731                "disk-residency capability requires a disk-resident writer".into(),
732            ));
733        }
734        if self.batch_active()? {
735            return Err(PagerError::InvalidDatabase(
736                "capability publication requires no active prepared batch".into(),
737            ));
738        }
739
740        let _publication = self
741            .superblock_publication
742            .lock()
743            .map_err(|_| PagerError::LockPoisoned)?;
744        let result = (|| {
745            for _ in 0..reddb_file::PAGED_SUPERBLOCK_SLOT_COUNT {
746                self.commit_superblock_locked(|image| {
747                    reddb_file::set_database_header_version(image, version)
748                        .and_then(|()| {
749                            reddb_file::set_database_header_required_capabilities(image, required)
750                        })
751                        .map_err(|error| PagerError::InvalidDatabase(error.to_string()))?;
752                    if required & reddb_file::FILE_CAPABILITY_CATALOG_ROOT != 0
753                        && current.required_capabilities & reddb_file::FILE_CAPABILITY_CATALOG_ROOT
754                            == 0
755                    {
756                        reddb_file::file_format::set_database_header_manifest_reference(
757                            image,
758                            reddb_file::page_proof::PageReference::default(),
759                        )
760                        .map_err(|error| PagerError::InvalidDatabase(error.to_string()))?;
761                    }
762                    if required & reddb_file::file_format::FILE_CAPABILITY_DWB_PUBLICATION != 0
763                        && current.required_capabilities
764                            & reddb_file::file_format::FILE_CAPABILITY_DWB_PUBLICATION
765                            == 0
766                    {
767                        if !self.dwb_enabled {
768                            return Err(PagerError::InvalidDatabase(
769                                "DWB generation authority requires protected page writes".into(),
770                            ));
771                        }
772                        reddb_file::file_format::set_database_header_dwb_publication(image, None)
773                            .map_err(|error| PagerError::InvalidDatabase(error.to_string()))?;
774                    }
775                    Ok(())
776                })?;
777            }
778            let mut header = self.header_write()?;
779            header.version = version;
780            header.required_capabilities = required;
781            Ok(())
782        })();
783        if result.is_err() {
784            self.writeback_failed
785                .store(true, std::sync::atomic::Ordering::Release);
786        }
787        result
788    }
789
790    /// Load the database header from the newest valid superblock copy.
791    fn load_header(&self) -> Result<(), PagerError> {
792        let (_, image) = self.newest_superblock()?;
793
794        let mut decoded_header = reddb_file::decode_published_database_header(&image)
795            .map_err(|err| PagerError::InvalidDatabase(err.to_string()))?;
796        // Cache eviction (or DWB recovery) can persist pages before the next
797        // superblock publication. After a crash the allocation counter may
798        // therefore lag behind live pages already in the file. Reserve the
799        // entire physical extent before allocating; never overwrite that tail.
800        // A partial last page is reserved too, without treating it as verified.
801        let physical_pages = self.file_lock()?.file_len()?.div_ceil(PAGE_SIZE as u64);
802        let mut physical_pages = u32::try_from(physical_pages).map_err(|_| {
803            PagerError::InvalidDatabase("data file exceeds the page address space".into())
804        })?;
805        if self.config.read_only {
806            if let Some(id) = self
807                .read_only_recovery
808                .read()
809                .map_err(|_| PagerError::LockPoisoned)?
810                .keys()
811                .max()
812            {
813                physical_pages = physical_pages.max(id.checked_add(1).ok_or_else(|| {
814                    PagerError::InvalidDatabase(
815                        "recovery page exceeds the page address space".into(),
816                    )
817                })?);
818            }
819        }
820        if decoded_header.page_count < physical_pages {
821            decoded_header.page_count = physical_pages;
822            if !self.config.read_only {
823                *self.header_dirty_lock()? = true;
824            }
825        }
826        let freelist_head = decoded_header.freelist_head;
827
828        {
829            let mut header = self.header_write()?;
830            *header = decoded_header;
831        }
832
833        // Initialize freelist
834        {
835            let mut freelist = self.freelist_write()?;
836            *freelist = FreeList::from_header(freelist_head, 0);
837        }
838
839        Ok(())
840    }
841
842    /// Publish the in-memory database header as a new superblock generation.
843    fn write_header(&self) -> Result<(), PagerError> {
844        if self.config.read_only {
845            return Err(PagerError::ReadOnly);
846        }
847
848        let header = self.header_read()?.clone();
849        self.commit_superblock(|image| {
850            reddb_file::encode_database_header(image, &header)
851                .map_err(|err| PagerError::InvalidDatabase(err.to_string()))
852        })?;
853        *self.header_dirty_lock()? = false;
854
855        Ok(())
856    }
857
858    /// Read a page from disk (bypassing cache)
859    fn read_page_raw(&self, page_id: u32) -> Result<Page, PagerError> {
860        let mut file = self.file_lock()?;
861        let page = match self
862            .staged_pages
863            .lock()
864            .map_err(|_| PagerError::LockPoisoned)?
865            .as_ref()
866        {
867            Some(batch) => match batch.read(&mut *file, page_id)? {
868                Some(page) => page,
869                None => pager_io::read_page(&mut *file, page_id, self.config.verify_checksums)?,
870            },
871            None => pager_io::read_page(&mut *file, page_id, self.config.verify_checksums)?,
872        };
873        drop(file);
874        if self.config.verify_checksums && page_id != 0 && page.lsn() != 0 {
875            self.wal
876                .validate_page_lsn(page.lsn(), self.header_read()?.checkpoint_lsn)
877                .map_err(|error| {
878                    PagerError::InvalidDatabase(format!(
879                        "page {page_id} has unverified LSN {}: {error}",
880                        page.lsn()
881                    ))
882                })?;
883        }
884        Ok(page)
885    }
886
887    fn ensure_writeback_available(&self) -> Result<(), PagerError> {
888        if self
889            .writeback_failed
890            .load(std::sync::atomic::Ordering::Acquire)
891        {
892            return Err(PagerError::Io(std::io::Error::other(
893                "page writeback failed; reopen the database to recover before writing",
894            )));
895        }
896        Ok(())
897    }
898
899    /// Reject new logical writes after a physical page writeback failed.
900    ///
901    /// The failed write may have reached disk partially. Reopening lets the
902    /// double-write buffer and WAL establish the durable generation before
903    /// the database accepts another mutation.
904    pub fn check_writeback_available(&self) -> Result<(), PagerError> {
905        self.ensure_writeback_available()
906    }
907
908    fn record_ownership(
909        &self,
910        operation: impl FnOnce(&W) -> std::io::Result<()>,
911    ) -> Result<(), PagerError> {
912        if let Err(error) = operation(&self.wal) {
913            self.writeback_failed
914                .store(true, std::sync::atomic::Ordering::Release);
915            return Err(PagerError::Io(error));
916        }
917        Ok(())
918    }
919
920    /// Amortize protected eviction over one bounded DWB frame. Keeping the
921    /// remaining cache dirty would otherwise pay three fsyncs per victim.
922    fn write_evicted_dirty_page(
923        &self,
924        page: Page,
925        pending_page: Option<u32>,
926    ) -> Result<(), PagerError> {
927        self.write_evicted_dirty_page_batch(page, pending_page)?;
928        self.evictions_written
929            .fetch_add(1, std::sync::atomic::Ordering::SeqCst);
930        Ok(())
931    }
932
933    fn write_evicted_dirty_page_batch(
934        &self,
935        page: Page,
936        pending_page: Option<u32>,
937    ) -> Result<(), PagerError> {
938        if self.bounded_writeback()? {
939            return self.write_dirty_page_batch(&[(page.page_id(), page)]);
940        }
941        let mut ids = self.cache.dirty_page_ids(pager_io::DWB_MAX_PAGES_PER_FRAME);
942        // The admitting write must not join its predecessor's eviction batch.
943        // Its image is dirty for readers, but publication still belongs to the
944        // caller after the earlier writeback has succeeded.
945        ids.retain(|id| Some(*id) != pending_page);
946        // Leave room for the already evicted image without reducing a full
947        // frame merely because the pending image occupied one candidate slot.
948        ids.truncate(pager_io::DWB_MAX_PAGES_PER_FRAME.saturating_sub(1));
949        ids.sort_unstable();
950        let mut pages = self.cache.flush_dirty_pages(&ids);
951        pages.push((page.page_id(), page));
952        pages.sort_unstable_by_key(|(id, _)| *id);
953        self.write_dirty_page_batch(&pages)
954    }
955
956    /// Write a page to disk (bypassing cache)
957    fn write_page_raw(&self, page_id: u32, page: &Page) -> Result<(), PagerError> {
958        self.ensure_writeback_available()?;
959        if self.config.read_only {
960            return Err(PagerError::ReadOnly);
961        }
962        self.record_ownership(|wal| wal.flush_page_ownership())?;
963        let mut file = self.file_lock()?;
964        self.ensure_writeback_available()?;
965        if let Some(batch) = self
966            .staged_pages
967            .lock()
968            .map_err(|_| PagerError::LockPoisoned)?
969            .as_mut()
970        {
971            return Ok(batch.stage(&mut *file, page_id, page)?);
972        }
973        Ok(pager_io::write_page(&mut *file, page_id, page)?)
974    }
975
976    /// Read a page (cache-aware)
977    pub fn read_page(&self, page_id: u32) -> Result<Page, PagerError> {
978        loop {
979            if let Some(page) = self.read_page_now(page_id, true)? {
980                return Ok(page);
981            }
982            self.wait_to_retry_read();
983        }
984    }
985
986    fn read_page_now(&self, page_id: u32, verify: bool) -> Result<Option<Page>, PagerError> {
987        if self.config.read_only {
988            if let Some(page) = self
989                .read_only_recovery
990                .read()
991                .map_err(|_| PagerError::LockPoisoned)?
992                .get(&page_id)
993            {
994                if verify && self.config.verify_checksums {
995                    page.verify_checksum()?;
996                }
997                return Ok(Some(page.clone()));
998            }
999        }
1000        // Check cache first
1001        if let Some(page) = self.cache.get(page_id) {
1002            return Ok(Some(page));
1003        }
1004        let read = || {
1005            if verify {
1006                return self.read_page_raw(page_id);
1007            }
1008            // The same byte I/O without a page CRC check.
1009            let mut file = self.file_lock()?;
1010            Ok(pager_io::read_page(&mut *file, page_id, false)?)
1011        };
1012
1013        // A miss can evict and write dirty pages. Keep cache publication
1014        // inside the same ownership epoch as writers/checkpoints. Hits retain
1015        // their existing path without taking this guard, and a miss during
1016        // another thread's epoch takes the page without publishing it.
1017        let Some(_ownership) = self.ownership_mutations.try_lock() else {
1018            return self.read_outside_epoch(page_id, read);
1019        };
1020        if let Some(page) = self.cache.get(page_id) {
1021            return Ok(Some(page));
1022        }
1023
1024        // Cache miss - read from disk
1025        let page = read()?;
1026
1027        // Add to cache
1028        if let Some(dirty_page) = self.cache.insert_if_absent(page_id, page.clone()) {
1029            // Evicted page was dirty, need to write it back
1030            self.write_evicted_dirty_page(dirty_page, None)?;
1031        }
1032
1033        Ok(Some(page))
1034    }
1035
1036    /// Read a page without verifying checksum (for encrypted pages)
1037    ///
1038    /// Use this when the page content has its own integrity protection
1039    /// (e.g., AES-GCM authentication tag for encrypted pages).
1040    pub fn read_page_no_checksum(&self, page_id: u32) -> Result<Page, PagerError> {
1041        loop {
1042            if let Some(page) = self.read_page_now(page_id, false)? {
1043                return Ok(page);
1044            }
1045            self.wait_to_retry_read();
1046        }
1047    }
1048
1049    /// Write a page (cache-aware)
1050    pub fn write_page(&self, page_id: u32, mut page: Page) -> Result<(), PagerError> {
1051        let _ownership = self.lock_ownership_mutations();
1052        self.ensure_writeback_available()?;
1053        if self.config.read_only {
1054            return Err(PagerError::ReadOnly);
1055        }
1056
1057        pager_io::check_page_identity(&page, page_id)?;
1058        self.capture_page_before_write(page_id)?;
1059
1060        // Update checksum
1061        page.update_checksum();
1062
1063        // Add to cache and mark dirty. If the cache had to evict a
1064        // dirty entry, write it through immediately — the evicted
1065        // page will never be flushed otherwise (same bug fixed in
1066        // `allocate_page`).
1067        if let Some(dirty_page) = self.cache.insert_dirty(page_id, page) {
1068            self.write_evicted_dirty_page(dirty_page, Some(page_id))?;
1069        }
1070
1071        Ok(())
1072    }
1073
1074    /// Write a page without updating checksum (for encrypted pages)
1075    ///
1076    /// Use this when the page content has its own integrity protection
1077    /// (e.g., AES-GCM authentication tag for encrypted pages).
1078    pub fn write_page_no_checksum(&self, page_id: u32, page: Page) -> Result<(), PagerError> {
1079        let _ownership = self.lock_ownership_mutations();
1080        self.ensure_writeback_available()?;
1081        if self.config.read_only {
1082            return Err(PagerError::ReadOnly);
1083        }
1084
1085        self.capture_page_before_write(page_id)?;
1086
1087        // Add to cache and mark dirty (no checksum update). Same
1088        // eviction-write-through guard as `write_page`.
1089        if let Some(dirty_page) = self.cache.insert_dirty(page_id, page) {
1090            self.write_evicted_dirty_page(dirty_page, Some(page_id))?;
1091        }
1092
1093        Ok(())
1094    }
1095
1096    fn capture_page_before_write(&self, page_id: u32) -> Result<(), PagerError> {
1097        let mut required = false;
1098        self.record_ownership(|wal| {
1099            required = wal.needs_page_image(page_id)?;
1100            Ok(())
1101        })?;
1102        if required {
1103            let previous = self.read_page(page_id)?;
1104            self.record_ownership(|wal| wal.capture_page_image(&previous))?;
1105        }
1106        Ok(())
1107    }
1108
1109    /// Allocate a new page
1110    pub fn allocate_page(&self, page_type: PageType) -> Result<Page, PagerError> {
1111        let _ownership = self.lock_ownership_mutations();
1112        self.ensure_writeback_available()?;
1113        if self.config.read_only {
1114            return Err(PagerError::ReadOnly);
1115        }
1116
1117        // Try to get from freelist first
1118        let page_id = if self.batch_active()? {
1119            // Prepared frames may extend the file but cannot reuse allocator
1120            // state whose published roots still name the old ownership.
1121            let mut header = self.header_write()?;
1122            let id = header.page_count;
1123            header.page_count = id
1124                .checked_add(1)
1125                .ok_or_else(|| PagerError::InvalidDatabase("page count overflow".into()))?;
1126            *self.header_dirty_lock()? = true;
1127            id
1128        } else {
1129            let mut freelist = self.freelist_write()?;
1130            // A previous fence can fail after loading the trunk into memory.
1131            // Retry it before the fast path can consume any of those pages.
1132            self.complete_allocation_fence()?;
1133            if let Some(id) = freelist.next_in_memory_page() {
1134                self.record_ownership(|wal| wal.reserve_pages(id, 1))?;
1135                let id = freelist
1136                    .allocate()
1137                    .expect("free page checked while allocator is locked");
1138                self.allocation_reused
1139                    .store(true, std::sync::atomic::Ordering::Release);
1140                id
1141            } else if freelist.trunk_head() != 0 {
1142                let trunk_id = freelist.trunk_head();
1143
1144                let trunk = self.read_page(trunk_id).map_err(|e| match e {
1145                    PagerError::PageNotFound(_) => {
1146                        PagerError::InvalidDatabase("Freelist trunk missing".to_string())
1147                    }
1148                    other => other,
1149                })?;
1150                if trunk.page_id() != trunk_id {
1151                    return Err(PagerError::InvalidDatabase(
1152                        "misdirected freelist trunk".into(),
1153                    ));
1154                }
1155
1156                // Persist ownership of every page detached from the trunk
1157                // before either superblock stops naming that trunk.
1158                let mut detached = FreeList::new();
1159                detached
1160                    .load_from_trunk(&trunk)
1161                    .map_err(|e| PagerError::InvalidDatabase(format!("Freelist: {e}")))?;
1162                let mut pages = Vec::new();
1163                let mut seen = std::collections::HashSet::new();
1164                let page_count = self.page_count()?;
1165                while let Some(id) = detached.allocate() {
1166                    if id < FIRST_ALLOCATABLE_PAGE || id >= page_count || !seen.insert(id) {
1167                        return Err(PagerError::InvalidDatabase(
1168                            "invalid freelist trunk page".into(),
1169                        ));
1170                    }
1171                    pages.push(id);
1172                }
1173                let mut journaled = false;
1174                self.record_ownership(|wal| {
1175                    journaled = wal.has_page_ownership_journal()?;
1176                    Ok(())
1177                })?;
1178                if !journaled {
1179                    self.allocate_unjournaled_trunk(&mut freelist, trunk, &pages)?
1180                } else {
1181                    self.record_ownership(|wal| wal.detach_free_pages(&pages))?;
1182
1183                    freelist
1184                        .load_from_trunk(&trunk)
1185                        .map_err(|e| PagerError::InvalidDatabase(format!("Freelist: {}", e)))?;
1186                    let mut header = self.header_write()?;
1187                    header.freelist_head = freelist.trunk_head();
1188                    *self.header_dirty_lock()? = true;
1189                    drop(header);
1190                    // The consumed trunk itself becomes reusable. Forget its old
1191                    // allocator role durably before cache eviction can overwrite it.
1192                    // Keep the allocator locked so another allocator cannot race
1193                    // ahead of this fence. A failed fence leaves allocation stopped.
1194                    self.allocation_fence_pending
1195                        .store(true, std::sync::atomic::Ordering::Release);
1196                    self.complete_allocation_fence()?;
1197                    let next = freelist.next_in_memory_page().ok_or_else(|| {
1198                        PagerError::InvalidDatabase("Freelist empty after trunk load".to_string())
1199                    })?;
1200                    self.record_ownership(|wal| wal.reserve_pages(next, 1))?;
1201                    let id = freelist.allocate().ok_or_else(|| {
1202                        PagerError::InvalidDatabase("Freelist empty after trunk load".to_string())
1203                    })?;
1204                    self.allocation_reused
1205                        .store(true, std::sync::atomic::Ordering::Release);
1206                    id
1207                }
1208            } else {
1209                // No free pages, extend file
1210                let mut header = self.header_write()?;
1211                let id = header.page_count;
1212                let next = id
1213                    .checked_add(1)
1214                    .ok_or_else(|| PagerError::InvalidDatabase("page count overflow".into()))?;
1215                self.record_ownership(|wal| wal.reserve_pages(id, 1))?;
1216                header.page_count = next;
1217                *self.header_dirty_lock()? = true;
1218                id
1219            }
1220        };
1221
1222        let page = Page::new(page_type, page_id);
1223
1224        // Write to cache. The evicted page (if any) is dirty by
1225        // definition — `cache.insert_dirty` only returns `Some` when it
1226        // had to evict a dirty entry to make room. The previous
1227        // version dropped that return value, which silently lost
1228        // writes whenever a freshly-allocated page caused an LRU
1229        // eviction. This shows up under heavy ingest as
1230        // "B-tree insert error: Pager error: I/O error: failed to
1231        // fill whole buffer" later, when something tries to read
1232        // back the never-flushed page. Mirror `read_page`'s
1233        // handling: write the evicted page through immediately so
1234        // the on-disk image stays consistent.
1235        if let Some(dirty_page) = self.cache.insert_dirty(page_id, page.clone()) {
1236            self.write_evicted_dirty_page(dirty_page, Some(page_id))?;
1237        }
1238
1239        Ok(page)
1240    }
1241
1242    /// Keep untouched free IDs reachable on disk when no ownership epoch can
1243    /// recover a detached trunk. Removing one ID costs one protected page write;
1244    /// checkpoint/replay epochs retain their batched, journaled allocation path.
1245    fn allocate_unjournaled_trunk(
1246        &self,
1247        freelist: &mut FreeList,
1248        mut trunk: Page,
1249        pages: &[u32],
1250    ) -> Result<u32, PagerError> {
1251        let id = *pages
1252            .first()
1253            .expect("validated trunk includes its own page");
1254        self.record_ownership(|wal| wal.reserve_pages(id, 1))?;
1255        if pages.len() > 1 {
1256            let remaining =
1257                u32::try_from(pages.len() - 2).expect("a validated trunk fits in one page");
1258            trunk.content_mut()[4..8].copy_from_slice(&remaining.to_le_bytes());
1259            trunk.update_checksum();
1260            self.cache.remove(trunk.page_id());
1261            self.write_pages_through_dwb(&[(trunk.page_id(), trunk)])?;
1262            freelist.note_durable_trunk_allocation(remaining);
1263        } else {
1264            // The empty trunk itself is the last available page. Fence both
1265            // superblocks before it can be overwritten as user data.
1266            freelist
1267                .load_from_trunk(&trunk)
1268                .map_err(|error| PagerError::InvalidDatabase(error.to_string()))?;
1269            self.header_write()?.freelist_head = freelist.trunk_head();
1270            *self.header_dirty_lock()? = true;
1271            self.allocation_fence_pending
1272                .store(true, std::sync::atomic::Ordering::Release);
1273            self.complete_allocation_fence()?;
1274            assert_eq!(freelist.allocate(), Some(id));
1275        }
1276        self.allocation_reused
1277            .store(true, std::sync::atomic::Ordering::Release);
1278        Ok(id)
1279    }
1280
1281    /// Reserve a contiguous extent of vector pages.
1282    pub fn reserve_contig_extent(&self, n_pages: u32) -> Result<ExtentId, PagerError> {
1283        let _ownership = self.lock_ownership_mutations();
1284        self.ensure_writeback_available()?;
1285        if self.config.read_only {
1286            return Err(PagerError::ReadOnly);
1287        }
1288        if n_pages == 0 {
1289            return Err(PagerError::InvalidDatabase(
1290                "contiguous extent must reserve at least one page".to_string(),
1291            ));
1292        }
1293
1294        let start_page = {
1295            let mut header = self.header_write()?;
1296            let start = header.page_count;
1297            let end = header.page_count.checked_add(n_pages).ok_or_else(|| {
1298                PagerError::InvalidDatabase("contiguous extent page count overflow".to_string())
1299            })?;
1300            self.record_ownership(|wal| wal.reserve_pages(start, n_pages))?;
1301            header.page_count = end;
1302            *self.header_dirty_lock()? = true;
1303            start
1304        };
1305
1306        for page_id in start_page..start_page + n_pages {
1307            let mut page = Page::new(PageType::Vector, page_id);
1308            page.update_checksum();
1309            if let Some(dirty_page) = self.cache.insert_dirty(page_id, page) {
1310                self.write_evicted_dirty_page(dirty_page, Some(page_id))?;
1311            }
1312        }
1313
1314        Ok(ExtentId {
1315            start_page,
1316            n_pages,
1317        })
1318    }
1319
1320    /// Free a page (return to freelist)
1321    pub fn free_page(&self, page_id: u32) -> Result<(), PagerError> {
1322        if self.batch_active()? {
1323            return Err(PagerError::InvalidDatabase(
1324                "prepared DWB batches cannot retire published pages".into(),
1325            ));
1326        }
1327        let _ownership = self.lock_ownership_mutations();
1328        self.ensure_writeback_available()?;
1329        if self.config.read_only {
1330            return Err(PagerError::ReadOnly);
1331        }
1332
1333        let mut deferred = self
1334            .deferred_reclamation
1335            .lock()
1336            .map_err(|_| PagerError::LockPoisoned)?;
1337        if deferred.enabled {
1338            if page_id < FIRST_ALLOCATABLE_PAGE || page_id >= self.page_count()? {
1339                return Err(PagerError::InvalidDatabase(
1340                    "invalid deferred free page".into(),
1341                ));
1342            }
1343            self.record_ownership(|wal| wal.retire_pages(&[page_id]))?;
1344            // Keep dirty forwarding/empty nodes until publication. An
1345            // incidental flush must leave the previous root traversable.
1346            deferred.pending.insert(page_id);
1347            return Ok(());
1348        }
1349        drop(deferred);
1350
1351        self.record_ownership(|wal| wal.retire_pages(&[page_id]))?;
1352
1353        // Remove from cache
1354        self.cache.remove(page_id);
1355
1356        // Add to freelist
1357        let mut freelist = self.freelist_write()?;
1358        freelist.free(page_id);
1359
1360        *self.header_dirty_lock()? = true;
1361
1362        Ok(())
1363    }
1364
1365    pub fn enable_deferred_reclamation(&self) -> Result<(), PagerError> {
1366        let _ownership = self.lock_ownership_mutations();
1367        self.deferred_reclamation
1368            .lock()
1369            .map_err(|_| PagerError::LockPoisoned)?
1370            .enabled = true;
1371        Ok(())
1372    }
1373
1374    pub fn deferred_reclamation_pages(&self) -> Result<(Vec<u32>, Vec<u32>), PagerError> {
1375        let deferred = self
1376            .deferred_reclamation
1377            .lock()
1378            .map_err(|_| PagerError::LockPoisoned)?;
1379        Ok((
1380            deferred.pending.iter().copied().collect(),
1381            deferred.published.iter().copied().collect(),
1382        ))
1383    }
1384
1385    pub fn restore_deferred_reclamation(&self, pages: &[u32]) -> Result<(), PagerError> {
1386        let _ownership = self.lock_ownership_mutations();
1387        let count = self.page_count()?;
1388        if pages
1389            .iter()
1390            .any(|id| *id < FIRST_ALLOCATABLE_PAGE || *id >= count)
1391        {
1392            return Err(PagerError::InvalidDatabase(
1393                "invalid persisted deferred free page".into(),
1394            ));
1395        }
1396        let mut deferred = self
1397            .deferred_reclamation
1398            .lock()
1399            .map_err(|_| PagerError::LockPoisoned)?;
1400        deferred.pending.extend(pages);
1401        deferred.published.extend(pages);
1402        Ok(())
1403    }
1404
1405    /// The caller has durably published a catalog that retains `retained`
1406    /// and no longer names `released`, after waiting for old tree readers.
1407    pub fn complete_deferred_publication(
1408        &self,
1409        retained: &[u32],
1410        released: &[u32],
1411    ) -> Result<(), PagerError> {
1412        let _ownership = self.lock_ownership_mutations();
1413        let mut deferred = self
1414            .deferred_reclamation
1415            .lock()
1416            .map_err(|_| PagerError::LockPoisoned)?;
1417        if !released.is_empty() {
1418            self.free_retired_pages(released)?;
1419        }
1420        for id in released {
1421            deferred.pending.remove(id);
1422        }
1423        deferred.published = retained.iter().copied().collect();
1424        Ok(())
1425    }
1426
1427    /// Record the pages whose catalog ownership is about to be retired.
1428    pub fn record_retirement_intent(&self, pages: &[u32]) -> Result<(), PagerError> {
1429        let _ownership = self.lock_ownership_mutations();
1430        self.ensure_writeback_available()?;
1431        if self.config.read_only {
1432            return Err(PagerError::ReadOnly);
1433        }
1434        let page_count = self.page_count()?;
1435        let mut seen = std::collections::HashSet::with_capacity(pages.len());
1436        if pages
1437            .iter()
1438            .any(|id| *id < FIRST_ALLOCATABLE_PAGE || *id >= page_count || !seen.insert(*id))
1439        {
1440            return Err(PagerError::InvalidDatabase(
1441                "invalid retirement intent".into(),
1442            ));
1443        }
1444        self.record_ownership(|wal| wal.retire_pages(pages))
1445    }
1446
1447    /// Return a fully validated, unpublished tree generation in one allocator
1448    /// mutation. Call only after its removal from the manifest is durable.
1449    pub fn free_retired_pages(&self, pages: &[u32]) -> Result<(), PagerError> {
1450        let _ownership = self.lock_ownership_mutations();
1451        self.ensure_writeback_available()?;
1452        if self.config.read_only {
1453            return Err(PagerError::ReadOnly);
1454        }
1455        let page_count = self.page_count()?;
1456        if pages
1457            .iter()
1458            .any(|id| *id < FIRST_ALLOCATABLE_PAGE || *id >= page_count)
1459        {
1460            return Err(PagerError::InvalidDatabase(
1461                "invalid retired page range".into(),
1462            ));
1463        }
1464        let mut seen = std::collections::HashSet::with_capacity(pages.len());
1465        if pages.iter().any(|id| !seen.insert(*id)) {
1466            return Err(PagerError::InvalidDatabase("duplicate retired page".into()));
1467        }
1468        let mut freelist = self.freelist_write()?;
1469        if freelist.contains_any(&seen) {
1470            return Err(PagerError::InvalidDatabase(
1471                "retired page is already free".into(),
1472            ));
1473        }
1474        // Some free pages remain in on-disk trunks until allocation reaches
1475        // them. Check those too before changing the cache or the allocator.
1476        // The allocator lock prevents concurrent consumption or publication.
1477        let mut trunk_id = freelist.trunk_head();
1478        let mut visited = std::collections::HashSet::new();
1479        while trunk_id != 0 && !seen.is_empty() {
1480            if trunk_id < FIRST_ALLOCATABLE_PAGE
1481                || trunk_id >= page_count
1482                || !visited.insert(trunk_id)
1483            {
1484                return Err(PagerError::InvalidDatabase(
1485                    "invalid freelist trunk chain".into(),
1486                ));
1487            }
1488            let trunk = self.read_page(trunk_id)?;
1489            if trunk.page_id() != trunk_id {
1490                return Err(PagerError::InvalidDatabase(
1491                    "misdirected freelist trunk".into(),
1492                ));
1493            }
1494            let mut loaded = FreeList::new();
1495            let next = loaded
1496                .load_from_trunk(&trunk)
1497                .map_err(|error| PagerError::InvalidDatabase(format!("Freelist: {error}")))?;
1498            while let Some(id) = loaded.allocate() {
1499                if id < FIRST_ALLOCATABLE_PAGE || id >= page_count {
1500                    return Err(PagerError::InvalidDatabase(
1501                        "invalid free page range".into(),
1502                    ));
1503                }
1504                if seen.contains(&id) {
1505                    return Err(PagerError::InvalidDatabase(
1506                        "retired page is already free".into(),
1507                    ));
1508                }
1509            }
1510            trunk_id = next.unwrap_or(0);
1511        }
1512        self.record_ownership(|wal| wal.retire_pages(pages))?;
1513        for id in pages {
1514            self.cache.remove(*id);
1515        }
1516        freelist.free_batch(pages);
1517        *self.header_dirty_lock()? = true;
1518        Ok(())
1519    }
1520
1521    fn pages_not_in_freelist(
1522        &self,
1523        pages: &[u32],
1524        freelist: &FreeList,
1525        page_count: u32,
1526    ) -> Result<std::collections::HashSet<u32>, PagerError> {
1527        let mut remaining = std::collections::HashSet::with_capacity(pages.len());
1528        if pages
1529            .iter()
1530            .any(|id| *id < FIRST_ALLOCATABLE_PAGE || *id >= page_count || !remaining.insert(*id))
1531        {
1532            return Err(PagerError::InvalidDatabase(
1533                "invalid recovery page set".into(),
1534            ));
1535        }
1536        let requested = remaining.clone();
1537        freelist
1538            .remove_existing_from(&requested, &mut remaining)
1539            .map_err(|error| PagerError::InvalidDatabase(format!("Freelist: {error}")))?;
1540        let mut trunk_id = freelist.trunk_head();
1541        let mut visited = std::collections::HashSet::new();
1542        while trunk_id != 0 {
1543            if trunk_id < FIRST_ALLOCATABLE_PAGE
1544                || trunk_id >= page_count
1545                || !visited.insert(trunk_id)
1546            {
1547                return Err(PagerError::InvalidDatabase(
1548                    "invalid freelist trunk chain".into(),
1549                ));
1550            }
1551            let trunk = self.read_page(trunk_id)?;
1552            if trunk.page_id() != trunk_id {
1553                return Err(PagerError::InvalidDatabase(
1554                    "misdirected freelist trunk".into(),
1555                ));
1556            }
1557            let mut loaded = FreeList::new();
1558            let next = loaded
1559                .load_from_trunk(&trunk)
1560                .map_err(|error| PagerError::InvalidDatabase(format!("Freelist: {error}")))?;
1561            while let Some(id) = loaded.allocate() {
1562                if id < FIRST_ALLOCATABLE_PAGE || id >= page_count {
1563                    return Err(PagerError::InvalidDatabase(
1564                        "invalid free page range".into(),
1565                    ));
1566                }
1567                if requested.contains(&id) && !remaining.remove(&id) {
1568                    return Err(PagerError::InvalidDatabase(
1569                        "duplicate recovery page".into(),
1570                    ));
1571                }
1572            }
1573            trunk_id = next.unwrap_or(0);
1574        }
1575        Ok(remaining)
1576    }
1577
1578    /// Add proven-unowned pages to the allocator exactly once during recovery.
1579    /// The caller must exclude all allocation and publication until this state
1580    /// has been synced to both superblocks and the journal is completed.
1581    pub fn recover_unowned_pages(&self, pages: &[u32]) -> Result<(), PagerError> {
1582        let _ownership = self.lock_ownership_mutations();
1583        self.ensure_writeback_available()?;
1584        if self.config.read_only {
1585            return Err(PagerError::ReadOnly);
1586        }
1587        let page_count = self.page_count()?;
1588        let mut freelist = self.freelist_write()?;
1589        let remaining = self.pages_not_in_freelist(pages, &freelist, page_count)?;
1590        if !remaining.is_empty() {
1591            let mut missing: Vec<_> = remaining.into_iter().collect();
1592            missing.sort_unstable();
1593            for id in &missing {
1594                self.cache.remove(*id);
1595            }
1596            freelist.free_batch(&missing);
1597            *self.header_dirty_lock()? = true;
1598        }
1599        Ok(())
1600    }
1601
1602    /// Reject a recovery plan if any page it must preserve is already free.
1603    /// The caller must exclude allocation and freelist mutation during recovery.
1604    pub fn validate_owned_pages(&self, pages: &[u32]) -> Result<(), PagerError> {
1605        let page_count = self.page_count()?;
1606        let freelist = self.freelist_write()?;
1607        let absent = self.pages_not_in_freelist(pages, &freelist, page_count)?;
1608        if absent.len() != pages.len() {
1609            return Err(PagerError::InvalidDatabase(
1610                "owned recovery page is free".into(),
1611            ));
1612        }
1613        Ok(())
1614    }
1615
1616    /// Persist the current allocator in both fallback copies during recovery.
1617    /// The caller must exclude allocation until journal completion is durable.
1618    pub fn sync_recovered_allocator(&self) -> Result<(), PagerError> {
1619        let _ownership = self.lock_ownership_mutations();
1620        let result = (|| {
1621            self.sync()?;
1622            let _publication = self
1623                .superblock_publication
1624                .lock()
1625                .map_err(|_| PagerError::LockPoisoned)?;
1626            let header = self.header_read()?.clone();
1627            for _ in 0..reddb_file::PAGED_SUPERBLOCK_SLOT_COUNT {
1628                self.commit_superblock_locked(|image| {
1629                    reddb_file::encode_database_header(image, &header)
1630                        .map_err(|error| PagerError::InvalidDatabase(error.to_string()))
1631                })?;
1632            }
1633            Ok(())
1634        })();
1635        if result.is_err() {
1636            self.writeback_failed
1637                .store(true, std::sync::atomic::Ordering::Release);
1638        }
1639        result
1640    }
1641
1642    /// Get database header
1643    /// Pages available to the allocator, including pages on unloaded trunks.
1644    pub fn free_page_count(&self) -> Result<u32, PagerError> {
1645        Ok(self.freelist_write()?.total_free())
1646    }
1647
1648    pub fn header(&self) -> Result<DatabaseHeader, PagerError> {
1649        Ok(self.header_read()?.clone())
1650    }
1651
1652    pub fn physical_header(&self) -> Result<PhysicalFileHeader, PagerError> {
1653        Ok(self.header_read()?.physical)
1654    }
1655
1656    pub fn update_physical_header(&self, physical: PhysicalFileHeader) -> Result<(), PagerError> {
1657        let _ownership = self.lock_ownership_mutations();
1658        self.ensure_writeback_available()?;
1659        if self.config.read_only {
1660            return Err(PagerError::ReadOnly);
1661        }
1662
1663        let mut header = self.header_write()?;
1664        header.physical = physical;
1665        *self.header_dirty_lock()? = true;
1666        Ok(())
1667    }
1668
1669    /// Get page count
1670    pub fn page_count(&self) -> Result<u32, PagerError> {
1671        Ok(self.header_read()?.page_count)
1672    }
1673
1674    /// Flush all dirty pages to disk
1675    pub fn flush(&self) -> Result<(), PagerError> {
1676        let _ownership = self.lock_ownership_mutations();
1677        self.ensure_writeback_available()?;
1678        if self.config.read_only {
1679            return Ok(());
1680        }
1681
1682        // Persist freelist to trunk pages when dirty
1683        let trunks = {
1684            let mut freelist = self.freelist_write()?;
1685            if freelist.is_dirty() {
1686                let mut header = self.header_write()?;
1687                let trunks = freelist.flush_to_trunks(0, || {
1688                    let id = header.page_count;
1689                    header.page_count += 1;
1690                    id
1691                });
1692                header.freelist_head = freelist.trunk_head();
1693                *self.header_dirty_lock()? = true;
1694                freelist.mark_clean();
1695                trunks
1696            } else {
1697                Vec::new()
1698            }
1699        };
1700
1701        let mut dirty_pages = Vec::new();
1702        for trunk in trunks {
1703            let page_id = trunk.page_id();
1704            if let Some(evicted) = self.cache.insert_dirty(page_id, trunk) {
1705                // Trunk publication can evict dirty data. Keep it in the same
1706                // WAL-first, double-write-protected batch as resident pages.
1707                dirty_pages.push((evicted.page_id(), evicted));
1708            }
1709        }
1710
1711        // IDs are compact; page images are not. At 16 KiB per page, staging
1712        // 256 images plus one DWB frame uses about 5 MiB, independently of
1713        // the dirty cache size. Publish the header only after every batch.
1714        const FLUSH_BATCH_PAGES: usize = 256;
1715        for batch in dirty_pages.chunks(FLUSH_BATCH_PAGES) {
1716            self.write_dirty_page_batch(batch)?;
1717        }
1718        self.evictions_written.fetch_add(
1719            dirty_pages.len() as u64,
1720            std::sync::atomic::Ordering::SeqCst,
1721        );
1722        drop(dirty_pages);
1723        // Batch dirty IDs, not every resident ID: otherwise a few edits in
1724        // a mostly clean cache pay a protected write per cache-sized slice.
1725        // Physical order also avoids arbitrary seeks among each batch's homes.
1726        let mut page_ids = self.cache.dirty_page_ids(usize::MAX);
1727        page_ids.sort_unstable();
1728        if self.bounded_writeback()? {
1729            for id in page_ids {
1730                if let Some(page) = self.cache.flush_dirty_page(id) {
1731                    self.write_dirty_page_batch(&[(id, page)])?;
1732                }
1733            }
1734        } else {
1735            for ids in page_ids.chunks(FLUSH_BATCH_PAGES) {
1736                let pages = self.cache.flush_dirty_pages(ids);
1737                self.write_dirty_page_batch(&pages)?;
1738            }
1739        }
1740
1741        // Write header if dirty
1742        if !self.batch_active()? && *self.header_dirty_lock()? {
1743            self.write_header()?;
1744        }
1745
1746        Ok(())
1747    }
1748
1749    fn write_dirty_page_batch(&self, pages: &[(u32, Page)]) -> Result<(), PagerError> {
1750        if pages.is_empty() {
1751            return Ok(());
1752        }
1753        // Every image's WAL must be durable before its home write, including
1754        // dirty data evicted while publishing freelist trunks. LSN zero is
1755        // reserved for pages not produced by a WAL append.
1756        let result = (|| {
1757            let max_lsn = pages
1758                .iter()
1759                .filter_map(|(_, page)| page.header().ok().map(|header| header.lsn))
1760                .max()
1761                .unwrap_or(0);
1762            if max_lsn > 0 {
1763                self.wal.flush_until(max_lsn)?;
1764            }
1765            self.write_pages_through_dwb(pages)
1766        })();
1767        if result.is_err() {
1768            self.writeback_failed
1769                .store(true, std::sync::atomic::Ordering::Release);
1770            for (page_id, _) in pages {
1771                self.cache.mark_dirty(*page_id);
1772            }
1773        }
1774        result
1775    }
1776
1777    /// Sync file to disk (fsync)
1778    pub fn sync(&self) -> Result<(), PagerError> {
1779        let _ownership = self.lock_ownership_mutations();
1780        self.flush()?;
1781
1782        if self
1783            .allocation_reused
1784            .swap(false, std::sync::atomic::Ordering::AcqRel)
1785        {
1786            // flush published the current allocator in one slot. Mirror that
1787            // ownership before callers publish roots that use reclaimed pages;
1788            // recovery through the sibling slot must never allocate them again.
1789            if let Err(error) = self.write_header_and_sync() {
1790                self.allocation_reused
1791                    .store(true, std::sync::atomic::Ordering::Release);
1792                return Err(error);
1793            }
1794        }
1795
1796        let file = self.file_lock()?;
1797        file.sync_all()?;
1798
1799        Ok(())
1800    }
1801
1802    /// Get cache statistics
1803    pub fn cache_stats(&self) -> super::page_cache::CacheStats {
1804        self.cache.stats()
1805    }
1806
1807    /// Pages currently resident in the page cache. Slots are fixed size, so
1808    /// this times the page size is the cache's memory footprint (ADR 0073 §2).
1809    pub fn cache_len(&self) -> usize {
1810        self.cache.len()
1811            + if self.config.read_only {
1812                self.read_only_recovery
1813                    .read()
1814                    .unwrap_or_else(|poisoned| poisoned.into_inner())
1815                    .len()
1816            } else {
1817                0
1818            }
1819    }
1820
1821    /// Preallocated page-cache slots — the sizing this process derived from
1822    /// its page-cache budget share.
1823    pub fn cache_capacity(&self) -> usize {
1824        self.cache.capacity()
1825    }
1826
1827    /// Count dirty pages currently in the page cache.
1828    pub fn dirty_page_count(&self) -> usize {
1829        self.cache.dirty_count()
1830    }
1831
1832    /// Estimated fraction of the page cache holding dirty pages.
1833    /// Returned in `[0, 1]`. Used by the background writer to
1834    /// decide when to kick in aggressive flushing.
1835    pub fn dirty_fraction(&self) -> f64 {
1836        let capacity = self.cache.capacity().max(1) as f64;
1837        self.cache.dirty_count() as f64 / capacity
1838    }
1839
1840    /// Flush up to `max` dirty pages from the cache. Returns the
1841    /// number actually written. Background-writer entry point —
1842    /// reuses the same persistence path as `flush()` but bounded.
1843    pub fn flush_some_dirty(&self, max: usize) -> Result<usize, PagerError> {
1844        let _ownership = self.lock_ownership_mutations();
1845        self.ensure_writeback_available()?;
1846        if self.config.read_only || max == 0 {
1847            return Ok(0);
1848        }
1849        let dirty_pages = self.cache.flush_some_dirty(max);
1850        if dirty_pages.is_empty() {
1851            return Ok(0);
1852        }
1853        let count = dirty_pages.len();
1854        // WAL-first: every cached dirty page carries an LSN that the
1855        // WAL must have already persisted. The full `flush()` path
1856        // enforces this with `wal.flush(max_lsn)`; here we simply
1857        // write through the pager — safe because callers only reach
1858        // this path via the bgwriter, which runs asynchronously
1859        // alongside normal commits that already respect WAL-first.
1860        for (page_id, page) in dirty_pages {
1861            self.write_page(page_id, page)?;
1862        }
1863        Ok(count)
1864    }
1865
1866    /// Get database file path
1867    pub fn path(&self) -> &Path {
1868        &self.path
1869    }
1870
1871    /// Return the exclusively owned handle. Callers must complete their
1872    /// publication boundary before consuming the pager.
1873    pub fn into_inner(self) -> F {
1874        self.file
1875            .into_inner()
1876            .unwrap_or_else(|poisoned| poisoned.into_inner())
1877    }
1878
1879    /// Check if database is read-only
1880    pub fn is_read_only(&self) -> bool {
1881        self.config.read_only
1882    }
1883
1884    /// Get file size in bytes
1885    pub fn file_size(&self) -> Result<u64, PagerError> {
1886        let file = self.file_lock()?;
1887        Ok(file.file_len()?)
1888    }
1889
1890    /// Clear the in-file DWB zone with valid reserved pages.
1891    fn clear_dwb_zone(&self) -> Result<(), PagerError> {
1892        let mut file = self.file_lock()?;
1893        Ok(pager_io::clear_dwb_zone(&mut *file)?)
1894    }
1895
1896    /// Read catalog authority from the newest sealed slot, independently of the
1897    /// cached ordinary header fields.
1898    pub fn manifest_reference(&self) -> Result<reddb_file::page_proof::PageReference, PagerError> {
1899        let _ownership = self.lock_ownership_mutations();
1900        let (_, image) = self.newest_superblock()?;
1901        reddb_file::file_format::database_header_manifest_reference(&image)
1902            .map_err(|err| PagerError::InvalidDatabase(err.to_string()))
1903    }
1904
1905    pub fn manifest_page_id(&self) -> Result<u32, PagerError> {
1906        let reference = self.manifest_reference()?;
1907        Ok(if reference.page_id == 0 {
1908            1
1909        } else {
1910            reference.page_id
1911        })
1912    }
1913
1914    /// Read the sealed catalog root, or page 1 for a legacy bootstrap header.
1915    ///
1916    /// ADR 0074 §2: manifest corruption fails the open didactically, naming the
1917    /// zone — it never falls back to a sidecar and never returns garbage.
1918    pub fn read_manifest_page(&self) -> Result<Page, PagerError> {
1919        let _ownership = self.lock_ownership_mutations();
1920        let root = self.manifest_page_id()?;
1921        self.read_page(root)
1922            .map_err(|_| PagerError::ManifestZoneCorrupt(self.path.clone()))
1923    }
1924
1925    /// The new catalog and all its children must already be durable. Both
1926    /// fallback headers stop naming its predecessor before that root is freed.
1927    pub fn publish_manifest_reference(
1928        &self,
1929        reference: reddb_file::page_proof::PageReference,
1930    ) -> Result<(), PagerError> {
1931        let _ownership = self.lock_ownership_mutations();
1932        self.ensure_writeback_available()?;
1933        if self.config.read_only {
1934            return Err(PagerError::ReadOnly);
1935        }
1936        if reference.page_id < FIRST_ALLOCATABLE_PAGE
1937            || reference.page_id >= self.page_count()?
1938            || reference.digest == [0; 32]
1939            || self.header_read()?.required_capabilities & reddb_file::FILE_CAPABILITY_CATALOG_ROOT
1940                == 0
1941        {
1942            return Err(PagerError::InvalidDatabase(
1943                "invalid catalog generation publication".into(),
1944            ));
1945        }
1946        let header = self.header_read()?.clone();
1947        let _publication = self
1948            .superblock_publication
1949            .lock()
1950            .map_err(|_| PagerError::LockPoisoned)?;
1951        let result = (|| {
1952            for _ in 0..reddb_file::PAGED_SUPERBLOCK_SLOT_COUNT {
1953                self.commit_superblock_locked(|image| {
1954                    reddb_file::encode_database_header(image, &header)
1955                        .map_err(|err| PagerError::InvalidDatabase(err.to_string()))?;
1956                    reddb_file::file_format::set_database_header_manifest_reference(
1957                        image, reference,
1958                    )
1959                    .map_err(|err| PagerError::InvalidDatabase(err.to_string()))
1960                })?;
1961            }
1962            *self.header_dirty_lock()? = false;
1963            Ok(())
1964        })();
1965        if result.is_err() {
1966            self.writeback_failed
1967                .store(true, std::sync::atomic::Ordering::Release);
1968        }
1969        result
1970    }
1971
1972    /// Write pages through the double-write buffer for torn page protection.
1973    ///
1974    /// 1. Write pages to the in-file DWB zone with a header (magic + count + checksum)
1975    /// 2. fsync the DWB zone
1976    /// 3. Write all pages to their final locations in the .rdb file
1977    /// 4. Clear the DWB zone (marks as consumed)
1978    fn write_pages_through_dwb(&self, pages: &[(u32, Page)]) -> Result<(), PagerError> {
1979        if self.config.read_only {
1980            return Err(PagerError::ReadOnly);
1981        }
1982        self.record_ownership(|wal| wal.flush_page_ownership())?;
1983        // Keep the file locked through staging, home writes and clearing so
1984        // another page writer cannot interleave with a protected batch.
1985        let _publication = self
1986            .superblock_publication
1987            .lock()
1988            .map_err(|_| PagerError::LockPoisoned)?;
1989        let mut file = self.file_lock()?;
1990        self.ensure_writeback_available()?;
1991        let result: Result<(), PagerError> = (|| {
1992            let mut staged = self
1993                .staged_pages
1994                .lock()
1995                .map_err(|_| PagerError::LockPoisoned)?;
1996            if let Some(batch) = staged.as_mut() {
1997                for (id, page) in pages {
1998                    batch.stage(&mut *file, *id, page)?;
1999                }
2000                Ok(())
2001            } else {
2002                Ok(pager_io::write_pages(&mut *file, pages, self.dwb_enabled)?)
2003            }
2004        })();
2005        if result.is_err() {
2006            // Set this while holding the file lock: a waiting writer must not
2007            // replace the recovery frame after an interrupted home write.
2008            self.writeback_failed
2009                .store(true, std::sync::atomic::Ordering::Release);
2010        }
2011        result
2012    }
2013
2014    /// Recover from double-write buffer after a crash.
2015    ///
2016    /// If the DWB zone contains valid pages, they were written before the crash
2017    /// interrupted writing to their home locations. Re-apply them.
2018    fn recover_from_dwb(&self) -> Result<(), PagerError> {
2019        let mut file = self.file_lock()?;
2020        if !self.config.read_only
2021            && !self.dwb_enabled
2022            && pager_io::requires_dwb_publication(&mut *file)?
2023        {
2024            return Err(PagerError::InvalidDatabase(
2025                "DWB generation authority requires protected page writes".into(),
2026            ));
2027        }
2028        if self.config.read_only {
2029            for (id, page) in pager_io::read_dwb_pages(&mut *file)? {
2030                // The DWB checksum seals raw bytes, which may be ciphertext.
2031                // Normal reads check the page checksum; encryption hosts use
2032                // read_page_no_checksum and authenticate after decrypting.
2033                self.install_read_only_page(id, page)?;
2034            }
2035            return Ok(());
2036        }
2037        Ok(pager_io::recover_from_dwb(&mut *file)?)
2038    }
2039
2040    /// Install a validated recovery image only in this reader's private view.
2041    /// The source and ordinary mutation APIs remain read-only. Bound pinned
2042    /// images by the cache budget (with room for one complete DWB frame).
2043    pub fn restore_read_only_page(&self, page_id: u32, page: Page) -> Result<(), PagerError> {
2044        if !self.config.read_only || page_id == 0 || page.page_id() != page_id {
2045            return Err(PagerError::InvalidDatabase(
2046                "invalid read-only recovery image".into(),
2047            ));
2048        }
2049        page.verify_checksum()?;
2050        self.install_read_only_page(page_id, page)
2051    }
2052
2053    fn install_read_only_page(&self, page_id: u32, page: Page) -> Result<(), PagerError> {
2054        let mut images = self
2055            .read_only_recovery
2056            .write()
2057            .map_err(|_| PagerError::LockPoisoned)?;
2058        let limit = self
2059            .config
2060            .cache_size
2061            .max(pager_io::DWB_MAX_PAGES_PER_FRAME);
2062        if images.len() >= limit && !images.contains_key(&page_id) {
2063            return Err(PagerError::InvalidDatabase(
2064                "read-only recovery exceeds the page cache budget".into(),
2065            ));
2066        }
2067        images.insert(page_id, page);
2068        Ok(())
2069    }
2070
2071    /// Finish a consumed trunk's durable ownership change, retaining errors
2072    /// across allocation attempts until both copies have been synchronized.
2073    /// Called with the freelist locked when consuming or retrying a trunk.
2074    fn complete_allocation_fence(&self) -> Result<(), PagerError> {
2075        if self
2076            .allocation_fence_pending
2077            .load(std::sync::atomic::Ordering::Acquire)
2078        {
2079            self.write_header_and_sync()?;
2080            self.write_header_and_sync()?;
2081            self.allocation_fence_pending
2082                .store(false, std::sync::atomic::Ordering::Release);
2083        }
2084        Ok(())
2085    }
2086
2087    /// Write header and sync to disk (public for checkpointer).
2088    pub fn write_header_and_sync(&self) -> Result<(), PagerError> {
2089        let _ownership = self.lock_ownership_mutations();
2090        self.write_header()?;
2091        let file = self.file_lock()?;
2092        file.sync_all()?;
2093        Ok(())
2094    }
2095
2096    /// Set the checkpoint_in_progress flag in the header.
2097    pub fn set_checkpoint_in_progress(
2098        &self,
2099        in_progress: bool,
2100        target_lsn: u64,
2101    ) -> Result<(), PagerError> {
2102        let _ownership = self.lock_ownership_mutations();
2103        let mut header = self.header_write()?;
2104        header.checkpoint_in_progress = in_progress;
2105        header.checkpoint_target_lsn = target_lsn;
2106        *self.header_dirty_lock()? = true;
2107        drop(header);
2108        self.write_header_and_sync()
2109    }
2110
2111    /// Update the checkpoint LSN and clear the in-progress flag.
2112    pub fn complete_checkpoint(&self, lsn: u64) -> Result<(), PagerError> {
2113        let _ownership = self.lock_ownership_mutations();
2114        let mut header = self.header_write()?;
2115        header.checkpoint_lsn = lsn;
2116        header.checkpoint_in_progress = false;
2117        header.checkpoint_target_lsn = 0;
2118        *self.header_dirty_lock()? = true;
2119        drop(header);
2120        self.write_header_and_sync()
2121    }
2122}
2123
2124#[cfg(test)]
2125mod integrity_guidance_tests {
2126    use super::PagerError;
2127    use std::path::PathBuf;
2128
2129    #[test]
2130    fn damaged_paged_zones_recommend_preserving_files_and_a_verified_backup() {
2131        for error in [
2132            PagerError::SuperblockZoneUnrecoverable(PathBuf::from("data.rdb")),
2133            PagerError::ManifestZoneCorrupt(PathBuf::from("data.rdb")),
2134            PagerError::DwbZoneCorrupt(PathBuf::from("data.rdb")),
2135        ] {
2136            let message = error.to_string();
2137            assert!(message.contains("Preserve the database"), "{message}");
2138            assert!(message.contains("verified backup"), "{message}");
2139            assert!(!message.contains("salvage"), "{message}");
2140            assert!(!message.contains("SCRUB"), "{message}");
2141        }
2142    }
2143}