Skip to main content

reddb_file/
file_format.rs

1//! Core persisted file-format constants.
2//!
3//! Runtime crates can own page management and columnar execution, but these
4//! durable magic/version values are file compatibility contracts.
5
6use std::fmt;
7
8/// Magic bytes for database file identification: `RDDB`.
9pub const PAGE_FILE_MAGIC: [u8; 4] = [0x52, 0x44, 0x44, 0x42];
10
11/// The first version that reserves the in-file double-write buffer zone.
12pub const PAGE_DWB_ZONE_FILE_VERSION: u32 = 0x0001_0001;
13/// The first version with durable page-ownership recovery.
14pub const PAGE_OWNERSHIP_FILE_VERSION: u32 = 0x0001_0002;
15/// Checkpoint before-images must be restored before following published roots.
16pub const PAGE_CHECKPOINT_UNDO_FILE_VERSION: u32 = 0x0001_0003;
17/// Current database file version. The phase-3 DWB layout itself starts at
18/// 1.0.1; older readers reject this version before using the new contract.
19pub const PAGE_DISK_RESIDENCY_FILE_VERSION: u32 = 0x0001_0004;
20/// Generation-bound secondary trees participate in catalog ownership/reclamation.
21/// Older readers must reject the file before recovering or recycling pages.
22pub const PAGE_SECONDARY_INDEX_FILE_VERSION: u32 = 0x0001_0005;
23/// Legacy recovery output: identity high-water marks are unknown and every
24/// writer must refuse this file. Older readers reject the version outright.
25pub const PAGE_RECOVERY_READ_ONLY_FILE_VERSION: u32 = 0x0001_0006;
26/// Result-cache epoch fencing for resident paged stores.
27pub const PAGE_RESULT_CACHE_FILE_VERSION: u32 = 0x0001_0007;
28/// Result-cache epoch fencing for disk-resident paged stores.
29pub const PAGE_RESULT_CACHE_DISK_FILE_VERSION: u32 = 0x0001_0008;
30/// The first version whose superblock declares mandatory reader capabilities.
31pub const PAGE_REQUIRED_CAPABILITIES_FILE_VERSION: u32 = 0x0001_0009;
32pub const PAGE_FILE_VERSION: u32 = PAGE_REQUIRED_CAPABILITIES_FILE_VERSION;
33
34/// Native measured-temperature values may appear in entity payloads.
35pub const FILE_CAPABILITY_TEMPERATURE: u64 = 1 << 0;
36/// The file's published trees require a disk-resident writer.
37pub const FILE_CAPABILITY_DISK_RESIDENCY: u64 = 1 << 1;
38/// A copy-on-write catalog is independently sealed by both superblock copies.
39pub const FILE_CAPABILITY_CATALOG_ROOT: u64 = 1 << 2;
40/// Recovery output whose identity high-water marks are unknown cannot admit writers.
41pub const FILE_CAPABILITY_RECOVERY_READ_ONLY: u64 = 1 << 3;
42/// Published catalog roots carry independently sealed tree-image maps.
43pub const FILE_CAPABILITY_TREE_PROOFS: u64 = 1 << 4;
44/// Double-write frames require independent superblock publication authority.
45pub const FILE_CAPABILITY_DWB_PUBLICATION: u64 = 1 << 5;
46/// Native cron rules may appear in schema and entity payloads.
47pub const FILE_CAPABILITY_CRON: u64 = 1 << 6;
48// Freeze the old entry point's reader contract. An older engine may link a
49// newer compatible codec crate without implementing its new recovery rules.
50const FILE_CAPABILITIES_LEGACY_HEADER: u64 =
51    FILE_CAPABILITY_TEMPERATURE | FILE_CAPABILITY_DISK_RESIDENCY;
52/// Capabilities understood by this reader. Unknown mandatory bits are fatal.
53pub const FILE_CAPABILITIES_SUPPORTED: u64 = FILE_CAPABILITY_TEMPERATURE
54    | FILE_CAPABILITY_DISK_RESIDENCY
55    | FILE_CAPABILITY_CATALOG_ROOT
56    | FILE_CAPABILITY_RECOVERY_READ_ONLY
57    | FILE_CAPABILITY_TREE_PROOFS
58    | FILE_CAPABILITY_DWB_PUBLICATION
59    | FILE_CAPABILITY_CRON;
60
61/// Whether a pre-capability format version implies disk residency.
62/// Capability-aware callers must use [`DatabaseHeader::requires_disk_residency`].
63pub fn page_format_is_disk_resident(version: u32) -> bool {
64    (PAGE_DISK_RESIDENCY_FILE_VERSION..PAGE_REQUIRED_CAPABILITIES_FILE_VERSION).contains(&version)
65        && version != PAGE_RESULT_CACHE_FILE_VERSION
66}
67
68/// Paged database page size.
69pub const PAGED_PAGE_SIZE: usize = 16_384;
70
71/// Paged database page-header size before the page-0 database header.
72pub const PAGED_PAGE_HEADER_SIZE: usize = 32;
73
74pub const PAGED_CELL_POINTER_SIZE: usize = 2;
75pub const PAGED_CELL_HEADER_SIZE: usize = 6;
76
77/// Raw persisted page header encoded at the start of every paged-store page.
78#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
79pub struct PagedPageHeader {
80    pub page_type: u8,
81    pub flags: u8,
82    pub cell_count: u16,
83    pub free_start: u16,
84    pub free_end: u16,
85    pub page_id: u32,
86    pub parent_id: u32,
87    pub right_child: u32,
88    pub lsn: u64,
89    pub checksum: u32,
90}
91
92pub fn encode_paged_page_header(header: &PagedPageHeader) -> [u8; PAGED_PAGE_HEADER_SIZE] {
93    let mut buf = [0u8; PAGED_PAGE_HEADER_SIZE];
94    buf[0] = header.page_type;
95    buf[1] = header.flags;
96    buf[2..4].copy_from_slice(&header.cell_count.to_le_bytes());
97    buf[4..6].copy_from_slice(&header.free_start.to_le_bytes());
98    buf[6..8].copy_from_slice(&header.free_end.to_le_bytes());
99    buf[8..12].copy_from_slice(&header.page_id.to_le_bytes());
100    buf[12..16].copy_from_slice(&header.parent_id.to_le_bytes());
101    buf[16..20].copy_from_slice(&header.right_child.to_le_bytes());
102    buf[20..28].copy_from_slice(&header.lsn.to_le_bytes());
103    buf[28..32].copy_from_slice(&header.checksum.to_le_bytes());
104    buf
105}
106
107pub fn decode_paged_page_header(buf: &[u8; PAGED_PAGE_HEADER_SIZE]) -> PagedPageHeader {
108    PagedPageHeader {
109        page_type: buf[0],
110        flags: buf[1],
111        cell_count: u16::from_le_bytes([buf[2], buf[3]]),
112        free_start: u16::from_le_bytes([buf[4], buf[5]]),
113        free_end: u16::from_le_bytes([buf[6], buf[7]]),
114        page_id: u32::from_le_bytes([buf[8], buf[9], buf[10], buf[11]]),
115        parent_id: u32::from_le_bytes([buf[12], buf[13], buf[14], buf[15]]),
116        right_child: u32::from_le_bytes([buf[16], buf[17], buf[18], buf[19]]),
117        lsn: u64::from_le_bytes([
118            buf[20], buf[21], buf[22], buf[23], buf[24], buf[25], buf[26], buf[27],
119        ]),
120        checksum: u32::from_le_bytes([buf[28], buf[29], buf[30], buf[31]]),
121    }
122}
123
124pub fn paged_page_type(page: &[u8; PAGED_PAGE_SIZE]) -> u8 {
125    page[0]
126}
127
128pub fn paged_page_id(page: &[u8; PAGED_PAGE_SIZE]) -> u32 {
129    read_u32(page, 8).expect("paged page has header")
130}
131
132pub fn paged_page_lsn(page: &[u8; PAGED_PAGE_SIZE]) -> u64 {
133    read_u64(page, 20).expect("paged page has header")
134}
135
136pub fn set_paged_page_lsn(page: &mut [u8; PAGED_PAGE_SIZE], lsn: u64) {
137    write_u64(page, 20, lsn).expect("paged page has header");
138}
139
140pub fn paged_page_cell_count(page: &[u8; PAGED_PAGE_SIZE]) -> u16 {
141    read_u16(page, 2).expect("paged page has header")
142}
143
144pub fn set_paged_page_cell_count(page: &mut [u8; PAGED_PAGE_SIZE], count: u16) {
145    write_u16(page, 2, count).expect("paged page has header");
146}
147
148pub fn paged_page_parent_id(page: &[u8; PAGED_PAGE_SIZE]) -> u32 {
149    read_u32(page, 12).expect("paged page has header")
150}
151
152pub fn set_paged_page_parent_id(page: &mut [u8; PAGED_PAGE_SIZE], parent_id: u32) {
153    write_u32(page, 12, parent_id).expect("paged page has header");
154}
155
156pub fn paged_page_right_child(page: &[u8; PAGED_PAGE_SIZE]) -> u32 {
157    read_u32(page, 16).expect("paged page has header")
158}
159
160pub fn set_paged_page_right_child(page: &mut [u8; PAGED_PAGE_SIZE], child_id: u32) {
161    write_u32(page, 16, child_id).expect("paged page has header");
162}
163
164pub fn paged_page_free_start(page: &[u8; PAGED_PAGE_SIZE]) -> u16 {
165    read_u16(page, 4).expect("paged page has header")
166}
167
168pub fn set_paged_page_free_start(page: &mut [u8; PAGED_PAGE_SIZE], offset: u16) {
169    write_u16(page, 4, offset).expect("paged page has header");
170}
171
172pub fn paged_page_free_end(page: &[u8; PAGED_PAGE_SIZE]) -> u16 {
173    read_u16(page, 6).expect("paged page has header")
174}
175
176pub fn set_paged_page_free_end(page: &mut [u8; PAGED_PAGE_SIZE], offset: u16) {
177    write_u16(page, 6, offset).expect("paged page has header");
178}
179
180pub fn paged_page_checksum(page: &[u8; PAGED_PAGE_SIZE]) -> u32 {
181    read_u32(page, 28).expect("paged page has header")
182}
183
184pub fn clear_paged_page_checksum(page: &mut [u8; PAGED_PAGE_SIZE]) {
185    write_u32(page, 28, 0).expect("paged page has header");
186}
187
188pub fn set_paged_page_checksum(page: &mut [u8; PAGED_PAGE_SIZE], checksum: u32) {
189    write_u32(page, 28, checksum).expect("paged page has header");
190}
191
192pub fn paged_cell_pointer_offset(index: usize) -> Option<usize> {
193    let offset = PAGED_PAGE_HEADER_SIZE.checked_add(index.checked_mul(PAGED_CELL_POINTER_SIZE)?)?;
194    (offset + PAGED_CELL_POINTER_SIZE <= PAGED_PAGE_SIZE).then_some(offset)
195}
196
197pub fn paged_cell_pointer(page: &[u8; PAGED_PAGE_SIZE], index: usize) -> Option<u16> {
198    read_u16(page, paged_cell_pointer_offset(index)?).ok()
199}
200
201pub fn set_paged_cell_pointer(
202    page: &mut [u8; PAGED_PAGE_SIZE],
203    index: usize,
204    pointer: u16,
205) -> bool {
206    let Some(offset) = paged_cell_pointer_offset(index) else {
207        return false;
208    };
209    if !paged_cell_pointer_is_valid(pointer) {
210        return false;
211    }
212    write_u16(page, offset, pointer).is_ok()
213}
214
215pub fn paged_cell_pointer_is_valid(pointer: u16) -> bool {
216    let pointer = pointer as usize;
217    (PAGED_PAGE_HEADER_SIZE..PAGED_PAGE_SIZE).contains(&pointer)
218}
219
220pub fn paged_cell_len(key_len: usize, value_len: usize) -> Option<usize> {
221    PAGED_CELL_HEADER_SIZE
222        .checked_add(key_len)?
223        .checked_add(value_len)
224}
225
226pub fn paged_cell_total_len(page: &[u8; PAGED_PAGE_SIZE], pointer: u16) -> Option<usize> {
227    let pointer = pointer as usize;
228    if pointer + PAGED_CELL_HEADER_SIZE > PAGED_PAGE_SIZE {
229        return None;
230    }
231    let key_len = read_u16(page, pointer).ok()? as usize;
232    let value_len = read_u32(page, pointer + 2).ok()? as usize;
233    let total_len = paged_cell_len(key_len, value_len)?;
234    (pointer + total_len <= PAGED_PAGE_SIZE).then_some(total_len)
235}
236
237pub fn paged_cell_bytes(page: &[u8; PAGED_PAGE_SIZE], pointer: u16) -> Option<&[u8]> {
238    let total_len = paged_cell_total_len(page, pointer)?;
239    let pointer = pointer as usize;
240    Some(&page[pointer..pointer + total_len])
241}
242
243pub fn paged_cell_key_value(cell: &[u8]) -> Option<(&[u8], &[u8])> {
244    if cell.len() < PAGED_CELL_HEADER_SIZE {
245        return None;
246    }
247    let key_len = u16::from_le_bytes(cell[0..2].try_into().ok()?) as usize;
248    let value_len = u32::from_le_bytes(cell[2..6].try_into().ok()?) as usize;
249    let total_len = paged_cell_len(key_len, value_len)?;
250    if total_len > cell.len() {
251        return None;
252    }
253    let key_start = PAGED_CELL_HEADER_SIZE;
254    let value_start = key_start + key_len;
255    Some((
256        &cell[key_start..value_start],
257        &cell[value_start..value_start + value_len],
258    ))
259}
260
261pub fn write_paged_cell(
262    page: &mut [u8; PAGED_PAGE_SIZE],
263    offset: u16,
264    key: &[u8],
265    value: &[u8],
266) -> bool {
267    let Ok(key_len) = u16::try_from(key.len()) else {
268        return false;
269    };
270    let Ok(value_len) = u32::try_from(value.len()) else {
271        return false;
272    };
273    let Some(total_len) = paged_cell_len(key.len(), value.len()) else {
274        return false;
275    };
276    let offset = offset as usize;
277    if offset + total_len > PAGED_PAGE_SIZE {
278        return false;
279    }
280
281    page[offset..offset + 2].copy_from_slice(&key_len.to_le_bytes());
282    page[offset + 2..offset + 6].copy_from_slice(&value_len.to_le_bytes());
283    page[offset + PAGED_CELL_HEADER_SIZE..offset + PAGED_CELL_HEADER_SIZE + key.len()]
284        .copy_from_slice(key);
285    page[offset + PAGED_CELL_HEADER_SIZE + key.len()..offset + total_len].copy_from_slice(value);
286    true
287}
288
289/// Encryption marker embedded in page 0 when page encryption is enabled.
290pub const PAGED_ENCRYPTION_MARKER: [u8; 4] = *b"RDBE";
291
292/// Current page-0 encryption marker offset.
293///
294/// This preserves the existing on-disk placement. It overlaps the historical
295/// physical-header region, so callers must preserve page-0 bytes around normal
296/// header writes.
297pub const PAGED_ENCRYPTION_MARKER_OFFSET: usize = PAGED_PAGE_HEADER_SIZE + 32;
298
299pub const PAGED_ENCRYPTION_SALT_SIZE: usize = 32;
300pub const PAGED_ENCRYPTION_KEY_CHECK_PLAINTEXT_SIZE: usize = 32;
301pub const PAGED_ENCRYPTION_KEY_CHECK_BLOB_SIZE: usize = 60;
302pub const PAGED_ENCRYPTION_HEADER_SIZE: usize =
303    PAGED_ENCRYPTION_SALT_SIZE + PAGED_ENCRYPTION_KEY_CHECK_BLOB_SIZE;
304
305#[derive(Debug, Clone, PartialEq, Eq)]
306pub struct PagedEncryptionHeader {
307    pub salt: [u8; PAGED_ENCRYPTION_SALT_SIZE],
308    pub key_check: Vec<u8>,
309}
310
311pub fn encode_paged_encryption_header(header: &PagedEncryptionHeader) -> Vec<u8> {
312    let mut out = Vec::with_capacity(PAGED_ENCRYPTION_HEADER_SIZE);
313    out.extend_from_slice(&header.salt);
314    out.extend_from_slice(&header.key_check);
315    out
316}
317
318pub fn decode_paged_encryption_header(
319    data: &[u8],
320) -> Result<PagedEncryptionHeader, DatabaseHeaderError> {
321    ensure_len(data, PAGED_ENCRYPTION_HEADER_SIZE)?;
322    let mut salt = [0u8; PAGED_ENCRYPTION_SALT_SIZE];
323    salt.copy_from_slice(&data[..PAGED_ENCRYPTION_SALT_SIZE]);
324    let key_check = data[PAGED_ENCRYPTION_SALT_SIZE..PAGED_ENCRYPTION_HEADER_SIZE].to_vec();
325    Ok(PagedEncryptionHeader { salt, key_check })
326}
327
328pub fn paged_encryption_marker_present(page: &[u8]) -> bool {
329    page.get(PAGED_ENCRYPTION_MARKER_OFFSET..PAGED_ENCRYPTION_MARKER_OFFSET + 4)
330        == Some(&PAGED_ENCRYPTION_MARKER)
331}
332
333pub fn paged_encryption_header_bytes(page: &[u8]) -> Option<&[u8]> {
334    let start = PAGED_ENCRYPTION_MARKER_OFFSET + PAGED_ENCRYPTION_MARKER.len();
335    page.get(start..start + PAGED_ENCRYPTION_HEADER_SIZE)
336}
337
338pub fn write_paged_encryption_marker_and_header(
339    page: &mut [u8],
340    header_bytes: &[u8],
341) -> Result<(), DatabaseHeaderError> {
342    let marker_end = PAGED_ENCRYPTION_MARKER_OFFSET + PAGED_ENCRYPTION_MARKER.len();
343    let header_end = marker_end + header_bytes.len();
344    ensure_len(page, header_end)?;
345    page[PAGED_ENCRYPTION_MARKER_OFFSET..marker_end].copy_from_slice(&PAGED_ENCRYPTION_MARKER);
346    page[marker_end..header_end].copy_from_slice(header_bytes);
347    Ok(())
348}
349
350const DB_MAGIC_OFFSET: usize = PAGED_PAGE_HEADER_SIZE;
351const DB_VERSION_OFFSET: usize = PAGED_PAGE_HEADER_SIZE + 4;
352const DB_PAGE_SIZE_OFFSET: usize = PAGED_PAGE_HEADER_SIZE + 8;
353const DB_PAGE_COUNT_OFFSET: usize = PAGED_PAGE_HEADER_SIZE + 12;
354const DB_FREELIST_HEAD_OFFSET: usize = PAGED_PAGE_HEADER_SIZE + 16;
355const DB_SCHEMA_VERSION_OFFSET: usize = PAGED_PAGE_HEADER_SIZE + 20;
356const DB_CHECKPOINT_LSN_OFFSET: usize = PAGED_PAGE_HEADER_SIZE + 24;
357const DB_PHYSICAL_FORMAT_VERSION_OFFSET: usize = PAGED_PAGE_HEADER_SIZE + 32;
358const DB_PHYSICAL_SEQUENCE_OFFSET: usize = PAGED_PAGE_HEADER_SIZE + 36;
359const DB_MANIFEST_ROOT_OFFSET: usize = PAGED_PAGE_HEADER_SIZE + 44;
360const DB_MANIFEST_OLDEST_ROOT_OFFSET: usize = PAGED_PAGE_HEADER_SIZE + 52;
361const DB_FREE_SET_ROOT_OFFSET: usize = PAGED_PAGE_HEADER_SIZE + 60;
362const DB_MANIFEST_PAGE_OFFSET: usize = PAGED_PAGE_HEADER_SIZE + 68;
363const DB_MANIFEST_CHECKSUM_OFFSET: usize = PAGED_PAGE_HEADER_SIZE + 72;
364const DB_COLLECTION_ROOTS_PAGE_OFFSET: usize = PAGED_PAGE_HEADER_SIZE + 80;
365const DB_COLLECTION_ROOTS_CHECKSUM_OFFSET: usize = PAGED_PAGE_HEADER_SIZE + 84;
366const DB_COLLECTION_ROOT_COUNT_OFFSET: usize = PAGED_PAGE_HEADER_SIZE + 92;
367const DB_SNAPSHOT_COUNT_OFFSET: usize = PAGED_PAGE_HEADER_SIZE + 96;
368const DB_INDEX_COUNT_OFFSET: usize = PAGED_PAGE_HEADER_SIZE + 100;
369const DB_CATALOG_COLLECTION_COUNT_OFFSET: usize = PAGED_PAGE_HEADER_SIZE + 104;
370const DB_CATALOG_TOTAL_ENTITIES_OFFSET: usize = PAGED_PAGE_HEADER_SIZE + 108;
371const DB_EXPORT_COUNT_OFFSET: usize = PAGED_PAGE_HEADER_SIZE + 116;
372const DB_GRAPH_PROJECTION_COUNT_OFFSET: usize = PAGED_PAGE_HEADER_SIZE + 120;
373const DB_ANALYTICS_JOB_COUNT_OFFSET: usize = PAGED_PAGE_HEADER_SIZE + 124;
374const DB_MANIFEST_EVENT_COUNT_OFFSET: usize = PAGED_PAGE_HEADER_SIZE + 128;
375const DB_REGISTRY_PAGE_OFFSET: usize = PAGED_PAGE_HEADER_SIZE + 132;
376const DB_REGISTRY_CHECKSUM_OFFSET: usize = PAGED_PAGE_HEADER_SIZE + 136;
377const DB_RECOVERY_PAGE_OFFSET: usize = PAGED_PAGE_HEADER_SIZE + 144;
378const DB_RECOVERY_CHECKSUM_OFFSET: usize = PAGED_PAGE_HEADER_SIZE + 148;
379const DB_CATALOG_PAGE_OFFSET: usize = PAGED_PAGE_HEADER_SIZE + 156;
380const DB_CATALOG_CHECKSUM_OFFSET: usize = PAGED_PAGE_HEADER_SIZE + 160;
381const DB_METADATA_STATE_PAGE_OFFSET: usize = PAGED_PAGE_HEADER_SIZE + 168;
382const DB_METADATA_STATE_CHECKSUM_OFFSET: usize = PAGED_PAGE_HEADER_SIZE + 172;
383const DB_VECTOR_ARTIFACT_PAGE_OFFSET: usize = PAGED_PAGE_HEADER_SIZE + 180;
384const DB_VECTOR_ARTIFACT_CHECKSUM_OFFSET: usize = PAGED_PAGE_HEADER_SIZE + 184;
385const DB_CHECKPOINT_IN_PROGRESS_OFFSET: usize = PAGED_PAGE_HEADER_SIZE + 192;
386const DB_CHECKPOINT_TARGET_LSN_OFFSET: usize = PAGED_PAGE_HEADER_SIZE + 193;
387const DB_REQUIRED_CAPABILITIES_OFFSET: usize = PAGED_PAGE_HEADER_SIZE + 208;
388const DB_HEADER_MIN_LEN: usize = DB_REQUIRED_CAPABILITIES_OFFSET + 8;
389// Keep the legacy encryption envelope (bytes 64..160) and all existing fields intact.
390const DB_MANIFEST_REFERENCE_OFFSET: usize = 256;
391const DB_MANIFEST_REFERENCE_END: usize = DB_MANIFEST_REFERENCE_OFFSET + 36;
392const _: () = assert!(DB_MANIFEST_REFERENCE_END < PAGED_SUPERBLOCK_TRAILER_OFFSET);
393// Maintained by protected page I/O, under the superblock publication lock.
394// Ordinary DatabaseHeader encoding preserves this extension from the newest
395// slot instead of copying stale publication state from the header cache.
396const DB_DWB_PUBLICATION_OFFSET: usize = 296;
397const DB_DWB_PUBLICATION_END: usize = DB_DWB_PUBLICATION_OFFSET + 40;
398const _: () = assert!(DB_MANIFEST_REFERENCE_END <= DB_DWB_PUBLICATION_OFFSET);
399const _: () = assert!(DB_DWB_PUBLICATION_END < PAGED_SUPERBLOCK_TRAILER_OFFSET);
400
401#[derive(Debug, Clone, Copy, PartialEq, Eq)]
402#[repr(u32)]
403pub enum DwbPhase {
404    Preparing = 1,
405    Ready = 2,
406    Consumed = 3,
407}
408
409/// Authority over the complete raw frame, including encrypted page images.
410#[derive(Debug, Clone, Copy, PartialEq, Eq)]
411pub struct DwbPublication {
412    pub phase: DwbPhase,
413    pub frame_bytes: u32,
414    pub digest: [u8; 32],
415}
416
417pub fn dwb_frame_digest(bytes: &[u8]) -> [u8; 32] {
418    *blake3::hash(bytes).as_bytes()
419}
420
421pub fn database_header_dwb_publication(
422    page: &[u8],
423) -> Result<Option<DwbPublication>, HeaderPublicationError> {
424    ensure_len(page, DB_DWB_PUBLICATION_END)?;
425    let field = &page[DB_DWB_PUBLICATION_OFFSET..DB_DWB_PUBLICATION_END];
426    if field == [0; 40] {
427        return Ok(None);
428    }
429    let phase = match read_u32(field, 0)? {
430        1 => DwbPhase::Preparing,
431        2 => DwbPhase::Ready,
432        3 => DwbPhase::Consumed,
433        _ => return Err(HeaderPublicationError::InvalidDwbPublication),
434    };
435    let frame_bytes = read_u32(field, 4)?;
436    let digest = field[8..40].try_into().expect("fixed digest field");
437    let count = (frame_bytes as usize).checked_sub(PAGED_DWB_HEADER_SIZE);
438    if digest == [0; 32]
439        || !count.is_some_and(|bytes| {
440            bytes >= PAGED_DWB_ENTRY_SIZE
441                && bytes.is_multiple_of(PAGED_DWB_ENTRY_SIZE)
442                && frame_bytes as usize <= 64 * PAGED_PAGE_SIZE
443        })
444    {
445        return Err(HeaderPublicationError::InvalidDwbPublication);
446    }
447    Ok(Some(DwbPublication {
448        phase,
449        frame_bytes,
450        digest,
451    }))
452}
453
454pub fn set_database_header_dwb_publication(
455    page: &mut [u8],
456    publication: Option<DwbPublication>,
457) -> Result<(), HeaderPublicationError> {
458    ensure_len(page, DB_DWB_PUBLICATION_END)?;
459    let field = &mut page[DB_DWB_PUBLICATION_OFFSET..DB_DWB_PUBLICATION_END];
460    field.fill(0);
461    if let Some(publication) = publication {
462        write_u32(field, 0, publication.phase as u32)?;
463        write_u32(field, 4, publication.frame_bytes)?;
464        field[8..40].copy_from_slice(&publication.digest);
465        database_header_dwb_publication(page)?;
466    }
467    Ok(())
468}
469
470/// Double-write-buffer file magic: `RDDW`.
471pub const DWB_MAGIC: [u8; 4] = [0x52, 0x44, 0x44, 0x57];
472pub const PAGED_DWB_HEADER_SIZE: usize = 12;
473pub const PAGED_DWB_ENTRY_HEADER_SIZE: usize = 4;
474pub const PAGED_DWB_ENTRY_SIZE: usize = PAGED_DWB_ENTRY_HEADER_SIZE + PAGED_PAGE_SIZE;
475
476#[derive(Debug, Clone, PartialEq, Eq)]
477pub struct PagedDwbEntry {
478    pub page_id: u32,
479    pub page: [u8; PAGED_PAGE_SIZE],
480}
481
482#[derive(Debug, Clone, PartialEq, Eq)]
483pub enum PagedDwbFrameError {
484    ShortHeader { got: usize },
485    InvalidMagic,
486    IncompleteFrame { expected: usize, got: usize },
487    ChecksumMismatch { expected: u32, actual: u32 },
488}
489
490impl fmt::Display for PagedDwbFrameError {
491    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
492        match self {
493            Self::ShortHeader { got } => write!(f, "DWB frame too short: got {got} bytes"),
494            Self::InvalidMagic => write!(f, "invalid DWB frame magic"),
495            Self::IncompleteFrame { expected, got } => {
496                write!(
497                    f,
498                    "incomplete DWB frame: expected {expected} bytes, got {got}"
499                )
500            }
501            Self::ChecksumMismatch { expected, actual } => write!(
502                f,
503                "DWB frame checksum mismatch: expected {expected}, actual {actual}"
504            ),
505        }
506    }
507}
508
509impl std::error::Error for PagedDwbFrameError {}
510
511pub fn encode_paged_dwb_header(count: u32, checksum: u32) -> [u8; PAGED_DWB_HEADER_SIZE] {
512    let mut header = [0; PAGED_DWB_HEADER_SIZE];
513    header[..4].copy_from_slice(&DWB_MAGIC);
514    header[4..8].copy_from_slice(&count.to_le_bytes());
515    header[8..12].copy_from_slice(&checksum.to_le_bytes());
516    header
517}
518
519pub fn decode_paged_dwb_header(bytes: &[u8]) -> Result<(u32, u32), PagedDwbFrameError> {
520    if bytes.len() < PAGED_DWB_HEADER_SIZE {
521        return Err(PagedDwbFrameError::ShortHeader { got: bytes.len() });
522    }
523    if bytes[..4] != DWB_MAGIC {
524        return Err(PagedDwbFrameError::InvalidMagic);
525    }
526    Ok((
527        u32::from_le_bytes(bytes[4..8].try_into().expect("header length checked")),
528        u32::from_le_bytes(bytes[8..12].try_into().expect("header length checked")),
529    ))
530}
531
532pub fn encode_paged_dwb_frame<'a>(
533    pages: impl IntoIterator<Item = (u32, &'a [u8; PAGED_PAGE_SIZE])>,
534) -> Vec<u8> {
535    let pages: Vec<_> = pages.into_iter().collect();
536    let total = PAGED_DWB_HEADER_SIZE + pages.len() * PAGED_DWB_ENTRY_SIZE;
537    let mut out = Vec::with_capacity(total);
538
539    out.extend_from_slice(&encode_paged_dwb_header(
540        u32::try_from(pages.len()).expect("DWB count fits u32"),
541        0,
542    ));
543
544    for (page_id, page) in pages {
545        out.extend_from_slice(&page_id.to_le_bytes());
546        out.extend_from_slice(page);
547    }
548
549    let checksum = crc32(&out[PAGED_DWB_HEADER_SIZE..]);
550    out[8..12].copy_from_slice(&checksum.to_le_bytes());
551    out
552}
553
554pub fn decode_paged_dwb_frame(bytes: &[u8]) -> Result<Vec<PagedDwbEntry>, PagedDwbFrameError> {
555    let (count, stored_checksum) = decode_paged_dwb_header(bytes)?;
556    let count = count as usize;
557    let expected_len = PAGED_DWB_HEADER_SIZE + count * PAGED_DWB_ENTRY_SIZE;
558    if bytes.len() < expected_len {
559        return Err(PagedDwbFrameError::IncompleteFrame {
560            expected: expected_len,
561            got: bytes.len(),
562        });
563    }
564
565    let actual_checksum = crc32(&bytes[PAGED_DWB_HEADER_SIZE..expected_len]);
566    if actual_checksum != stored_checksum {
567        return Err(PagedDwbFrameError::ChecksumMismatch {
568            expected: stored_checksum,
569            actual: actual_checksum,
570        });
571    }
572
573    let mut offset = PAGED_DWB_HEADER_SIZE;
574    let mut entries = Vec::with_capacity(count);
575    for _ in 0..count {
576        let page_id =
577            u32::from_le_bytes(bytes[offset..offset + 4].try_into().expect("len checked"));
578        offset += PAGED_DWB_ENTRY_HEADER_SIZE;
579        let mut page = [0u8; PAGED_PAGE_SIZE];
580        page.copy_from_slice(&bytes[offset..offset + PAGED_PAGE_SIZE]);
581        offset += PAGED_PAGE_SIZE;
582        entries.push(PagedDwbEntry { page_id, page });
583    }
584    Ok(entries)
585}
586
587fn crc32(data: &[u8]) -> u32 {
588    crc32fast::hash(data)
589}
590
591/// `b"RDCC"` — RedDB Columnar Chunk. Opens and closes every column block.
592pub const COLUMN_BLOCK_MAGIC: [u8; 4] = *b"RDCC";
593
594/// Column block on-disk format version.
595pub const COLUMN_BLOCK_VERSION_V1: u16 = 1;
596
597/// Reusable segment-level bloom frame v2 magic.
598pub const BLOOM_SEGMENT_V2_MAGIC: u8 = 0xC0;
599
600/// Legacy vector B-tree on-disk page format.
601pub const VECTOR_BTREE_FORMAT_VERSION_V1: u16 = 1;
602
603/// Current vector B-tree on-disk page format.
604pub const VECTOR_BTREE_FORMAT_VERSION_V2: u16 = 2;
605
606/// Vector B-tree format stamped into freshly-written page headers.
607pub const VECTOR_BTREE_FORMAT_VERSION: u16 = VECTOR_BTREE_FORMAT_VERSION_V2;
608
609/// Database file header information persisted in page 0 after the page header.
610#[derive(Debug, Clone, PartialEq, Eq)]
611pub struct DatabaseHeader {
612    pub version: u32,
613    pub page_size: u32,
614    pub page_count: u32,
615    pub freelist_head: u32,
616    pub schema_version: u32,
617    pub checkpoint_lsn: u64,
618    pub checkpoint_in_progress: bool,
619    pub checkpoint_target_lsn: u64,
620    /// Monotonic set of byte-level features required to decode this file.
621    pub required_capabilities: u64,
622    pub physical: PhysicalFileHeader,
623}
624
625impl DatabaseHeader {
626    pub fn is_recovery_read_only(&self) -> bool {
627        self.version == PAGE_RECOVERY_READ_ONLY_FILE_VERSION
628            || self.required_capabilities & FILE_CAPABILITY_RECOVERY_READ_ONLY != 0
629    }
630
631    /// Whether the file requires a writer that participates in the bounded
632    /// disk-residency protocol.
633    ///
634    /// Versions before the capability bitmap encoded that requirement in the
635    /// monotonically increasing version number. Newer files declare it as an
636    /// independent capability so unrelated codecs can evolve the format.
637    pub fn requires_disk_residency(&self) -> bool {
638        if self.version < PAGE_REQUIRED_CAPABILITIES_FILE_VERSION {
639            page_format_is_disk_resident(self.version)
640        } else {
641            self.required_capabilities & FILE_CAPABILITY_DISK_RESIDENCY != 0
642        }
643    }
644}
645
646impl Default for DatabaseHeader {
647    fn default() -> Self {
648        Self {
649            // Prepared disk residency is an explicit host opt-in.
650            version: PAGE_CHECKPOINT_UNDO_FILE_VERSION,
651            page_size: PAGED_PAGE_SIZE as u32,
652            page_count: 1,
653            freelist_head: 0,
654            schema_version: 0,
655            checkpoint_lsn: 0,
656            checkpoint_in_progress: false,
657            checkpoint_target_lsn: 0,
658            required_capabilities: 0,
659            physical: PhysicalFileHeader::default(),
660        }
661    }
662}
663
664/// Minimal physical state mirrored into page 0 for paged databases.
665///
666/// The pager owns when this is read and written, but the field layout is a
667/// durable file compatibility contract.
668#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
669pub struct PhysicalFileHeader {
670    pub format_version: u32,
671    pub sequence: u64,
672    pub manifest_oldest_root: u64,
673    pub manifest_root: u64,
674    pub free_set_root: u64,
675    pub manifest_page: u32,
676    pub manifest_checksum: u64,
677    pub collection_roots_page: u32,
678    pub collection_roots_checksum: u64,
679    pub collection_root_count: u32,
680    pub snapshot_count: u32,
681    pub index_count: u32,
682    pub catalog_collection_count: u32,
683    pub catalog_total_entities: u64,
684    pub export_count: u32,
685    pub graph_projection_count: u32,
686    pub analytics_job_count: u32,
687    pub manifest_event_count: u32,
688    pub registry_page: u32,
689    pub registry_checksum: u64,
690    pub recovery_page: u32,
691    pub recovery_checksum: u64,
692    pub catalog_page: u32,
693    pub catalog_checksum: u64,
694    pub metadata_state_page: u32,
695    pub metadata_state_checksum: u64,
696    pub vector_artifact_page: u32,
697    pub vector_artifact_checksum: u64,
698}
699
700#[derive(Debug, Clone, PartialEq, Eq)]
701pub enum DatabaseHeaderError {
702    ShortPage { need: usize, got: usize },
703    InvalidMagic,
704    UnsupportedPageSize(u32),
705    UnsupportedDatabaseVersion { file_version: u32, supported: u32 },
706    UnsupportedRequiredCapabilities(u64),
707}
708
709impl fmt::Display for DatabaseHeaderError {
710    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
711        match self {
712            Self::ShortPage { need, got } => {
713                write!(f, "database header page too short: need {need} bytes, got {got}")
714            }
715            Self::InvalidMagic => write!(f, "invalid database header magic"),
716            Self::UnsupportedPageSize(size) => write!(f, "Unsupported page size: {size}"),
717            Self::UnsupportedDatabaseVersion {
718                file_version,
719                supported,
720            } => write!(
721                f,
722                "Unsupported database version: file version {file_version} is newer than supported {supported}"
723            ),
724            Self::UnsupportedRequiredCapabilities(bits) => write!(
725                f,
726                "Unsupported required database capabilities: {bits:#018x}"
727            ),
728        }
729    }
730}
731
732impl std::error::Error for DatabaseHeaderError {}
733
734/// Errors in the independently published catalog and recovery extensions.
735/// Keeping these separate preserves exhaustive matches on `DatabaseHeaderError`.
736#[derive(Debug, Clone, PartialEq, Eq)]
737#[non_exhaustive]
738pub enum HeaderPublicationError {
739    Header(DatabaseHeaderError),
740    InvalidManifestReference,
741    InvalidDwbPublication,
742}
743
744impl From<DatabaseHeaderError> for HeaderPublicationError {
745    fn from(error: DatabaseHeaderError) -> Self {
746        Self::Header(error)
747    }
748}
749
750impl fmt::Display for HeaderPublicationError {
751    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
752        match self {
753            Self::Header(error) => error.fmt(f),
754            Self::InvalidManifestReference => write!(f, "invalid catalog generation reference"),
755            Self::InvalidDwbPublication => write!(f, "invalid DWB generation publication"),
756        }
757    }
758}
759
760impl std::error::Error for HeaderPublicationError {
761    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
762        match self {
763            Self::Header(error) => Some(error),
764            _ => None,
765        }
766    }
767}
768
769pub fn database_header_magic_matches(page: &[u8]) -> bool {
770    page.get(DB_MAGIC_OFFSET..DB_MAGIC_OFFSET + PAGE_FILE_MAGIC.len()) == Some(&PAGE_FILE_MAGIC)
771}
772
773pub fn init_database_header_page(
774    page: &mut [u8],
775    page_count: u32,
776) -> Result<(), DatabaseHeaderError> {
777    encode_database_header(
778        page,
779        &DatabaseHeader {
780            page_count,
781            ..DatabaseHeader::default()
782        },
783    )
784}
785
786pub fn database_header_page_count(page: &[u8]) -> Result<u32, DatabaseHeaderError> {
787    read_u32(page, DB_PAGE_COUNT_OFFSET)
788}
789
790pub fn set_database_header_version(
791    page: &mut [u8],
792    version: u32,
793) -> Result<(), DatabaseHeaderError> {
794    write_u32(page, DB_VERSION_OFFSET, version)
795}
796
797pub fn set_database_header_page_count(
798    page: &mut [u8],
799    page_count: u32,
800) -> Result<(), DatabaseHeaderError> {
801    write_u32(page, DB_PAGE_COUNT_OFFSET, page_count)
802}
803
804pub fn database_header_freelist_head(page: &[u8]) -> Result<u32, DatabaseHeaderError> {
805    read_u32(page, DB_FREELIST_HEAD_OFFSET)
806}
807
808pub fn set_database_header_freelist_head(
809    page: &mut [u8],
810    page_id: u32,
811) -> Result<(), DatabaseHeaderError> {
812    write_u32(page, DB_FREELIST_HEAD_OFFSET, page_id)
813}
814
815pub fn set_database_header_required_capabilities(
816    page: &mut [u8],
817    capabilities: u64,
818) -> Result<(), DatabaseHeaderError> {
819    write_u64(page, DB_REQUIRED_CAPABILITIES_OFFSET, capabilities)
820}
821
822pub fn set_database_header_manifest_reference(
823    page: &mut [u8],
824    reference: crate::page_proof::PageReference,
825) -> Result<(), HeaderPublicationError> {
826    ensure_len(page, DB_MANIFEST_REFERENCE_END)?;
827    if (reference.page_id == 0) != (reference.digest == [0; 32]) {
828        return Err(HeaderPublicationError::InvalidManifestReference);
829    }
830    crate::page_proof::encode_reference(
831        &mut page[DB_MANIFEST_REFERENCE_OFFSET..DB_MANIFEST_REFERENCE_END],
832        reference,
833    );
834    Ok(())
835}
836
837/// Digest over the catalog root and all continuation pages. The zero reference
838/// retains the legacy fixed page-1 bootstrap catalog. Storage owners validate
839/// this extension before recovery can modify the file.
840pub fn database_header_manifest_reference(
841    page: &[u8],
842) -> Result<crate::page_proof::PageReference, HeaderPublicationError> {
843    let header = decode_database_header_fields(page, FILE_CAPABILITIES_SUPPORTED)?;
844    if header.required_capabilities & FILE_CAPABILITY_CATALOG_ROOT == 0 {
845        return Ok(crate::page_proof::PageReference::default());
846    }
847    ensure_len(page, DB_MANIFEST_REFERENCE_END)?;
848    crate::page_proof::decode_reference(
849        &page[DB_MANIFEST_REFERENCE_OFFSET..DB_MANIFEST_REFERENCE_END],
850    )
851    .ok_or(HeaderPublicationError::InvalidManifestReference)
852}
853
854pub fn database_header_page_size(page: &[u8]) -> Result<u32, DatabaseHeaderError> {
855    read_u32(page, DB_PAGE_SIZE_OFFSET)
856}
857
858/// Decode the legacy header contract. Engines implementing publication-aware
859/// recovery must explicitly opt into [`decode_published_database_header`].
860pub fn decode_database_header(page: &[u8]) -> Result<DatabaseHeader, DatabaseHeaderError> {
861    decode_database_header_fields(page, FILE_CAPABILITIES_LEGACY_HEADER)
862}
863
864/// Validate the ordinary header and its required catalog/recovery publications.
865/// Only storage owners that implement those protocols should use this entry point.
866pub fn decode_published_database_header(
867    page: &[u8],
868) -> Result<DatabaseHeader, HeaderPublicationError> {
869    let header = decode_database_header_fields(page, FILE_CAPABILITIES_SUPPORTED)?;
870    database_header_manifest_reference(page)?;
871    if header.required_capabilities & FILE_CAPABILITY_DWB_PUBLICATION != 0 {
872        database_header_dwb_publication(page)?;
873    }
874    Ok(header)
875}
876
877fn decode_database_header_fields(
878    page: &[u8],
879    supported_capabilities: u64,
880) -> Result<DatabaseHeader, DatabaseHeaderError> {
881    ensure_len(page, DB_HEADER_MIN_LEN)?;
882    if !database_header_magic_matches(page) {
883        return Err(DatabaseHeaderError::InvalidMagic);
884    }
885
886    let version = read_u32(page, DB_VERSION_OFFSET)?;
887    let page_size = read_u32(page, DB_PAGE_SIZE_OFFSET)?;
888    if page_size != PAGED_PAGE_SIZE as u32 {
889        return Err(DatabaseHeaderError::UnsupportedPageSize(page_size));
890    }
891    if version > PAGE_FILE_VERSION {
892        return Err(DatabaseHeaderError::UnsupportedDatabaseVersion {
893            file_version: version,
894            supported: PAGE_FILE_VERSION,
895        });
896    }
897    let required_capabilities = if version >= PAGE_REQUIRED_CAPABILITIES_FILE_VERSION {
898        read_u64(page, DB_REQUIRED_CAPABILITIES_OFFSET)?
899    } else {
900        0
901    };
902    let unsupported_capabilities = required_capabilities & !supported_capabilities;
903    if unsupported_capabilities != 0 {
904        return Err(DatabaseHeaderError::UnsupportedRequiredCapabilities(
905            unsupported_capabilities,
906        ));
907    }
908    Ok(DatabaseHeader {
909        version,
910        page_size,
911        page_count: read_u32(page, DB_PAGE_COUNT_OFFSET)?,
912        freelist_head: read_u32(page, DB_FREELIST_HEAD_OFFSET)?,
913        schema_version: read_u32(page, DB_SCHEMA_VERSION_OFFSET)?,
914        checkpoint_lsn: read_u64(page, DB_CHECKPOINT_LSN_OFFSET)?,
915        checkpoint_in_progress: page[DB_CHECKPOINT_IN_PROGRESS_OFFSET] != 0,
916        checkpoint_target_lsn: read_u64(page, DB_CHECKPOINT_TARGET_LSN_OFFSET)?,
917        required_capabilities,
918        physical: PhysicalFileHeader {
919            format_version: read_u32(page, DB_PHYSICAL_FORMAT_VERSION_OFFSET)?,
920            sequence: read_u64(page, DB_PHYSICAL_SEQUENCE_OFFSET)?,
921            manifest_oldest_root: read_u64(page, DB_MANIFEST_OLDEST_ROOT_OFFSET)?,
922            manifest_root: read_u64(page, DB_MANIFEST_ROOT_OFFSET)?,
923            free_set_root: read_u64(page, DB_FREE_SET_ROOT_OFFSET)?,
924            manifest_page: read_u32(page, DB_MANIFEST_PAGE_OFFSET)?,
925            manifest_checksum: read_u64(page, DB_MANIFEST_CHECKSUM_OFFSET)?,
926            collection_roots_page: read_u32(page, DB_COLLECTION_ROOTS_PAGE_OFFSET)?,
927            collection_roots_checksum: read_u64(page, DB_COLLECTION_ROOTS_CHECKSUM_OFFSET)?,
928            collection_root_count: read_u32(page, DB_COLLECTION_ROOT_COUNT_OFFSET)?,
929            snapshot_count: read_u32(page, DB_SNAPSHOT_COUNT_OFFSET)?,
930            index_count: read_u32(page, DB_INDEX_COUNT_OFFSET)?,
931            catalog_collection_count: read_u32(page, DB_CATALOG_COLLECTION_COUNT_OFFSET)?,
932            catalog_total_entities: read_u64(page, DB_CATALOG_TOTAL_ENTITIES_OFFSET)?,
933            export_count: read_u32(page, DB_EXPORT_COUNT_OFFSET)?,
934            graph_projection_count: read_u32(page, DB_GRAPH_PROJECTION_COUNT_OFFSET)?,
935            analytics_job_count: read_u32(page, DB_ANALYTICS_JOB_COUNT_OFFSET)?,
936            manifest_event_count: read_u32(page, DB_MANIFEST_EVENT_COUNT_OFFSET)?,
937            registry_page: read_u32(page, DB_REGISTRY_PAGE_OFFSET)?,
938            registry_checksum: read_u64(page, DB_REGISTRY_CHECKSUM_OFFSET)?,
939            recovery_page: read_u32(page, DB_RECOVERY_PAGE_OFFSET)?,
940            recovery_checksum: read_u64(page, DB_RECOVERY_CHECKSUM_OFFSET)?,
941            catalog_page: read_u32(page, DB_CATALOG_PAGE_OFFSET)?,
942            catalog_checksum: read_u64(page, DB_CATALOG_CHECKSUM_OFFSET)?,
943            metadata_state_page: read_u32(page, DB_METADATA_STATE_PAGE_OFFSET)?,
944            metadata_state_checksum: read_u64(page, DB_METADATA_STATE_CHECKSUM_OFFSET)?,
945            vector_artifact_page: read_u32(page, DB_VECTOR_ARTIFACT_PAGE_OFFSET)?,
946            vector_artifact_checksum: read_u64(page, DB_VECTOR_ARTIFACT_CHECKSUM_OFFSET)?,
947        },
948    })
949}
950
951pub fn encode_database_header(
952    page: &mut [u8],
953    header: &DatabaseHeader,
954) -> Result<(), DatabaseHeaderError> {
955    ensure_len(page, DB_HEADER_MIN_LEN)?;
956    page[DB_MAGIC_OFFSET..DB_MAGIC_OFFSET + PAGE_FILE_MAGIC.len()]
957        .copy_from_slice(&PAGE_FILE_MAGIC);
958    write_u32(page, DB_VERSION_OFFSET, header.version)?;
959    write_u32(page, DB_PAGE_SIZE_OFFSET, header.page_size)?;
960    write_u32(page, DB_PAGE_COUNT_OFFSET, header.page_count)?;
961    write_u32(page, DB_FREELIST_HEAD_OFFSET, header.freelist_head)?;
962    write_u32(page, DB_SCHEMA_VERSION_OFFSET, header.schema_version)?;
963    write_u64(page, DB_CHECKPOINT_LSN_OFFSET, header.checkpoint_lsn)?;
964    write_u32(
965        page,
966        DB_PHYSICAL_FORMAT_VERSION_OFFSET,
967        header.physical.format_version,
968    )?;
969    write_u64(page, DB_PHYSICAL_SEQUENCE_OFFSET, header.physical.sequence)?;
970    write_u64(page, DB_MANIFEST_ROOT_OFFSET, header.physical.manifest_root)?;
971    write_u64(
972        page,
973        DB_MANIFEST_OLDEST_ROOT_OFFSET,
974        header.physical.manifest_oldest_root,
975    )?;
976    write_u64(page, DB_FREE_SET_ROOT_OFFSET, header.physical.free_set_root)?;
977    write_u32(page, DB_MANIFEST_PAGE_OFFSET, header.physical.manifest_page)?;
978    write_u64(
979        page,
980        DB_MANIFEST_CHECKSUM_OFFSET,
981        header.physical.manifest_checksum,
982    )?;
983    write_u32(
984        page,
985        DB_COLLECTION_ROOTS_PAGE_OFFSET,
986        header.physical.collection_roots_page,
987    )?;
988    write_u64(
989        page,
990        DB_COLLECTION_ROOTS_CHECKSUM_OFFSET,
991        header.physical.collection_roots_checksum,
992    )?;
993    write_u32(
994        page,
995        DB_COLLECTION_ROOT_COUNT_OFFSET,
996        header.physical.collection_root_count,
997    )?;
998    write_u32(
999        page,
1000        DB_SNAPSHOT_COUNT_OFFSET,
1001        header.physical.snapshot_count,
1002    )?;
1003    write_u32(page, DB_INDEX_COUNT_OFFSET, header.physical.index_count)?;
1004    write_u32(
1005        page,
1006        DB_CATALOG_COLLECTION_COUNT_OFFSET,
1007        header.physical.catalog_collection_count,
1008    )?;
1009    write_u64(
1010        page,
1011        DB_CATALOG_TOTAL_ENTITIES_OFFSET,
1012        header.physical.catalog_total_entities,
1013    )?;
1014    write_u32(page, DB_EXPORT_COUNT_OFFSET, header.physical.export_count)?;
1015    write_u32(
1016        page,
1017        DB_GRAPH_PROJECTION_COUNT_OFFSET,
1018        header.physical.graph_projection_count,
1019    )?;
1020    write_u32(
1021        page,
1022        DB_ANALYTICS_JOB_COUNT_OFFSET,
1023        header.physical.analytics_job_count,
1024    )?;
1025    write_u32(
1026        page,
1027        DB_MANIFEST_EVENT_COUNT_OFFSET,
1028        header.physical.manifest_event_count,
1029    )?;
1030    write_u32(page, DB_REGISTRY_PAGE_OFFSET, header.physical.registry_page)?;
1031    write_u64(
1032        page,
1033        DB_REGISTRY_CHECKSUM_OFFSET,
1034        header.physical.registry_checksum,
1035    )?;
1036    write_u32(page, DB_RECOVERY_PAGE_OFFSET, header.physical.recovery_page)?;
1037    write_u64(
1038        page,
1039        DB_RECOVERY_CHECKSUM_OFFSET,
1040        header.physical.recovery_checksum,
1041    )?;
1042    write_u32(page, DB_CATALOG_PAGE_OFFSET, header.physical.catalog_page)?;
1043    write_u64(
1044        page,
1045        DB_CATALOG_CHECKSUM_OFFSET,
1046        header.physical.catalog_checksum,
1047    )?;
1048    write_u32(
1049        page,
1050        DB_METADATA_STATE_PAGE_OFFSET,
1051        header.physical.metadata_state_page,
1052    )?;
1053    write_u64(
1054        page,
1055        DB_METADATA_STATE_CHECKSUM_OFFSET,
1056        header.physical.metadata_state_checksum,
1057    )?;
1058    write_u32(
1059        page,
1060        DB_VECTOR_ARTIFACT_PAGE_OFFSET,
1061        header.physical.vector_artifact_page,
1062    )?;
1063    write_u64(
1064        page,
1065        DB_VECTOR_ARTIFACT_CHECKSUM_OFFSET,
1066        header.physical.vector_artifact_checksum,
1067    )?;
1068    page[DB_CHECKPOINT_IN_PROGRESS_OFFSET] = if header.checkpoint_in_progress { 1 } else { 0 };
1069    write_u64(
1070        page,
1071        DB_CHECKPOINT_TARGET_LSN_OFFSET,
1072        header.checkpoint_target_lsn,
1073    )?;
1074    write_u64(
1075        page,
1076        DB_REQUIRED_CAPABILITIES_OFFSET,
1077        header.required_capabilities,
1078    )?;
1079    // Independently published catalog and DWB authority carry forward from the
1080    // newest slot; an ordinary header update must not replace either extension.
1081    Ok(())
1082}
1083
1084// ── Paged superblock zone (ADR 0038 §2 phase 1) ─────────────────────────
1085//
1086// The first two sectors of a paged `.rdb` are the superblock zone: a
1087// ping-pong pair of fixed-size slots. Each slot holds the page-0 image (page
1088// header + database header + encryption header) followed by a trailer that
1089// carries the slot's copy index, generation counter and CRC.
1090//
1091// An update always writes the *older* slot and fsyncs before it becomes the
1092// newest valid copy, so a crash mid-write can only ever damage the copy that
1093// was already stale. `select_paged_superblock` picks the highest generation
1094// whose CRC verifies; both invalid means the store does not open.
1095//
1096// The zone lives inside page 0's 16 KiB, whose tail was unused. Page 0 is
1097// therefore no longer a checksummed `Page` — the slot CRCs are its integrity
1098// contract.
1099
1100/// Bytes per superblock slot. Sector-aligned so one slot write never touches
1101/// its sibling.
1102pub const PAGED_SUPERBLOCK_SLOT_SIZE: usize = 4096;
1103
1104/// The ping-pong pair.
1105pub const PAGED_SUPERBLOCK_SLOT_COUNT: usize = 2;
1106
1107/// Total bytes reserved for the superblock zone at the head of the file.
1108pub const PAGED_SUPERBLOCK_ZONE_SIZE: usize =
1109    PAGED_SUPERBLOCK_SLOT_SIZE * PAGED_SUPERBLOCK_SLOT_COUNT;
1110
1111const PAGED_SUPERBLOCK_MAGIC: [u8; 8] = *b"RDBPSBK1";
1112const PAGED_SUPERBLOCK_SLOT_VERSION: u32 = 1;
1113
1114/// Offset of the trailer within a slot: magic(8) ‖ version(4) ‖ copy(4) ‖
1115/// generation(8) ‖ crc(4) ‖ reserved(4). Everything before it is the page-0
1116/// image, which is why the offline migration tool can strip the trailer to
1117/// recover the sidecar-era page 0 byte for byte.
1118pub const PAGED_SUPERBLOCK_TRAILER_OFFSET: usize = PAGED_SUPERBLOCK_SLOT_SIZE - 32;
1119const PAGED_SUPERBLOCK_VERSION_OFFSET: usize = PAGED_SUPERBLOCK_TRAILER_OFFSET + 8;
1120const PAGED_SUPERBLOCK_COPY_OFFSET: usize = PAGED_SUPERBLOCK_TRAILER_OFFSET + 12;
1121const PAGED_SUPERBLOCK_GENERATION_OFFSET: usize = PAGED_SUPERBLOCK_TRAILER_OFFSET + 16;
1122const PAGED_SUPERBLOCK_CRC_OFFSET: usize = PAGED_SUPERBLOCK_TRAILER_OFFSET + 24;
1123
1124/// The newest valid copy found in a superblock zone.
1125#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1126pub struct PagedSuperblockSelection {
1127    pub copy_index: usize,
1128    pub generation: u64,
1129}
1130
1131/// Byte offset of `copy_index`'s slot from the start of the file.
1132pub fn paged_superblock_slot_offset(copy_index: usize) -> u64 {
1133    (copy_index % PAGED_SUPERBLOCK_SLOT_COUNT) as u64 * PAGED_SUPERBLOCK_SLOT_SIZE as u64
1134}
1135
1136/// The copy a fresh update must target: always the one that is *not* newest,
1137/// so the newest durable copy survives a crash during the write.
1138pub fn paged_superblock_next_copy(newest: Option<PagedSuperblockSelection>) -> usize {
1139    match newest {
1140        Some(selection) => (selection.copy_index + 1) % PAGED_SUPERBLOCK_SLOT_COUNT,
1141        None => 0,
1142    }
1143}
1144
1145/// Stamp `slot`'s trailer (copy index, generation) and seal it with a CRC over
1146/// everything that precedes the checksum field.
1147pub fn seal_paged_superblock_slot(
1148    slot: &mut [u8],
1149    copy_index: usize,
1150    generation: u64,
1151) -> Result<(), DatabaseHeaderError> {
1152    ensure_len(slot, PAGED_SUPERBLOCK_SLOT_SIZE)?;
1153    slot[PAGED_SUPERBLOCK_TRAILER_OFFSET..PAGED_SUPERBLOCK_TRAILER_OFFSET + 8]
1154        .copy_from_slice(&PAGED_SUPERBLOCK_MAGIC);
1155    write_u32(
1156        slot,
1157        PAGED_SUPERBLOCK_VERSION_OFFSET,
1158        PAGED_SUPERBLOCK_SLOT_VERSION,
1159    )?;
1160    write_u32(
1161        slot,
1162        PAGED_SUPERBLOCK_COPY_OFFSET,
1163        u32::try_from(copy_index).unwrap_or(u32::MAX),
1164    )?;
1165    write_u64(slot, PAGED_SUPERBLOCK_GENERATION_OFFSET, generation)?;
1166    let crc = paged_superblock_crc(&slot[..PAGED_SUPERBLOCK_CRC_OFFSET]);
1167    write_u32(slot, PAGED_SUPERBLOCK_CRC_OFFSET, crc)?;
1168    // The 4 trailing reserved bytes stay zero.
1169    write_u32(slot, PAGED_SUPERBLOCK_CRC_OFFSET + 4, 0)
1170}
1171
1172/// Decode `slot`'s generation, or `None` when the slot was never written, is
1173/// torn, carries a foreign copy index, or fails its CRC.
1174pub fn paged_superblock_slot_generation(slot: &[u8], copy_index: usize) -> Option<u64> {
1175    if slot.len() < PAGED_SUPERBLOCK_SLOT_SIZE {
1176        return None;
1177    }
1178    if slot[PAGED_SUPERBLOCK_TRAILER_OFFSET..PAGED_SUPERBLOCK_TRAILER_OFFSET + 8]
1179        != PAGED_SUPERBLOCK_MAGIC
1180    {
1181        return None;
1182    }
1183    if read_u32(slot, PAGED_SUPERBLOCK_VERSION_OFFSET).ok()? != PAGED_SUPERBLOCK_SLOT_VERSION {
1184        return None;
1185    }
1186    // A slot that names a different copy is a misdirected write, not a
1187    // legitimately older generation.
1188    if read_u32(slot, PAGED_SUPERBLOCK_COPY_OFFSET).ok()? != u32::try_from(copy_index).ok()? {
1189        return None;
1190    }
1191    let stored = read_u32(slot, PAGED_SUPERBLOCK_CRC_OFFSET).ok()?;
1192    if paged_superblock_crc(&slot[..PAGED_SUPERBLOCK_CRC_OFFSET]) != stored {
1193        return None;
1194    }
1195    read_u64(slot, PAGED_SUPERBLOCK_GENERATION_OFFSET).ok()
1196}
1197
1198/// Pick the newest valid copy in a full superblock zone. `None` means both
1199/// copies are invalid: the caller must refuse to open the store.
1200pub fn select_paged_superblock(zone: &[u8]) -> Option<PagedSuperblockSelection> {
1201    (0..PAGED_SUPERBLOCK_SLOT_COUNT)
1202        .filter_map(|copy_index| {
1203            let start = copy_index * PAGED_SUPERBLOCK_SLOT_SIZE;
1204            let slot = zone.get(start..start + PAGED_SUPERBLOCK_SLOT_SIZE)?;
1205            Some(PagedSuperblockSelection {
1206                copy_index,
1207                generation: paged_superblock_slot_generation(slot, copy_index)?,
1208            })
1209        })
1210        .max_by_key(|selection| selection.generation)
1211}
1212
1213fn paged_superblock_crc(bytes: &[u8]) -> u32 {
1214    let mut hasher = crc32fast::Hasher::new();
1215    hasher.update(bytes);
1216    hasher.finalize()
1217}
1218
1219fn ensure_len(bytes: &[u8], need: usize) -> Result<(), DatabaseHeaderError> {
1220    if bytes.len() < need {
1221        return Err(DatabaseHeaderError::ShortPage {
1222            need,
1223            got: bytes.len(),
1224        });
1225    }
1226    Ok(())
1227}
1228
1229fn read_u32(bytes: &[u8], offset: usize) -> Result<u32, DatabaseHeaderError> {
1230    ensure_len(bytes, offset + 4)?;
1231    Ok(u32::from_le_bytes(
1232        bytes[offset..offset + 4].try_into().expect("len checked"),
1233    ))
1234}
1235
1236fn read_u16(bytes: &[u8], offset: usize) -> Result<u16, DatabaseHeaderError> {
1237    ensure_len(bytes, offset + 2)?;
1238    Ok(u16::from_le_bytes(
1239        bytes[offset..offset + 2].try_into().expect("len checked"),
1240    ))
1241}
1242
1243fn read_u64(bytes: &[u8], offset: usize) -> Result<u64, DatabaseHeaderError> {
1244    ensure_len(bytes, offset + 8)?;
1245    Ok(u64::from_le_bytes(
1246        bytes[offset..offset + 8].try_into().expect("len checked"),
1247    ))
1248}
1249
1250fn write_u32(bytes: &mut [u8], offset: usize, value: u32) -> Result<(), DatabaseHeaderError> {
1251    ensure_len(bytes, offset + 4)?;
1252    bytes[offset..offset + 4].copy_from_slice(&value.to_le_bytes());
1253    Ok(())
1254}
1255
1256fn write_u16(bytes: &mut [u8], offset: usize, value: u16) -> Result<(), DatabaseHeaderError> {
1257    ensure_len(bytes, offset + 2)?;
1258    bytes[offset..offset + 2].copy_from_slice(&value.to_le_bytes());
1259    Ok(())
1260}
1261
1262fn write_u64(bytes: &mut [u8], offset: usize, value: u64) -> Result<(), DatabaseHeaderError> {
1263    ensure_len(bytes, offset + 8)?;
1264    bytes[offset..offset + 8].copy_from_slice(&value.to_le_bytes());
1265    Ok(())
1266}
1267
1268#[cfg(test)]
1269mod tests {
1270    use super::*;
1271
1272    fn sealed_zone(gen_a: Option<u64>, gen_b: Option<u64>) -> Vec<u8> {
1273        let mut zone = vec![0u8; PAGED_SUPERBLOCK_ZONE_SIZE];
1274        for (copy_index, generation) in [gen_a, gen_b].into_iter().enumerate() {
1275            let Some(generation) = generation else {
1276                continue;
1277            };
1278            let start = copy_index * PAGED_SUPERBLOCK_SLOT_SIZE;
1279            let slot = &mut zone[start..start + PAGED_SUPERBLOCK_SLOT_SIZE];
1280            init_database_header_page(slot, 3).expect("init header");
1281            seal_paged_superblock_slot(slot, copy_index, generation).expect("seal slot");
1282        }
1283        zone
1284    }
1285
1286    #[test]
1287    fn superblock_zone_fits_two_sector_aligned_slots_before_page_one() {
1288        assert_eq!(PAGED_SUPERBLOCK_SLOT_SIZE, 4096);
1289        assert_eq!(PAGED_SUPERBLOCK_ZONE_SIZE, 8192);
1290        // Both slots live inside page 0, so page 1 is never touched by a
1291        // superblock update.
1292        assert!(PAGED_SUPERBLOCK_ZONE_SIZE <= PAGED_PAGE_SIZE);
1293        // The database header must not overrun into the slot trailer.
1294        assert!(DB_HEADER_MIN_LEN < PAGED_SUPERBLOCK_TRAILER_OFFSET);
1295        assert_eq!(paged_superblock_slot_offset(0), 0);
1296        assert_eq!(paged_superblock_slot_offset(1), 4096);
1297    }
1298
1299    #[test]
1300    fn sealed_slot_round_trips_generation_and_keeps_the_header_readable() {
1301        let mut slot = vec![0u8; PAGED_SUPERBLOCK_SLOT_SIZE];
1302        init_database_header_page(&mut slot, 7).expect("init header");
1303        seal_paged_superblock_slot(&mut slot, 1, 42).expect("seal slot");
1304
1305        assert_eq!(paged_superblock_slot_generation(&slot, 1), Some(42));
1306        assert_eq!(
1307            database_header_page_count(&slot).expect("database_header_page_count() should succeed"),
1308            7
1309        );
1310    }
1311
1312    #[test]
1313    fn selection_prefers_the_newest_valid_copy_and_survives_one_torn_slot() {
1314        let zone = sealed_zone(Some(4), Some(5));
1315        assert_eq!(
1316            select_paged_superblock(&zone),
1317            Some(PagedSuperblockSelection {
1318                copy_index: 1,
1319                generation: 5
1320            })
1321        );
1322
1323        // Tear the newer copy: open falls back to the older intact one.
1324        let mut torn = zone.clone();
1325        torn[PAGED_SUPERBLOCK_SLOT_SIZE + 64] ^= 0xFF;
1326        assert_eq!(
1327            select_paged_superblock(&torn),
1328            Some(PagedSuperblockSelection {
1329                copy_index: 0,
1330                generation: 4
1331            })
1332        );
1333    }
1334
1335    #[test]
1336    fn a_misdirected_slot_copy_is_rejected_not_read_as_an_older_generation() {
1337        // Slot 0's bytes written at slot 1's offset: right data, wrong place.
1338        let zone = sealed_zone(Some(9), None);
1339        let (slot_zero, _) = zone.split_at(PAGED_SUPERBLOCK_SLOT_SIZE);
1340        assert_eq!(paged_superblock_slot_generation(slot_zero, 1), None);
1341    }
1342
1343    #[test]
1344    fn both_copies_invalid_yields_no_selection() {
1345        assert_eq!(
1346            select_paged_superblock(&vec![0u8; PAGED_SUPERBLOCK_ZONE_SIZE]),
1347            None
1348        );
1349        assert_eq!(select_paged_superblock(&[]), None);
1350
1351        let mut zone = sealed_zone(Some(1), Some(2));
1352        zone[64] ^= 0xFF;
1353        zone[PAGED_SUPERBLOCK_SLOT_SIZE + 64] ^= 0xFF;
1354        assert_eq!(select_paged_superblock(&zone), None);
1355    }
1356
1357    #[test]
1358    fn the_next_copy_to_write_is_always_the_stale_one() {
1359        assert_eq!(paged_superblock_next_copy(None), 0);
1360        assert_eq!(
1361            paged_superblock_next_copy(Some(PagedSuperblockSelection {
1362                copy_index: 0,
1363                generation: 3
1364            })),
1365            1
1366        );
1367        assert_eq!(
1368            paged_superblock_next_copy(Some(PagedSuperblockSelection {
1369                copy_index: 1,
1370                generation: 3
1371            })),
1372            0
1373        );
1374    }
1375
1376    #[test]
1377    fn bit_rot_anywhere_in_the_slot_payload_fails_the_crc() {
1378        let mut slot = vec![0u8; PAGED_SUPERBLOCK_SLOT_SIZE];
1379        init_database_header_page(&mut slot, 3).expect("init header");
1380        seal_paged_superblock_slot(&mut slot, 0, 1).expect("seal slot");
1381
1382        for offset in [
1383            0,
1384            40,
1385            DB_HEADER_MIN_LEN - 1,
1386            PAGED_SUPERBLOCK_SLOT_SIZE - 33,
1387        ] {
1388            let mut rotted = slot.clone();
1389            rotted[offset] ^= 0x01;
1390            assert_eq!(
1391                paged_superblock_slot_generation(&rotted, 0),
1392                None,
1393                "bit rot at offset {offset} must fail the slot CRC"
1394            );
1395        }
1396    }
1397
1398    #[test]
1399    fn paged_page_header_round_trips_raw_layout() {
1400        let header = PagedPageHeader {
1401            page_type: 13,
1402            flags: 0b1010_0001,
1403            cell_count: 42,
1404            free_start: 44,
1405            free_end: 16_000,
1406            page_id: 99,
1407            parent_id: 88,
1408            right_child: 77,
1409            lsn: 66,
1410            checksum: 55,
1411        };
1412
1413        let encoded = encode_paged_page_header(&header);
1414
1415        assert_eq!(encoded.len(), PAGED_PAGE_HEADER_SIZE);
1416        assert_eq!(decode_paged_page_header(&encoded), header);
1417    }
1418
1419    #[test]
1420    fn paged_page_header_accessors_update_expected_offsets() {
1421        let mut page = [0u8; PAGED_PAGE_SIZE];
1422        page[0] = 13;
1423
1424        set_paged_page_cell_count(&mut page, 2);
1425        set_paged_page_free_start(&mut page, 34);
1426        set_paged_page_free_end(&mut page, 4096);
1427        set_paged_page_parent_id(&mut page, 7);
1428        set_paged_page_right_child(&mut page, 8);
1429        set_paged_page_lsn(&mut page, 9);
1430        set_paged_page_checksum(&mut page, 10);
1431
1432        assert_eq!(paged_page_type(&page), 13);
1433        assert_eq!(paged_page_cell_count(&page), 2);
1434        assert_eq!(paged_page_free_start(&page), 34);
1435        assert_eq!(paged_page_free_end(&page), 4096);
1436        assert_eq!(paged_page_parent_id(&page), 7);
1437        assert_eq!(paged_page_right_child(&page), 8);
1438        assert_eq!(paged_page_lsn(&page), 9);
1439        assert_eq!(paged_page_checksum(&page), 10);
1440        clear_paged_page_checksum(&mut page);
1441        assert_eq!(paged_page_checksum(&page), 0);
1442    }
1443
1444    #[test]
1445    fn paged_cell_helpers_round_trip_pointer_and_payload() {
1446        let mut page = [0u8; PAGED_PAGE_SIZE];
1447        let pointer = (PAGED_PAGE_SIZE - 14) as u16;
1448
1449        assert!(write_paged_cell(&mut page, pointer, b"key", b"value"));
1450        assert!(set_paged_cell_pointer(&mut page, 0, pointer));
1451
1452        assert_eq!(paged_cell_pointer(&page, 0), Some(pointer));
1453        let cell = paged_cell_bytes(&page, pointer).expect("cell bytes");
1454        let (key, value) = paged_cell_key_value(cell).expect("key value");
1455
1456        assert_eq!(key, b"key");
1457        assert_eq!(value, b"value");
1458        assert_eq!(paged_cell_total_len(&page, pointer), Some(14));
1459    }
1460
1461    #[test]
1462    fn database_header_field_helpers_preserve_page_zero_offsets() {
1463        let mut page = vec![0u8; PAGED_PAGE_SIZE];
1464
1465        init_database_header_page(&mut page, 7).expect("init database header page");
1466        set_database_header_version(&mut page, PAGE_FILE_VERSION + 1).expect("set version");
1467        set_database_header_page_count(&mut page, 9).expect("set page count");
1468        set_database_header_freelist_head(&mut page, 4).expect("set freelist head");
1469
1470        assert!(database_header_magic_matches(&page));
1471        assert!(matches!(
1472            decode_database_header(&page),
1473            Err(DatabaseHeaderError::UnsupportedDatabaseVersion { .. })
1474        ));
1475        set_database_header_version(&mut page, PAGE_FILE_VERSION).expect("restore version");
1476        assert_eq!(
1477            database_header_page_size(&page).unwrap(),
1478            PAGED_PAGE_SIZE as u32
1479        );
1480        assert_eq!(database_header_page_count(&page).unwrap(), 9);
1481        assert_eq!(database_header_freelist_head(&page).unwrap(), 4);
1482    }
1483
1484    #[test]
1485    fn required_capabilities_round_trip_and_unknown_bits_fail_before_page_reads() {
1486        let mut page = vec![0u8; PAGED_SUPERBLOCK_SLOT_SIZE];
1487        let header = DatabaseHeader {
1488            version: PAGE_REQUIRED_CAPABILITIES_FILE_VERSION,
1489            required_capabilities: FILE_CAPABILITY_TEMPERATURE,
1490            ..DatabaseHeader::default()
1491        };
1492        encode_database_header(&mut page, &header).expect("encode capabilities");
1493        assert_eq!(
1494            decode_database_header(&page)
1495                .expect("supported capabilities")
1496                .required_capabilities,
1497            FILE_CAPABILITY_TEMPERATURE
1498        );
1499
1500        set_database_header_required_capabilities(&mut page, 1 << 63)
1501            .expect("set unknown capability");
1502        assert_eq!(
1503            decode_database_header(&page),
1504            Err(DatabaseHeaderError::UnsupportedRequiredCapabilities(
1505                1 << 63
1506            ))
1507        );
1508    }
1509
1510    #[test]
1511    fn disk_residency_moves_from_legacy_version_to_explicit_capability() {
1512        let legacy = DatabaseHeader {
1513            version: PAGE_DISK_RESIDENCY_FILE_VERSION,
1514            ..DatabaseHeader::default()
1515        };
1516        assert!(legacy.requires_disk_residency());
1517
1518        let resident_result_cache = DatabaseHeader {
1519            version: PAGE_RESULT_CACHE_FILE_VERSION,
1520            ..DatabaseHeader::default()
1521        };
1522        assert!(!resident_result_cache.requires_disk_residency());
1523
1524        let disk_result_cache = DatabaseHeader {
1525            version: PAGE_RESULT_CACHE_DISK_FILE_VERSION,
1526            ..DatabaseHeader::default()
1527        };
1528        assert!(disk_result_cache.requires_disk_residency());
1529
1530        let temperature_only = DatabaseHeader {
1531            version: PAGE_REQUIRED_CAPABILITIES_FILE_VERSION,
1532            required_capabilities: FILE_CAPABILITY_TEMPERATURE,
1533            ..DatabaseHeader::default()
1534        };
1535        assert!(!temperature_only.requires_disk_residency());
1536
1537        let disk_resident = DatabaseHeader {
1538            required_capabilities: FILE_CAPABILITY_DISK_RESIDENCY,
1539            ..temperature_only
1540        };
1541        assert!(disk_resident.requires_disk_residency());
1542    }
1543
1544    #[test]
1545    fn legacy_headers_ignore_the_reserved_capability_bytes() {
1546        let mut page = vec![0u8; PAGED_SUPERBLOCK_SLOT_SIZE];
1547        init_database_header_page(&mut page, 7).expect("init header");
1548        set_database_header_required_capabilities(&mut page, u64::MAX)
1549            .expect("fill reserved bytes");
1550
1551        assert_eq!(
1552            decode_database_header(&page)
1553                .expect("legacy header")
1554                .required_capabilities,
1555            0
1556        );
1557    }
1558
1559    #[test]
1560    fn paged_dwb_frame_round_trips_entries_and_validates_checksum() {
1561        let mut page = [0u8; PAGED_PAGE_SIZE];
1562        page[0] = 7;
1563        let frame = encode_paged_dwb_frame([(42, &page)]);
1564
1565        let entries = decode_paged_dwb_frame(&frame).expect("decode DWB frame");
1566        assert_eq!(entries.len(), 1);
1567        assert_eq!(entries[0].page_id, 42);
1568        assert_eq!(entries[0].page, page);
1569
1570        let mut corrupted = frame;
1571        let last = corrupted.len() - 1;
1572        corrupted[last] ^= 0xFF;
1573        assert!(matches!(
1574            decode_paged_dwb_frame(&corrupted),
1575            Err(PagedDwbFrameError::ChecksumMismatch { .. })
1576        ));
1577    }
1578
1579    #[test]
1580    fn paged_encryption_header_round_trips_marker_and_raw_bytes() {
1581        let header = PagedEncryptionHeader {
1582            salt: [7u8; PAGED_ENCRYPTION_SALT_SIZE],
1583            key_check: vec![9u8; PAGED_ENCRYPTION_KEY_CHECK_BLOB_SIZE],
1584        };
1585        let mut page = vec![0u8; PAGED_PAGE_SIZE];
1586        let bytes = encode_paged_encryption_header(&header);
1587
1588        write_paged_encryption_marker_and_header(&mut page, &bytes)
1589            .expect("write encryption marker");
1590
1591        assert!(paged_encryption_marker_present(&page));
1592        let raw = paged_encryption_header_bytes(&page).expect("header bytes");
1593        assert_eq!(decode_paged_encryption_header(raw).unwrap(), header);
1594    }
1595
1596    #[test]
1597    fn database_header_round_trips_page_zero_contract() {
1598        let header = DatabaseHeader {
1599            version: PAGE_FILE_VERSION,
1600            page_size: PAGED_PAGE_SIZE as u32,
1601            page_count: 42,
1602            freelist_head: 7,
1603            schema_version: 3,
1604            checkpoint_lsn: 99,
1605            checkpoint_in_progress: true,
1606            checkpoint_target_lsn: 123,
1607            required_capabilities: FILE_CAPABILITY_TEMPERATURE,
1608            physical: PhysicalFileHeader {
1609                format_version: 11,
1610                sequence: 12,
1611                manifest_oldest_root: 13,
1612                manifest_root: 14,
1613                free_set_root: 15,
1614                manifest_page: 16,
1615                manifest_checksum: 17,
1616                collection_roots_page: 18,
1617                collection_roots_checksum: 19,
1618                collection_root_count: 20,
1619                snapshot_count: 21,
1620                index_count: 22,
1621                catalog_collection_count: 23,
1622                catalog_total_entities: 24,
1623                export_count: 25,
1624                graph_projection_count: 26,
1625                analytics_job_count: 27,
1626                manifest_event_count: 28,
1627                registry_page: 29,
1628                registry_checksum: 30,
1629                recovery_page: 31,
1630                recovery_checksum: 32,
1631                catalog_page: 33,
1632                catalog_checksum: 34,
1633                metadata_state_page: 35,
1634                metadata_state_checksum: 36,
1635                vector_artifact_page: 37,
1636                vector_artifact_checksum: 38,
1637            },
1638        };
1639        let mut page = vec![0u8; PAGED_PAGE_SIZE];
1640
1641        encode_database_header(&mut page, &header).expect("encode header");
1642
1643        assert!(database_header_magic_matches(&page));
1644        let decoded = decode_database_header(&page).expect("decode header");
1645        assert_eq!(decoded, header);
1646    }
1647
1648    #[test]
1649    fn database_header_rejects_newer_versions() {
1650        let mut page = vec![0u8; PAGED_PAGE_SIZE];
1651        let header = DatabaseHeader {
1652            version: PAGE_FILE_VERSION + 1,
1653            ..DatabaseHeader::default()
1654        };
1655        encode_database_header(&mut page, &header).expect("encode header");
1656
1657        assert!(matches!(
1658            decode_database_header(&page),
1659            Err(DatabaseHeaderError::UnsupportedDatabaseVersion { .. })
1660        ));
1661    }
1662}