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