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        self.capture_page_before_write(page_id)?;
1089
1090        // Update checksum
1091        page.update_checksum();
1092
1093        // Add to cache and mark dirty. If the cache had to evict a
1094        // dirty entry, write it through immediately — the evicted
1095        // page will never be flushed otherwise (same bug fixed in
1096        // `allocate_page`).
1097        if let Some(dirty_page) = self.cache.insert_dirty(page_id, page) {
1098            self.write_evicted_dirty_page(dirty_page, Some(page_id))?;
1099        }
1100
1101        Ok(())
1102    }
1103
1104    /// Write a page without updating checksum (for encrypted pages)
1105    ///
1106    /// Use this when the page content has its own integrity protection
1107    /// (e.g., AES-GCM authentication tag for encrypted pages).
1108    pub fn write_page_no_checksum(&self, page_id: u32, page: Page) -> Result<(), PagerError> {
1109        let _ownership = self.lock_ownership_mutations();
1110        self.ensure_writeback_available()?;
1111        if self.config.read_only {
1112            return Err(PagerError::ReadOnly);
1113        }
1114
1115        self.capture_page_before_write(page_id)?;
1116
1117        // Add to cache and mark dirty (no checksum update). Same
1118        // eviction-write-through guard as `write_page`.
1119        if let Some(dirty_page) = self.cache.insert_dirty(page_id, page) {
1120            self.write_evicted_dirty_page(dirty_page, Some(page_id))?;
1121        }
1122
1123        Ok(())
1124    }
1125
1126    fn capture_page_before_write(&self, page_id: u32) -> Result<(), PagerError> {
1127        let mut required = false;
1128        self.record_ownership(|wal| {
1129            required = wal.needs_page_image(page_id)?;
1130            Ok(())
1131        })?;
1132        if required {
1133            let previous = self.read_page(page_id)?;
1134            self.record_ownership(|wal| wal.capture_page_image(&previous))?;
1135        }
1136        Ok(())
1137    }
1138
1139    /// Allocate a new page
1140    pub fn allocate_page(&self, page_type: PageType) -> Result<Page, PagerError> {
1141        let _ownership = self.lock_ownership_mutations();
1142        self.ensure_writeback_available()?;
1143        if self.config.read_only {
1144            return Err(PagerError::ReadOnly);
1145        }
1146
1147        // Try to get from freelist first
1148        let page_id = if self.batch_active()? {
1149            // Prepared frames may extend the file but cannot reuse allocator
1150            // state whose published roots still name the old ownership.
1151            let mut header = self.header_write()?;
1152            let id = header.page_count;
1153            header.page_count = id
1154                .checked_add(1)
1155                .ok_or_else(|| PagerError::InvalidDatabase("page count overflow".into()))?;
1156            *self.header_dirty_lock()? = true;
1157            id
1158        } else {
1159            let mut freelist = self.freelist_write()?;
1160            // A previous fence can fail after loading the trunk into memory.
1161            // Retry it before the fast path can consume any of those pages.
1162            self.complete_allocation_fence()?;
1163            if let Some(id) = freelist.next_in_memory_page() {
1164                self.record_ownership(|wal| wal.reserve_pages(id, 1))?;
1165                let id = freelist
1166                    .allocate()
1167                    .expect("free page checked while allocator is locked");
1168                self.allocation_reused
1169                    .store(true, std::sync::atomic::Ordering::Release);
1170                id
1171            } else if freelist.trunk_head() != 0 {
1172                let trunk_id = freelist.trunk_head();
1173
1174                let trunk = self.read_page(trunk_id).map_err(|e| match e {
1175                    PagerError::PageNotFound(_) => {
1176                        PagerError::InvalidDatabase("Freelist trunk missing".to_string())
1177                    }
1178                    other => other,
1179                })?;
1180                if trunk.page_id() != trunk_id {
1181                    return Err(PagerError::InvalidDatabase(
1182                        "misdirected freelist trunk".into(),
1183                    ));
1184                }
1185
1186                // Persist ownership of every page detached from the trunk
1187                // before either superblock stops naming that trunk.
1188                let mut detached = FreeList::new();
1189                detached
1190                    .load_from_trunk(&trunk)
1191                    .map_err(|e| PagerError::InvalidDatabase(format!("Freelist: {e}")))?;
1192                let mut pages = Vec::new();
1193                let mut seen = std::collections::HashSet::new();
1194                let page_count = self.page_count()?;
1195                while let Some(id) = detached.allocate() {
1196                    if id < FIRST_ALLOCATABLE_PAGE || id >= page_count || !seen.insert(id) {
1197                        return Err(PagerError::InvalidDatabase(
1198                            "invalid freelist trunk page".into(),
1199                        ));
1200                    }
1201                    pages.push(id);
1202                }
1203                let mut journaled = false;
1204                self.record_ownership(|wal| {
1205                    journaled = wal.has_page_ownership_journal()?;
1206                    Ok(())
1207                })?;
1208                if !journaled {
1209                    self.allocate_unjournaled_trunk(&mut freelist, trunk, &pages)?
1210                } else {
1211                    self.record_ownership(|wal| wal.detach_free_pages(&pages))?;
1212
1213                    freelist
1214                        .load_from_trunk(&trunk)
1215                        .map_err(|e| PagerError::InvalidDatabase(format!("Freelist: {}", e)))?;
1216                    let mut header = self.header_write()?;
1217                    header.freelist_head = freelist.trunk_head();
1218                    *self.header_dirty_lock()? = true;
1219                    drop(header);
1220                    // The consumed trunk itself becomes reusable. Forget its old
1221                    // allocator role durably before cache eviction can overwrite it.
1222                    // Keep the allocator locked so another allocator cannot race
1223                    // ahead of this fence. A failed fence leaves allocation stopped.
1224                    self.allocation_fence_pending
1225                        .store(true, std::sync::atomic::Ordering::Release);
1226                    self.complete_allocation_fence()?;
1227                    let next = freelist.next_in_memory_page().ok_or_else(|| {
1228                        PagerError::InvalidDatabase("Freelist empty after trunk load".to_string())
1229                    })?;
1230                    self.record_ownership(|wal| wal.reserve_pages(next, 1))?;
1231                    let id = freelist.allocate().ok_or_else(|| {
1232                        PagerError::InvalidDatabase("Freelist empty after trunk load".to_string())
1233                    })?;
1234                    self.allocation_reused
1235                        .store(true, std::sync::atomic::Ordering::Release);
1236                    id
1237                }
1238            } else {
1239                // No free pages, extend file
1240                let mut header = self.header_write()?;
1241                let id = header.page_count;
1242                let next = id
1243                    .checked_add(1)
1244                    .ok_or_else(|| PagerError::InvalidDatabase("page count overflow".into()))?;
1245                self.record_ownership(|wal| wal.reserve_pages(id, 1))?;
1246                header.page_count = next;
1247                *self.header_dirty_lock()? = true;
1248                id
1249            }
1250        };
1251
1252        let page = Page::new(page_type, page_id);
1253
1254        // Write to cache. The evicted page (if any) is dirty by
1255        // definition — `cache.insert_dirty` only returns `Some` when it
1256        // had to evict a dirty entry to make room. The previous
1257        // version dropped that return value, which silently lost
1258        // writes whenever a freshly-allocated page caused an LRU
1259        // eviction. This shows up under heavy ingest as
1260        // "B-tree insert error: Pager error: I/O error: failed to
1261        // fill whole buffer" later, when something tries to read
1262        // back the never-flushed page. Mirror `read_page`'s
1263        // handling: write the evicted page through immediately so
1264        // the on-disk image stays consistent.
1265        if let Some(dirty_page) = self.cache.insert_dirty(page_id, page.clone()) {
1266            self.write_evicted_dirty_page(dirty_page, Some(page_id))?;
1267        }
1268
1269        Ok(page)
1270    }
1271
1272    /// Keep untouched free IDs reachable on disk when no ownership epoch can
1273    /// recover a detached trunk. Removing one ID costs one protected page write;
1274    /// checkpoint/replay epochs retain their batched, journaled allocation path.
1275    fn allocate_unjournaled_trunk(
1276        &self,
1277        freelist: &mut FreeList,
1278        mut trunk: Page,
1279        pages: &[u32],
1280    ) -> Result<u32, PagerError> {
1281        let id = *pages
1282            .first()
1283            .expect("validated trunk includes its own page");
1284        self.record_ownership(|wal| wal.reserve_pages(id, 1))?;
1285        if pages.len() > 1 {
1286            let remaining =
1287                u32::try_from(pages.len() - 2).expect("a validated trunk fits in one page");
1288            trunk.content_mut()[4..8].copy_from_slice(&remaining.to_le_bytes());
1289            trunk.update_checksum();
1290            self.cache.remove(trunk.page_id());
1291            self.write_pages_through_dwb(&[(trunk.page_id(), trunk)])?;
1292            freelist.note_durable_trunk_allocation(remaining);
1293        } else {
1294            // The empty trunk itself is the last available page. Fence both
1295            // superblocks before it can be overwritten as user data.
1296            freelist
1297                .load_from_trunk(&trunk)
1298                .map_err(|error| PagerError::InvalidDatabase(error.to_string()))?;
1299            self.header_write()?.freelist_head = freelist.trunk_head();
1300            *self.header_dirty_lock()? = true;
1301            self.allocation_fence_pending
1302                .store(true, std::sync::atomic::Ordering::Release);
1303            self.complete_allocation_fence()?;
1304            assert_eq!(freelist.allocate(), Some(id));
1305        }
1306        self.allocation_reused
1307            .store(true, std::sync::atomic::Ordering::Release);
1308        Ok(id)
1309    }
1310
1311    /// Reserve a contiguous extent of vector pages.
1312    pub fn reserve_contig_extent(&self, n_pages: u32) -> Result<ExtentId, PagerError> {
1313        let _ownership = self.lock_ownership_mutations();
1314        self.ensure_writeback_available()?;
1315        if self.config.read_only {
1316            return Err(PagerError::ReadOnly);
1317        }
1318        if n_pages == 0 {
1319            return Err(PagerError::InvalidDatabase(
1320                "contiguous extent must reserve at least one page".to_string(),
1321            ));
1322        }
1323
1324        let start_page = {
1325            let mut header = self.header_write()?;
1326            let start = header.page_count;
1327            let end = header.page_count.checked_add(n_pages).ok_or_else(|| {
1328                PagerError::InvalidDatabase("contiguous extent page count overflow".to_string())
1329            })?;
1330            self.record_ownership(|wal| wal.reserve_pages(start, n_pages))?;
1331            header.page_count = end;
1332            *self.header_dirty_lock()? = true;
1333            start
1334        };
1335
1336        for page_id in start_page..start_page + n_pages {
1337            let mut page = Page::new(PageType::Vector, page_id);
1338            page.update_checksum();
1339            if let Some(dirty_page) = self.cache.insert_dirty(page_id, page) {
1340                self.write_evicted_dirty_page(dirty_page, Some(page_id))?;
1341            }
1342        }
1343
1344        Ok(ExtentId {
1345            start_page,
1346            n_pages,
1347        })
1348    }
1349
1350    /// Free a page (return to freelist)
1351    pub fn free_page(&self, page_id: u32) -> Result<(), PagerError> {
1352        if self.batch_active()? {
1353            return Err(PagerError::InvalidDatabase(
1354                "prepared DWB batches cannot retire published pages".into(),
1355            ));
1356        }
1357        let _ownership = self.lock_ownership_mutations();
1358        self.ensure_writeback_available()?;
1359        if self.config.read_only {
1360            return Err(PagerError::ReadOnly);
1361        }
1362
1363        let mut deferred = self
1364            .deferred_reclamation
1365            .lock()
1366            .map_err(|_| PagerError::LockPoisoned)?;
1367        if deferred.enabled {
1368            if page_id < FIRST_ALLOCATABLE_PAGE || page_id >= self.page_count()? {
1369                return Err(PagerError::InvalidDatabase(
1370                    "invalid deferred free page".into(),
1371                ));
1372            }
1373            // The host waits for this record only once the generation is
1374            // published: see `WalBarrier::retire_deferred_page`.
1375            self.record_ownership(|wal| wal.retire_deferred_page(page_id))?;
1376            // Keep dirty forwarding/empty nodes until publication. An
1377            // incidental flush must leave the previous root traversable.
1378            deferred.pending.insert(page_id);
1379            return Ok(());
1380        }
1381        drop(deferred);
1382
1383        self.record_ownership(|wal| wal.retire_pages(&[page_id]))?;
1384
1385        // Remove from cache
1386        self.cache.remove(page_id);
1387
1388        // Add to freelist
1389        let mut freelist = self.freelist_write()?;
1390        freelist.free(page_id);
1391
1392        *self.header_dirty_lock()? = true;
1393
1394        Ok(())
1395    }
1396
1397    pub fn enable_deferred_reclamation(&self) -> Result<(), PagerError> {
1398        let _ownership = self.lock_ownership_mutations();
1399        self.deferred_reclamation
1400            .lock()
1401            .map_err(|_| PagerError::LockPoisoned)?
1402            .enabled = true;
1403        Ok(())
1404    }
1405
1406    pub fn deferred_reclamation_pages(&self) -> Result<(Vec<u32>, Vec<u32>), PagerError> {
1407        let deferred = self
1408            .deferred_reclamation
1409            .lock()
1410            .map_err(|_| PagerError::LockPoisoned)?;
1411        Ok((
1412            deferred.pending.iter().copied().collect(),
1413            deferred.published.iter().copied().collect(),
1414        ))
1415    }
1416
1417    pub fn restore_deferred_reclamation(&self, pages: &[u32]) -> Result<(), PagerError> {
1418        let _ownership = self.lock_ownership_mutations();
1419        let count = self.page_count()?;
1420        if pages
1421            .iter()
1422            .any(|id| *id < FIRST_ALLOCATABLE_PAGE || *id >= count)
1423        {
1424            return Err(PagerError::InvalidDatabase(
1425                "invalid persisted deferred free page".into(),
1426            ));
1427        }
1428        let mut deferred = self
1429            .deferred_reclamation
1430            .lock()
1431            .map_err(|_| PagerError::LockPoisoned)?;
1432        deferred.pending.extend(pages);
1433        deferred.published.extend(pages);
1434        Ok(())
1435    }
1436
1437    /// The caller has durably published a catalog that retains `retained`
1438    /// and no longer names `released`, after waiting for old tree readers.
1439    pub fn complete_deferred_publication(
1440        &self,
1441        retained: &[u32],
1442        released: &[u32],
1443    ) -> Result<(), PagerError> {
1444        let _ownership = self.lock_ownership_mutations();
1445        let mut deferred = self
1446            .deferred_reclamation
1447            .lock()
1448            .map_err(|_| PagerError::LockPoisoned)?;
1449        if !released.is_empty() {
1450            self.free_retired_pages(released)?;
1451        }
1452        for id in released {
1453            deferred.pending.remove(id);
1454        }
1455        deferred.published = retained.iter().copied().collect();
1456        Ok(())
1457    }
1458
1459    /// Record the pages whose catalog ownership is about to be retired.
1460    pub fn record_retirement_intent(&self, pages: &[u32]) -> Result<(), PagerError> {
1461        let _ownership = self.lock_ownership_mutations();
1462        self.ensure_writeback_available()?;
1463        if self.config.read_only {
1464            return Err(PagerError::ReadOnly);
1465        }
1466        let page_count = self.page_count()?;
1467        let mut seen = std::collections::HashSet::with_capacity(pages.len());
1468        if pages
1469            .iter()
1470            .any(|id| *id < FIRST_ALLOCATABLE_PAGE || *id >= page_count || !seen.insert(*id))
1471        {
1472            return Err(PagerError::InvalidDatabase(
1473                "invalid retirement intent".into(),
1474            ));
1475        }
1476        self.record_ownership(|wal| wal.retire_pages(pages))
1477    }
1478
1479    /// Return a fully validated, unpublished tree generation in one allocator
1480    /// mutation. Call only after its removal from the manifest is durable.
1481    pub fn free_retired_pages(&self, pages: &[u32]) -> Result<(), PagerError> {
1482        let _ownership = self.lock_ownership_mutations();
1483        self.ensure_writeback_available()?;
1484        if self.config.read_only {
1485            return Err(PagerError::ReadOnly);
1486        }
1487        let page_count = self.page_count()?;
1488        if pages
1489            .iter()
1490            .any(|id| *id < FIRST_ALLOCATABLE_PAGE || *id >= page_count)
1491        {
1492            return Err(PagerError::InvalidDatabase(
1493                "invalid retired page range".into(),
1494            ));
1495        }
1496        let mut seen = std::collections::HashSet::with_capacity(pages.len());
1497        if pages.iter().any(|id| !seen.insert(*id)) {
1498            return Err(PagerError::InvalidDatabase("duplicate retired page".into()));
1499        }
1500        let mut freelist = self.freelist_write()?;
1501        if freelist.contains_any(&seen) {
1502            return Err(PagerError::InvalidDatabase(
1503                "retired page is already free".into(),
1504            ));
1505        }
1506        // Some free pages remain in on-disk trunks until allocation reaches
1507        // them. Check those too before changing the cache or the allocator.
1508        // The allocator lock prevents concurrent consumption or publication.
1509        let mut trunk_id = freelist.trunk_head();
1510        let mut visited = std::collections::HashSet::new();
1511        while trunk_id != 0 && !seen.is_empty() {
1512            if trunk_id < FIRST_ALLOCATABLE_PAGE
1513                || trunk_id >= page_count
1514                || !visited.insert(trunk_id)
1515            {
1516                return Err(PagerError::InvalidDatabase(
1517                    "invalid freelist trunk chain".into(),
1518                ));
1519            }
1520            let trunk = self.read_page(trunk_id)?;
1521            if trunk.page_id() != trunk_id {
1522                return Err(PagerError::InvalidDatabase(
1523                    "misdirected freelist trunk".into(),
1524                ));
1525            }
1526            let mut loaded = FreeList::new();
1527            let next = loaded
1528                .load_from_trunk(&trunk)
1529                .map_err(|error| PagerError::InvalidDatabase(format!("Freelist: {error}")))?;
1530            while let Some(id) = loaded.allocate() {
1531                if id < FIRST_ALLOCATABLE_PAGE || id >= page_count {
1532                    return Err(PagerError::InvalidDatabase(
1533                        "invalid free page range".into(),
1534                    ));
1535                }
1536                if seen.contains(&id) {
1537                    return Err(PagerError::InvalidDatabase(
1538                        "retired page is already free".into(),
1539                    ));
1540                }
1541            }
1542            trunk_id = next.unwrap_or(0);
1543        }
1544        self.record_ownership(|wal| wal.retire_pages(pages))?;
1545        for id in pages {
1546            self.cache.remove(*id);
1547        }
1548        freelist.free_batch(pages);
1549        *self.header_dirty_lock()? = true;
1550        Ok(())
1551    }
1552
1553    fn pages_not_in_freelist(
1554        &self,
1555        pages: &[u32],
1556        freelist: &FreeList,
1557        page_count: u32,
1558    ) -> Result<std::collections::HashSet<u32>, PagerError> {
1559        let mut remaining = std::collections::HashSet::with_capacity(pages.len());
1560        if pages
1561            .iter()
1562            .any(|id| *id < FIRST_ALLOCATABLE_PAGE || *id >= page_count || !remaining.insert(*id))
1563        {
1564            return Err(PagerError::InvalidDatabase(
1565                "invalid recovery page set".into(),
1566            ));
1567        }
1568        let requested = remaining.clone();
1569        freelist
1570            .remove_existing_from(&requested, &mut remaining)
1571            .map_err(|error| PagerError::InvalidDatabase(format!("Freelist: {error}")))?;
1572        let mut trunk_id = freelist.trunk_head();
1573        let mut visited = std::collections::HashSet::new();
1574        while trunk_id != 0 {
1575            if trunk_id < FIRST_ALLOCATABLE_PAGE
1576                || trunk_id >= page_count
1577                || !visited.insert(trunk_id)
1578            {
1579                return Err(PagerError::InvalidDatabase(
1580                    "invalid freelist trunk chain".into(),
1581                ));
1582            }
1583            let trunk = self.read_page(trunk_id)?;
1584            if trunk.page_id() != trunk_id {
1585                return Err(PagerError::InvalidDatabase(
1586                    "misdirected freelist trunk".into(),
1587                ));
1588            }
1589            let mut loaded = FreeList::new();
1590            let next = loaded
1591                .load_from_trunk(&trunk)
1592                .map_err(|error| PagerError::InvalidDatabase(format!("Freelist: {error}")))?;
1593            while let Some(id) = loaded.allocate() {
1594                if id < FIRST_ALLOCATABLE_PAGE || id >= page_count {
1595                    return Err(PagerError::InvalidDatabase(
1596                        "invalid free page range".into(),
1597                    ));
1598                }
1599                if requested.contains(&id) && !remaining.remove(&id) {
1600                    return Err(PagerError::InvalidDatabase(
1601                        "duplicate recovery page".into(),
1602                    ));
1603                }
1604            }
1605            trunk_id = next.unwrap_or(0);
1606        }
1607        Ok(remaining)
1608    }
1609
1610    /// Add proven-unowned pages to the allocator exactly once during recovery.
1611    /// The caller must exclude all allocation and publication until this state
1612    /// has been synced to both superblocks and the journal is completed.
1613    pub fn recover_unowned_pages(&self, pages: &[u32]) -> Result<(), PagerError> {
1614        let _ownership = self.lock_ownership_mutations();
1615        self.ensure_writeback_available()?;
1616        if self.config.read_only {
1617            return Err(PagerError::ReadOnly);
1618        }
1619        let page_count = self.page_count()?;
1620        let mut freelist = self.freelist_write()?;
1621        let remaining = self.pages_not_in_freelist(pages, &freelist, page_count)?;
1622        if !remaining.is_empty() {
1623            let mut missing: Vec<_> = remaining.into_iter().collect();
1624            missing.sort_unstable();
1625            for id in &missing {
1626                self.cache.remove(*id);
1627            }
1628            freelist.free_batch(&missing);
1629            *self.header_dirty_lock()? = true;
1630        }
1631        Ok(())
1632    }
1633
1634    /// Reject a recovery plan if any page it must preserve is already free.
1635    /// The caller must exclude allocation and freelist mutation during recovery.
1636    pub fn validate_owned_pages(&self, pages: &[u32]) -> Result<(), PagerError> {
1637        let page_count = self.page_count()?;
1638        let freelist = self.freelist_write()?;
1639        let absent = self.pages_not_in_freelist(pages, &freelist, page_count)?;
1640        if absent.len() != pages.len() {
1641            return Err(PagerError::InvalidDatabase(
1642                "owned recovery page is free".into(),
1643            ));
1644        }
1645        Ok(())
1646    }
1647
1648    /// Persist the current allocator in both fallback copies during recovery.
1649    /// The caller must exclude allocation until journal completion is durable.
1650    pub fn sync_recovered_allocator(&self) -> Result<(), PagerError> {
1651        let _ownership = self.lock_ownership_mutations();
1652        let result = (|| {
1653            self.sync()?;
1654            let _publication = self
1655                .superblock_publication
1656                .lock()
1657                .map_err(|_| PagerError::LockPoisoned)?;
1658            let header = self.header_read()?.clone();
1659            for _ in 0..reddb_file::PAGED_SUPERBLOCK_SLOT_COUNT {
1660                self.commit_superblock_locked(|image| {
1661                    reddb_file::encode_database_header(image, &header)
1662                        .map_err(|error| PagerError::InvalidDatabase(error.to_string()))
1663                })?;
1664            }
1665            Ok(())
1666        })();
1667        if result.is_err() {
1668            self.writeback_failed
1669                .store(true, std::sync::atomic::Ordering::Release);
1670        }
1671        result
1672    }
1673
1674    /// Get database header
1675    /// Pages available to the allocator, including pages on unloaded trunks.
1676    pub fn free_page_count(&self) -> Result<u32, PagerError> {
1677        Ok(self.freelist_write()?.total_free())
1678    }
1679
1680    pub fn header(&self) -> Result<DatabaseHeader, PagerError> {
1681        Ok(self.header_read()?.clone())
1682    }
1683
1684    pub fn physical_header(&self) -> Result<PhysicalFileHeader, PagerError> {
1685        Ok(self.header_read()?.physical)
1686    }
1687
1688    pub fn update_physical_header(&self, physical: PhysicalFileHeader) -> Result<(), PagerError> {
1689        let _ownership = self.lock_ownership_mutations();
1690        self.ensure_writeback_available()?;
1691        if self.config.read_only {
1692            return Err(PagerError::ReadOnly);
1693        }
1694
1695        let mut header = self.header_write()?;
1696        header.physical = physical;
1697        *self.header_dirty_lock()? = true;
1698        Ok(())
1699    }
1700
1701    /// Get page count
1702    pub fn page_count(&self) -> Result<u32, PagerError> {
1703        Ok(self.header_read()?.page_count)
1704    }
1705
1706    /// Flush all dirty pages to disk
1707    pub fn flush(&self) -> Result<(), PagerError> {
1708        let _ownership = self.lock_ownership_mutations();
1709        self.ensure_writeback_available()?;
1710        if self.config.read_only {
1711            return Ok(());
1712        }
1713
1714        // Persist freelist to trunk pages when dirty
1715        let trunks = {
1716            let mut freelist = self.freelist_write()?;
1717            if freelist.is_dirty() {
1718                let mut header = self.header_write()?;
1719                let trunks = freelist.flush_to_trunks(0, || {
1720                    let id = header.page_count;
1721                    header.page_count += 1;
1722                    id
1723                });
1724                header.freelist_head = freelist.trunk_head();
1725                *self.header_dirty_lock()? = true;
1726                freelist.mark_clean();
1727                trunks
1728            } else {
1729                Vec::new()
1730            }
1731        };
1732
1733        let mut dirty_pages = Vec::new();
1734        for trunk in trunks {
1735            let page_id = trunk.page_id();
1736            if let Some(evicted) = self.cache.insert_dirty(page_id, trunk) {
1737                // Trunk publication can evict dirty data. Keep it in the same
1738                // WAL-first, double-write-protected batch as resident pages.
1739                dirty_pages.push((evicted.page_id(), evicted));
1740            }
1741        }
1742
1743        // IDs are compact; page images are not. At 16 KiB per page, staging
1744        // 256 images plus one DWB frame uses about 5 MiB, independently of
1745        // the dirty cache size. Publish the header only after every batch.
1746        const FLUSH_BATCH_PAGES: usize = 256;
1747        for batch in dirty_pages.chunks(FLUSH_BATCH_PAGES) {
1748            self.write_dirty_page_batch(batch)?;
1749        }
1750        self.evictions_written.fetch_add(
1751            dirty_pages.len() as u64,
1752            std::sync::atomic::Ordering::SeqCst,
1753        );
1754        drop(dirty_pages);
1755        // Batch dirty IDs, not every resident ID: otherwise a few edits in
1756        // a mostly clean cache pay a protected write per cache-sized slice.
1757        // Physical order also avoids arbitrary seeks among each batch's homes.
1758        let mut page_ids = self.cache.dirty_page_ids(usize::MAX);
1759        page_ids.sort_unstable();
1760        if self.bounded_writeback()? {
1761            for id in page_ids {
1762                if let Some(page) = self.cache.flush_dirty_page(id) {
1763                    self.write_dirty_page_batch(&[(id, page)])?;
1764                }
1765            }
1766        } else {
1767            for ids in page_ids.chunks(FLUSH_BATCH_PAGES) {
1768                let pages = self.cache.flush_dirty_pages(ids);
1769                self.write_dirty_page_batch(&pages)?;
1770            }
1771        }
1772
1773        // Write header if dirty
1774        if !self.batch_active()? && *self.header_dirty_lock()? {
1775            self.write_header()?;
1776        }
1777
1778        Ok(())
1779    }
1780
1781    fn write_dirty_page_batch(&self, pages: &[(u32, Page)]) -> Result<(), PagerError> {
1782        if pages.is_empty() {
1783            return Ok(());
1784        }
1785        // Every image's WAL must be durable before its home write, including
1786        // dirty data evicted while publishing freelist trunks. LSN zero is
1787        // reserved for pages not produced by a WAL append.
1788        let result = (|| {
1789            let max_lsn = pages
1790                .iter()
1791                .filter_map(|(_, page)| page.header().ok().map(|header| header.lsn))
1792                .max()
1793                .unwrap_or(0);
1794            if max_lsn > 0 {
1795                self.wal.flush_until(max_lsn)?;
1796            }
1797            self.write_pages_through_dwb(pages)
1798        })();
1799        if result.is_err() {
1800            self.writeback_failed
1801                .store(true, std::sync::atomic::Ordering::Release);
1802            for (page_id, _) in pages {
1803                self.cache.mark_dirty(*page_id);
1804            }
1805        }
1806        result
1807    }
1808
1809    /// Sync file to disk (fsync)
1810    pub fn sync(&self) -> Result<(), PagerError> {
1811        let _ownership = self.lock_ownership_mutations();
1812        self.flush()?;
1813
1814        if self
1815            .allocation_reused
1816            .swap(false, std::sync::atomic::Ordering::AcqRel)
1817        {
1818            // flush published the current allocator in one slot. Mirror that
1819            // ownership before callers publish roots that use reclaimed pages;
1820            // recovery through the sibling slot must never allocate them again.
1821            if let Err(error) = self.write_header_and_sync() {
1822                self.allocation_reused
1823                    .store(true, std::sync::atomic::Ordering::Release);
1824                return Err(error);
1825            }
1826        }
1827
1828        let file = self.file_lock()?;
1829        file.sync_all()?;
1830
1831        Ok(())
1832    }
1833
1834    /// Get cache statistics
1835    pub fn cache_stats(&self) -> super::page_cache::CacheStats {
1836        self.cache.stats()
1837    }
1838
1839    /// Pages currently resident in the page cache. Slots are fixed size, so
1840    /// this times the page size is the cache's memory footprint (ADR 0073 §2).
1841    pub fn cache_len(&self) -> usize {
1842        self.cache.len()
1843            + if self.config.read_only {
1844                self.read_only_recovery
1845                    .read()
1846                    .unwrap_or_else(|poisoned| poisoned.into_inner())
1847                    .len()
1848            } else {
1849                0
1850            }
1851    }
1852
1853    /// Preallocated page-cache slots — the sizing this process derived from
1854    /// its page-cache budget share.
1855    pub fn cache_capacity(&self) -> usize {
1856        self.cache.capacity()
1857    }
1858
1859    /// Count dirty pages currently in the page cache.
1860    pub fn dirty_page_count(&self) -> usize {
1861        self.cache.dirty_count()
1862    }
1863
1864    /// Estimated fraction of the page cache holding dirty pages.
1865    /// Returned in `[0, 1]`. Used by the background writer to
1866    /// decide when to kick in aggressive flushing.
1867    pub fn dirty_fraction(&self) -> f64 {
1868        let capacity = self.cache.capacity().max(1) as f64;
1869        self.cache.dirty_count() as f64 / capacity
1870    }
1871
1872    /// Flush up to `max` dirty pages from the cache. Returns the
1873    /// number actually written. Background-writer entry point —
1874    /// reuses the same persistence path as `flush()` but bounded.
1875    pub fn flush_some_dirty(&self, max: usize) -> Result<usize, PagerError> {
1876        let _ownership = self.lock_ownership_mutations();
1877        self.ensure_writeback_available()?;
1878        if self.config.read_only || max == 0 {
1879            return Ok(0);
1880        }
1881        let dirty_pages = self.cache.flush_some_dirty(max);
1882        if dirty_pages.is_empty() {
1883            return Ok(0);
1884        }
1885        let count = dirty_pages.len();
1886        // WAL-first: every cached dirty page carries an LSN that the
1887        // WAL must have already persisted. The full `flush()` path
1888        // enforces this with `wal.flush(max_lsn)`; here we simply
1889        // write through the pager — safe because callers only reach
1890        // this path via the bgwriter, which runs asynchronously
1891        // alongside normal commits that already respect WAL-first.
1892        for (page_id, page) in dirty_pages {
1893            self.write_page(page_id, page)?;
1894        }
1895        Ok(count)
1896    }
1897
1898    /// Get database file path
1899    pub fn path(&self) -> &Path {
1900        &self.path
1901    }
1902
1903    /// Return the exclusively owned handle. Callers must complete their
1904    /// publication boundary before consuming the pager.
1905    pub fn into_inner(self) -> F {
1906        self.file
1907            .into_inner()
1908            .unwrap_or_else(|poisoned| poisoned.into_inner())
1909    }
1910
1911    /// Check if database is read-only
1912    pub fn is_read_only(&self) -> bool {
1913        self.config.read_only
1914    }
1915
1916    /// Get file size in bytes
1917    pub fn file_size(&self) -> Result<u64, PagerError> {
1918        let file = self.file_lock()?;
1919        Ok(file.file_len()?)
1920    }
1921
1922    /// Clear the in-file DWB zone with valid reserved pages.
1923    fn clear_dwb_zone(&self) -> Result<(), PagerError> {
1924        let mut file = self.file_lock()?;
1925        Ok(pager_io::clear_dwb_zone(&mut *file)?)
1926    }
1927
1928    /// Read catalog authority from the newest sealed slot, independently of the
1929    /// cached ordinary header fields.
1930    pub fn manifest_reference(&self) -> Result<reddb_file::page_proof::PageReference, PagerError> {
1931        let _ownership = self.lock_ownership_mutations();
1932        let (_, image) = self.newest_superblock()?;
1933        reddb_file::file_format::database_header_manifest_reference(&image)
1934            .map_err(|err| PagerError::InvalidDatabase(err.to_string()))
1935    }
1936
1937    pub fn manifest_page_id(&self) -> Result<u32, PagerError> {
1938        let reference = self.manifest_reference()?;
1939        Ok(if reference.page_id == 0 {
1940            1
1941        } else {
1942            reference.page_id
1943        })
1944    }
1945
1946    /// Read the sealed catalog root, or page 1 for a legacy bootstrap header.
1947    ///
1948    /// ADR 0074 §2: manifest corruption fails the open didactically, naming the
1949    /// zone — it never falls back to a sidecar and never returns garbage.
1950    pub fn read_manifest_page(&self) -> Result<Page, PagerError> {
1951        let _ownership = self.lock_ownership_mutations();
1952        let root = self.manifest_page_id()?;
1953        self.read_page(root)
1954            .map_err(|_| PagerError::ManifestZoneCorrupt(self.path.clone()))
1955    }
1956
1957    /// The new catalog and all its children must already be durable. Both
1958    /// fallback headers stop naming its predecessor before that root is freed.
1959    pub fn publish_manifest_reference(
1960        &self,
1961        reference: reddb_file::page_proof::PageReference,
1962    ) -> Result<(), PagerError> {
1963        let _ownership = self.lock_ownership_mutations();
1964        self.ensure_writeback_available()?;
1965        if self.config.read_only {
1966            return Err(PagerError::ReadOnly);
1967        }
1968        if reference.page_id < FIRST_ALLOCATABLE_PAGE
1969            || reference.page_id >= self.page_count()?
1970            || reference.digest == [0; 32]
1971            || self.header_read()?.required_capabilities & reddb_file::FILE_CAPABILITY_CATALOG_ROOT
1972                == 0
1973        {
1974            return Err(PagerError::InvalidDatabase(
1975                "invalid catalog generation publication".into(),
1976            ));
1977        }
1978        let header = self.header_read()?.clone();
1979        // From here a crash may find this generation published.
1980        self.wal.generation_published();
1981        let _publication = self
1982            .superblock_publication
1983            .lock()
1984            .map_err(|_| PagerError::LockPoisoned)?;
1985        let result = (|| {
1986            for _ in 0..reddb_file::PAGED_SUPERBLOCK_SLOT_COUNT {
1987                self.commit_superblock_locked(|image| {
1988                    reddb_file::encode_database_header(image, &header)
1989                        .map_err(|err| PagerError::InvalidDatabase(err.to_string()))?;
1990                    reddb_file::file_format::set_database_header_manifest_reference(
1991                        image, reference,
1992                    )
1993                    .map_err(|err| PagerError::InvalidDatabase(err.to_string()))
1994                })?;
1995            }
1996            *self.header_dirty_lock()? = false;
1997            Ok(())
1998        })();
1999        if result.is_err() {
2000            self.writeback_failed
2001                .store(true, std::sync::atomic::Ordering::Release);
2002        }
2003        result
2004    }
2005
2006    /// Write pages through the double-write buffer for torn page protection.
2007    ///
2008    /// 1. Write pages to the in-file DWB zone with a header (magic + count + checksum)
2009    /// 2. fsync the DWB zone
2010    /// 3. Write all pages to their final locations in the .rdb file
2011    /// 4. Clear the DWB zone (marks as consumed)
2012    fn write_pages_through_dwb(&self, pages: &[(u32, Page)]) -> Result<(), PagerError> {
2013        if self.config.read_only {
2014            return Err(PagerError::ReadOnly);
2015        }
2016        self.record_ownership(|wal| wal.flush_page_ownership())?;
2017        // Keep the file locked through staging, home writes and clearing so
2018        // another page writer cannot interleave with a protected batch.
2019        let _publication = self
2020            .superblock_publication
2021            .lock()
2022            .map_err(|_| PagerError::LockPoisoned)?;
2023        let mut file = self.file_lock()?;
2024        self.ensure_writeback_available()?;
2025        let result: Result<(), PagerError> = (|| {
2026            let mut staged = self
2027                .staged_pages
2028                .lock()
2029                .map_err(|_| PagerError::LockPoisoned)?;
2030            if let Some(batch) = staged.as_mut() {
2031                for (id, page) in pages {
2032                    batch.stage(&mut *file, *id, page)?;
2033                }
2034                Ok(())
2035            } else if self.dwb_enabled {
2036                // A frame costs nine syncs for 63 pages, and a checkpoint
2037                // writes mostly pages of the generation it is building: nine
2038                // frames for one that changed 20 small tables. Those pages
2039                // go straight home; `sync` makes them durable before the
2040                // manifest names them. So do the published pages a delta
2041                // rewrites in place: their first images are in the WAL before
2042                // this write, and recovery restores them for a generation
2043                // that was not published. A store with 173 tables paid one
2044                // frame for every 63 of those, most of a second on its disk.
2045                // The catalog root, the page the manifest will name, keeps
2046                // its frame. The frames borrow their pages: a flush must not
2047                // hold a second copy of its batch.
2048                let mut guarded: Vec<(u32, &Page)> = Vec::new();
2049                for (id, page) in pages {
2050                    if page.page_type().ok() != Some(PageType::Header)
2051                        && (self.wal.unpublished_reservation(*id)
2052                            || self.wal.unpublished_overwrite(*id))
2053                    {
2054                        pager_io::write_page(&mut *file, *id, page)?;
2055                    } else {
2056                        guarded.push((*id, page));
2057                    }
2058                }
2059                Ok(pager_io::write_pages(&mut *file, &guarded, true)?)
2060            } else {
2061                Ok(pager_io::write_pages(&mut *file, pages, false)?)
2062            }
2063        })();
2064        if result.is_err() {
2065            // Set this while holding the file lock: a waiting writer must not
2066            // replace the recovery frame after an interrupted home write.
2067            self.writeback_failed
2068                .store(true, std::sync::atomic::Ordering::Release);
2069        }
2070        result
2071    }
2072
2073    /// Recover from double-write buffer after a crash.
2074    ///
2075    /// If the DWB zone contains valid pages, they were written before the crash
2076    /// interrupted writing to their home locations. Re-apply them.
2077    fn recover_from_dwb(&self) -> Result<(), PagerError> {
2078        let mut file = self.file_lock()?;
2079        if !self.config.read_only
2080            && !self.dwb_enabled
2081            && pager_io::requires_dwb_publication(&mut *file)?
2082        {
2083            return Err(PagerError::InvalidDatabase(
2084                "DWB generation authority requires protected page writes".into(),
2085            ));
2086        }
2087        if self.config.read_only {
2088            for (id, page) in pager_io::read_dwb_pages(&mut *file)? {
2089                // The DWB checksum seals raw bytes, which may be ciphertext.
2090                // Normal reads check the page checksum; encryption hosts use
2091                // read_page_no_checksum and authenticate after decrypting.
2092                self.install_read_only_page(id, page)?;
2093            }
2094            return Ok(());
2095        }
2096        Ok(pager_io::recover_from_dwb(&mut *file)?)
2097    }
2098
2099    /// Install a validated recovery image only in this reader's private view.
2100    /// The source and ordinary mutation APIs remain read-only. Bound pinned
2101    /// images by the cache budget (with room for one complete DWB frame).
2102    pub fn restore_read_only_page(&self, page_id: u32, page: Page) -> Result<(), PagerError> {
2103        if !self.config.read_only || page_id == 0 || page.page_id() != page_id {
2104            return Err(PagerError::InvalidDatabase(
2105                "invalid read-only recovery image".into(),
2106            ));
2107        }
2108        page.verify_checksum()?;
2109        self.install_read_only_page(page_id, page)
2110    }
2111
2112    fn install_read_only_page(&self, page_id: u32, page: Page) -> Result<(), PagerError> {
2113        let mut images = self
2114            .read_only_recovery
2115            .write()
2116            .map_err(|_| PagerError::LockPoisoned)?;
2117        let limit = self
2118            .config
2119            .cache_size
2120            .max(pager_io::DWB_MAX_PAGES_PER_FRAME);
2121        if images.len() >= limit && !images.contains_key(&page_id) {
2122            return Err(PagerError::InvalidDatabase(
2123                "read-only recovery exceeds the page cache budget".into(),
2124            ));
2125        }
2126        images.insert(page_id, page);
2127        Ok(())
2128    }
2129
2130    /// Finish a consumed trunk's durable ownership change, retaining errors
2131    /// across allocation attempts until both copies have been synchronized.
2132    /// Called with the freelist locked when consuming or retrying a trunk.
2133    fn complete_allocation_fence(&self) -> Result<(), PagerError> {
2134        if self
2135            .allocation_fence_pending
2136            .load(std::sync::atomic::Ordering::Acquire)
2137        {
2138            self.write_header_and_sync()?;
2139            self.write_header_and_sync()?;
2140            self.allocation_fence_pending
2141                .store(false, std::sync::atomic::Ordering::Release);
2142        }
2143        Ok(())
2144    }
2145
2146    /// Write header and sync to disk (public for checkpointer).
2147    ///
2148    /// The superblock write syncs the file after it writes its slot, which
2149    /// covers everything written before it; a second sync here found nothing
2150    /// to write and still went to the device.
2151    pub fn write_header_and_sync(&self) -> Result<(), PagerError> {
2152        let _ownership = self.lock_ownership_mutations();
2153        self.write_header()
2154    }
2155
2156    /// Set the checkpoint_in_progress flag in the header.
2157    pub fn set_checkpoint_in_progress(
2158        &self,
2159        in_progress: bool,
2160        target_lsn: u64,
2161    ) -> Result<(), PagerError> {
2162        let _ownership = self.lock_ownership_mutations();
2163        let mut header = self.header_write()?;
2164        header.checkpoint_in_progress = in_progress;
2165        header.checkpoint_target_lsn = target_lsn;
2166        *self.header_dirty_lock()? = true;
2167        drop(header);
2168        self.write_header_and_sync()
2169    }
2170
2171    /// Update the checkpoint LSN and clear the in-progress flag.
2172    pub fn complete_checkpoint(&self, lsn: u64) -> Result<(), PagerError> {
2173        let _ownership = self.lock_ownership_mutations();
2174        let mut header = self.header_write()?;
2175        header.checkpoint_lsn = lsn;
2176        header.checkpoint_in_progress = false;
2177        header.checkpoint_target_lsn = 0;
2178        *self.header_dirty_lock()? = true;
2179        drop(header);
2180        self.write_header_and_sync()
2181    }
2182}
2183
2184#[cfg(test)]
2185mod integrity_guidance_tests {
2186    use super::PagerError;
2187    use std::path::PathBuf;
2188
2189    #[test]
2190    fn damaged_paged_zones_recommend_preserving_files_and_a_verified_backup() {
2191        for error in [
2192            PagerError::SuperblockZoneUnrecoverable(PathBuf::from("data.rdb")),
2193            PagerError::ManifestZoneCorrupt(PathBuf::from("data.rdb")),
2194            PagerError::DwbZoneCorrupt(PathBuf::from("data.rdb")),
2195        ] {
2196            let message = error.to_string();
2197            assert!(message.contains("Preserve the database"), "{message}");
2198            assert!(message.contains("verified backup"), "{message}");
2199            assert!(!message.contains("salvage"), "{message}");
2200            assert!(!message.contains("SCRUB"), "{message}");
2201        }
2202    }
2203}