use anyhow::Result;
use xxhash_rust::xxh3::xxh3_64;
pub const MAGIC: &[u8; 8] = b"CHASSIS\0";
pub const VERSION: u32 = 4;
pub(crate) const fn version_of(precision: u8) -> u32 {
if precision == 0 { 3 } else { VERSION }
}
pub(crate) const HEADER_STRIDE: usize = 64 * 1024;
pub(crate) const REGIONS_START: u64 = 3 * HEADER_STRIDE as u64;
pub(crate) const MAX_TABLE_PAGES: usize = 512;
pub(crate) const FLAG_CUSTOM_IDS: u8 = 1;
pub(crate) const FLAG_SUPERSEDED: u8 = 2;
const CHECKSUM: std::ops::Range<usize> = 16..24;
const FIXED_LEN: usize = 136;
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct FileHeader {
pub write_version: u32,
pub sequence: u64,
pub dims: u32,
pub m: u16,
pub m0: u16,
pub max_layers: u8,
pub metric: u8,
pub precision: u8,
pub flags: u8,
pub segment_base_log2: u8,
pub doubling_segments: u8,
pub heap_base_log2: u8,
pub doubling_chunks: u8,
pub table_page_log2: u8,
pub count: u64,
pub entry_point: u64,
pub max_layer: u32,
pub epoch: u64,
pub pending_epoch: u64,
pub deleted_count: u64,
pub file_end: u64,
pub segments: u32,
pub heap_chunks: u32,
pub heap_used: u64,
pub segment_table: Vec<u64>,
pub heap_table: Vec<u64>,
pub next_id: u64,
}
impl FileHeader {
pub fn to_bytes(&self) -> Vec<u8> {
let tables = FIXED_LEN + 8 * (self.segment_table.len() + self.heap_table.len());
let mut b = vec![0u8; tables + 8];
let version = version_of(self.precision);
b[0..8].copy_from_slice(MAGIC);
b[8..12].copy_from_slice(&version.to_le_bytes()); b[12..16].copy_from_slice(&version.to_le_bytes()); b[24..32].copy_from_slice(&self.sequence.to_le_bytes());
let len = b.len() as u32;
b[32..36].copy_from_slice(&len.to_le_bytes());
b[36..40].copy_from_slice(&self.dims.to_le_bytes());
b[40..42].copy_from_slice(&self.m.to_le_bytes());
b[42..44].copy_from_slice(&self.m0.to_le_bytes());
b[44] = self.max_layers;
b[45] = self.metric;
b[46] = self.flags;
b[47] = self.table_page_log2;
b[48] = self.segment_base_log2;
b[49] = self.doubling_segments;
b[50] = self.heap_base_log2;
b[51] = self.doubling_chunks;
b[52] = self.precision;
b[56..64].copy_from_slice(&self.count.to_le_bytes());
b[64..72].copy_from_slice(&self.entry_point.to_le_bytes());
b[72..76].copy_from_slice(&self.max_layer.to_le_bytes());
b[80..88].copy_from_slice(&self.epoch.to_le_bytes());
b[88..96].copy_from_slice(&self.pending_epoch.to_le_bytes());
b[96..104].copy_from_slice(&self.deleted_count.to_le_bytes());
b[104..112].copy_from_slice(&self.file_end.to_le_bytes());
b[112..116].copy_from_slice(&self.segments.to_le_bytes());
b[116..120].copy_from_slice(&self.heap_chunks.to_le_bytes());
b[120..128].copy_from_slice(&self.heap_used.to_le_bytes());
b[128..132].copy_from_slice(&(self.segment_table.len() as u32).to_le_bytes());
b[132..136].copy_from_slice(&(self.heap_table.len() as u32).to_le_bytes());
for (i, offset) in self.segment_table.iter().chain(&self.heap_table).enumerate() {
b[FIXED_LEN + 8 * i..FIXED_LEN + 8 * (i + 1)].copy_from_slice(&offset.to_le_bytes());
}
b[tables..].copy_from_slice(&self.next_id.to_le_bytes());
let checksum = xxh3_64(&b);
b[CHECKSUM].copy_from_slice(&checksum.to_le_bytes());
b
}
pub fn from_bytes(copy: &[u8]) -> Result<Option<Self>> {
if copy.len() < FIXED_LEN || copy[0..8] != *MAGIC {
return Ok(None);
}
let u16_at = |at: usize| u16::from_le_bytes([copy[at], copy[at + 1]]);
let u32_at = |at: usize| u32::from_le_bytes(copy[at..at + 4].try_into().expect("4 bytes"));
let u64_at = |at: usize| u64::from_le_bytes(copy[at..at + 8].try_into().expect("8 bytes"));
let (read_version, write_version) = (u32_at(8), u32_at(12));
if read_version > VERSION {
crate::error::fail!(
Other,
"The file is in format {read_version}, and this release of Chassis reads up to \
{VERSION}\nhelp: open it with a newer release of Chassis"
);
}
if read_version < 3 {
return Ok(None);
}
let len = u32_at(32) as usize;
if !(FIXED_LEN..=copy.len()).contains(&len) {
return Ok(None);
}
let mut scratch = copy[..len].to_vec();
scratch[CHECKSUM].fill(0);
if xxh3_64(&scratch) != u64_at(16) {
return Ok(None);
}
let (segment_pages, heap_pages) = (u32_at(128) as usize, u32_at(132) as usize);
let tables =
FIXED_LEN + 8 * (segment_pages.min(MAX_TABLE_PAGES) + heap_pages.min(MAX_TABLE_PAGES));
if segment_pages > MAX_TABLE_PAGES || heap_pages > MAX_TABLE_PAGES || len < tables {
crate::error::fail!(
Corrupt,
"Corrupt file header: table page counts don't match its length\nhelp: restore the \
index from a backup, or rebuild it from its vectors"
);
}
let table = |start: usize, n: usize| (0..n).map(|i| u64_at(start + 8 * i)).collect();
if copy[45] > 1 {
crate::error::fail!(
Corrupt,
"The file header names distance metric {}, which this release doesn't know\nhelp: \
open it with a newer release of Chassis; if it is from this one, it is damaged",
copy[45]
);
}
if copy[52] > 1 {
crate::error::fail!(
Corrupt,
"The file header names precision {}, which this release doesn't know\nhelp: open \
it with a newer release of Chassis; if it is from this one, it is damaged",
copy[52]
);
}
Ok(Some(Self {
write_version,
sequence: u64_at(24),
dims: u32_at(36),
m: u16_at(40),
m0: u16_at(42),
max_layers: copy[44],
metric: copy[45],
precision: copy[52],
flags: copy[46],
table_page_log2: copy[47],
segment_base_log2: copy[48],
doubling_segments: copy[49],
heap_base_log2: copy[50],
doubling_chunks: copy[51],
count: u64_at(56),
entry_point: u64_at(64),
max_layer: u32_at(72),
epoch: u64_at(80),
pending_epoch: u64_at(88),
deleted_count: u64_at(96),
file_end: u64_at(104),
segments: u32_at(112),
heap_chunks: u32_at(116),
heap_used: u64_at(120),
segment_table: table(FIXED_LEN, segment_pages),
heap_table: table(FIXED_LEN + 8 * segment_pages, heap_pages),
next_id: if len >= tables + 8 { u64_at(tables) } else { 0 },
}))
}
pub(crate) fn graph_hash(&self) -> u64 {
let mut b = [0u8; 56];
b[0..4].copy_from_slice(&self.dims.to_le_bytes());
b[4..6].copy_from_slice(&self.m.to_le_bytes());
b[6..8].copy_from_slice(&self.m0.to_le_bytes());
b[8] = self.max_layers;
b[9] = self.metric;
b[12..16].copy_from_slice(&self.max_layer.to_le_bytes());
b[16..24].copy_from_slice(&self.count.to_le_bytes());
b[24..32].copy_from_slice(&self.entry_point.to_le_bytes());
b[32..40].copy_from_slice(&self.epoch.to_le_bytes());
b[40..48].copy_from_slice(&self.deleted_count.to_le_bytes());
b[48..56].copy_from_slice(&self.next_id.to_le_bytes());
xxh3_64(&b)
}
pub fn newest(a: Option<Self>, b: Option<Self>) -> Result<(usize, Self)> {
match (a, b) {
(Some(a), Some(b)) if a.sequence == b.sequence => {
crate::error::fail!(
Corrupt,
"Corrupt file: both header copies have sequence number {}\nhelp: restore the \
index from a backup, or rebuild it from its vectors",
a.sequence
)
}
(Some(a), Some(b)) => Ok(if a.sequence > b.sequence { (0, a) } else { (1, b) }),
(Some(a), None) => Ok((0, a)),
(None, Some(b)) => Ok((1, b)),
(None, None) => crate::error::fail!(
NotAnIndex,
"Neither copy of the file's header is valid: it isn't a Chassis index, or both \
copies are damaged\nhelp: check the path; if it was an index, restore it from a \
backup or rebuild it from its vectors"
),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn sample() -> FileHeader {
FileHeader {
write_version: version_of(0),
sequence: 7,
dims: 768,
m: 16,
m0: 32,
max_layers: 16,
metric: 1,
precision: 0,
flags: FLAG_CUSTOM_IDS,
segment_base_log2: 10,
doubling_segments: 6,
heap_base_log2: 16,
doubling_chunks: 12,
table_page_log2: 13,
count: 5000,
entry_point: 42,
max_layer: 3,
epoch: 2,
pending_epoch: 0,
deleted_count: 9,
file_end: 1 << 30,
segments: 3,
heap_chunks: 1,
heap_used: 960,
segment_table: vec![196_608],
heap_table: vec![262_144],
next_id: 9_000,
}
}
#[test]
fn test_roundtrip() {
let header = sample();
assert_eq!(FileHeader::from_bytes(&header.to_bytes()).unwrap(), Some(header));
}
#[test]
fn test_any_flipped_bit_invalidates_the_copy() {
let bytes = sample().to_bytes();
for i in 16..bytes.len() {
let mut torn = bytes.clone();
torn[i] ^= 0x10;
assert_eq!(FileHeader::from_bytes(&torn).unwrap(), None, "byte {i}");
}
}
#[test]
fn test_a_header_from_before_next_id_reads_as_never_compacted() {
let mut bytes = sample().to_bytes();
bytes.truncate(bytes.len() - 8);
let len = bytes.len() as u32;
bytes[32..36].copy_from_slice(&len.to_le_bytes());
bytes[CHECKSUM].fill(0);
let checksum = xxh3_64(&bytes);
bytes[CHECKSUM].copy_from_slice(&checksum.to_le_bytes());
let header = FileHeader::from_bytes(&bytes).unwrap().unwrap();
assert_eq!(header, FileHeader { next_id: 0, ..sample() });
}
#[test]
fn test_unknown_metric_is_an_error() {
let mut bytes = sample().to_bytes();
bytes[45] = 2;
bytes[CHECKSUM].fill(0);
let checksum = xxh3_64(&bytes);
bytes[CHECKSUM].copy_from_slice(&checksum.to_le_bytes());
assert!(FileHeader::from_bytes(&bytes).is_err());
}
#[test]
fn test_newer_versions_are_errors_and_old_ones_are_not_v3() {
let mut bytes = sample().to_bytes();
bytes[8..12].copy_from_slice(&2u32.to_le_bytes());
assert_eq!(FileHeader::from_bytes(&bytes).unwrap(), None);
bytes[8..12].copy_from_slice(&(VERSION + 1).to_le_bytes());
assert!(FileHeader::from_bytes(&bytes).is_err());
}
#[test]
fn test_only_a_half_precision_file_needs_format_4() {
let version = |bytes: &[u8]| (bytes[8..12].to_vec(), bytes[12..16].to_vec());
let three = 3u32.to_le_bytes().to_vec();
assert_eq!(version(&sample().to_bytes()), (three.clone(), three));
let half = FileHeader { precision: 1, write_version: 4, ..sample() };
let bytes = half.to_bytes();
let four = 4u32.to_le_bytes().to_vec();
assert_eq!(version(&bytes), (four.clone(), four));
assert_eq!(FileHeader::from_bytes(&bytes).unwrap(), Some(half));
}
#[test]
fn test_unknown_precision_is_an_error() {
let mut bytes = sample().to_bytes();
bytes[52] = 2;
bytes[CHECKSUM].fill(0);
let checksum = xxh3_64(&bytes);
bytes[CHECKSUM].copy_from_slice(&checksum.to_le_bytes());
assert!(FileHeader::from_bytes(&bytes).is_err());
}
#[test]
fn test_a_newer_write_version_with_more_fields_still_reads() {
let mut bytes = sample().to_bytes();
bytes[12..16].copy_from_slice(&(VERSION + 1).to_le_bytes());
bytes.extend_from_slice(&[0xab; 16]);
let len = bytes.len() as u32;
bytes[32..36].copy_from_slice(&len.to_le_bytes());
bytes[CHECKSUM].fill(0);
let checksum = xxh3_64(&bytes);
bytes[CHECKSUM].copy_from_slice(&checksum.to_le_bytes());
let header = FileHeader::from_bytes(&bytes).unwrap().unwrap();
assert_eq!(header, FileHeader { write_version: VERSION + 1, ..sample() });
}
#[test]
fn test_newest_copy() {
let a = sample();
let b = FileHeader { sequence: 8, ..sample() };
assert_eq!(FileHeader::newest(Some(a.clone()), Some(b.clone())).unwrap().0, 1);
assert_eq!(FileHeader::newest(Some(a.clone()), None).unwrap().0, 0);
assert!(FileHeader::newest(Some(a.clone()), Some(a)).is_err());
assert!(FileHeader::newest(None, None).is_err());
}
}