chassisdb 0.9.0

Chassis: an embedded vector index for local semantic search, in one file.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
//! File header, format v3 (ADR-0008).
//!
//! Two copies sit 64 KiB apart, so they never share a page. Each carries a sequence number and an
//! xxh3-64 checksum; the valid copy with the higher sequence number is current. A commit writes
//! the other copy, so a torn header write always leaves the previous commit readable.

use anyhow::Result;
use xxhash_rust::xxh3::xxh3_64;

/// Magic bytes at the start of every Chassis file, in every format version.
pub const MAGIC: &[u8; 8] = b"CHASSIS\0";

/// The newest file format this release reads and writes: half-precision vectors (ADR-0018). A
/// file with full-precision vectors is written as format 3, which releases before it read too.
/// Versions 1 and 2 are migrated.
pub const VERSION: u32 = 4;

/// The format of a file whose header says `precision`. A release that doesn't know half
/// precision would read those vectors as f32s, so it has to refuse the file; a full-precision
/// file stays one it can read and write.
pub(crate) const fn version_of(precision: u8) -> u32 {
    if precision == 0 { 3 } else { VERSION }
}

/// Distance between the two header copies.
pub(crate) const HEADER_STRIDE: usize = 64 * 1024;

/// Header A, header B, then the live page for readers in other processes; regions start after it.
pub(crate) const REGIONS_START: u64 = 3 * HEADER_STRIDE as u64;

/// Table pages one header can reference, per table: enough for 2^32 slots in 1,024-slot segments.
pub(crate) const MAX_TABLE_PAGES: usize = 512;

/// Some slot's id differs from the slot number.
pub(crate) const FLAG_CUSTOM_IDS: u8 = 1;
/// A compacted copy is about to replace, or has replaced, this file at its path (ADR-0011).
pub(crate) const FLAG_SUPERSEDED: u8 = 2;

const CHECKSUM: std::ops::Range<usize> = 16..24;
const FIXED_LEN: usize = 136;

/// One header copy. Offsets are bytes, little-endian; see `docs/src/architecture/file-format.md`.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct FileHeader {
    /// As read; `to_bytes` writes the version `precision` needs. Only a writer refuses a newer
    /// one.
    pub write_version: u32,
    pub sequence: u64,
    pub dims: u32,
    pub m: u16,
    pub m0: u16,
    pub max_layers: u8,
    /// 0: Euclidean; 1: cosine, over vectors stored at unit length.
    pub metric: u8,
    /// 0: vectors are f32s; 1: 16-bit floats, in a file of format 4.
    pub precision: u8,
    pub flags: u8,
    /// log2 of the first segment's slot count.
    pub segment_base_log2: u8,
    /// Segments that double in size before every later one has the same size.
    pub doubling_segments: u8,
    /// log2 of the first upper-heap chunk's byte size.
    pub heap_base_log2: u8,
    /// Heap chunks that double in size before every later one has the same size.
    pub doubling_chunks: u8,
    /// log2 of the entries in one table page.
    pub table_page_log2: u8,
    /// Committed slots: slots at or past this are leftovers of a crashed flush.
    pub count: u64,
    /// Entry point slot, `u64::MAX` when the graph is empty.
    pub entry_point: u64,
    pub max_layer: u32,
    /// Last flush that committed deletes.
    pub epoch: u64,
    /// Nonzero while a flush with deletes is in progress: recovery clears marks above `epoch`.
    pub pending_epoch: u64,
    pub deleted_count: u64,
    /// End of the last committed region; the next region is allocated here.
    pub file_end: u64,
    pub segments: u32,
    pub heap_chunks: u32,
    /// Next free upper-heap position, as `chunk << 32 | byte offset`.
    pub heap_used: u64,
    /// File offsets of the table pages listing segment offsets.
    pub segment_table: Vec<u64>,
    /// File offsets of the table pages listing heap chunk offsets.
    pub heap_table: Vec<u64>,
    /// One past the largest id used before the last compaction, which removed the deleted slots
    /// that showed it; 0 if never compacted. Stored after the tables.
    pub next_id: u64,
    /// The application's own number, committed with the data (ADR-0023). 0 if never set.
    pub user_version: u64,
}

impl FileHeader {
    /// Encodes this copy, checksum included.
    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 + 16];
        let version = version_of(self.precision);
        b[0..8].copy_from_slice(MAGIC);
        b[8..12].copy_from_slice(&version.to_le_bytes()); // read version
        b[12..16].copy_from_slice(&version.to_le_bytes()); // write version
        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..tables + 8].copy_from_slice(&self.next_id.to_le_bytes());
        b[tables + 8..].copy_from_slice(&self.user_version.to_le_bytes());
        let checksum = xxh3_64(&b);
        b[CHECKSUM].copy_from_slice(&checksum.to_le_bytes());
        b
    }

    /// Decodes one copy: `Ok(None)` if it is torn or was never written, an error if it needs a
    /// newer release to read. The read version is checked before the checksum, so a newer layout
    /// is reported as too new, not as corrupt. A newer write version is only recorded.
    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"
            );
        }
        // Versions 1 and 2 keep the dimensions where v3 keeps the write version.
        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);
        // After the tables come `next_id` and `user_version`, each absent from files written
        // before it existed; bytes after them belong to a later write version, and this release
        // ignores them.
        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 },
            user_version: if len >= tables + 16 { u64_at(tables + 8) } else { 0 },
        }))
    }

    /// The current header and which copy holds it.
    /// Names the graph this header commits. A header written for a flag or for an intent to
    /// delete names the same graph as the one before it.
    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,
            user_version: 77,
        }
    }

    /// `sample()` as a release from before its last `cut` bytes of fields would have written it.
    fn older(cut: usize) -> Vec<u8> {
        let mut bytes = sample().to_bytes();
        bytes.truncate(bytes.len() - cut);
        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());
        bytes
    }

    #[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 header = FileHeader::from_bytes(&older(16)).unwrap().unwrap();
        assert_eq!(header, FileHeader { next_id: 0, user_version: 0, ..sample() });
    }

    #[test]
    fn test_a_header_from_before_user_version_reads_as_never_set() {
        let header = FileHeader::from_bytes(&older(8)).unwrap().unwrap();
        assert_eq!(header, FileHeader { user_version: 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());
    }
}