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