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