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