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