Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Chassis

Chassis is an embedded vector index for local semantic search. Your index is one file, and Chassis runs inside your process: no server to run, nothing to connect to. Store embeddings under your own ids, search them, and keep the rest of your data where it already lives.

pip install chassisdb   # Python 3.11+: import chassisdb
cargo add chassisdb     # Rust: use chassisdb

The C library and its header come with each release.

Example

import numpy as np
from chassisdb import VectorIndex

embeddings = np.random.rand(1000, 768).astype(np.float32)  # stands for your model's output
note_ids = np.arange(1000, 2000)  # the ids your notes already have

index = VectorIndex("notes.chassis", dimensions=768)
index.add_batch(embeddings, ids=note_ids)
index.flush()

query = embeddings[0]
for hit in index.search(query, k=5):
    print(hit.id, hit.distance)  # 1000 first, at distance 0

Start

Features

  • Approximate nearest-neighbor search (HNSW) by Euclidean or cosine distance.
  • Filtered search, over the ids your application allows.
  • Your own ids, deletes, and compact() to reclaim their space.
  • Batch builds on every core.
  • Half precision, for half the file and half the memory.
  • Durable flush(): after a crash, reopening keeps every add and delete up to the last flush and drops the rest.
  • One writer and any number of readers, in other processes too.
  • Errors that say what was wrong and what to do instead.

Opening an index reads only its headers. On an Apple M5 (2026-10-15), opening one of 50,000 vectors of 384 dimensions took 0.08 ms through Python, with the file in memory. At the same recall, Chassis searches a million 128-dimension vectors faster than hnswlib on every server CPU measured, x86 and ARM (Performance).

Non-goals

Chassis is kept small on purpose, so that it stays correct and fast. It is not:

  • A database server: there is no network listener, query language or daemon.
  • A distributed system: replication and sharding are left to the application.
  • A metadata store: Chassis keeps vectors and ids only. Keep your text and metadata in a store of your own, such as SQLite, under the same ids, and pass the ids it selects to a filtered search.

Status

The latest release is v0.11.0; the changelog lists what each release changed. Files from older releases open, and opening one for writing converts it.

Requirements

  • Python 3.11 or later with numpy 1.26 or later, or Rust 1.89 or later.
  • Linux, macOS or Windows, on a file system that supports memory mapping and fsync. Wheels and the C library are built for Linux (x86-64 and ARM64), macOS (ARM64) and Windows (x86-64).

License

Chassis is dual-licensed under MIT and Apache 2.0. You may use either license at your option.

Getting started

This page takes you from nothing to a first search, in Python or Rust. From C, start with the C API.

Python

pip install chassisdb
from chassisdb import VectorIndex

index = VectorIndex("quickstart.chassis", dimensions=3)  # created if it doesn't exist

index.add([1.0, 0.0, 0.0])  # id 0
index.add([0.0, 1.0, 0.0])  # id 1
index.add([0.0, 0.0, 1.0])  # id 2
index.flush()  # on disk once this returns

results = index.search([1.0, 0.1, 0.0], k=1)
print("nearest:", results[0].id)  # 0

The Python docs go on from here: batches, your own ids, options and every method.

Rust

Add Chassis to your Cargo.toml:

[dependencies]
chassisdb = "0.9"
use chassisdb::{IndexOptions, VectorIndex};

fn main() -> chassisdb::Result<()> {
    // Created if it doesn't exist
    let mut index = VectorIndex::open("quickstart.chassis", 3, IndexOptions::default())?;

    index.add(&[1.0, 0.0, 0.0])?; // id 0
    index.add(&[0.0, 1.0, 0.0])?; // id 1
    index.add(&[0.0, 0.0, 1.0])?; // id 2
    index.flush()?; // on disk once this returns

    let results = index.search(&[1.0, 0.1, 0.0], 1)?;
    assert_eq!(results[0].id, 0);
    println!("nearest: {}", results[0].id);
    Ok(())
}

A debug build runs Chassis’s arithmetic many times slower. To build Chassis optimized while your own crate stays in debug:

[profile.dev.package.chassisdb]
opt-level = 3

Basic usage goes on from here, and the Rust API has every method.

Basic usage

This page shows the three things you do with an index from Rust: open it, add vectors and keep them, and search them. Getting started has the setup, and the Rust API has every method.

Example

use chassisdb::{IndexOptions, VectorIndex};
use std::hash::{DefaultHasher, Hash, Hasher};

/// Stands for your embedding model: here, each word counts in a dimension picked by its hash.
fn embed(text: &str) -> Vec<f32> {
    let mut vector = vec![0.0; 1536];
    for word in text.split_whitespace() {
        let mut hasher = DefaultHasher::new();
        word.to_lowercase().hash(&mut hasher);
        vector[hasher.finish() as usize % 1536] += 1.0;
    }
    vector
}

fn main() -> chassisdb::Result<()> {
    let options = IndexOptions {
        max_connections: Some(16),
        ef_construction: 200,
        ef_search: 50,
        ..IndexOptions::default()
    };
    let mut index = VectorIndex::open("data.chassis", 1536, options)?;

    let id = index.add(&embed("The cat sat on the mat"))?;
    index.add_with_id(1000, &embed("A dog dug in the garden"))?;
    index.flush()?;
    println!("stored under ids {id} and 1000");

    for result in index.search(&embed("the cat on the mat"), 5)? {
        println!("id {}, distance {}", result.id, result.distance);
    }
    Ok(())
}

Open

open creates the file if it doesn’t exist. The dimensions, metric, precision and max_connections are fixed when the index is created; opening it again takes each from the file unless you give it, and checks any you do. Dimensions of 0 open an existing index with its own. The options above are the defaults.

Add

Every vector has an id, a u64. add gives it the next one. To keep a vector under an id your application already has, such as a database row’s, use add_with_id, and keep the rest of the row where it already lives.

A search finds a vector as soon as it is added, but the vector is on disk only after flush(). Dropping the index without a flush discards everything added since the last one, as a crash would.

search returns the k nearest vectors, nearest first, each with its id and distance. Smaller is nearer.

search takes &self, so many threads can search one VectorIndex at once. Wrap it in an Arc<RwLock<VectorIndex>>: searches take the read lock, and add, delete and flush, which take &mut self, take the write lock. To search while another thread or process writes, open an IndexReader on the same file. It sees what the writer’s last flush() committed.

Rust API

Every type and method of the chassisdb crate, with what each one does to the file and when it fails. docs.rs has the same API generated from the code.

Indexes

VectorIndex

VectorIndex opens an index file to add, delete and search vectors. One process writes a file at a time; to search a file that another process writes, use IndexReader. The examples below continue from one another, starting with the index opened here.

Open

#![allow(unused)]
fn main() {
use chassisdb::{VectorIndex, IndexOptions};

// Open or create a persistent index
let mut index = VectorIndex::open(
    "embeddings.chassis", 
    768, 
    IndexOptions::default()
)?;
}

Parameters:

  • path: Path to the backing file (created if missing).
  • dims: Vector dimensionality (must be static for the file’s lifetime), or 0 to open an existing index with its own. 0 where there is no index is a NotFound error, and creates nothing.
  • options: Configuration for graph construction and search. The metric, precision and max_connections are fixed when the index is created, with defaults for any left out (None). Opening it again takes each from the file unless it’s given; one given that differs is an OptionsMismatch error that names it (ADR-0026).
#![allow(unused)]
fn main() {
// An index made elsewhere, opened with whatever it holds.
let index = VectorIndex::open("embeddings.chassis", 0, IndexOptions::default())?;
}

Returns:

  • Ok(VectorIndex): Handle to the index.
  • Err: If file is locked, corrupted, or dimensions mismatch.

Add

#![allow(unused)]
fn main() {
let vector = vec![0.5; 768];
let id = index.add(&vector)?;
}

Behavior:

  • Crash behavior: If the process dies before the next flush(), this vector is gone on reopen. The index stays usable.
  • Ids: add returns one past the largest id used so far (0, 1, 2… unless you chose ids yourself). It never reuses an id, even after a delete.
  • Durability: Data is written to memory-mapped pages immediately but requires flush() for persistence guarantees.

Errors:

  • Dimension mismatch.
  • Storage write failure (e.g., disk full).

Your ids

#![allow(unused)]
fn main() {
index.add_with_id(42, &vector)?;
}

Search results report 42. Fails if a live vector already has that id; delete it first to replace it. u64::MAX is reserved. Indexes that use their own ids build an id table in memory on the first lookup in a process, which scans the index once (ADR-0007).

Batches

#![allow(unused)]
fn main() {
let rows: Vec<Vec<f32>> = (0..100).map(|i| vec![i as f32 / 100.0; 768]).collect(); // your vectors
let vectors: Vec<f32> = rows.concat(); // count × dims floats, back to back
let ids = index.add_batch(&vectors)?;  // or index.add_batch_with_ids(&my_ids, &vectors)?
}

Links the batch on every core, so a large batch builds many times faster than add in a loop (ADR-0010). Ids are assigned as add assigns them. A batch is added whole or not at all. The graph depends on thread timing, so two builds of the same data differ slightly, as sequential builds already do through their random layers.

Delete

#![allow(unused)]
fn main() {
let deleted = index.delete(id)?; // false if no live vector has that id
}

Search stops returning the vector immediately, and len() drops by one. The delete is durable after the next flush(); a crash before then rolls it back. A delete and an add in the same flush are all-or-nothing, so delete(id) followed by add_with_id(id, new_vector) replaces a vector safely. Deleted vectors keep their disk space until compact(); deleted_count() says how many the file holds.

Compact

#![allow(unused)]
fn main() {
index.compact()?;
}

Rewrites the index without its deleted vectors and with a newly built graph, then replaces the file with the copy (ADR-0011). Ids don’t change, and add still never reuses one. Like flush(), it makes every add and delete so far durable. It takes as long as building the index, on every core, and needs free disk for a second copy of the live vectors. Readers in other processes keep searching and move to the new file by themselves. On Windows it fails, leaving the index as it was, while another process has the index open.

When to compact: deletes cost speed and space, not recall. With half the vectors deleted, searches ran at about 70% of their speed, and with 90% deleted at a fifth (ADR-0011). Compacting once deleted_count() nears len() keeps most of the speed; compact sooner when disk space matters. The file shrinks only by whole segments, which double in size as an index grows, so it gets smaller only when the live vectors fit in fewer of them.

Search

#![allow(unused)]
fn main() {
let query = vec![0.5; 768];
let k = 10; // Neighbors to retrieve

let results = index.search(&query, k)?;

for hit in results {
    println!("id {}, distance {}", hit.id, hit.distance);
}
}

Returns: Vec<SearchResult>, sorted by distance (nearest first), identified by the ids from add/add_with_id. Deleted vectors are never returned.

k is at least 1. The search keeps the best max(k, ef_search) candidates, so a k above ef_search is fine; it returns at most len() results.

#![allow(unused)]
fn main() {
use std::collections::HashSet;

// Stands for the ids your application allows, e.g. from `SELECT id FROM docs WHERE owner = ?`
let allowed: HashSet<u64> = HashSet::from([42, 101, 102]);
let results = index.search_filtered(&query, 10, |id| allowed.contains(&id))?;
}

Only vectors whose id the filter accepts are returned. The filter is called with ids from add/add_with_id, many times per search, so it should be cheap. When the filter passes many vectors, the search walks the graph as usual. When it passes few, or its matches lie far from the query, walking the graph would visit most of the index to find them. Then the search checks every vector instead and returns the exact nearest. Measured, a filtered search takes at most about twice an exact scan of the matching vectors (ADR-0009). IndexReader has the same method.

To leave a few ids out, as “more like this” leaves out the vector it starts from, pass a filter that rejects them:

#![allow(unused)]
fn main() {
let vector = index.get(42)?.expect("42 is in the index");
let results = index.search_filtered(&vector, 10, |id| id != 42)?;
}

Flush

#![allow(unused)]
fn main() {
// Every add and delete so far is durable once this returns.
index.flush()?;
}

A flush waits for the disk, so it takes milliseconds. Call it after a batch of changes, every 1,000 vectors say, or before shutting down. To bound what a crash can lose by time instead, flush from a timer.

Dropping a VectorIndex doesn’t flush: what was added or deleted since the last flush() is discarded, as after a crash.

Rollback

#![allow(unused)]
fn main() {
// Every add, delete and user version since the last flush is gone.
index.rollback()?;
}

As closing the index and opening it again would, without letting go of the writer’s lock. Call it where a write’s transaction in your own store rolls back, or the next flush commits what that write did to the index (With a database). If it fails, later flushes fail too: close the index and open it again.

At rest the index is one file. A <name>.undo file sits beside it from the first add after a flush until the next flush, and after a crash until a writer reopens the index (file format). Move, copy or delete the two together, or copy the index with backup while it is open.

Backup

#![allow(unused)]
fn main() {
// A copy of the index, every add and delete so far: it flushes first.
index.backup("backups/embeddings.chassis")?;
}

The backup opens like any index. It is written beside its path and renamed into place once whole, so a crash never leaves half a backup there, and it replaces a file already at that path. An IndexReader makes one too, of the writer’s last flush, while the writer keeps writing; see IndexReader. To restore a backup, copy it into place while nothing has the index open (ADR-0024).

Lookups

#![allow(unused)]
fn main() {
let vector = index.get(42)?;     // Some(vector), or None if no live vector has id 42
let known = index.contains(42)?; // Whether a live vector has id 42
let ids = index.ids()?;          // Every live id, in the order they were added
}

get returns the vector as the index keeps it: scaled to length 1 in a cosine index, and rounded in half precision. With ids you chose, the first lookup in a process scans the index once to map ids to vectors, as add_with_id does.

Metadata

#![allow(unused)]
fn main() {
let len = index.len();           // Live vectors (deleted ones excluded)
let deleted = index.deleted_count(); // Deleted vectors the file holds until compact()
let dim = index.dimensions();    // Vector size
let metric = index.metric();     // DistanceMetric::Euclidean or ::Cosine
let precision = index.precision(); // Precision::Full or ::Half
let empty = index.is_empty();    // True if count == 0
}

User version

#![allow(unused)]
fn main() {
index.set_user_version(42); // Committed by the next flush, with the data
index.flush()?;
let version = index.user_version(); // 42; 0 until one is set
}

Like SQLite’s user_version, a number for your application. The next flush commits it with the adds and deletes, so after a crash it says which flush the index holds. Keep the same number in your own store, in the transaction the flush sits in, and compare the two on open and as each write begins: they differ only when a flush’s commit never came, after a crash or a failed commit (With a database, ADR-0023). The writer returns the number last set, flushed or not, and rollback sets it back to the flushed one. IndexReader::user_version returns the number of the flush its last snapshot shows.

Check

#![allow(unused)]
fn main() {
let check = index.check()?; // Reads the whole graph and every vector
assert!(check.is_ok());     // Nothing out of reach, nothing that isn't a finite number
}

Checks what opening can’t; opening checks the header and that the file holds every region it names. A check of 200,000 vectors of 384 dimensions takes about 0.1 s.

  • check.unreachable: live vectors that no path through the graph reaches, so no search that walks the graph returns them; a filtered search that checks every vector can. Damage leaves them, and compact() builds the graph again. A sound graph can have a few too. On uniform random numbers in 384 dimensions, 0.3% to 1.4% of them, rebuilt or not; on clustered data, as embeddings are, none. Among many exact copies of one vector, some, and a search for that vector finds the others.
  • check.not_finite: vectors with a component that isn’t a finite number, which only damage to the file leaves, since add refuses them. Delete them and add them again from your own data.

IndexReader

Searches an index while a VectorIndex writes it, in another process or this one. It takes no lock, so any number of readers can open one file next to its single writer (ADR-0008, decision 5). Like a writer, it takes the dimensions (given as 0), metric, precision and max_connections from the file, and checks any that is given.

#![allow(unused)]
fn main() {
use chassisdb::{IndexOptions, IndexReader};

let mut reader = IndexReader::open("embeddings.chassis", 768, IndexOptions::default())?;
let results = reader.search(&query, 10)?;
}

Every search first takes a new snapshot: it returns what the writer’s newest flush() committed, and nothing that flush deleted, while routing through vectors added since, so a long unflushed batch costs readers little recall. A flush becomes visible just before its final fsync, so one that then fails, or is lost to power loss, may already have been seen. get, contains, ids and check take a new snapshot too; while the writer is linking a vector, check can find it out of reach for a moment. len() and deleted_count() report the last snapshot; refresh() takes a new one without searching, and snapshot() identifies it, for keying a cache. search takes &mut self: open one reader per thread. The file must exist in the current format; open it once with VectorIndex::open to create or migrate it.

reader.backup(path) copies the writer’s last flush while the writer keeps writing. It copies the file, then the undo file beside it, and starts over if a flush lands meanwhile; after five tries it gives up. The copy needs a pause in the writer’s flushes as long as itself, about a third of a second for 200 MB on a laptop: a writer that flushes more often than that backs up itself.

Errors

VectorIndex and IndexReader return chassisdb::Result<T>, whose error says what was wrong, with the value, and on a line starting help: what to do instead. Error::kind() is an ErrorKind to act on (Errors lists them, with causes and fixes):

#![allow(unused)]
fn main() {
use chassisdb::{ErrorKind, IndexOptions, IndexReader, VectorIndex};

match VectorIndex::open("embeddings.chassis", 768, IndexOptions::default()) {
    Ok(index) => { /* write */ }
    // One writer at a time; a reader searches while it writes.
    Err(e) if e.kind() == ErrorKind::Locked => {
        let reader = IndexReader::open("embeddings.chassis", 768, IndexOptions::default())?;
    }
    Err(e) => return Err(e.into()),
}
}

chassisdb::Error converts into anyhow::Error and Box<dyn std::error::Error>, so ? works in functions that return those.

Options

IndexOptions

Parameters tuning the HNSW graph trade-offs between recall, speed, and memory.

#![allow(unused)]
fn main() {
pub struct IndexOptions {
    /// Max connections per node (M): 16 if left out when creating. Default: None
    pub max_connections: Option<u16>,
    
    /// Size of the dynamic candidate list during construction. Default: 200
    /// Higher = Better graph quality, slower inserts.
    pub ef_construction: usize,
    
    /// Size of the dynamic candidate list during search. Default: 50
    /// Higher = Better recall, slower search.
    pub ef_search: usize,

    /// `DistanceMetric::Euclidean` (if left out when creating) or `DistanceMetric::Cosine`.
    /// Default: None
    pub metric: Option<DistanceMetric>,

    /// `Precision::Full` (if left out when creating) or `Precision::Half`. Default: None
    pub precision: Option<Precision>,

    /// Ask the operating system to keep the vectors on huge pages. Default: None, left to `warm`
    pub huge_pages: Option<bool>,

    /// Read the index into memory on another thread from the moment it is opened. Default: false
    pub warm: bool,
}
}

The metric is fixed when the index is created: reopening takes the file’s, giving another one is an error, and metric() reports it. A cosine index stores vectors scaled to unit length, rejects zero vectors and vectors with NaN or infinite components, and reports 1 - cosine similarity, from 0 to 2. Search speed is the same for both.

precision is fixed when the index is created, as the metric is: reopening takes the file’s, giving another one is an error, and precision() reports it. Precision::Half keeps each component of a vector as a 16-bit float (ADR-0018), so the vectors take half the space in the file and in memory. A search over an index too large for the CPU’s caches is a tenth to two thirds faster for it on most of the machines measured. Builds on x86 take 11 to 48% less time. An index that fits in cache searches no faster, and on Neoverse-N2 a fifth more slowly when its vectors are long. Each component is rounded to 11 significant bits, about three decimal digits, and reported distances are to the vectors as kept; on the embeddings measured, recall was the same. A vector with a component of 65,520 or more in magnitude is refused. A file in half precision is format version 4, which releases from before this option refuse to open.

Besides half precision, the way to shrink an index is fewer dimensions. Matryoshka embeddings, such as OpenAI’s text-embedding-3 with its dimensions argument, are trained so that the first part of a vector works on its own. 512 of 1,536 dimensions make the index about a third of the size. Measure recall on your own queries first, and cut vectors yourself only with DistanceMetric::Cosine, or normalize them again. max_connections: Some(12) instead of 16 saves less. A 128-dimension file in half precision is 7% smaller, and one of 1,536 dimensions 1%. Builds are 7 to 18% faster, but searches for 0.99 recall at 128 and 384 dimensions take up to 14% longer.

huge_pages is for an index too large for the CPU’s caches: with the vectors on 2 MB pages, searches are up to a quarter faster and batch builds a little faster (ADR-0016). It works on Linux, where the kernel and filesystem keep files on huge pages (ext4 on Linux 6.17 does), and does nothing elsewhere. A writer and its readers each ask for themselves. On most CPUs measured, searches were faster on huge pages, by up to 27%. With vectors of 128 dimensions they were 2 to 5% slower on AMD’s Zen 5, and with 384 dimensions, or 768 in half precision, 10 to 20% slower on a Zen 4. A Xeon 6973P-C at 128 dimensions and a Xeon 8370C at 768 and 960 were level. In half precision at 1,536 dimensions, a Zen 4 was 4% slower.

Some(true) asks from the moment the index is opened. A page not yet in memory is then read 2 MB at a time, which an index much larger than memory pays for on every miss. Some(false) never asks. None, the default, leaves it to warm, which asks under vectors of 2 KB or more: 512 dimensions at full precision, 1,024 at half. Shorter vectors in half precision may gain anyway: at 128 dimensions, five CPUs, none of them a Zen 4, searched 3 to 20% faster on huge pages in one run, so Some(true) is worth measuring there. use_huge_pages and keep_small_pages, on VectorIndex and IndexReader, do the same after opening.

Only pages read from the disk after asking go on huge pages. Vectors a writer added one at a time, and pages that a process which didn’t ask read first, stay on 4 KB pages until they leave memory, and searches over them are no faster. Copying the file may do the same.

warm is for an index whose file is not in memory yet, as after a reboot. Until it is, each page a search touches is read from the disk, one read at a time. With warm, another thread reads in what the index holds, at the disk’s sequential speed, while searches go on (ADR-0019). On an Apple M5, from the start of a process, the hundredth search over 99,000 vectors of 1,536 dimensions returned after 0.37 s with it and 1.9 s without. On Linux servers with slower disks, it returned after 1.3 to 1.7 s where it took 1.5 to 2.9 s. It reads only what has been written, and changes nothing in the file. It is off by default because an index much larger than memory would push everything else out, itself included, and on a slow disk reading the whole file can take longer than the searches would. It takes Linux 5.14 or later, or macOS; an older Linux reads in only some of the index, and Windows none. On Linux, unless huge_pages says otherwise, it asks for huge pages under vectors of 2 KB or more: read in whole, the index costs no more on them. VectorIndex::warm and IndexReader::warm ask for it after opening and return at once. From then on the option is on, so a reader that opens the file again after a compaction reads the new one in too.

Tuning Guide:

  • High Recall: Increase ef_construction to 400 and max_connections to 32.
  • Fast Search: Decrease ef_search to 20-30.
  • Low Memory: Precision::Half, or vectors with fewer dimensions.

Results

SearchResult

#![allow(unused)]
fn main() {
pub struct SearchResult {
    /// The id the vector was added under
    pub id: u64,
    
    /// Distance from the query by the index's metric
    pub distance: f32,
}
}

Results order by distance, then by id, and two are equal only when both their ids and their distances are. Check a search’s results with ==: a result with the right distance but another id doesn’t match.

C API

Chassis from C, or from any language that can call C: a shared library and its header, chassis.h. This page shows how to get them and build against them, then describes every function.

Install

Each release has the library and the header for Linux (x86-64 and ARM64), macOS (ARM64) and Windows (x86-64). To build them from a checkout instead, which needs Rust:

cd chassis-ffi
cargo build --release

That writes the library to target/release: libchassis_ffi.so on Linux, libchassis_ffi.dylib on macOS, chassis_ffi.dll on Windows. The header is chassis-ffi/include/chassis.h.

Example

#include "chassis.h"
#include <inttypes.h>
#include <stdio.h>

int main(void) {
    // Open index
    ChassisIndex* index = chassis_open("vectors.chassis", 768);
    if (index == NULL) {
        fprintf(stderr, "Error: %s\n", chassis_last_error_message());
        return 1;
    }
    
    // Add vector
    float vec[768] = {0.1, 0.2, /* ... */};
    uint64_t id = chassis_add(index, vec, 768);
    if (id == UINT64_MAX) {
        fprintf(stderr, "Error: %s\n", chassis_last_error_message());
        chassis_free(index);
        return 1;
    }
    
    // Flush to disk
    if (chassis_flush(index) != 0) {
        fprintf(stderr, "Error: %s\n", chassis_last_error_message());
        chassis_free(index);
        return 1;
    }
    
    // Search
    float query[768] = {0.1, 0.2, /* ... */};
    uint64_t ids[10];
    float distances[10];
    
    size_t count = chassis_search(index, query, 768, 10, ids, distances);
    for (size_t i = 0; i < count; i++) {
        printf("id %" PRIu64 ", distance %f\n", ids[i], distances[i]);
    }
    
    // Clean up
    chassis_free(index);
    return 0;
}

Compiling

# Linux and macOS, from the repository or an unpacked release
cc -o myapp myapp.c -Ichassis-ffi/include -Ltarget/release -lchassis_ffi \
  -Wl,-rpath,$PWD/target/release
./myapp

# Windows (MSVC)
cl myapp.c /I chassis-ffi\include /link /LIBPATH:target\release chassis_ffi.dll.lib

Functions

Lifecycle

chassis_open

ChassisIndex* chassis_open(const char* path, uint32_t dimensions);

Open or create an index. Returns NULL on error. Dimensions of 0 open an existing index with its own, and are an error where there is none. An existing index keeps its metric, precision and max_connections; a new one gets the defaults: Euclidean, full precision and 16 (ADR-0026).

chassis_open_with_options

ChassisIndex* chassis_open_with_options(
    const char* path,
    uint32_t dimensions,
    uint32_t max_connections,
    uint32_t ef_construction,
    uint32_t ef_search
);

Open with custom HNSW parameters. A max_connections of 0 takes an existing index’s, or 16 for a new one; another differing from an existing index’s fails.

chassis_open_with_metric

ChassisIndex* chassis_open_with_metric(
    const char* path,
    uint32_t dimensions,
    uint32_t max_connections,
    uint32_t ef_construction,
    uint32_t ef_search,
    uint32_t metric
);

Like chassis_open_with_options, with a distance metric: CHASSIS_METRIC_EUCLIDEAN (0) or CHASSIS_METRIC_COSINE (1, 1 - cosine similarity; vectors are stored at unit length and zero vectors are rejected). The metric is fixed when the index is created; reopening with another one fails, and CHASSIS_FROM_FILE takes an existing index’s, or Euclidean for a new one.

chassis_open_with_precision

ChassisIndex* chassis_open_with_precision(
    const char* path,
    uint32_t dimensions,
    uint32_t max_connections,
    uint32_t ef_construction,
    uint32_t ef_search,
    uint32_t metric,
    uint32_t precision
);

Like chassis_open_with_metric, with a precision: CHASSIS_PRECISION_FULL (0) keeps each component of a vector as a 32-bit float, CHASSIS_PRECISION_HALF (1) as a 16-bit float (ADR-0018). Half precision halves the vectors’ size in the file and in memory, and a search over an index too large for the CPU’s caches is faster for it. Each component is rounded to about three decimal digits, and a vector with a component of 65,520 or more in magnitude is refused. The precision is fixed when the index is created; reopening with another one fails, and CHASSIS_FROM_FILE takes an existing index’s, or full precision for a new one.

chassis_open_reader

ChassisIndex* chassis_open_reader(
    const char* path,
    uint32_t dimensions,
    uint32_t max_connections,
    uint32_t ef_search
);

Open an existing index to search it while a writer, possibly in another process, adds to it. Takes no lock, so any number of readers can open the file next to one writer. Each search sees the writer’s newest flush, which becomes visible just before its final fsync; chassis_len takes a new snapshot first. Adds, deletes and flushes on the handle fail. A file in an older format must be opened once with chassis_open to migrate it. The metric and precision come from the file; dimensions and max_connections of 0 do too, and others are checked.

chassis_use_huge_pages

int chassis_use_huge_pages(ChassisIndex* index);

Ask the operating system to keep the index’s vectors on huge pages (ADR-0016). On an index too large for the CPU’s caches, searches are up to a quarter faster. Linux only, where the kernel and filesystem keep files on huge pages (ext4 on Linux 6.17 does); elsewhere it does nothing. Unless this is called, only chassis_warm asks, under vectors of 2 KB or more: with huge pages a page not yet in memory is read 2 MB at a time, which an index much larger than memory pays for on every miss. Call it right after opening, on a writer’s handle or a reader’s. Returns 0, or -1 for a NULL handle.

chassis_keep_small_pages

int chassis_keep_small_pages(ChassisIndex* index);

Ask for no huge pages, not even by chassis_warm. Searches were faster on huge pages on most CPUs measured, not all; this is for a machine where they aren’t. What was asked for already stays asked: call it right after opening, before chassis_warm, on a writer’s handle or a reader’s. Returns 0, or -1 for a NULL handle.

chassis_warm

int chassis_warm(ChassisIndex* index);

Read the index into memory on another thread (ADR-0019), so that searches stop waiting for the disk one page at a time while its file is not in memory yet, as after a reboot. Doesn’t wait for the reading: searches go on meanwhile. What is read is what the index holds when this is called; while that is under way, calling again does nothing. A reader that opens the file again after a compaction reads the new one in too. For an index that fits in memory: one much larger would push everything else out. Linux 5.14 or macOS; an older Linux reads only some of the index, and Windows none. Under vectors of 2 KB or more it asks for huge pages too, unless chassis_keep_small_pages was called: read in whole, the index costs no more on them. Pages already in memory stay as they are. Call it on a writer’s handle or a reader’s, right after opening or later. Returns 0, or -1 for a NULL handle.

chassis_free

void chassis_free(ChassisIndex* index);

Free an index and release resources. Safe to call with NULL. It doesn’t flush: adds and deletes since the last chassis_flush are discarded, as after a crash.

Operations

chassis_add

uint64_t chassis_add(
    ChassisIndex* index,
    const float* vector,
    size_t len
);

Add a vector. Returns the id assigned (one past the largest id used so far) or UINT64_MAX on error.

Thread Safety: Safe from any thread; writes run one at a time and searches wait for them

chassis_add_with_id

int chassis_add_with_id(
    ChassisIndex* index,
    uint64_t id,
    const float* vector,
    size_t len
);

Add a vector under your own id; search reports it. Returns 0, or -1 if a live vector already has id, id is UINT64_MAX, or the add fails.

Thread Safety: Safe from any thread; writes run one at a time and searches wait for them

chassis_add_batch

size_t chassis_add_batch(
    ChassisIndex* index,
    const float* vectors,  // count * dim floats, row-major
    size_t count,
    size_t dim,
    uint64_t* out_ids      // room for count ids
);

Add many vectors at once, linking them on every core: a large batch builds many times faster than chassis_add in a loop (ADR-0010). Writes their ids, assigned as chassis_add assigns them, to out_ids. Returns count, or 0 if the batch fails, in which case none of it is added.

chassis_add_batch_with_ids

int chassis_add_batch_with_ids(
    ChassisIndex* index,
    const uint64_t* ids,   // count ids
    const float* vectors,  // count * dim floats, row-major
    size_t count,
    size_t dim
);

chassis_add_with_id for a whole batch, linked on every core. Returns 0, or -1 with none of the batch added if an id repeats, already exists or is UINT64_MAX.

Thread Safety (both): a batch holds the write lock until it is linked, so searches on the same handle wait for the whole batch.

chassis_delete

int chassis_delete(ChassisIndex* index, uint64_t id);

Delete the vector with id. Returns 1 if deleted, 0 if no live vector has id, -1 on error. Durable after the next chassis_flush(); a crash before then rolls it back.

Thread Safety: Safe from any thread; writes run one at a time and searches wait for them

size_t chassis_search(
    const ChassisIndex* index,
    const float* query,
    size_t len,
    size_t k,
    uint64_t* out_ids,
    float* out_dists
);

Search for k nearest neighbors. Returns how many results were written, or 0 on error, which chassis_last_error_code() tells apart from an index with nothing to return.

Thread Safety: Safe from any thread; runs concurrently with other searches

chassis_search_filtered

size_t chassis_search_filtered(
    const ChassisIndex* index,
    const float* query,
    size_t len,
    size_t k,
    const uint64_t* allowed_ids,
    size_t allowed_len,
    uint64_t* out_ids,
    float* out_dists
);

Like chassis_search, returning only vectors whose id is in allowed_ids. Ids not in the index are ignored; an empty list matches nothing. When walking the graph would cost more, as when few vectors match, every vector is checked instead and the results are exact. Ids in ascending order are read where they lie; in any other order they are copied into a set first, a pass over all of them per call.

chassis_search_excluding

size_t chassis_search_excluding(
    const ChassisIndex* index,
    const float* query,
    size_t len,
    size_t k,
    const uint64_t* excluded_ids,
    size_t excluded_len,
    uint64_t* out_ids,
    float* out_dists
);

Like chassis_search, never returning a vector whose id is in excluded_ids, as “more like this” leaves out the vector it starts from (see chassis_get). Ids not in the index are ignored; an empty list leaves out nothing.

chassis_search_batch

size_t chassis_search_batch(
    const ChassisIndex* index,
    const float* queries,
    size_t count,
    size_t dim,
    size_t k,
    uint64_t* out_ids,
    float* out_dists
);

Search for the k nearest neighbors of each of count queries, given one after another, dim floats each. out_ids and out_dists hold count * k values: row i is query i’s results, nearest first. A row with fewer than k results is filled out with id UINT64_MAX, which no vector has, and distance INFINITY. Returns count, or 0 on error or for an empty batch, which sets no error. An error names the query that failed, as in Query 3 of the batch has NaN at component 0.

Thread Safety: Safe from any thread; runs concurrently with other searches, and a write waits for the whole batch

chassis_flush

int chassis_flush(ChassisIndex* index);

Flush changes to disk. Returns 0 on success, -1 on error.

Thread Safety: Safe from any thread; writes run one at a time and searches wait for them

chassis_rollback

int chassis_rollback(ChassisIndex* index);

Discard every add, delete and user version since the last flush, as closing the index and opening it again would, without letting go of the writer’s lock. Call it where a write’s transaction in your own store rolls back, or the next chassis_flush commits what that write did to the index. Returns 0, or -1 for a reader handle, a NULL one, or a file that can’t be read or synced; after that, later flushes fail too: close the index and open it again.

Thread Safety: Safe from any thread; writes run one at a time and searches wait for them

chassis_backup

int chassis_backup(ChassisIndex* index, const char* path);

Write a copy of the index to path. From a writer’s handle it flushes first, and the backup holds every add and delete so far. From a reader’s handle it holds the writer’s last flush, taken while the writer keeps writing: it starts over if a flush lands during the copy, and gives up after five tries. The copy is renamed into place once whole, replacing a file already at path. Returns 0, or -1 for a NULL or non-UTF-8 path, the index’s own file, a copy that can’t be written, or a reader whose writer flushed during every try.

Thread Safety: Safe from any thread; from a writer’s handle it runs as a write does

chassis_compact

int chassis_compact(ChassisIndex* index);

Rewrite the index without its deleted vectors and with a newly built graph, then replace the file with the copy (ADR-0011). Ids don’t change. Like chassis_flush, it makes every add and delete so far durable. Returns 0, or -1 with the index left as it was; on Windows it fails while another process has the index open. It takes as long as building the index and needs free disk for a second copy.

Thread Safety: holds the write lock for its whole run, so searches on this handle wait; readers in other processes keep searching

Introspection

chassis_len

uint64_t chassis_len(const ChassisIndex* index);

Get number of vectors in the index.

chassis_get

int chassis_get(const ChassisIndex* index, uint64_t id, float* out, size_t len);

Copy the vector with id into out, which has space for len floats: the index’s dimensions. Returns 1 if a live vector has id, 0 if none has, -1 on error. The vector comes back as the index keeps it: scaled to length 1 in a cosine index, and rounded in half precision.

chassis_contains

int chassis_contains(const ChassisIndex* index, uint64_t id);

Returns 1 if a live vector has id, 0 if none has, -1 on error.

chassis_ids

size_t chassis_ids(const ChassisIndex* index, uint64_t* out, size_t cap);

Copy the ids of the live vectors into out, in the order they were added, and return how many there are. Only the first cap are written, so if the return is more than cap, call again with more space; a reader can see a newer flush than a chassis_len just before. Returns 0 on error, as for an empty index, which sets no error.

size_t cap = chassis_len(index), count;
uint64_t* ids = NULL;
do {
    ids = realloc(ids, (cap ? cap : 1) * sizeof *ids);
    count = chassis_ids(index, ids, cap);
} while (count > cap && (cap = count));

chassis_check

size_t chassis_check(const ChassisIndex* index, uint64_t* out, size_t cap, size_t* unreachable);

Check what opening can’t, reading the whole graph and every vector, and return how many ids it found; 0 means the index is in good order. The ids go into out, the first cap of them, as with chassis_ids: first the live vectors that no path through the graph reaches, so no search returns them, and *unreachable says how many those are; then the vectors with a component that isn’t a finite number, which only damage leaves. Damage can leave vectors out of reach, and chassis_compact builds the graph again; so can data with no structure, or many exact copies of one vector, rebuilt or not (Rust API). Returns 0 on error too; check chassis_last_error_code().

size_t unreachable;
size_t found = chassis_check(index, NULL, 0, &unreachable);  // Then again with space for found

chassis_deleted_count

uint64_t chassis_deleted_count(const ChassisIndex* index);

Deleted vectors the file still holds, until chassis_compact removes them.

chassis_user_version

uint64_t chassis_user_version(const ChassisIndex* index);

Your application’s number for the index, 0 until one is set: like SQLite’s user_version. Each chassis_flush commits the number set before it with the data, so after a crash it says which flush the index holds; compare it on open and as each write begins with the same number kept in your own store. A writer handle returns the number last set, flushed or not, and chassis_rollback sets it back to the flushed one; a reader handle returns the number in its newest snapshot. Returns 0 for a NULL handle, with an error set.

chassis_set_user_version

int chassis_set_user_version(ChassisIndex* index, uint64_t version);

Set the number the next chassis_flush commits. Until then, a crash leaves the one flushed before. Returns 0, or -1 for a reader handle or a NULL one.

chassis_is_empty

int chassis_is_empty(const ChassisIndex* index);

Check if index is empty. Returns 1 if empty, 0 otherwise.

chassis_dimensions

uint32_t chassis_dimensions(const ChassisIndex* index);

Get vector dimensionality.

chassis_metric

int chassis_metric(const ChassisIndex* index);

The metric the index was created with: 0 Euclidean, 1 cosine, -1 if index is NULL.

chassis_precision

int chassis_precision(const ChassisIndex* index);

The precision the index keeps its vectors in: 0 full, 1 half, -1 if index is NULL.

Errors

chassis_last_error_message

const char* chassis_last_error_message(void);

The last error on this thread: what was wrong, with the value, then a line starting help: with what to do instead. Returns NULL if no error.

Lifetime: Valid until next FFI call on this thread.

chassis_last_error_code

int chassis_last_error_code(void);

The last error’s kind, for a program to act on: one of the CHASSIS_ERROR_ constants (CHASSIS_ERROR_INVALID_ARGUMENT, CHASSIS_ERROR_DIMENSION_MISMATCH, CHASSIS_ERROR_LOCKED, …), or CHASSIS_OK (0) after a call that succeeded. Errors lists them, with their causes and fixes.

Version

chassis_version

const char* chassis_version(void);

Get library version string.

Threads

Every function except chassis_free is safe to call from any thread on the same handle. Searches, chassis_len, chassis_is_empty and chassis_dimensions run concurrently. chassis_add, chassis_add_with_id, chassis_add_batch, chassis_delete and chassis_flush take the handle’s write lock, so they run one at a time and searches wait for them. chassis_free must not race with any other call on the same handle. A handle from chassis_open_reader runs one call at a time, introspection included; open one per thread to search in parallel.

In this example, generate_vector, generate_query, process_results and keep_running stand for your own code.

// Thread 1: Writer
void* writer_thread(void* arg) {
    ChassisIndex* index = (ChassisIndex*)arg;
    
    // Each add takes the write lock; searches in other threads wait for it
    float vec[768];
    for (int i = 0; i < 1000; i++) {
        generate_vector(vec, i);
        chassis_add(index, vec, 768);
    }
    
    chassis_flush(index);
    return NULL;
}

// Thread 2: Reader
void* reader_thread(void* arg) {
    const ChassisIndex* index = (const ChassisIndex*)arg;
    
    // Runs concurrently with other searches, and waits while a write runs
    float query[768];
    uint64_t ids[10];
    float dists[10];
    
    while (keep_running) {
        generate_query(query);
        chassis_search(index, query, 768, 10, ids, dists);
        process_results(ids, dists);
    }
    
    return NULL;
}

Error checks

A function’s return value says whether it failed: NULL, UINT64_MAX or -1, or a count of 0 with an error set, as its entry above says. chassis_last_error_message and chassis_last_error_code then describe the failure. Each thread keeps its own last error, so threads never see each other’s.

if (chassis_flush(index) != 0) {
    fprintf(stderr, "Flush failed: %s\n", chassis_last_error_message());
    chassis_free(index);
    exit(1);
}

A panic inside Chassis never unwinds into C. The call returns its error value with a message that starts Chassis panicked:. After a panic in a write, the handle refuses later calls: free it and open the index again.

Safety

Each function’s entry in chassis.h lists what it needs from you. These hold for all of them:

  1. Never pass NULL where a function doesn’t say it accepts one.
  2. A vector’s length must match the index’s dimensions.
  3. The message from chassis_last_error_message is valid until the next call on the same thread.
  4. Don’t call chassis_free while another thread still uses the handle, or use the handle after.

Performance

  1. Add many vectors before each chassis_flush: a flush waits for the disk.
  2. Allocate result buffers once, and reuse them for every search.
  3. Tune max_connections, ef_construction and ef_search as the Rust API describes; the options mean the same in C.

chassis-ffi/examples/example.c is a complete program, with a Makefile beside it.

Errors

Every error from Chassis says what was wrong, with the value that was wrong, and on a line starting help: what to do instead:

The index at vectors.chassis holds vectors of 768 dimensions, not 1536
help: leave the dimensions out (0) to use the file's, or create a new index at another path

Each also has a kind, the same in every language, for a program to act on: Error::kind() in Rust, chassis_last_error_code() in C, and the exception’s class in Python. Each Python class is also the built-in exception it is a kind of, so except ValueError catches a bad argument (ADR-0020).

KindRust ErrorKindC codePython exception
Invalid argumentInvalidArgumentCHASSIS_ERROR_INVALID_ARGUMENT (1)InvalidArgumentError (ValueError), or TypeError
Dimension mismatchDimensionMismatchCHASSIS_ERROR_DIMENSION_MISMATCH (2)DimensionMismatchError (ValueError)
Options mismatchOptionsMismatchCHASSIS_ERROR_OPTIONS_MISMATCH (3)OptionsMismatchError (ValueError)
Not foundNotFoundCHASSIS_ERROR_NOT_FOUND (4)IndexNotFoundError (FileNotFoundError)
Not an indexNotAnIndexCHASSIS_ERROR_NOT_AN_INDEX (5)NotAnIndexError (ValueError)
Id in useIdInUseCHASSIS_ERROR_ID_IN_USE (6)IdInUseError (ValueError)
LockedLockedCHASSIS_ERROR_LOCKED (7)IndexLockedError
Read-onlyReadOnlyCHASSIS_ERROR_READ_ONLY (8)ReadOnlyError
CorruptCorruptCHASSIS_ERROR_CORRUPT (9)CorruptIndexError
FullFullCHASSIS_ERROR_FULL (10)IndexFullError
Input or outputIoCHASSIS_ERROR_IO (11)InvalidPathError (OSError)
OtherOtherCHASSIS_ERROR_OTHER (12)ChassisError

Every Python class is a ChassisError. In C, a call that succeeds sets the code back to CHASSIS_OK (0).

Invalid argument

An argument is out of range or malformed. The message names it and its value.

  • Dimensions are 1 to 4,096: the length of the vectors the index will hold. 0 (or none, in Python) opens an existing index with its own.
  • max_connections is 2 to 32,767; 16 suits most indexes.
  • k is at least 1. In Python it is an int; 5.0 is a TypeError.
  • A vector or query with NaN or infinity is refused, at every metric and precision, with the component’s position. NaN usually comes from dividing by zero, as in normalizing a zero vector.
  • A zero vector in a cosine index has no direction, so it can’t be compared by angle.
  • A component of 65,520 or more in magnitude doesn’t fit half precision, which holds up to 65,504. Scale the vectors down, or use full precision.
  • Ids are integers from 0 to 2⁶⁴ − 2. In Python a string id is a TypeError: keep a dict from your own keys to integer ids.
  • A path that is a directory: give the path of a file in it.
  • In Python, an unknown option is a TypeError that names the option it was likely meant to be, including other libraries’ names for them (ef is ef_search, M is max_connections). metric takes any case, and "l2" for "euclidean"; precision takes "float16" and "f16" for "half". There is no inner-product metric: for vectors of length 1, cosine orders results the same way.

Dimension mismatch

A vector or query has another number of components than the index’s vectors, or the file holds vectors of other dimensions than it was opened with. The usual cause is a vector made by another embedding model than the index’s.

  • Python, a 2-D array where one vector belongs: vector[0] or vector.ravel() for one row, add_batch to add several, and search_batch to search several.
  • A batch is its vectors back to back, dimensions floats each: a (count, dimensions) array in Python, dim equal to the index’s in C.

Options mismatch

The file was created with another metric, precision or max_connections than the one given. All three are fixed when the index is created, and opening it takes each from the file unless it’s given. Leave the option out, or create a new index at another path.

Not found

There is no index at the path a reader was given, or a writer was given dimensions of 0 (or none, in Python) to take an index’s, or the directory of a path a writer was given doesn’t exist. Create an index by opening it as a writer with its dimensions.

Not an index

The file at the path is not a Chassis index. Chassis never writes to such a file. Check the path; to create a new index, give a path where no file exists yet.

Id in use

add_with_id (add(..., id=) or add_batch(..., ids=) in Python) gave an id that a live vector already has. Delete that vector first to replace it, or use another id. Within one batch, ids have to differ.

Locked

Another writer has the index open, in this process or another. An index has one writer at a time. Close the other writer first, or open a reader (IndexReader, chassis_open_reader, read_only=True), which searches while the writer writes.

Read-only

A reader was asked to add, delete, flush or compact. Open the index as a writer to change it.

Corrupt

The file is damaged: its header or regions don’t add up. Restore it from a backup (backup), or rebuild it from its vectors. A crash or power loss doesn’t do this (the index recovers to its last flush()); a disk error or another program writing the file can. So can a copy that stopped partway: a file shorter than its header says is refused with both lengths in the message.

Full

The index can hold no more: 4,294,967,295 vectors, or no room for another region in its tables. Compact it to drop deleted vectors, or split the vectors across indexes.

Input or output

The operating system refused: no permission, a read-only or full disk, a failed read or write. The message ends with the system’s own words. An earlier flush or rollback that failed makes later flushes refuse too, since what reached the disk is unknown: open the index again.

Limits

What one index can hold, and what it needs from the machine to hold it well. Going past a hard limit is an error that names it (Errors), never a wrong answer.

Poor fits

Some limits come with the design, and no option changes them. Reach for something else for:

  • An index much larger than memory. Searches wait on the disk, over a thousand times slower (Memory). An index built for the disk, such as DiskANN, fits that better.
  • Many writers. One process writes a file at a time; a server such as Qdrant or pgvector takes writes from many.
  • Heavy churn. Deleted vectors slow searches until compact(), which builds the graph again: to about 70% of their speed with half the vectors deleted, and a fifth with 90%.
  • Metadata in the index. Chassis keeps vectors and ids. Keep the rest in SQLite or a store of your own under the same ids, and pass the ids it selects to a filtered search.
  • Inner product. There is Euclidean and cosine distance; for vectors of length 1, cosine orders results as inner product does, so only vectors of other lengths miss it.
  • Storage that fails reads. The file is mapped into memory, so a read the disk fails ends the process (SIGBUS on Linux and macOS) instead of returning an error, as with every store that maps its file.

Hard limits

WhatLimit
Vectors4,294,967,295 in a file, counting deleted ones until compact()
Ids0 to 2⁶⁴ − 2; 2⁶⁴ − 1 is reserved
Dimensions1 to 4,096
max_connections2 to 32,767; 16 by default
Componentsfinite numbers; in half precision, under 65,520 in magnitude

The file system’s own limits apply too: FAT32 holds files up to 4 GiB. A full disk is an error, except on Btrfs: it copies a page on every write, so the space Chassis allocates ahead doesn’t cover it, and a disk that fills as Chassis writes ends the process (SIGBUS) (Verification).

Size

Each vector takes its components, 4 bytes each in full precision or 2 in half, and about 164 bytes for its slot header and links at the default max_connections; each step up adds about 8 (Size).

DimensionsFull precisionHalf precisionA million, fullA million, half
128676 B420 B0.68 GB0.42 GB
3841,700 B932 B1.7 GB0.93 GB
7683,236 B1,700 B3.2 GB1.7 GB
1,5366,308 B3,236 B6.3 GB3.2 GB
3,07212,452 B6,308 B12.5 GB6.3 GB

Measured on disk, 10 million vectors of 128 dimensions in full precision took 676.3 bytes each, and 3 million of 1,536 in half precision 3,236.3. The file’s length runs up to a segment, at most 256 MiB, ahead of what’s written; where the file system keeps holes, that end takes no disk.

Memory

Chassis reads the file through the operating system’s cache, so an index searches at full speed while the file fits in the memory the process can have. Past that, searches wait on the disk. Ten million vectors of 128 dimensions, a 6.9 GB file, on a GitHub runner whose disk reads 4 KB at random in 0.19 ms (Scale):

Where the file wasQueries a second, ef 64
In memoryabout 9,000
The first 1,000 queries from a cold cache, with room to keep the file55
In a 2 GB cgroup, a third of the file2.5 to 5

warm() reads an index in ahead of the first pass, when it fits; when it doesn’t, it can’t help. Adds in the 2 GB went at 2 a second, so an index much larger than its memory can’t be built or compacted in useful time. Keep an index within the memory it has, or shrink it with half precision. A faster disk helps by an amount not yet measured.

Compaction

compact() builds a new file beside the index and renames it over the old one. It needs:

  • Disk for a second file holding the live vectors, until the rename.
  • Time about a build’s, as it builds the graph again: 1,185 s for 10 million vectors of 128 dimensions, where the build took 1,145 s; 789 s for 3 million of 1,536 in half precision, where it took 988 s.
  • Memory for about one file, not two: it reads the old one in order, a piece at a time. In a cgroup of 1.2 times the file it ran at that speed; less wasn’t measured.

Crashes

The first writer to open an index after a crash reads its undo file whole, to put back the links the unflushed adds changed: at most about 150 bytes for each flushed vector, at the default max_connections. Killed partway through adding a million vectors to ten million, it left 203 MB, and the next writer opened in 8.4 s.

With a database

Chassis keeps vectors and integer ids; the rows they belong to live in your database. This page is how to keep the two in step, through a crash at any point. The examples use SQLite from Python; the same order works with Postgres, and from Rust or C.

Ids

Give each vector an id of its own, kept in its row, and a new one whenever the row’s text changes. Mending (below) compares the ids the index holds with the ids the rows hold, so an id must never stand for two texts: an edit that kept its id would look the same before and after, and a crash between the two would leave the old text with the new vector, with nothing to show it.

import sqlite3
from contextlib import contextmanager

from chassisdb import IndexOptions, VectorIndex

db = sqlite3.connect("notes.db", isolation_level=None)  # Transactions only where we BEGIN them
db.execute(
    "CREATE TABLE IF NOT EXISTS notes ("
    "id INTEGER PRIMARY KEY, text TEXT NOT NULL, vector INTEGER UNIQUE NOT NULL)"
)
# The number of the last write, which the index keeps too; see Opening.
db.execute("CREATE TABLE IF NOT EXISTS sync (version INTEGER NOT NULL)")
db.execute("INSERT INTO sync SELECT 0 WHERE NOT EXISTS (SELECT 1 FROM sync)")
index = VectorIndex("notes.chassis", dimensions=384, options=IndexOptions(metric="cosine"))


def new_vector_ids(n):
    """Ids no row holds: past the largest, so a new text never takes an id an old one had."""
    (top,) = db.execute("SELECT coalesce(max(vector), 0) FROM notes").fetchone()
    return list(range(top + 1, top + 1 + n))

embed(texts) below stands for your embedding model.

Writing

Each write changes the rows in a transaction, changes the index, flush()es it, and only then commits. It also counts itself in sync and gives the index the same number as its user_version, which the flush commits with the vectors. If any of it fails, the commit too, it rolls back the transaction and then the index: what the write did to the index would otherwise wait there for the next write’s flush. writing() does all of that around a write’s own changes:

@contextmanager
def writing():
    """The rows and the index change together, or neither does."""
    db.execute("BEGIN IMMEDIATE")
    try:
        check()  # A write whose commit failed left the index one ahead: mend that first
        yield
        db.execute("UPDATE sync SET version = version + 1")
        index.user_version = db.execute("SELECT version FROM sync").fetchone()[0]
        index.flush()
        db.execute("COMMIT")
    except BaseException:
        if db.in_transaction:  # A failed COMMIT, as a busy reader can cause, leaves it open
            db.execute("ROLLBACK")
        index.rollback()
        raise


def add_notes(texts):
    vectors = embed(texts)  # Before the transaction: a model can take a while
    with writing():
        ids = new_vector_ids(len(texts))
        notes = [
            db.execute("INSERT INTO notes (text, vector) VALUES (?, ?)", (text, id)).lastrowid
            for text, id in zip(texts, ids)
        ]
        index.add_batch(vectors, ids=ids)
    return notes


def edit_note(note, text):
    vector = embed([text])[0]
    with writing():
        (old,) = db.execute("SELECT vector FROM notes WHERE id = ?", (note,)).fetchone()
        (new,) = new_vector_ids(1)
        db.execute("UPDATE notes SET text = ?, vector = ? WHERE id = ?", (text, new, note))
        index.delete(old)
        index.add(vector, id=new)


def delete_note(note):
    with writing():
        (vector,) = db.execute("SELECT vector FROM notes WHERE id = ?", (note,)).fetchone()
        db.execute("DELETE FROM notes WHERE id = ?", (note,))
        index.delete(vector)

What a crash leaves:

  • Before the flush: nothing. The transaction rolls back, and the index discards what wasn’t flushed, as it does whenever it is closed without one.
  • Between the flush and the commit: an index one write ahead of the rows. A new note’s vector has no row, a deleted note’s row has no vector, and an edited note has its new vector while its row keeps the old text and the old vector’s id. The next start sees the numbers differ and mends it, as Opening shows. A commit that fails without a crash leaves the same, and the next write mends it before it counts itself, which is why writing() calls check() first.

Reading

Search the index, then join the rows back by their vectors’ ids:

def search(query, k=5):
    hits = index.search(embed([query])[0], k=k)
    rows = dict(db.execute(
        f"SELECT vector, text FROM notes WHERE vector IN ({','.join('?' * len(hits))})",
        [hit.id for hit in hits],
    ).fetchall()) if hits else {}
    return [(hit.distance, rows[hit.id]) for hit in hits if hit.id in rows]

A vector a crash left without its row finds no row in the join and is dropped, and the next start mends it, so a search needs no filter for it. Don’t pass every row’s vector id as allowed to keep such vectors out: building the filter costs a pass over all of them on every search.

For a filter of your own, pass the vector ids it selects as allowed, in id order: SELECT vector FROM notes WHERE owner = ? ORDER BY vector. Ids in ascending order are searched where they lie; in any other order they are copied into a set first (ADR-0022).

Opening

When the app starts, and as each write begins, compare the two numbers. They differ only when a write flushed the index and its commit never happened, after a crash or a failed commit, the one case that leaves anything to mend:

def check():
    (version,) = db.execute("SELECT version FROM sync").fetchone()
    if index.user_version != version:
        return mend()
    return 0, 0

Mending

What a crash left is found by comparing the two sets of ids, which takes one pass over each, so run it only when check finds the numbers differ. Since each text has its own id, the comparison finds every difference, an edit’s too: its new vector is one without a row, and its old one is missing.

def mend():
    rows = dict(db.execute("SELECT vector, text FROM notes"))
    held = set(index.ids())
    for id in held - rows.keys():  # Vectors without a row
        index.delete(id)
    missing = sorted(rows.keys() - held)  # Rows without a vector
    if missing:
        index.add_batch(embed([rows[id] for id in missing]), ids=missing)
    index.user_version = db.execute("SELECT version FROM sync").fetchone()[0]
    index.flush()
    return len(held - rows.keys()), len(missing)

Backups

Back up each store with its own tool, SQLite’s .backup and the index’s backup(), at whatever moment suits: they needn’t match. After restoring both, check finds the numbers differ and mend closes the gap, as after a crash.

Other processes

Processes that only search open the index with read_only=True (Python), IndexReader (Rust) or chassis_open_reader (C). They see each flush, so with the order above a reader can see a vector a moment before its row is committed: join on the rows, as search does, and it never shows.

Recipes

Short programs for what people most often build with Chassis: search over a folder of notes, retrieval for a language model, an agent’s memory, “more like this”, and leaving out duplicates. They are in Python, keep text in SQLite and vectors in Chassis under the same ids, and continue from the setup below, so you can run them one after another.

Setup

embed stands for your embedding model. This one counts words, so the recipes run without a model to download; replace it with a real one to search by meaning.

import hashlib
import re
import sqlite3

import numpy as np
from chassisdb import IndexOptions, VectorIndex

DIMENSIONS = 256  # your model's output size


def embed(texts):
    """Stands for your embedding model: each word of four letters or more counts in a bucket."""
    vectors = np.zeros((len(texts), DIMENSIONS), dtype=np.float32)
    for row, text in enumerate(texts):
        for word in re.findall(r"[a-z]{4,}", text.lower()):
            digest = hashlib.blake2b(word.encode(), digest_size=4).digest()
            vectors[row, int.from_bytes(digest, "little") % DIMENSIONS] += 1.0
    return vectors


db = sqlite3.connect("recipes.db")
db.execute("CREATE TABLE IF NOT EXISTS docs (id INTEGER PRIMARY KEY AUTOINCREMENT, text TEXT)")
index = VectorIndex("recipes.chassis", dimensions=DIMENSIONS, options=IndexOptions(metric="cosine"))


def add(texts):
    """Rows first, then their vectors under the same ids; flush before the commit."""
    ids = [db.execute("INSERT INTO docs (text) VALUES (?)", (t,)).lastrowid for t in texts]
    index.add_batch(embed(texts), ids=ids)
    index.flush()
    db.commit()
    return ids


def search(query, k=3):
    """The nearest texts to the query, nearest first, with their distances."""
    hits = index.search(embed([query])[0], k=k)
    return [(db.execute("SELECT text FROM docs WHERE id = ?", (h.id,)).fetchone()[0], h.distance)
            for h in hits]

To search by meaning with fastembed, for example, define embed this way in the setup instead, and set DIMENSIONS to 384:

from fastembed import TextEmbedding

model = TextEmbedding("BAAI/bge-small-en-v1.5")


def embed(texts):
    return np.array(list(model.embed(texts)), dtype=np.float32)

With a database explains the write order in add, and what a crash between the flush and the commit leaves.

Notes

Search a folder of notes: one row per file.

from pathlib import Path

folder = Path("notes")
folder.mkdir(exist_ok=True)
(folder / "groceries.md").write_text("Buy milk, eggs and bread on the way home")
(folder / "report.md").write_text("The quarterly report is due on Friday")
(folder / "dentist.txt").write_text("Call the dentist to move Tuesday's appointment")

files = sorted(p for p in folder.iterdir() if p.suffix in {".md", ".txt"})
add([p.read_text() for p in files])
print(search("when is the report due", k=1))

Retrieval

For a language model’s prompt: split a document into chunks, keep each chunk as a row, and put the chunks nearest the question in the prompt.

document = """Refunds take five working days from the day the return arrives.

We ship to the European Union and the United Kingdom, in three to seven days.

Returns are free within thirty days, in the original packaging."""

chunks = [part.strip() for part in document.split("\n\n")]
add(chunks)

question = "How many days do refunds take?"
context = "\n\n".join(text for text, _ in search(question, k=2))
prompt = f"Answer from this context:\n\n{context}\n\nQuestion: {question}"
print(prompt)  # send it to your language model

Memory

An agent’s memory is the same three operations. For coding agents there is chassisdb-mcp, an MCP server built this way; in your own agent:

def remember(text):
    return add([text])[0]


def recall(query, k=3):
    return search(query, k=k)


def forget(memory_id):
    db.execute("DELETE FROM docs WHERE id = ?", (memory_id,))
    index.delete(memory_id)
    index.flush()
    db.commit()


memory = remember("The staging database is called orders_staging")
print(recall("which database is staging", k=1))
forget(memory)

Similar

“More like this”: search with a stored vector, and leave that vector out.

(first,) = db.execute("SELECT id FROM docs ORDER BY id LIMIT 1").fetchone()
for hit in index.search(index.get(first), k=3, excluded=[first]):
    print(hit.id, hit.distance)

Duplicates

Before adding a text, look for one already stored within a small distance, and keep the first. With the cosine metric, 0 is the same direction; how close counts as a duplicate depends on your model, so measure it on texts you know.

def add_unless_stored(text, within=0.05):
    hits = index.search(embed([text])[0], k=1)
    if hits and hits[0].distance <= within:
        return hits[0].id
    return add([text])[0]


first = add_unless_stored("Pick up bread and coffee beans")
assert add_unless_stored("pick up bread and coffee beans") == first

index.close()
db.close()

Coding agents

A coding agent writes better code with Chassis when it has the rules that matter in front of it: what to keep where, when writes are durable, which options are fixed. Give it one of these.

Claude Code

/plugin install chassis --marketplace tanvincible/chassis

That works in one step on Claude Code 2.1.275 or later. On older versions, run /plugin marketplace add tanvincible/chassis, then /plugin install chassis@chassis. The plugin adds a skill that Claude uses when you ask for semantic search, “more like this”, RAG retrieval or agent memory.

Cursor

mkdir -p .cursor/rules
curl -fsSL https://raw.githubusercontent.com/tanvincible/chassis/main/plugins/chassis/cursor/chassis.mdc \
  -o .cursor/rules/chassis.mdc

The rule says the same as the skill, and Cursor applies it when a task calls for vector search.

AGENTS.md

For Codex and the other agents that read AGENTS.md, add this line to the project’s AGENTS.md:

For vector or semantic search, use Chassis (Python: chassisdb; Rust: chassisdb). Read https://tanvincible.github.io/chassis/llms-full.txt before writing code with it.

Memory

chassisdb-mcp is an MCP server built on Chassis that gives agents a long-term memory on your machine: remember, recall and forget, with the embedding model you pick, local or an API.

claude mcp add --scope user chassis-memory -- \
  uvx --from 'chassisdb-mcp[fastembed]' chassisdb-mcp --embedder fastembed:BAAI/bge-small-en-v1.5

Claude Code keeps a memory of its own and uses it when both are there: set "autoMemoryEnabled": false in ~/.claude/settings.json to have it use this one. Its README has the setup for Cursor, Codex and other clients, the embedding models, and a command line to see and change what is remembered.

LangChain

langchain-chassisdb is a LangChain vector store on Chassis (pip install langchain-chassisdb): ChassisVectorStore, with metadata filters, maximal marginal relevance and readers in other processes. It passes LangChain’s standard tests for vector stores.

MCP servers

For an exception other than its own ToolError, the MCP Python SDK shows an agent only “Error executing tool”. Chassis’s messages and their help: lines never reach the model unless the tool passes them on:

from chassisdb import ChassisError
from mcp.server.mcpserver.exceptions import ToolError

def search_notes(query: str, k: int = 5) -> list[dict]:
    try:
        return find(query, k)
    except ChassisError as e:
        raise ToolError(str(e)) from e

The SDK runs synchronous tools on worker threads: open SQLite with check_same_thread=False and take a lock around it. Keep the index and your rows in step as With a database says.

Docs

  • llms.txt: an index of the docs
  • llms-full.txt: the guides, the Python, Rust and C references, the errors and an example, as one page of Markdown
  • Each page of this book: its address with .md in place of .html, as guide/errors.md

llms.txt

These docs as plain Markdown, for coding agents and other LLM tools:

  • llms.txt: what Chassis is, the rules that matter, and a link to each page
  • llms-full.txt: the guides, the Python, Rust and C references, the errors and an example, as one page
  • Each page of this book: its address with .md in place of .html, as guide/errors.md

Coding agents has a line to paste into an agent’s rules that points it at llms-full.txt.

Overview

This page is a map of how Chassis keeps and searches your vectors: what is in the file, what a write does, what a crash leaves behind, and what each choice costs. Each section links to the page or decision record with the details.

One file

An index is one file. It holds every vector, each in a slot numbered in the order it was added, and an HNSW graph over them: the lists of near neighbors that a search walks. Chassis maps the file into memory and reads vectors and lists where they lie, so opening an index loads nothing, and the operating system’s page cache decides what stays in memory.

The file only grows. Slots fill fixed-size segments; when one is full, the next region is appended and mapped. Nothing already mapped ever moves, so a reference into the file stays valid while the index grows, and a reader in another process never finds part of its mapping gone. A deleted vector keeps its space until compact() writes a new file without it. Storage and File format have the details.

Graph

Every vector has a list of neighbors on layer 0, which sits in its slot. A few vectors also have lists on sparser layers above, kept in a heap of their own; a search crosses the index on those in a few steps, then narrows in on layer 0.

To link a new vector, Chassis searches the graph for its nearest vectors, keeps a set of them that point in different directions (heuristic 2 of the HNSW paper, over all ef_construction candidates), and adds the new vector to each one’s list, pruning a list that is full. Every edge points at a vector whose data is already written. add links one vector at a time; add_batch writes the whole batch first, then links it on every core, so its graph depends on thread timing. See Graph, ADR-0004 and ADR-0010.

Ids

Your id and the slot are separate. Each slot keeps the id the vector was added under, and search returns ids. While every id equals its slot, a lookup needs no table; once one differs, the first lookup in a process scans the slots once to build an id-to-slot table in memory (ADR-0007).

Search

A search descends the upper layers greedily, then explores layer 0, keeping the ef_search nearest candidates it has seen. In that loop:

  • the set of visited vectors is a bitmap that each thread reuses, clearing only the words it set;
  • a candidate is its slot and squared distance packed into one integer;
  • distances are computed several neighbors at a time, with the next neighbors’ vectors fetched ahead;
  • the distance code is chosen when the program runs: on x86-64, AVX-512 for vectors in full precision where it pays (ADR-0025), and AVX2 and FMA otherwise (with F16C for half precision); NEON on ARM; portable code elsewhere.

A search with allowed ids walks the graph past the others, or, when that would cost more, as when few vectors match, checks every allowed vector instead and returns exact results (ADR-0009). Performance has the measured numbers and how to reproduce them.

Writes

One process writes a file at a time. The writer holds an exclusive lock (flock on Unix, LockFileEx on Windows), and a second writer’s open fails at once instead of waiting. Within the process, search takes &self while add, delete and flush take &mut self, so many threads can search one index while writes wait their turn.

An add or delete goes straight into the mapped file, and searches see it at once. It is durable after flush(), which syncs the file (msync, then fsync; F_FULLFSYNC on macOS, FlushFileBuffers on Windows), writes whichever of the two header copies doesn’t hold the newest header, and syncs again. The header’s counts are what is committed. A flush with deletes writes an intent header first, so a crash partway rolls its deletes back together. If a sync fails, the index refuses every later flush until it is reopened: after a failed fsync the OS may have dropped the pages, and a flush that then succeeded would claim data that is gone.

Readers

An IndexReader searches a file that another process writes, and takes no lock. Before each search it reads the newest valid header and maps any region added since, and it returns only vectors the last flush committed. The writer stores lists, delete marks and headers as atomic words, and rewrites a list in place so that a neighbor in both the old and the new list keeps its position: a reader partway through a list never misses an edge that was there before and after (ADR-0008).

Crashes

After a crash, reopening keeps every add and delete up to the last flush(), drops the rest, and finds the graph as that flush left it:

  • Each header copy has a checksum, so a torn header write is skipped and the other copy is used.
  • Slots past the committed count are ignored, and the next adds reuse them.
  • Adds after a flush change the lists of vectors that flush committed. Before a committed vector’s lists first change, they are saved to an undo file, <name>.undo, next to the index, and reopening puts them back (ADR-0012).
  • A crash during a flush with deletes rolls those deletes back.

A power loss between flushes can still leave some lists changed, which can lower recall. Process kills at random points are tested (chassis-core/tests/crash_tests.rs), and a simulator drops, reorders and tears unsynced writes to stand in for power loss (chassis-core/src/power_loss.rs); neither has run on real hardware.

Compaction

compact() builds a new file beside the old one, <name>.compacting, copying each live vector under its id and linking them as a batch. Then it marks the old file superseded, renames the new one over it, and continues on the new file. Ids stay the same; slots change. A crash at any point leaves one complete file at the path, and readers move to the new file on their next search (ADR-0011).

Trade-offs

ChoiceWhat it givesWhat it costs
A mapped fileNothing to load at open; vectors read where they lieunsafe code. A disk error while reading a mapped page, or a full disk on Btrfs, can crash the process (SIGBUS) instead of returning an error
A file that only growsMappings never move, so references and readers stay validDeleted vectors keep their space until compact()
One writerNo coordination between writers; readers take no lockWrites from several processes have to go through one
Commits at flush()An add costs no syncA crash loses what came after the last flush; a flush waits for the disk
An undo fileA crash leaves the committed graph wholeA second file beside the index from the first add after a flush until the next one, and one more fsync in that flush
Batches on every coreadd_batch links with every coreThe graph depends on thread timing

Verification

How Chassis is tested, so you can judge how much to trust the file you keep your vectors in: what each kind of test shows, how often it runs, and what none of them covers yet. Testing has the commands.

Crashes

Killed processes. crash_tests.rs starts a writer in a child process and kills it at random points, including during batch builds and compactions, then reopens the file. Every reopen has to show exactly the last flush: no add or delete after it, none before it lost.

Power loss. A process that is killed keeps the page cache, so it can’t show what a power cut does. power_loss.rs takes the file’s bytes at every fsync of every operation and builds the files a power cut could leave, with each 512-byte sector as last synced, as last written, or torn between the two. Each one has to reopen to the last flush or the one in progress, as a reader and as a writer, and keep working after one more flush. On 2026-10-15 that was 210 crash points, 160 of them inside the recovery a reopen runs, and 520 files. A model checker run while the protocol was designed showed why every condition is there: “every reopen shows exactly one committed state” on its own accepted 6 of 8 broken protocols (ADR-0008).

Power cuts on the real path. The simulator stands in for the kernel and the disk. In a lab run, Linux’s dm-log-writes recorded every write ext4 sent to a disk while a writer added, deleted and compacted, and the disk was replayed to each write in turn, 1,259 points. Each opened to a commit, with its length, vectors and slots exact and nothing not finite; a build that commits data before syncing it failed at 31 of its own 1,110. With the kernel writing pages back every 10 ms, 46% of the points between flushes kept most of the batch’s links, as ADR-0012 allows, and none left more vectors unreachable than its commit. The plan and numbers are in bench/lab/powercut-plan.md on the lab/x86 branch; it runs again after any change to the file format or storage.

The application’s number. Each simulated flush sets a new user_version, and every file the simulator builds has to hold the number of the flush whose vectors it holds (ADR-0023).

Histories

model_tests.rs runs random sequences of every write: adds, batches, deletes, flushes, compactions, and reopens without a flush. After each step it checks the index against a model of what it should hold: every result is a live vector at its true distance, lookups agree, readers see only what was flushed, and no search loses its way through the graph. CI runs 36 histories; run 2,000 with CHASSIS_MODEL_SEEDS.

Readers

reader_tests.rs searches while a writer adds, deletes and flushes, in the same process and from another one, and through a writer that crashes and restarts. Before format 3 was accepted, two reader processes searched 587,200 times while a writer worked: no errors, no result outside its snapshot, and no recall lost to the writer’s changes (ADR-0008).

Memory

Miri runs the tests that need no file on every pull request: the header, node records, the search loop’s parts, distances, half precision, and readers walking a neighbor list while the writer rewrites it. It reports undefined behavior, such as a word read by one thread and written by another other than atomically, which it found twice while format 3 was designed. Miri can’t map a file, so the code that reads the file through a mapping is covered by the other tests instead. Every unsafe block in the core says why it is sound, and clippy refuses one that doesn’t.

Damaged files

An embedded file meets bit rot, partial copies and sync tools. Fuzzing (fuzz/) opens files from the compatibility set with bytes changed or cut off, and any bytes at all, as a reader and as a writer, then searches and changes them: every outcome has to be an error, never a panic or a crash. It runs a minute per target on each pull request and half an hour each night. It found that a file cut off after its header crashed the process on its first search; that is now an error.

Old files

compat_tests.rs opens indexes written by earlier releases, from v0.6.3’s format 1 to v0.9.1, with deletes, custom ids, cosine, half precision and a compaction, and one of 1,500 vectors, past the first segment. Each has to show what the release that wrote it showed, and take one more vector (ADR-0023).

Platforms

Every pull request runs the tests on Linux (x86-64 and ARM64), macOS and Windows, with the newest Rust and with 1.89, the oldest supported; the Python package on Python 3.11 with numpy 1.26 and on 3.14; and clippy with warnings as errors.

Limits

  • No test has cut the power to real hardware. The simulator stands in for it, under the assumptions power_loss.rs states: a write never tears inside an aligned 8-byte word.
  • Readers were not tested during a compaction, nor with exFAT on Windows (ADR-0008).
  • A full disk is an error, tested on ext4, XFS, tmpfs, APFS and NTFS. On Btrfs, which copies a page on every write, it can still end the process (SIGBUS).

Storage

The storage layer (storage.rs) owns the index file: its lock, its regions, and the commit protocol. The byte layout is in File format.

Opening

Storage::open and VectorIndex::open:

  1. Open or create the file, and take an exclusive lock on it: flock on Unix, and on Windows LockFileEx on one byte at offset 2^62, since a lock on the whole file would also block readers’ ReadFile. On Unix they then check that the locked file is still the one at the path, since a migration may have replaced it in between.
  2. Initialize an empty file: header copies A and B, fsync, then fsync the directory so power loss can’t take the new file with it.
  3. Migrate a version 1 or 2 file to version 3.
  4. Read both header copies, take the newest valid one, map every committed region, and run recovery if a flush with deletes was interrupted.

Growth

Slots fill segments; when a slot needs a segment that doesn’t exist yet, the next region is appended at the header’s file end and mapped. Existing mappings never change, so a reference into the file stays valid while the index grows, and nothing is ever copied or remapped. Regions past the committed file end were left by a flush that never committed, and are reused.

Durability

Writes are not durable until a commit. A commit calls msync on every mapped region, then sync_all (fsync on Linux, fcntl(F_FULLFSYNC) on macOS, FlushFileBuffers on Windows), then writes the header copy that does not hold the newest header, and syncs again. If any of those fails, the storage refuses every later commit: after a failed fsync the OS may already have dropped the dirty pages, so a retry that succeeds would commit data that is gone. Reopen the index instead.

Concurrency

One writer at a time: a second writer’s open of a locked file returns an error immediately. It does not block or retry. The lock is released when the Storage is dropped.

Readers (Storage::open_read_only, behind IndexReader) take no lock and map the file read-only. Before every search a reader takes a snapshot:

  1. It copies both header copies a word at a time, and keeps the newest valid one. It never goes back to an older one than it already used.
  2. It maps any region the header or the live page shows.
  3. It routes through slots up to the live page’s routing count.

Search returns only slots the header commits and no flush up to its epoch deleted. The writer stores neighbor lists, delete marks, headers and the live page as atomic words, and rewrites a neighbor list in place so that an entry in both the old and the new list keeps its slot.

Graph

Chassis searches a persistent HNSW graph (Hierarchical Navigable Small World): lists of near neighbors, kept in the index file next to the vectors. This page explains how a vector is linked into the graph, how batches link in parallel, and what a crash can leave in the lists. The Overview shows where the graph sits among the other parts.

Layers

Every vector is on layer 0, where its list holds up to 2 × max_connections neighbors. When a vector is added, it draws a top layer at random, as the HNSW paper describes. Most vectors stay on layer 0, and each layer up holds about one in max_connections of the layer below, up to 16 layers. On each upper layer a vector’s list holds up to max_connections neighbors. The graph’s entry point is a vector on its highest layer.

A search starts at the entry point, takes the nearest neighbor on each upper layer until it reaches layer 0, and then explores layer 0 keeping the ef_search nearest vectors it has seen.

Linking

Adding a vector links it in three steps:

  1. Search. From the entry point, Chassis searches each layer the new vector is on, keeping the ef_construction nearest vectors it finds.
  2. Select. When there are more candidates than the list holds, it keeps a set that point in different directions: heuristic 2 of the HNSW paper. Taking candidates nearest first, it keeps one only if it is no nearer to a neighbor already kept than to the new vector. If that keeps fewer than a quarter of the list, the nearest of the rest fill it up to a quarter, so vectors along a line stay connected (ADR-0013).
  3. Link back. It adds the new vector to each neighbor’s list. When a list is full, it selects again among the old neighbors and the new vector the same way, and keeps the new vector if it is among the nearest. Adding a link a list already has changes nothing.

Every edge points at a vector whose data is already written: a vector’s own lists can only name vectors that exist, and a backlink is added only after the new vector is written.

Batches

add_batch writes every vector of the batch and an empty list for each first. Then a thread per core takes the batch’s vectors in order and links each one as above (ADR-0010).

  • A thread holds a vector’s lock while it changes that vector’s lists. There are 4,096 locks, shared by slot number, so threads seldom wait for each other.
  • No search reaches a batch vector before that vector has written its own lists.
  • A vector that raises the graph’s top layer holds the entry point until it is linked, so the new top connects to the old one. This is rare, and other threads wait meanwhile.

The graph then depends on the order in which threads finish, so two builds of the same batch differ, as two sequential builds already do through their random layers.

Deletes

A deleted vector stays in the graph. Searches still walk through it, so the graph stays connected, but never return it. It keeps its space until compact() builds a new graph without it.

Crashes

The write order of a link, the new vector’s lists before any backlink and the header last, holds only against a process crash: the operating system writes changed pages back to disk in any order. Against power loss, the syncs in flush() are what order the writes (ADR-0005 amendment).

After a process crash, reopening finds the graph as the last flush left it. Before a committed vector’s lists first change after a flush, they are saved to an undo file, and reopening puts them back (ADR-0012).

A power loss between flushes can leave lists that name a vector the crash rolled back. Search skips such a neighbor, and linking drops it, until the next add reuses its slot; after that it is an ordinary edge to the new vector. A link on a layer the new vector isn’t on finds no neighbors there. Edges that were pruned to make room for a lost vector stay lost, which can lower recall until the next compact().

Edge cases

CaseWhat happens
A vector as its own neighborNever kept: the search for its neighbors leaves it out.
A link a list already hasSkipped, so retrying a link writes nothing.
Exact copies of a vectorA list keeps one, plus any the quarter floor adds: copies kept among themselves would fill every list and leave other vectors out of reach.
A neighbor on fewer layers than the linkSkipped: the link names a slot that, after a power loss, a vector on fewer layers reused.

File format

This page describes the bytes of an index file, and how they change when a flush commits.

A Chassis file is one file in format version 3 (ADR-0008), or version 4 if it keeps its vectors in half precision (ADR-0018). It holds two header copies, then append-only regions: segments of slots, heap chunks of upper-layer neighbor lists, and table pages that list where the others start. Each region is mapped once, and committed bytes never move.

Opening a version 1 or 2 file migrates it to version 3 (see Migration).

Layout

OffsetSizeContents
064 KiBHeader copy A
64 KiB64 KiBHeader copy B
128 KiB64 KiBLive page, for readers in other processes
192 KiBrestRegions, in the order they were allocated

The header copies sit 64 KiB apart so they never share a page. Every region starts at a multiple of 64 KiB, the Windows mapping granularity and a multiple of every supported page size, so each one can be mapped on its own. The file only grows by appending a region, and never shrinks.

Each copy is a header of 152 + 8 × (segment table pages + heap table pages) bytes, little-endian. A later write version may add fields after these; the length covers them. The valid copy with the higher sequence number is current.

OffsetSizeFieldDescription
08MagicCHASSIS\0 in every format version
84Read versionOldest format a reader must understand: 3, or 4 in half precision
124Write versionOldest format a writer must understand: 3, or 4 in half precision
168Checksumxxh3-64 of the header’s bytes with this field zeroed
248SequenceIncreases by one with every header written
324LengthHeader length in bytes, table page lists included
364DimensionsComponents per vector, 1 to 4096
402MNeighbors per upper-layer list
422M0Neighbors per layer-0 list
441Max layersLayers a node can belong to
451Metric0: Euclidean; 1: cosine, over vectors stored at unit length
461FlagsBit 0: some id differs from its slot. Bit 1: superseded, a compacted copy is replacing this file at its path (ADR-0011)
471Table page log2Entries per table page, as a power of two
481Segment base log2Slots in the first segment, as a power of two
491Doubling segmentsSegments that double in size before the size stays constant
501Heap base log2Bytes in the first heap chunk, as a power of two
511Doubling chunksHeap chunks that double in size before the size stays constant
521Precision0: each component is an f32; 1: an IEEE 754 16-bit float, in a file of version 4
568CountCommitted slots
648Entry pointSlot of the graph’s entry point, u64::MAX if empty
724Max layerHighest layer in the graph
808EpochLast flush that committed deletes
888Pending epochNonzero while a flush with deletes is in progress
968Deleted countDeleted slots
1048File endEnd of the last committed region
1124SegmentsCommitted segments
1164Heap chunksCommitted heap chunks
1208Heap usedNext free heap position, chunk << 32 | byte offset
1284Segment table pagesNumber of segment table pages
1324Heap table pagesNumber of heap table pages
1368 eachTable page offsetsSegment table pages, then heap table pages
after the tables8Next idOne past the largest id used before the last compaction, which removed the deleted slots that showed it; 0 if never compacted. Absent from headers written before it existed, which read as 0
after next id8User versionThe application’s number, committed with the data (ADR-0023); 0 if never set. Absent from headers written before it existed, which read as 0; a release from before it ignores it, and drops it if it writes the file

A release checks the read version before the checksum, so a newer layout is reported as too new, not as corrupt. A newer write version only stops writers: IndexReader reads the file and ignores the bytes after the fields it knows. Releases up to 0.6.3 read bytes 8–11 as their version and refuse anything above 2.

A file in half precision is version 4 to readers and writers alike, so that a release from before half precision refuses it and doesn’t read its vectors as f32s. A file in full precision is written as version 3 by every release, with byte 52 zero as it always was.

Live page

What the writer has added since its last commit, so readers in other processes can route through it. Every field is a little-endian u64. The counts and the routing count are written with release ordering after the data, offsets and table entries they cover. It is not durable. A writer resets it to its committed state when it opens the file. A reader that opens the file after a crash, before any writer, uses it as found, and treats records past the committed count that it can’t read as having no neighbors.

Offset in pageField
0Routing count: slots whose nodes and backlinks are written
8, 16, 24, 32Segments, heap chunks, segment table pages, heap table pages
64Segment table page offsets (512 entries)
4,160Heap table page offsets (512 entries)

Segments

Segment k holds 2^(base + min(k, K)) slots, where base is the segment base log2 and K the number of doubling segments. A new file uses base = 10 and the largest K whose segment fits in 256 MiB, so every segment after the first K has the same C = 2^(base + K) slots. With B = C − 2^base, the slots in all doubling segments together:

  • slot s < B is in segment ⌊log2(s + 2^base)⌋ − base, at index s + 2^base − 2^⌊log2(s + 2^base)⌋;
  • slot s ≥ B is in segment K + ((s − B) >> log2 C), at index (s − B) & (C − 1).

A segment of n slots holds three arrays, each starting at a multiple of 64 bytes:

ArrayPer slotContents
Slot headers24 bytesid (u64), metadata reference (u64, 0), deleted epoch (u64, 0 while live)
Vectorsdims × 4 bytes, or dims × 2 in half precisionthe vector, little-endian
Level-0 records8 + 4 × M0 byteshead (u64), then M0 neighbor slots (u32)

A record’s head holds the node’s layer count in bits 0–7 and, for a node above layer 0, the heap position of its upper-layer lists in bits 8–63. Empty neighbor entries are 0xFFFFFFFF. A slot is deleted once its deleted epoch is nonzero; only a flush writes it.

Upper heap

Heap chunk c is 2^(heap base + min(c, doubling chunks)) bytes; a new file uses 64 KiB chunks that double up to 256 MiB. A node on L layers has one heap entry of L − 1 lists of M neighbor slots (u32), for layers 1 to L − 1. An entry never straddles two chunks.

Table pages

A table page holds 2^(table page log2) file offsets (u64), 8,192 in a new file, so a page is 64 KiB. Entry i of the segment table is in page i >> log2, at index i & (2^log2 − 1); the heap table works the same way. The header lists up to 512 pages per table, enough for 2^32 slots.

Commits

A flush writes data in place, fsyncs, then writes the header copy that does not hold the newest header and fsyncs again. Slots, regions and table entries past the committed counts are leftovers of a flush that never committed: the next writer reuses them, and until then readers may route through them but never return them.

A flush with deletes commits through an intent header first: the previous commit with pending epoch = epoch + 1, then the delete marks, then the commit header in the other copy, with an fsync after each step. Opening a file whose newest header has a pending epoch clears every deleted epoch above the header’s epoch in committed slots, then writes a clean header. Process kills are tested in chassis-core/tests/crash_tests.rs; power loss is simulated in chassis-core/src/power_loss.rs, including crashes inside recovery.

Size

10,000 vectors with 768 dimensions and default parameters take 3,232 bytes per slot (24-byte slot header, 3,072-byte vector, 136-byte level-0 record) plus about 4 bytes of upper heap. The first four segments hold 1,024, 2,048, 4,096 and 8,192 slots, so the file is about 50 MB, of which 32 MB is written. The unused end of the last segment is never written, but whether the file system keeps it sparse varies. On APFS, a real build of this example allocated 33.6 MB, and unused ranges of 16 MiB or less next to written data were sometimes allocated in full. ext4 is untested.

Undo file

Adds change the neighbor lists of committed nodes in place before they are committed themselves. Before a committed node’s lists first change after a flush, they are appended to <name>.undo, and a writer that opens the index after a crash writes them back (ADR-0012). The file exists only between a flush and the next one that follows adds, or after a crash; a flush removes it. An index moved or copied while the file exists has to take it along.

After the 8 bytes CHSUNDO1, each entry is:

  • the slot (u32) and its layer count (u8);
  • per layer, a count (u16) and that many neighbor ids (u32);
  • an xxh3-64 of the entry, seeded with a hash of the committed vector count, entry point, top layer, delete epoch, deleted count and id mark.

Entries saved from another commit fail the checksum and are ignored.

Migration

Opening a version 1 or 2 file converts it. Chassis takes the original’s lock, writes the committed state into <name>.migrating: slots below the graph’s node count, and only the delete marks the graph header committed. It converts neighbor ids from u64 to u32 and moves upper layers into the heap, then fsyncs the new file and renames it over the original, and fsyncs the directory. The graph is converted, not rebuilt, so search results are unchanged. A failed or interrupted migration leaves the original in place.

Validation

On open, Chassis checks that:

  • one header copy has the magic, versions it understands and a valid checksum; two valid copies with the same sequence number are corruption;
  • the dimensions match, and the graph parameters and geometry are possible;
  • the counts fit the tables, and every committed region lies inside the file;
  • VectorIndex::open only: the graph parameters match the requested max_connections, and a file with vectors has a graph.

A failed check returns an error and never modifies the file.

Stability

Format 3, and format 4, which is format 3 with half-precision vectors, are frozen: every later release reads every file written in them (ADR-0023). A change gets in one of two ways:

  • A field older releases can ignore goes after the last field they know, as the next id and the user version did. If an older writer dropping it would be unsafe, the change also raises the write version, so older releases open the file only to read it.
  • Anything older releases would misread, such as another way of storing vectors, raises the read version, so they refuse the file before reading it. 8-bit vectors will be read version 5.

Performance

How fast Chassis searches and builds, against hnswlib and FAISS, with the machines, the data and the commands to measure it yourself.

Summary

On GitHub’s server runners on 2026-10-19 (AMD EPYC Zen 3, 4 and 5, Intel Xeon, Arm Neoverse-N2), Chassis 0.10.0 as pip installs it against hnswlib 0.8.0 and FAISS 1.15.1, each through its Python package with every query in one call (Chassis’s search_batch), on one thread. Queries a second for 0.95 recall@10, Chassis over the other engine, as the median of a CPU’s jobs; the plan, the checks and every job are in bench/lab/compare-plan.md on the lab/x86 branch. In brackets, Chassis opened with warm, which put the vectors on huge pages where they are 2 KB or more.

Full precision

VectorsCPU (jobs)Over hnswlibOver FAISS’s HNSWOver FAISS with Panorama
128 dims × 1MZen 3 (4)1.12×1.00×1.28×
Zen 5 (1)2.49×2.05×2.72×
Neoverse-N2 (1)4.01×1.89×2.12×
960 dims × 200kZen 4 (1)1.18× (1.34×)0.85× (0.97×)0.63× (0.72×)
Neoverse-N2 (1)1.96× (2.10×)1.06× (1.14×)0.44× (0.48×)
1,536 dims × 99kZen 3 (3)1.15× (1.30×)0.86× (0.99×)0.95× (1.09×)
Xeon 6973P-C (1)1.05× (1.10×)0.93× (0.97×)0.97× (1.02×)
Neoverse-N2 (1)2.50× (2.79×)0.99× (1.11×)0.87× (0.97×)

Half precision

VectorsCPU (jobs)Over hnswlibOver FAISS’s HNSWOver FAISS with Panorama
128 dims × 1MZen 3 (4)1.62×1.43×1.85×
Zen 5 (1)2.65×2.18×2.89×
Neoverse-N2 (1)4.22×1.99×2.23×
960 dims × 200kZen 4 (1)2.07×1.50×1.10×
Neoverse-N2 (1)2.71×1.47×0.61×
1,536 dims × 99kZen 3 (3)1.46× (1.57×)1.11× (1.20×)1.20× (1.30×)
Xeon 6973P-C (1)1.42× (1.70×)1.26× (1.50×)1.32× (1.57×)
Neoverse-N2 (1)3.10× (3.34×)1.23× (1.33×)1.08× (1.16×)
  • Huge pages are most of FAISS’s lead at long vectors. FAISS’s memory gets them from Linux without asking; Chassis’s file gets them from warm, or from huge_pages (ADR-0016). On CPUs with AVX-512 the rest was AVX-512, which Chassis uses after 0.10.0: with both, a lab version of its kernel made 1.01 to 1.04 times FAISS’s queries a second at 1,536 dimensions on Zen 4, Zen 5 and two Xeons (ADR-0025).
  • Panorama keeps vectors in PCA order and stops a distance once it can’t win. It gained most where a few components carry most of a vector, as in GIST’s image descriptors. It was slower than FAISS’s plain HNSW at 128 dimensions, and on x86 with the text embeddings for 0.95 recall.
  • Jobs where FAISS searched more than 5% faster or slower a second time are left out, 8 of 21, which leaves GIST one x86 job. Counting them, Panorama was ahead of Chassis’s fastest setting on GIST on Zen 3 (1.23×, three jobs) and on a Xeon 8370C (1.11×).

With one call per query instead of one for all, Chassis spends 13 to 26 µs a query outside the library on server CPUs (2026-10-17); in one call it is within 5% of Rust.

Across search settings on a Xeon, in an earlier run (2026-10-10, without warm or Panorama):

Comparison has Annoy, sqlite-vec and LanceDB too, with build times, file sizes and cold starts.

From a cold start (ADR-0019, Apple M5, 99,000 × 1,536 dims, the file not in memory): the first result came 0.11 s after the process started. hnswlib, which loads its file first, gave its first at 0.5 to 0.8 s. With warm(), the hundredth result came at 0.37 s instead of 1.9 s.

Builds

Measured on 2026-10-07 on the same M5, which has 4 performance and 6 efficiency cores and was in Low Power Mode, with other applications running. One build at a time, M 16, ef_construction 200; “every core” is Chassis’s add_batch and hnswlib’s num_threads=-1. Search is one thread.

DatasetEngineOne threadEvery coreSpeedupef 64, every core: recall / QPS
SIFT-1MChassis545 s110 s5.0×0.968 / 4,111
hnswlib682 s131 s5.2×0.959 / 2,878
dbpedia, 99k × 1536Chassis417 s176 s2.4×0.978 / 841
hnswlib596 s163 s3.7×0.970 / 481

Graphs built on every core reach the same recall as one-thread builds of either engine (within 0.002 from ef 32 up, and 0.007 below). Their QPS varied by up to 40% either way between single passes, so these runs don’t compare search speed. An earlier parallel dbpedia run the same day took 159 s for Chassis and 158 s for hnswlib, so builds vary by about 10% between runs. The 1,536-dimension build scales less for both engines; ADR-0010 has the details.

A one-thread build of SIFT-1M peaked at 1.09 GB of memory, 0.51 GB of it the vectors the harness holds, and one of dbpedia at 1.22 GB with 0.61 GB.

Size

Each slot takes a 24-byte slot header, its vector, and a level-0 record of 8 + 4 × M0 bytes (136 with the defaults). The few nodes above layer 0 add 4 × M bytes per extra layer in the upper heap, about 4 bytes per vector on average. For 1M vectors with 768 dimensions that is 3.07 GB of vectors and 0.16 GB of everything else; half precision halves the vectors. Built as above, SIFT-1M’s file is 713 MB and dbpedia’s 821 MB.

Segments double in size up to 256 MiB, so the file can be up to one segment longer than the data written. That unused end is never written, and takes no disk where the file system keeps holes: ext4, XFS and btrfs keep all of them, and APFS those of 16 MiB or more. On Linux the writer allocates 1 MiB ahead of what it writes, so that a full disk is an error, not a crash. On APFS, files as long as SIFT-1M’s and dbpedia’s took 688 and 630 MB of disk. A backup keeps the holes too.

Deletes

A search still walks through deleted vectors, to keep the graph connected, so deletes cost speed and space but not recall. With half the vectors deleted, searches ran at about 70% of their speed, and with 90% deleted at a fifth. compact() gives the speed back (ADR-0011).

Scale

Ten million vectors of 128 dimensions with the default options, on one GitHub runner (AMD EPYC Zen 4, 4 vCPUs, 15 GB) on 2026-10-20: a file of 6.9 GB. The vectors were made up, points around 1,000 centers in 16 dimensions projected to 128, so their recall says nothing about real embeddings’. Every step ran without an error, and check found one vector that no path reaches, which a search through the graph can’t return until compact builds the graph again, as it did here.

StepTook
Build, on every core20 minutes; each million took longer, 52 s the first and 149 s the tenth
Search, one threadef 64: recall@10 0.988 at 8,859 queries a second; ef 256: 0.999 at 3,015
Openunder 0.01 s as a reader or a writer; 6 s after a writer was killed mid-add
check4 s
Delete 100,000; add 99,0000.9 s; 67 s, 10,000 at a time, each flushed
backup17 s, keeping the file’s holes
compact18.5 minutes; at its peak 12.5 GB in memory, nearly all of it the two files, though a later run held it to 1.2 times one file at the build’s speed

Memory besides the file’s pages, sampled after each million added, peaked at 534 MB, 512 MB of it the million vectors being added.

The same index in a cgroup with 2 GB of memory, a third of the file, gave the same results, but at 5 queries a second, and took 2 adds a second, with most of the index on the runner’s disk. warm didn’t help, as it can’t keep more than fits. How much a faster disk helps wasn’t measured. Keep an index within the memory it has, or shrink it with half precision (ADR-0018): each vector also takes about 164 bytes for its links and header at the default M, so half precision takes 62% of the room at 128 dimensions, and nearly half from 768 (Limits). Building or compacting one larger than memory is out of reach at that rate: a million adds would take nearly a week. The plan, the predictions and every number are in bench/lab/scale-plan.md on the lab/x86 branch.

History

Measurements of file format 2, before v0.7.0, are in the decision records that each change came with, and in this page’s history.

Reproduce

# Against hnswlib and usearch (downloads about 1.9 GB of datasets)
pip install numpy h5py pyarrow hnswlib usearch
python bench/ann/prepare.py
cargo run --release --example ann -- bench/ann/data sift-128          # add `batch` for every core
python bench/ann/reference_bench.py hnswlib bench/ann/data sift-128   # add `0` for every core
python bench/ann/reference_bench.py usearch bench/ann/data sift-128

Benchmarking has the other harnesses, and how to measure fairly.

Comparison

How Chassis compares with other ways to search vectors on one machine: what each one is, and how each measured on the same vectors, on the same machines, on the same day. Pick by shape first; the numbers matter only among tools that fit.

Engines

EngineWhat it isWhat it keeps
ChassisA library: an HNSW index in one file, read where it liesVectors under your integer ids; one writer, readers in other processes
hnswlibA library: an HNSW index in memory, saved and loaded wholeVectors under integer labels
FAISSA library of in-memory indexes; HNSW hereVectors; ids with an id map
usearchA library: an HNSW index, in memory or viewed from its fileVectors under integer keys
AnnoyA library: random-projection trees, built once, then read-onlyVectors under integer ids
sqlite-vecA SQLite extension: vectors in SQL tables, searched by scanning them all (as of 0.1.9)Vectors beside your rows, in your SQLite file
LanceDBAn embedded database of columns and vectorsVectors with their columns, filters in the query, versions of the data

Measured

On GitHub’s runners, 2026-10-10. Each engine through its Python package: built on every core with M 16 and ef_construction 200 where it has such settings, saved to disk, opened, and searched on one thread for the 10 nearest. Queries a second is the middle of three passes over the queries; the recall beside it is recall@10 against the dataset’s true neighbors, at the first search setting that reached about 0.96 and 0.99. First result, cold: a fresh process opens the file after it was put out of memory, and searches once.

Chassis was called once per query in this run, which costs it 15 to 38 µs a query in Python; the other engines were given all their queries at once. A run of 0.10.0 on 2026-10-19, with every engine called the same way, is on Performance.

SIFT, 1M vectors of 128 dimensions, on an AMD EPYC 7763:

EngineQueries a second (recall)Queries a second (recall)BuildFileFirst result, cold
Chassis6,959 (0.967)3,619 (0.992)119 s713 MB317 ms
Chassis, half precision8,265 (0.967)5,835 (0.992)89 s444 MB273 ms
FAISS (HNSW)7,941 (0.964)4,270 (0.991)137 s656 MB1,469 ms
hnswlib7,338 (0.960)2,385 (0.997)136 s661 MB2,159 ms
usearch3,817 (0.956)896 (0.997)201 s661 MB1,417 ms
LanceDB323 (0.957)229 (0.997, re-ranked)114 s828 MB1,380 ms
Annoy331 (0.988)92 (0.999)22 s904 MB850 ms
sqlite-vec5 (0.999, every vector)9 s536 MB1,003 ms

dbpedia, 99,000 vectors of 1,536 dimensions (OpenAI embeddings), on an AMD EPYC 9V74:

EngineQueries a second (recall)Queries a second (recall)BuildFileFirst result, cold
Chassis1,214 (0.979)693 (0.993)92 s821 MB512 ms
Chassis, half precision1,929 (0.979)1,124 (0.993)61 s421 MB252 ms
FAISS (HNSW)2,565 (0.975)1,415 (0.991)70 s623 MB3,308 ms
hnswlib1,926 (0.967)614 (0.996)58 s623 MB2,067 ms
usearch1,224 (0.967)384 (0.996)72 s623 MB1,312 ms
LanceDB383 (0.963)224 (0.999, re-ranked)33 s777 MB1,139 ms
Annoy142 (0.962)14 s647 MB1,362 ms
sqlite-vec4 (1.000, every vector)37 s613 MB2,617 ms

What these show:

  • Search speed among the HNSW libraries. Here, on SIFT, Chassis searched at 0.85 to 0.9 times FAISS’s speed in full precision and 1.04 to 1.37 times in half precision. On dbpedia, FAISS was about twice as fast as Chassis in full precision, and 1.3 times as fast in half. In the run of 0.10.0, with every engine called alike, Chassis ran at 1.00 to 2.05 times FAISS’s speed on SIFT, and on dbpedia at 0.86 to 0.99 times in full precision, 0.97 to 1.11 with warm, and 1.11 to 1.26 in half (Performance).
  • First result from a cold file. Chassis took 0.15 to 0.45 of the time the others did, since it reads only the pages a search touches instead of loading the index first.
  • File size. Segments double up to 256 MiB, and the length counted here includes the unused end of the last one, which takes no disk on ext4, XFS and btrfs past the 1 MiB allocated ahead, nor on APFS from 16 MiB (Performance). On disk on APFS, Chassis’s files took 4% more than hnswlib’s on SIFT and 1% more on dbpedia. Half precision halves the vectors.
  • LanceDB and sqlite-vec are databases, not just indexes: they keep your columns and filter in their queries, and here they searched one to three orders of magnitude more slowly. sqlite-vec checks every vector, so its results are exact.

Choosing

  • Chassis fits an app that embeds its own data and searches it on the same machine: one file, in your process, with your rows in your own store under the same ids (With a database).
  • sqlite-vec, when the data is in SQLite already and the search should be part of SQL queries, over few enough vectors that a scan is fast enough.
  • LanceDB, when you want one store for vectors and their columns, with filters in the query and versions of the data.
  • FAISS, hnswlib or usearch, when the index fits in memory, is built in one go, and you handle saving it and keeping it in step with your data yourself.
  • A server such as pgvector or Qdrant, when many machines write to one index, or other services query it over the network.

zvec was not measured. The harness is bench/lab/incumbents.py on the lab/x86 branch, and every row it wrote for this page is in bench/results/engines-2026-10-10.csv.

Building

This page shows how to build Chassis from a checkout, on Linux, macOS or Windows.

Requirements

  • Rust 1.89 or later
  • A C compiler (for some dependencies)
  • Git

Clone

git clone https://github.com/tanvincible/chassis.git
cd chassis

Build

Build the project in release mode:

cargo build --release

The compiled library will be in target/release/.

For development builds without optimizations:

cargo build

Checks

Run the linter and the formatter as CI does, and fix any warning before you open a pull request:

cargo clippy --all-features --all-targets -- -D warnings
cargo fmt --all -- --check

Platforms

Linux

No special setup required. The build uses standard glibc.

macOS

Xcode command line tools are required for the C compiler:

xcode-select --install

Windows

Install Visual Studio Build Tools or the full Visual Studio IDE. The Rust installer will detect and use the MSVC toolchain automatically.

Cross-compiling

Chassis runs on x86-64 and ARM64. To build for ARM on an x86 machine:

rustup target add aarch64-unknown-linux-gnu
cargo build --target aarch64-unknown-linux-gnu --release

Test on ARM hardware too: an emulator may not catch alignment mistakes.

Testing

This page shows how to run Chassis’s tests, what each suite checks, and what CI runs, so you know which tests cover a change and where a new one belongs. Verification has what the tests show, and what none of them covers yet.

Running

# Every Rust test in the workspace
cargo test --workspace --all-features

# One suite
cargo test -p chassisdb --test crash_tests

# The random-history test with many more histories (12 by default)
CHASSIS_MODEL_SEEDS=2000 cargo test -p chassisdb --release --test model_tests

Run the slower suites (crash_tests, model_tests, batch_tests) in release when you run them often: a debug build computes distances many times slower.

The Python package, the MCP server and the LangChain integration test against the C library in target/release. The Python package’s tests need its dev extras, which include pytest-cov:

cargo build --release -p chassis-ffi
pip install -e "./chassisdb[dev]"

(cd chassisdb && CHASSIS_LIB_PATH=../target/release PYTHONPATH=. pytest)
(cd chassisdb-mcp && pip install -e ../chassisdb -e . && python -m pytest tests)
(cd integrations/langchain-chassisdb && pip install -e ../../chassisdb -e . && python -m pytest tests)

Suites

The Rust suites are in chassis-core/tests; each file says at its top what it checks.

SuiteWhat it checks
index_integrationVectorIndex end to end: open, add, delete, search, flush, reopen
storage_testsThe file: the lock, growth, commits and reopening
graph_io_tests, link_testsNeighbor lists on disk, and linking with the diversity heuristic
search_testsSearch: results, ordering, edge cases
batch_testsadd_batch on every core builds a graph as good as one built a vector at a time
filter_testsFiltered search returns only allowed ids, and the nearest of them
metric_testsCosine ranking and distances match brute force; the metric is the file’s
half_precision_testsHalf precision finds what brute force over the rounded vectors finds
compaction_testscompact() keeps every vector under its id and drops the deleted ones
migration_testsOpening a format 1 or 2 file migrates it to format 3
compat_testsFiles written by earlier releases (tests/compat) open, search as they did, and take writes
duplicate_testsMany exact copies of a vector leave every other vector reachable
reader_testsReaders in other processes, while a writer changes the file
crash_testsA writer killed at random points: every reopen shows exactly the last flush
model_testsRandom sequences of every write, checked against a model of what the index should hold
error_testsEach mistake gets its error kind, its values and a help: line
warm_tests, huge_pages_tests, fork_testswarm, huge pages, and a forked child dropping an index its parent was reading in
compile_failCode that would let a vector outlive its borrow doesn’t compile (tests/ui)

Unit tests sit next to the code they test. Among them, power_loss.rs stands in for a power loss at every fsync of every operation. It builds the files a power loss could leave, with each 512-byte sector as last synced, as last written, or torn between the two, and checks that each one reopens to the last flush or the one in progress.

The Python tests are in chassisdb/tests: the bindings, every error, and the code agents copy, which they run: the agent skill’s Python blocks and the examples.

CI

WorkflowWhat it runs
CIcargo test --all-features on Linux x86-64 and ARM64, macOS and Windows, with stable Rust and 1.89; the in-memory tests under Miri; the AVX-512 kernel’s and search loop’s under Intel SDE; the Python tests on Python 3.11 with numpy 1.26 and on 3.14; the MCP and LangChain tests; cargo fmt, cargo clippy -D warnings, cargo doc; ruff, black and mypy
MSRVcargo check and cargo test on Rust 1.89
Coveragecargo llvm-cov on Linux
FuzzDamaged files and any bytes, opened and changed: a minute per target on each pull request, half an hour each night
FilesystemsThe core’s tests with their files on tmpfs, XFS, Btrfs, exFAT and NFS on Linux, exFAT on macOS, and an SMB share, exFAT and ReFS on Windows
BuildThe C library and the Python wheels for Linux x86-64 and ARM64, macOS and Windows
BenchmarkEach pull request against main, on Linux x86-64 and ARM64 (Benchmarking)

compile_fail runs only on stable: it compares rustc’s error text, which changes between releases.

Writing tests

  • Put each index in a temporary directory (tempfile::tempdir()), never a fixed path.
  • Make random data deterministic: seed it, as model_tests.rs does with its own xorshift.
  • To test a crash, run the writer in a child process and kill it, as crash_tests.rs does.
  • When a test checks recall, which varies with thread timing, check it over many queries with a margin, not one query exactly.

Benchmarking

This page shows how to measure Chassis: against other engines on standard datasets, one feature at a time, on every pull request, and down to single functions. The numbers these produce, with the machines and dates, are on Performance.

Datasets

bench/ann measures Chassis against hnswlib and usearch on the ANN benchmark datasets, with the same settings for every engine: M 16, ef_construction 200, recall@10 against queries a second on one thread.

pip install numpy h5py pyarrow hnswlib usearch
python bench/ann/prepare.py bench/ann/data sift-128     # also glove-100, dbpedia-openai3-1536

cargo run --release --example ann -- bench/ann/data sift-128          # an add per vector
cargo run --release --example ann -- bench/ann/data sift-128 batch    # add_batch on every core
python bench/ann/reference_bench.py hnswlib bench/ann/data sift-128
python bench/ann/reference_bench.py usearch bench/ann/data sift-128

Features

Each of these examples measures one thing, and names the decision record it was written for:

ExampleWhat it measures
recallBuild time, recall@10 and search latency on random vectors: -- [count] [dims]
filteredFiltered search latency and recall on a dataset (ADR-0009)
churnWhat deletes cost, and what compact() gives back (ADR-0011)
lost_addsWhat a crash that loses adds does to the vectors committed before it (ADR-0012)
undo_costWhat saving committed vectors’ lists costs (ADR-0012)

Run one with cargo run --release --example <name> -- <arguments>; the top of each file says what it takes.

Pull requests

Every pull request is measured against main on Linux x86-64 and ARM64, on SIFT (128 dimensions, 100,000 vectors) and dbpedia (1,536 dimensions, 20,000 vectors, in full and half precision). bench/compare.py builds both versions of chassis-core/examples/bench.rs and runs them by turns on one machine, so the machine’s speed cancels out. It posts the result as a comment, and the check fails if anything got markedly slower or lost recall.

Functions

The criterion benchmarks in chassis-core/benches time single functions on small, hand-built inputs: distances, storage writes and reads, linking, graph reads and search. They are for comparing two versions of one function, not for numbers to publish.

cargo bench -p chassisdb --bench distance_bench                 # also storage_bench, link_bench,
                                                               # search_bench, graph_io_bench,
                                                               # hnsw_node_bench
cargo bench -p chassisdb --bench search_bench -- high_ef        # only the groups matching high_ef
cargo bench -p chassisdb --bench search_bench -- --save-baseline before
cargo bench -p chassisdb --bench search_bench -- --baseline before

The last two compare a change with the code before it. Criterion writes HTML reports to target/criterion.

Measuring

  • Compare at equal recall. A faster search that finds less hasn’t won anything (ADR-0017).
  • Use release builds, and a quiet machine: close what you can, and run each side more than once.
  • Say whether the index was in memory. On macOS a file you just copied isn’t, so a first run reads it from disk.
  • With every number, give the machine, the data and the date, as STYLE.md asks.

Contributing

How to build Chassis, run its tests, and propose a change is in CONTRIBUTING.md in the repository.