picovolt 2.2.0

Embedded SQL database with MVCC history and single-file deployment
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
//! Virtualization Layer Engine (VLE), the router that hides whether pages live
//! in a mutable `.pv/` directory (Development Mode) or inside a single immutable
//! snapshotted `.pvdb` monolith (Production Mode), per spec ยง2.
//!
//! * [`DevStore`], append-only 4096-byte pages spread across `chunks/*.pvd`
//!   files capped at 64 MiB each.
//! * [`Monolith`], an owned read-only memory map snapshotted from a baked
//!   `.pvdb`, slicing pages and exposing the CAS / manifest regions by offset.
//! * [`bake_monolith`], compiles a dev workspace's pages + CAS pool + manifest
//!   into the contiguous monolith layout.

use std::cell::RefCell;
use std::collections::BTreeSet;
use std::fs::{self, File, OpenOptions};
use std::io::{Read, Seek, SeekFrom, Write};
use std::path::{Path, PathBuf};
use std::sync::Arc;

use memmap2::Mmap;

use crate::core::errors::{PvError, Result};
use crate::core::types::{
    FileHeader, CHUNK_CAP_BYTES, FILE_HEADER_SIZE, FORMAT_VERSION_BASE, PAGE_CHECKSUM_OFFSET,
    PAGE_SIZE,
};

/// Pages per 64 MiB chunk file: 16 384.
pub const PAGES_PER_CHUNK: u64 = CHUNK_CAP_BYTES / PAGE_SIZE as u64;

/// A boxed 4096-byte page buffer.
pub type PageBuf = Box<[u8; PAGE_SIZE]>;

// ---------------------------------------------------------------------------
// Per-page integrity checksum
// ---------------------------------------------------------------------------

/// Compute a page's integrity checksum: a 32-bit truncation of BLAKE3 over every
/// byte except the 4-byte checksum field itself (at [`PAGE_CHECKSUM_OFFSET`]).
///
/// BLAKE3 is already a dependency and builds cleanly on wasm, so this needs no
/// new crate. The checksum guards against torn writes and bit-rot, not an
/// adversary, so 32 bits is ample. It never returns `0`: that value is reserved
/// to mean "unstamped" (see [`verify_page_checksum`]).
pub fn page_checksum(page: &[u8; PAGE_SIZE]) -> u32 {
    let mut hasher = blake3::Hasher::new();
    hasher.update(&page[..PAGE_CHECKSUM_OFFSET]);
    hasher.update(&page[PAGE_CHECKSUM_OFFSET + 4..]);
    let bytes = hasher.finalize();
    let bytes = bytes.as_bytes();
    let value = u32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]);
    if value == 0 {
        1
    } else {
        value
    }
}

/// Stamp the freshly-computed checksum into a page's checksum field. Call this on
/// every page immediately before it is handed to a backend to be written.
pub fn stamp_page_checksum(page: &mut [u8; PAGE_SIZE]) {
    let checksum = page_checksum(page);
    page[PAGE_CHECKSUM_OFFSET..PAGE_CHECKSUM_OFFSET + 4].copy_from_slice(&checksum.to_le_bytes());
}

/// Verify a page's stored checksum, returning [`PvError::Corruption`] on
/// mismatch. A stored value of `0` marks a page that was never stamped (blank, or
/// written outside the cache) and is accepted as-is.
pub fn verify_page_checksum(id: u64, page: &[u8; PAGE_SIZE]) -> Result<()> {
    let stored = u32::from_le_bytes(
        page[PAGE_CHECKSUM_OFFSET..PAGE_CHECKSUM_OFFSET + 4]
            .try_into()
            .expect("4-byte checksum field"),
    );
    if stored == 0 {
        return Ok(());
    }
    let computed = page_checksum(page);
    if stored != computed {
        return Err(PvError::Corruption(format!(
            "page {id} checksum mismatch (stored {stored:#010x}, computed {computed:#010x})"
        )));
    }
    Ok(())
}

// ---------------------------------------------------------------------------
// Development Mode: directory of append-only chunk files
// ---------------------------------------------------------------------------

/// Mutable page store backed by `chunks/chunk_NNNNN.pvd` files under a workspace.
///
/// Keeps the write handle for the most-recently-written chunk open, so a stream
/// of appends (autocommit) does not reopen the file per page. Reads use separate
/// handles; Rust opens files with shared read/write modes, so this is safe.
/// [`sync_data`](Self::sync_data) `fsync`s every chunk written since the last
/// sync (tracked in `dirty_chunks`).
pub struct DevStore {
    root: PathBuf,
    page_count: u64,
    write_handle: RefCell<Option<(u64, File)>>,
    dirty_chunks: RefCell<BTreeSet<u64>>,
    journal: RefCell<Option<crate::journal::Journal>>,
}

impl DevStore {
    /// Create a fresh, empty workspace at `root` (creates `root/chunks/`).
    pub fn create(root: impl Into<PathBuf>) -> Result<Self> {
        let root = root.into();
        fs::create_dir_all(root.join("chunks"))?;
        Ok(Self {
            root,
            page_count: 0,
            write_handle: RefCell::new(None),
            dirty_chunks: RefCell::new(BTreeSet::new()),
            journal: RefCell::new(None),
        })
    }

    /// Re-open an existing workspace whose page count is known from the manifest.
    pub fn open(root: impl Into<PathBuf>, page_count: u64) -> Result<Self> {
        let root = root.into();
        fs::create_dir_all(root.join("chunks"))?;
        Ok(Self {
            root,
            page_count,
            write_handle: RefCell::new(None),
            dirty_chunks: RefCell::new(BTreeSet::new()),
            journal: RefCell::new(None),
        })
    }

    /// Number of pages allocated so far.
    pub fn page_count(&self) -> u64 {
        self.page_count
    }

    pub(crate) fn begin_journal(&self, options: crate::CommitLogOptions) -> Result<()> {
        *self.journal.borrow_mut() = Some(
            crate::journal::Journal::begin(&self.root, options).map_err(|error| {
                if self
                    .root
                    .join(crate::COMMIT_LOG_DIR)
                    .join("active")
                    .exists()
                {
                    PvError::TransactionOutcomeUnknown(format!(
                        "journal preparation requires recovery: {error}"
                    ))
                } else {
                    error
                }
            })?,
        );
        Ok(())
    }

    pub(crate) fn commit_journal(&self) -> Result<()> {
        let mut journal = self.journal.borrow_mut();
        journal
            .as_mut()
            .ok_or_else(|| PvError::Transaction("no active page journal".into()))?
            .commit()?;
        journal.take();
        Ok(())
    }

    pub(crate) fn journal_sequence(&self) -> Option<u64> {
        self.journal
            .borrow()
            .as_ref()
            .map(crate::journal::Journal::sequence)
    }

    /// Overwrite the page count (used when the workspace is rewritten wholesale
    /// during a flush). Pages beyond `n` in the chunk files become unreachable.
    pub fn set_page_count(&mut self, n: u64) {
        self.page_count = n;
    }

    fn chunk_path(&self, chunk_ix: u64) -> PathBuf {
        self.root
            .join("chunks")
            .join(format!("chunk_{chunk_ix:05}.pvd"))
    }

    /// Reserve a new page id (the caller is expected to `write_page` it next).
    pub fn alloc_page(&mut self) -> u64 {
        let id = self.page_count;
        self.page_count += 1;
        id
    }

    /// Run `f` against the (cached) write handle for `chunk_ix`, opening and
    /// caching it if a different chunk's handle is currently held.
    fn with_chunk_write<R>(
        &self,
        chunk_ix: u64,
        f: impl FnOnce(&mut File) -> Result<R>,
    ) -> Result<R> {
        self.dirty_chunks.borrow_mut().insert(chunk_ix);
        let mut slot = self.write_handle.borrow_mut();
        let needs_open = slot.as_ref().map(|(ix, _)| *ix) != Some(chunk_ix);
        if needs_open {
            let file = OpenOptions::new()
                .read(true)
                .write(true)
                .create(true)
                .truncate(false) // pages are written at offsets; keep existing content
                .open(self.chunk_path(chunk_ix))?;
            *slot = Some((chunk_ix, file));
        }
        let (_, file) = slot.as_mut().expect("handle present");
        f(file)
    }

    /// Write a full page to its chunk file, extending the file if necessary.
    pub fn write_page(&self, id: u64, page: &[u8; PAGE_SIZE]) -> Result<()> {
        if let Some(journal) = self.journal.borrow_mut().as_mut() {
            journal.before_write(id)?;
        }
        let within = (id % PAGES_PER_CHUNK) * PAGE_SIZE as u64;
        self.with_chunk_write(id / PAGES_PER_CHUNK, |file| {
            file.seek(SeekFrom::Start(within))?;
            file.write_all(page)?;
            Ok(())
        })
    }

    /// Write `pages` at consecutive ids starting from `start_id`, opening each
    /// chunk file **once** and issuing one bulk write per chunk. Dramatically
    /// faster than per-page [`Self::write_page`] calls.
    pub fn write_pages_from(&self, start_id: u64, pages: &[&PageBuf]) -> Result<()> {
        if self.journal.borrow().is_some() {
            for (offset, page) in pages.iter().enumerate() {
                self.write_page(start_id + offset as u64, page)?;
            }
            return Ok(());
        }
        let end = start_id + pages.len() as u64;
        let mut id = start_id;
        let mut idx = 0usize;
        while id < end {
            let chunk_ix = id / PAGES_PER_CHUNK;
            let chunk_start = chunk_ix * PAGES_PER_CHUNK;
            let chunk_page_end = ((chunk_ix + 1) * PAGES_PER_CHUNK).min(end);
            let count = (chunk_page_end - id) as usize;
            let mut batch = Vec::with_capacity(count * PAGE_SIZE);
            for page in &pages[idx..idx + count] {
                batch.extend_from_slice(&page[..]);
            }
            self.with_chunk_write(chunk_ix, |file| {
                file.seek(SeekFrom::Start((id - chunk_start) * PAGE_SIZE as u64))?;
                file.write_all(&batch)?;
                Ok(())
            })?;
            idx += count;
            id = chunk_page_end;
        }
        Ok(())
    }

    /// `fsync` every chunk written since the last sync to stable storage.
    ///
    /// `fsync` flushes a file's OS-cached writes regardless of which handle
    /// initiated them, so chunks no longer held by the cached write handle are
    /// synced by briefly reopening them. This gives full crash-safety across a
    /// workspace spanning multiple 64 MiB chunks.
    pub fn sync_data(&self) -> Result<()> {
        let dirty: Vec<u64> = self.dirty_chunks.borrow().iter().copied().collect();
        for chunk_ix in dirty {
            let cached = self.write_handle.borrow().as_ref().map(|(ix, _)| *ix) == Some(chunk_ix);
            if cached {
                if let Some((_, file)) = self.write_handle.borrow().as_ref() {
                    file.sync_all()?;
                }
            } else {
                OpenOptions::new()
                    .read(true)
                    .write(true)
                    .open(self.chunk_path(chunk_ix))?
                    .sync_all()?;
            }
        }
        self.dirty_chunks.borrow_mut().clear();
        Ok(())
    }

    /// Read a full page out of its chunk file.
    pub fn read_page(&self, id: u64) -> Result<PageBuf> {
        if id >= self.page_count {
            return Err(PvError::PageFault { page_id: id });
        }
        let within = (id % PAGES_PER_CHUNK) * PAGE_SIZE as u64;
        let path = self.chunk_path(id / PAGES_PER_CHUNK);
        let mut file = File::open(&path)?;
        file.seek(SeekFrom::Start(within))?;
        let mut buf: PageBuf = Box::new([0u8; PAGE_SIZE]);
        file.read_exact(&mut buf[..])?;
        Ok(buf)
    }

    /// Read every allocated page, in id order, opening each chunk file once.
    pub fn read_all_pages(&self) -> Result<Vec<PageBuf>> {
        let capacity = usize::try_from(self.page_count).map_err(|_| {
            PvError::Corruption("workspace page count is too large for this platform".into())
        })?;
        let mut out = Vec::with_capacity(capacity);
        let mut id = 0u64;
        while id < self.page_count {
            let chunk_ix = id / PAGES_PER_CHUNK;
            let chunk_start = chunk_ix * PAGES_PER_CHUNK;
            let chunk_end = ((chunk_ix + 1) * PAGES_PER_CHUNK).min(self.page_count);
            let path = self.chunk_path(chunk_ix);
            let mut file = File::open(&path)?;
            file.seek(SeekFrom::Start((id - chunk_start) * PAGE_SIZE as u64))?;
            for _ in id..chunk_end {
                let mut buf: PageBuf = Box::new([0u8; PAGE_SIZE]);
                file.read_exact(&mut buf[..])?;
                out.push(buf);
            }
            id = chunk_end;
        }
        Ok(out)
    }
}

// ---------------------------------------------------------------------------
// Production Mode: owned read-only snapshot of a baked monolith
// ---------------------------------------------------------------------------

/// An owned, read-only snapshot of a `.pvdb` monolith.
pub struct Monolith {
    mmap: Arc<Mmap>,
    header: FileHeader,
    cas_offset: usize,
    manifest_offset: usize,
    // Keeps the private snapshot alive on platforms where mappings retain a
    // relationship with their source handle.
    _snapshot_file: File,
}

impl Monolith {
    /// Open and validate a `.pvdb` file (checks magic, reads the offset header).
    ///
    /// The bytes are copied into a private unnamed snapshot before mapping and
    /// parsing. Keeping a direct mapping of a publicly writable file behind a safe
    /// Rust API would allow another process to mutate it while borrowed, violating
    /// `Mmap`'s safety contract. The snapshot also gives every query one consistent
    /// image without keeping the full file resident in memory.
    pub fn open(path: impl AsRef<Path>) -> Result<Self> {
        let source = File::open(path)?;
        let source_len = source.metadata()?.len();
        if source_len < FILE_HEADER_SIZE as u64 {
            return Err(PvError::Corruption(
                "monolith smaller than file header".into(),
            ));
        }
        usize::try_from(source_len)
            .map_err(|_| PvError::Corruption("monolith is too large for this platform".into()))?;
        let mut snapshot_file = tempfile::tempfile()?;
        let copied = std::io::copy(&mut source.take(source_len), &mut snapshot_file)?;
        if copied != source_len {
            return Err(PvError::Corruption(
                "monolith changed length while it was being opened".into(),
            ));
        }
        snapshot_file.flush()?;
        snapshot_file.seek(SeekFrom::Start(0))?;
        // SAFETY: `snapshot_file` is a private, unnamed temporary file. It was
        // fully written before mapping, is retained by `Monolith`, and no mutable
        // handle or path is ever exposed, so its contents cannot change while
        // the mapping is borrowed.
        let mmap = unsafe { Mmap::map(&snapshot_file)? };
        let header = FileHeader::decode(&mmap[..FILE_HEADER_SIZE])?;
        let cas_offset = usize::try_from(header.cas_offset)
            .map_err(|_| PvError::Corruption("monolith CAS offset is too large".into()))?;
        let manifest_offset = usize::try_from(header.manifest_offset)
            .map_err(|_| PvError::Corruption("monolith manifest offset is too large".into()))?;
        if cas_offset < FILE_HEADER_SIZE
            || manifest_offset < cas_offset
            || manifest_offset > mmap.len()
            || (cas_offset - FILE_HEADER_SIZE) % PAGE_SIZE != 0
        {
            return Err(PvError::Corruption(
                "monolith offsets are inconsistent".into(),
            ));
        }
        Ok(Self {
            mmap: Arc::new(mmap),
            header,
            cas_offset,
            manifest_offset,
            _snapshot_file: snapshot_file,
        })
    }

    /// Number of pages packed into the page-data block.
    pub fn page_count(&self) -> u64 {
        ((self.cas_offset - FILE_HEADER_SIZE) / PAGE_SIZE) as u64
    }

    /// On-disk format version recorded in the monolith header.
    pub fn format_version(&self) -> u16 {
        self.header.format_version
    }

    /// Read a page out of the mapped page-data block.
    pub fn read_page(&self, id: u64) -> Result<PageBuf> {
        if id >= self.page_count() {
            return Err(PvError::PageFault { page_id: id });
        }
        let start = FILE_HEADER_SIZE + id as usize * PAGE_SIZE;
        let mut buf: PageBuf = Box::new([0u8; PAGE_SIZE]);
        buf.copy_from_slice(&self.mmap[start..start + PAGE_SIZE]);
        Ok(buf)
    }

    /// Absolute offset of the CAS blob pool within the file.
    pub fn cas_offset(&self) -> usize {
        self.cas_offset
    }

    /// Absolute offset of the trailing JSON manifest.
    pub fn manifest_offset(&self) -> usize {
        self.manifest_offset
    }

    /// The trailing JSON manifest payload.
    pub fn manifest_bytes(&self) -> &[u8] {
        &self.mmap[self.manifest_offset..]
    }

    /// A clonable handle to the underlying mapping (for [`crate::storage::cas`]).
    pub fn mmap(&self) -> Arc<Mmap> {
        self.mmap.clone()
    }
}

// ---------------------------------------------------------------------------
// In-memory backend (no filesystem), `Database::open_memory` and wasm targets
// ---------------------------------------------------------------------------

/// A page store held entirely in RAM (no filesystem / mmap). Useful for tests,
/// ephemeral databases, and `wasm32` targets (browser/Node) where there is no
/// filesystem available at runtime.
#[derive(Default)]
pub struct MemStore {
    pages: RefCell<Vec<PageBuf>>,
}

impl MemStore {
    /// An empty in-memory store.
    pub fn new() -> Self {
        Self::default()
    }

    /// Number of pages held.
    pub fn page_count(&self) -> u64 {
        self.pages.borrow().len() as u64
    }

    /// Allocate a fresh zeroed page, returning its id.
    pub fn alloc_page(&self) -> u64 {
        let mut pages = self.pages.borrow_mut();
        let id = pages.len() as u64;
        pages.push(Box::new([0u8; PAGE_SIZE]));
        id
    }

    /// Overwrite an allocated page.
    pub fn write_page(&self, id: u64, page: &[u8; PAGE_SIZE]) -> Result<()> {
        let index = usize::try_from(id).map_err(|_| PvError::PageFault { page_id: id })?;
        let mut pages = self.pages.borrow_mut();
        let slot = pages
            .get_mut(index)
            .ok_or(PvError::PageFault { page_id: id })?;
        **slot = *page;
        Ok(())
    }

    /// Write consecutive pages starting at `start_id`.
    pub fn write_pages_from(&self, start_id: u64, pages: &[&PageBuf]) -> Result<()> {
        for (i, page) in pages.iter().enumerate() {
            self.write_page(start_id + i as u64, page)?;
        }
        Ok(())
    }

    /// Read a page.
    pub fn read_page(&self, id: u64) -> Result<PageBuf> {
        let index = usize::try_from(id).map_err(|_| PvError::PageFault { page_id: id })?;
        self.pages
            .borrow()
            .get(index)
            .cloned()
            .ok_or(PvError::PageFault { page_id: id })
    }

    /// Snapshot every page (for baking an in-memory database to bytes).
    pub fn read_all_pages(&self) -> Result<Vec<PageBuf>> {
        Ok(self.pages.borrow().clone())
    }
}

// ---------------------------------------------------------------------------
// Remote / streamed backend: pages fetched on demand by byte range
// ---------------------------------------------------------------------------

/// Reads arbitrary byte ranges of a baked `.pvdb` image from some backing store
/// (an HTTP server over range requests, a file, ...). It lets a database be
/// opened and queried without holding the whole image in memory: the header,
/// CAS pool, and manifest are read once on open, and pages are fetched on demand.
pub trait RangeReader {
    /// Read exactly `len` bytes starting at `offset`.
    fn read_at(&self, offset: u64, len: usize) -> Result<Vec<u8>>;
}

/// A read-only page store that fetches each page through a [`RangeReader`].
pub struct RemoteStore {
    reader: Box<dyn RangeReader>,
    page_count: u64,
}

impl RemoteStore {
    /// Wrap a reader serving a baked monolith whose page-data block holds
    /// `page_count` pages.
    pub fn new(reader: Box<dyn RangeReader>, page_count: u64) -> Self {
        Self { reader, page_count }
    }

    /// Number of pages in the page-data block.
    pub fn page_count(&self) -> u64 {
        self.page_count
    }

    /// Fetch a single page by id.
    pub fn read_page(&self, id: u64) -> Result<PageBuf> {
        if id >= self.page_count {
            return Err(PvError::PageFault { page_id: id });
        }
        let offset = FILE_HEADER_SIZE as u64 + id * PAGE_SIZE as u64;
        let bytes = self.reader.read_at(offset, PAGE_SIZE)?;
        let arr: [u8; PAGE_SIZE] = bytes
            .as_slice()
            .try_into()
            .map_err(|_| PvError::Corruption("streamed page has the wrong length".into()))?;
        Ok(Box::new(arr))
    }

    /// Fetch every page (used only if a streamed db is re-baked; normal queries
    /// fetch pages lazily through the buffer pool).
    pub fn read_all_pages(&self) -> Result<Vec<PageBuf>> {
        (0..self.page_count).map(|id| self.read_page(id)).collect()
    }
}

// ---------------------------------------------------------------------------
// Backend router
// ---------------------------------------------------------------------------

/// Uniform access over the backends, used by the buffer pool and engine.
pub enum Backend {
    /// Mutable development workspace (filesystem).
    Dev(DevStore),
    /// Mutable in-memory store (no filesystem).
    Mem(MemStore),
    /// Read-only production monolith snapshot.
    Prod(Monolith),
    /// Read-only streamed monolith (pages fetched on demand by byte range).
    Remote(RemoteStore),
}

impl Backend {
    /// Total pages available.
    pub fn page_count(&self) -> u64 {
        match self {
            Backend::Dev(d) => d.page_count(),
            Backend::Mem(m) => m.page_count(),
            Backend::Prod(m) => m.page_count(),
            Backend::Remote(r) => r.page_count(),
        }
    }

    /// Read a page from whichever backend is active.
    pub fn read_page(&self, id: u64) -> Result<PageBuf> {
        match self {
            Backend::Dev(d) => d.read_page(id),
            Backend::Mem(m) => m.read_page(id),
            Backend::Prod(m) => m.read_page(id),
            Backend::Remote(r) => r.read_page(id),
        }
    }

    /// Whether the backend accepts writes (dev and in-memory, not production).
    pub fn is_writable(&self) -> bool {
        matches!(self, Backend::Dev(_) | Backend::Mem(_))
    }

    /// Allocate a new page id (writable backends only).
    pub fn alloc_page(&mut self) -> Result<u64> {
        match self {
            Backend::Dev(d) => Ok(d.alloc_page()),
            Backend::Mem(m) => Ok(m.alloc_page()),
            Backend::Prod(_) | Backend::Remote(_) => Err(PvError::ReadOnly),
        }
    }

    /// Write a single page (writable backends only).
    pub fn write_page(&self, id: u64, page: &[u8; PAGE_SIZE]) -> Result<()> {
        match self {
            Backend::Dev(d) => d.write_page(id, page),
            Backend::Mem(m) => m.write_page(id, page),
            Backend::Prod(_) | Backend::Remote(_) => Err(PvError::ReadOnly),
        }
    }

    /// Bulk-write consecutive pages (writable backends only).
    pub fn write_pages_from(&self, start_id: u64, pages: &[&PageBuf]) -> Result<()> {
        match self {
            Backend::Dev(d) => d.write_pages_from(start_id, pages),
            Backend::Mem(m) => m.write_pages_from(start_id, pages),
            Backend::Prod(_) | Backend::Remote(_) => Err(PvError::ReadOnly),
        }
    }

    /// `fsync` durable backends (no-op for in-memory / read-only).
    pub fn sync_data(&self) -> Result<()> {
        match self {
            Backend::Dev(d) => d.sync_data(),
            _ => Ok(()),
        }
    }

    /// Read every page in id order.
    pub fn read_all_pages(&self) -> Result<Vec<PageBuf>> {
        match self {
            Backend::Dev(d) => d.read_all_pages(),
            Backend::Mem(m) => m.read_all_pages(),
            Backend::Prod(m) => (0..m.page_count()).map(|id| m.read_page(id)).collect(),
            Backend::Remote(r) => r.read_all_pages(),
        }
    }
}

// ---------------------------------------------------------------------------
// Bake: directory -> monolith compilation (spec ยง2.B, pv_bake)
// ---------------------------------------------------------------------------

/// Compile a page set, CAS blob pool, and manifest into the `.pvdb` monolith
/// **byte image** (no filesystem). Used directly for in-memory/wasm export and
/// by [`bake_monolith`] for the file path.
///
/// Layout: `header(FILE_HEADER_SIZE) | pages | cas_pool | manifest`, with
/// `cas_offset` and `manifest_offset` recorded in the header. Each page already
/// carries its own integrity checksum (see [`stamp_page_checksum`]).
pub fn bake_monolith_bytes(
    pages: &[PageBuf],
    cas_pool: &[u8],
    manifest_json: &[u8],
) -> Result<Vec<u8>> {
    bake_monolith_bytes_with_index(pages, cas_pool, &[], manifest_json, FORMAT_VERSION_BASE)
}

/// Like [`bake_monolith_bytes`] but inserts a binary secondary-index region
/// between the CAS pool and the manifest, and stamps an explicit format version.
///
/// Layout: `header | pages | cas_pool | index_region | manifest`. The manifest's
/// `cas_offset` points at the CAS pool and `manifest_offset` at the trailing
/// manifest, so the region occupies `[cas_offset + cas_pool.len(), manifest_offset)`
/// and its exact extent is recorded inside the manifest. Pass an empty
/// `index_region` and [`FORMAT_VERSION_BASE`] to reproduce the version-1 layout.
pub fn bake_monolith_bytes_with_index(
    pages: &[PageBuf],
    cas_pool: &[u8],
    index_region: &[u8],
    manifest_json: &[u8],
    format_version: u16,
) -> Result<Vec<u8>> {
    let overflow = || PvError::Corruption("monolith size overflows address space".into());
    let cas_offset = pages
        .len()
        .checked_mul(PAGE_SIZE)
        .and_then(|n| n.checked_add(FILE_HEADER_SIZE))
        .ok_or_else(overflow)?;
    let index_offset = cas_offset
        .checked_add(cas_pool.len())
        .ok_or_else(overflow)?;
    let manifest_offset = index_offset
        .checked_add(index_region.len())
        .ok_or_else(overflow)?;
    let total = manifest_offset
        .checked_add(manifest_json.len())
        .ok_or_else(overflow)?;
    let header =
        FileHeader::new_versioned(manifest_offset as u64, cas_offset as u64, format_version);

    let mut out = Vec::with_capacity(total);
    out.extend_from_slice(&header.encode());
    for page in pages {
        out.extend_from_slice(&page[..]);
    }
    out.extend_from_slice(cas_pool);
    out.extend_from_slice(index_region);
    out.extend_from_slice(manifest_json);
    Ok(out)
}

/// Compile a page set, CAS blob pool, and manifest into a `.pvdb` file.
pub fn bake_monolith(
    out_path: impl AsRef<Path>,
    pages: &[PageBuf],
    cas_pool: &[u8],
    manifest_json: &[u8],
) -> Result<()> {
    let bytes = bake_monolith_bytes(pages, cas_pool, manifest_json)?;
    let mut out = File::create(out_path)?;
    out.write_all(&bytes)?;
    out.flush()?;
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn dev_store_round_trips_pages() {
        let tmp = tempfile::tempdir().unwrap();
        let mut dev = DevStore::create(tmp.path()).unwrap();
        let id0 = dev.alloc_page();
        let id1 = dev.alloc_page();
        let mut p0: PageBuf = Box::new([0u8; PAGE_SIZE]);
        p0[0] = 0xAA;
        let mut p1: PageBuf = Box::new([0u8; PAGE_SIZE]);
        p1[4095] = 0xBB;
        dev.write_page(id0, &p0).unwrap();
        dev.write_page(id1, &p1).unwrap();

        assert_eq!(dev.read_page(id0).unwrap()[0], 0xAA);
        assert_eq!(dev.read_page(id1).unwrap()[4095], 0xBB);
        assert!(matches!(dev.read_page(2), Err(PvError::PageFault { .. })));
    }

    #[test]
    fn bake_then_open_monolith_matches_pages() {
        let tmp = tempfile::tempdir().unwrap();
        let mut dev = DevStore::create(tmp.path().join("ws")).unwrap();
        let id = dev.alloc_page();
        let mut page: PageBuf = Box::new([0u8; PAGE_SIZE]);
        page[10] = 0x42;
        dev.write_page(id, &page).unwrap();

        let pages = dev.read_all_pages().unwrap();
        let cas_pool = b"blobpool".to_vec();
        let manifest = br#"{"ok":true}"#.to_vec();
        let out = tmp.path().join("db.pvdb");
        bake_monolith(&out, &pages, &cas_pool, &manifest).unwrap();

        let mono = Monolith::open(&out).unwrap();
        assert_eq!(mono.page_count(), 1);
        assert_eq!(mono.read_page(0).unwrap()[10], 0x42);
        assert_eq!(mono.manifest_bytes(), manifest.as_slice());
        // CAS pool sits between pages and manifest.
        let pool_end = mono.cas_offset() + cas_pool.len();
        assert_eq!(
            &mono.mmap()[mono.cas_offset()..pool_end],
            cas_pool.as_slice()
        );

        // The public API owns a stable snapshot: later mutations of the source
        // path cannot race readers or alter the opened database.
        std::fs::write(&out, vec![0u8; FILE_HEADER_SIZE]).unwrap();
        assert_eq!(mono.read_page(0).unwrap()[10], 0x42);
        assert_eq!(mono.manifest_bytes(), manifest.as_slice());
    }

    #[test]
    fn open_rejects_bad_magic() {
        let tmp = tempfile::tempdir().unwrap();
        let path = tmp.path().join("bad.pvdb");
        std::fs::write(&path, vec![0u8; 64]).unwrap();
        assert!(matches!(
            Monolith::open(&path),
            Err(PvError::SignatureMismatch { .. })
        ));
    }

    #[test]
    fn sync_data_fsyncs_all_dirty_chunks() {
        let tmp = tempfile::tempdir().unwrap();
        let dev = DevStore::create(tmp.path()).unwrap();
        let page = [7u8; PAGE_SIZE];
        dev.write_page(0, &page).unwrap(); // chunk 0
        dev.write_page(PAGES_PER_CHUNK, &page).unwrap(); // chunk 1 (different file)
                                                         // Must fsync both chunks (the cached one and the reopened one) without error.
        dev.sync_data().unwrap();
        assert!(tmp.path().join("chunks").join("chunk_00000.pvd").exists());
        assert!(tmp.path().join("chunks").join("chunk_00001.pvd").exists());
    }

    #[test]
    fn page_checksum_excludes_its_own_field_and_is_nonzero() {
        let mut page: PageBuf = Box::new([0u8; PAGE_SIZE]);
        page[0] = 0xAB;
        page[100] = 0xCD;
        let c1 = page_checksum(&page);
        assert_ne!(c1, 0);
        // Overwriting the checksum field must not change the computed checksum.
        page[PAGE_CHECKSUM_OFFSET..PAGE_CHECKSUM_OFFSET + 4].copy_from_slice(&[1, 2, 3, 4]);
        assert_eq!(page_checksum(&page), c1);
    }

    #[test]
    fn stamp_then_verify_round_trips() {
        let mut page: PageBuf = Box::new([0u8; PAGE_SIZE]);
        page[42] = 0x7F;
        stamp_page_checksum(&mut page);
        assert!(verify_page_checksum(7, &page).is_ok());
    }

    #[test]
    fn verify_detects_a_flipped_body_byte() {
        let mut page: PageBuf = Box::new([0u8; PAGE_SIZE]);
        page[42] = 0x7F;
        stamp_page_checksum(&mut page);
        page[42] ^= 0x01; // simulate bit-rot in the page body
        assert!(matches!(
            verify_page_checksum(7, &page),
            Err(PvError::Corruption(_))
        ));
    }

    #[test]
    fn verify_detects_a_corrupt_checksum_field() {
        let mut page: PageBuf = Box::new([0u8; PAGE_SIZE]);
        page[42] = 0x7F;
        stamp_page_checksum(&mut page);
        page[PAGE_CHECKSUM_OFFSET] ^= 0xFF; // corrupt the stored checksum itself
        assert!(matches!(
            verify_page_checksum(7, &page),
            Err(PvError::Corruption(_))
        ));
    }

    #[test]
    fn verify_accepts_an_unstamped_blank_page() {
        // A zeroed (allocated-but-never-written) page has a zero checksum field and
        // is accepted without verification.
        let page: PageBuf = Box::new([0u8; PAGE_SIZE]);
        assert!(verify_page_checksum(0, &page).is_ok());
    }
}