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