Vector Indexing
Vector indexing powers similarity-based search. When a document’s vector field is indexed, Laurus stores the embedding vector in a specialized index structure that enables fast approximate nearest neighbor (ANN) retrieval.
How Vector Indexing Works
sequenceDiagram
participant Doc as Document
participant Embedder
participant Normalize as Normalizer
participant Index as Vector Index
Doc->>Embedder: "Rust is a systems language"
Embedder-->>Normalize: [0.12, -0.45, 0.78, ...]
Normalize->>Normalize: L2 normalize
Normalize-->>Index: [0.14, -0.52, 0.90, ...]
Index->>Index: Insert into index structure
Step by Step
- Embed: The text (or image) is converted to a vector by the configured embedder
- Normalize: The vector is L2-normalized only for the Cosine metric (a magnitude-invariant metric). Euclidean, DotProduct, and Manhattan fields keep their original vectors so their distances are preserved
- Index: The vector is inserted into the configured index structure (Flat, HNSW, or IVF)
- Commit: On
commit(), the index is flushed to persistent storage
Index Types
Laurus supports three vector index types, each with different performance characteristics:
Comparison
| Property | Flat | HNSW | IVF |
|---|---|---|---|
| Accuracy | 100% (exact) | ~95-99% (approximate) | ~90-98% (approximate) |
| Search speed | O(n) linear scan | O(log n) graph walk | O(n/k) cluster scan |
| Memory usage | Low | Higher (graph edges) | Moderate (centroids) |
| Index build time | Fast | Moderate | Slower (clustering) |
| Best for | < 10K vectors | 10K - 10M vectors | > 1M vectors |
Flat Index
The simplest index. Compares the query vector against every stored vector (brute-force).
#![allow(unused)]
fn main() {
use laurus::vector::FlatOption;
use laurus::vector::core::distance::DistanceMetric;
let opt = FlatOption {
dimension: 384,
distance: DistanceMetric::Cosine,
..Default::default()
};
}
- Pros: 100% recall (exact results), simple, low memory
- Cons: Slow for large datasets (linear scan)
- Use when: You have fewer than ~10,000 vectors, or you need exact results
HNSW Index
Hierarchical Navigable Small World graph. The default and most commonly used index type.
graph TB
subgraph "Layer 2 (sparse)"
A2["A"] --- C2["C"]
end
subgraph "Layer 1 (medium)"
A1["A"] --- B1["B"]
A1 --- C1["C"]
B1 --- D1["D"]
C1 --- D1
end
subgraph "Layer 0 (dense - all vectors)"
A0["A"] --- B0["B"]
A0 --- C0["C"]
B0 --- D0["D"]
B0 --- E0["E"]
C0 --- D0
C0 --- F0["F"]
D0 --- E0
E0 --- F0
end
A2 -.->|"entry point"| A1
A1 -.-> A0
C2 -.-> C1
C1 -.-> C0
B1 -.-> B0
D1 -.-> D0
The HNSW algorithm searches from the top (sparse) layer down to the bottom (dense) layer, narrowing the search space at each level.
#![allow(unused)]
fn main() {
use laurus::vector::HnswOption;
use laurus::vector::core::distance::DistanceMetric;
let opt = HnswOption {
dimension: 384,
distance: DistanceMetric::Cosine,
m: 16, // max connections per node per layer
ef_construction: 200, // search width during index building
..Default::default()
};
}
HNSW Parameters
| Parameter | Default | Description | Impact |
|---|---|---|---|
m | 16 | Max bi-directional connections per layer | Higher = better recall, more memory |
ef_construction | 200 | Search width during index building | Higher = better recall, slower build |
dimension | 128 | Vector dimensions | Must match embedder output |
distance | Cosine | Distance metric | See Distance Metrics below |
Tuning tips:
- Increase
m(e.g., 32 or 64) for higher recall at the cost of memory - Increase
ef_construction(e.g., 400) for better index quality at the cost of build time - At search time, the
ef_searchparameter (set in the search request) controls the search width
IVF Index
Inverted File Index. Partitions vectors into clusters, then only searches relevant clusters.
graph TB
Q["Query Vector"]
Q --> C1["Cluster 1\n(centroid)"]
Q --> C2["Cluster 2\n(centroid)"]
C1 --> V1["vec_3"]
C1 --> V2["vec_7"]
C1 --> V3["vec_12"]
C2 --> V4["vec_1"]
C2 --> V5["vec_9"]
C2 --> V6["vec_15"]
style C1 fill:#f9f,stroke:#333
style C2 fill:#f9f,stroke:#333
#![allow(unused)]
fn main() {
use laurus::vector::IvfOption;
use laurus::vector::core::distance::DistanceMetric;
let opt = IvfOption {
dimension: 384,
distance: DistanceMetric::Cosine,
n_clusters: 100, // number of clusters
n_probe: 10, // clusters to search at query time
..Default::default()
};
}
IVF Parameters
| Parameter | Default | Description | Impact |
|---|---|---|---|
n_clusters | 100 | Number of Voronoi cells | More clusters = faster search, lower recall |
n_probe | 1 | Clusters to search at query time | Higher = better recall, slower search |
dimension | (required) | Vector dimensions | Must match embedder output |
distance | Cosine | Distance metric | See Distance Metrics below |
Tuning tips:
- Set
n_clustersto roughlysqrt(n)wherenis the number of vectors - Set
n_probeto 5-20% ofn_clustersfor a good recall/speed trade-off - IVF requires a training phase — initial indexing may be slower
Distance Metrics
| Metric | Description | Range | Best For |
|---|---|---|---|
Cosine | 1 - cosine similarity | [0, 2] | Text embeddings (most common) |
Euclidean | L2 distance | [0, +inf) | Spatial data |
Manhattan | L1 distance | [0, +inf) | Feature vectors |
DotProduct | Negative inner product | (-inf, +inf) | Pre-normalized vectors |
Angular | Angular distance | [0, pi] | Directional similarity |
#![allow(unused)]
fn main() {
use laurus::vector::core::distance::DistanceMetric;
let metric = DistanceMetric::Cosine; // Default for text
let metric = DistanceMetric::Euclidean; // For spatial data
let metric = DistanceMetric::Manhattan; // L1 distance
let metric = DistanceMetric::DotProduct; // For pre-normalized vectors
let metric = DistanceMetric::Angular; // Angular distance
}
Note: Vectors are automatically L2-normalized before indexing only for the
Cosinemetric. Normalizing is magnitude-invariant, so it is safe for Cosine (and additionally tightens the int8 quantization range), but it would change the distances of magnitude-sensitive metrics — soEuclidean,DotProduct, andManhattanfields are stored without normalization. Lower distance = more similar.Migration note: non-Cosine fields created before this behavior was corrected have L2-normalized vectors on disk (the original magnitudes are not recoverable). Rebuild such an index to get correct distances.
Quantization
By default, vectors are stored on disk as 8-bit scalar-quantized
integers (Issue #481 Stage 1). Compared to the previous 32-bit float
storage this is ~4x smaller with negligible recall loss in practice
(Recall@10 remains ≥ 0.95 against the f32 ground truth — see the
recall test at laurus/tests/vector_recall_test.rs).
| Method | Enum Variant | Description | Memory Reduction | Index Types |
|---|---|---|---|---|
| Scalar 8-bit (default) | Scalar8Bit | Per-segment global affine quantization to u8 | ~4x | HNSW, Flat, IVF |
| Product Quantization | ProductQuantization { subvector_count } | Stage 3 of #481 — codebook of M × 256 centroids (trained per segment, or trained once and shared via pq_codebook_path), each vector stored as M bytes | ~16-64x | HNSW |
| PQ FastScan (experimental) | ProductQuantizationFastScan { subvector_count } | Issue #695 — M × 16 centroids, each vector stored as M 4-bit codes; needs the pq-fastscan cargo feature | ~32-128x | HNSW |
| Float16 | Float16 | Issue #623 — IEEE 754 half precision, 2 bytes per dimension; nothing to train (see Float16) | ~2x | HNSW, Flat, IVF |
Product Quantization and PQ FastScan support only the Euclidean and
Cosine distance metrics. Defining an HNSW field with another metric is
rejected; reopening an older index warns and leaves the field repairable
with Engine::update_field. To use another metric, choose a non-PQ
quantizer such as Scalar8Bit or Float16.
A Flat or IVF field with a quantizer its index type does not support is rejected when the index is created or the field is added or updated (Issue #1457).
Breaking change (Issue #1457): a Flat or IVF field with
ProductQuantization(orProductQuantizationFastScan) used to be accepted and stored asScalar8Bitwithout an error. It is now rejected, and an index whoseschema.tomlalready holds such a field fails to open. Its segments are alreadyScalar8Bit, so setting that field’s quantizer toScalar8Bitinschema.tomlreopens the index unchanged; to move toFloat16, reopen it first and then change the quantizer withupdate_field(a reindex).
#![allow(unused)]
fn main() {
use laurus::vector::HnswOption;
use laurus::vector::core::quantization::QuantizationMethod;
// `quantizer` defaults to `Scalar8Bit`; the explicit form below is
// equivalent to `HnswOption { dimension: 384, ..Default::default() }`.
let opt = HnswOption {
dimension: 384,
quantizer: QuantizationMethod::Scalar8Bit,
..Default::default()
};
}
Breaking change (Issue #481 Stage 1): the
quantizerfield is no longerOption<QuantizationMethod>; quantization is mandatory and defaults toScalar8Bit. There is no longer an unquantized (f32) on-disk format. Existing pre-Stage-1 vector indexes are intentionally not readable by this version — rebuild the index from source data.
How Scalar8Bit works
- Each segment trains a single global
(offset, scale)pair from its f32 vectors at flush time (offset = min,scale = (max - min) / 255). - Each
f32element is encoded asu8 = clamp(round((v - offset) / scale), 0, 255). - Per-vector metadata (
sum_q: u32,norm_q: f32) is precomputed and persisted alongside the int8 payload so the cosine search hot loop collapses to one int8 SIMD multiply-accumulate plus three scalar corrections — no per-element dequantization at search time. - Segment files start with the
LVS1magic + a 16-byte header so the reader can detect the format at load time. The header carries a version (a feature ladder: v2 = ordinal-encoded HNSW graph block, v3 = per-segment field-name dictionary) and, from v3 on, the dictionary itself — records then reference field names by a 16-bit id instead of repeating the full name inline. - Where the rows live depends on the loading mode, and both modes run
the same int8 kernels and return the same scores. With the default
mmap-backed
FileStorage(Lazy), the int8 rows and their metadata are read in place from the mapped segment file (Issue #1463): they are not copied onto the heap, and a search allocates nothing per candidate. WithEagerloading (MemoryStorage, orFileStoragewithLAURUS_NO_MMAP=1), the rows are copied into memory when the segment is loaded, each padded to a multiple of 32 bytes. On Windows, a mapped segment file that a merge deletes stays on disk until its reader is dropped; leftover files are removed on the next open.
Two-stage rerank (Issue #481 Stage 2)
Stage 1 stores vectors as int8 only. The graph search runs entirely against int8 distances, which is fast but introduces a small quantization error. Stage 2 adds an optional per-field f32 sidecar so the searcher can rescore the top candidates against the original full-precision vectors:
- The HNSW int8 graph search returns up to
ef_searchcandidates ranked by quantized cosine distance. - The top
top_k * rerank_factorcandidates are rescored against the f32 vectors loaded from the LRS1 sidecar (*.hnsw.f32). - The new ranking is truncated to
top_kand returned.
Since #932 the same sidecar mechanism serves Flat and IVF too (the
shared RerankPipeline, #650); the description below uses HNSW, the
original Stage-2 host. Stage 2 is opt-in per field via
HnswOption.rerank_storage:
#![allow(unused)]
fn main() {
use laurus::vector::HnswOption;
use laurus::vector::core::rerank::RerankStorageKind;
let opt = HnswOption {
rerank_storage: Some(RerankStorageKind::F32),
..HnswOption::default()
};
}
Queries pass the rerank factor through VectorIndexQuery::rerank_factor
(low-level), SearchRequestBuilder::vector_rerank_factor (engine), or
the gRPC / JSON VectorParams.rerank_factor field.
Fields without rerank_storage enabled silently fall back to the
Stage 1 int8 ranking even when rerank_factor is set — there is no
f32 information to recover from a Stage 1 segment.
LRS1 rerank sidecar
The sidecar is a separate file written next to the LVS1 segment when
rerank_storage is enabled:
offset size field
------ ---- -------------------------------------------
0 4 magic ASCII "LRS1"
4 2 version u16 LE (current = 1)
6 2 storage_kind u16 LE (1 = F32; 0 reserved; 2.. future)
8 8 reserved zero-padded
16 4 dim u32 LE
20 4 vector_count u32 LE
24 - payload vector_count * dim * bytes_per_element
end 8 footer magic "LRC1" u32 LE + CRC-32 u32 LE
over header + payload
Vectors are written in the same (doc_id, field_name) order as the
matching LVS1 segment, so a (sidecar position) → (LVS1 position)
mapping is the identity. The reader (HNSW, Flat or IVF) loads the
sidecar into a RerankStoragePool when it opens the segment, in both
loading modes. Under Lazy (the mmap-backed FileStorage) the vector
rows stay mapped, but the sidecar is read into memory, so enabling
rerank_storage costs vector_count * dim * 4 bytes of RAM per
segment in either mode.
The sidecar is enabled per field by rerank_storage in the schema’s
HNSW options, and that setting is honored on every write path: direct
commits, the active write segment, and segment merges all re-emit the
sidecar for the segment they produce. A merged segment’s sidecar is
rebuilt from the source segments’ original f32 sidecars (not from
the int8-dequantized segment data), so a merge stays lossless for the
rerank vectors instead of compounding one round of quantization error
per merge.
New sidecars end with an 8-byte CRC-32 footer over the header and payload that is verified whenever the sidecar is read (both the searcher load and the writer reload), so silent on-disk corruption is rejected instead of skewing rerank scores. Because the header fully determines the content length, the footer is detected by the bytes remaining after the payload — sidecars written before the footer was introduced have zero trailing bytes and still load, with verification skipped.
Bounded allocations from on-disk header counts
Every vector segment header carries element counts (num_vectors,
n_clusters, the HNSW graph’s node_count / layer_count /
neighbor_count) and per-record byte lengths (the v1/v2 inline field_name_len, PQ
codes) that the reader uses to size Vec / HashMap capacities and
read buffers. The HNSW CRC footer is verified before the structural
parse, but legacy footer-less segments — and the writer reload paths,
which run no footer verification — reach those counts unverified. A
single flipped byte could otherwise turn a small count into a multi-GiB
allocation request that aborts the process through handle_alloc_error
(out of memory) before any corruption check runs.
To prevent that, the HNSW, Flat, and IVF loaders bound each such
allocation against ground truth — the true file length from
StorageInput::size(). Because the bytes a count or buffer describes
must physically exist in the file, a header that declares more elements
or bytes than the file can hold is rejected as a corrupted segment
before the allocation. This generalizes the rerank sidecar’s
file-size bound to the main segment readers and covers legacy
footer-less segments, so a corrupt or hostile header surfaces a clean
“corrupted segment” error rather than an OOM abort.
Recall vs speed trade-off
rerank_factor lets you exchange a small per-query rerank cost
(~top_k * rerank_factor exact-distance calls — a few µs at dim
128) for higher Recall@10. The gain depends on the corpus and the
graph search budget (ef_search):
- Real clustered embedding data (text-embedding-3, BERT, etc.)
reaches
Recall@10 ≥ 0.99at lowef_search; rerank polishes the ranking with negligible latency overhead. - Synthetic random unit-norm data (the worst case for HNSW recall
recovery) needs a higher
ef_searchfor the int8 graph to visit enough true top-10 candidates; rerank then re-orders the visited set but cannot retrieve candidates the graph never reached.
The recall acceptance is split into two CI gates so the rerank kernel and the full HNSW pipeline can fail independently:
stage2_brute_force_rerank_recall_at_10_meets_kernel_gateassertsRecall@10 ≥ 0.99. Bypasses the HNSW graph entirely (brute-force int8 over the corpus, widen totop_k * rerank_factor, rescore with f32) so any miss is a rerank-kernel regression.hnsw_quantized_recall_at_10_with_rerank_meets_stage2_recall_gateassertsRecall@10 ≥ 0.98. Adds the HNSW graph-construction non-determinism that an f32 HNSW baseline would also contribute; the looser gate matches the observed run-to-run variance band on this synthetic adversarial distribution. Real clustered embedding data and a stronger HNSW config (m=32, ef_construction=500) reach ≥ 0.99 on this path too — see the diagnostic sweep below.
The companion stage2_recall_sweep_diagnostic (opt-in via
LAURUS_STAGE2_SWEEP=1) sweeps (ef_search, rerank_factor) across
three corpus / query distributions and two HNSW configs so
production deployments can calibrate the budget for their actual
embedding distribution.
Real-data validation (Issue #498)
A third opt-in CI gate validates Stage 2 against a real ANN benchmark dataset (SIFT1M from TEXMEX) so the synthetic-data gates above do not become the only signal:
hnsw_quantized_recall_at_10_with_rerank_on_sift_meets_stage2_real_data_recall_gateassertsRecall@10 ≥ 0.99on a 50 000-vector SIFT1M subsample at(m=16, ef_construction=200, ef_search=200, rerank_factor=5).- The companion bench
bench_hnsw_graph_search_rerank_real_data(inlaurus/benches/vector_search_bench.rs) measures end-to-end Stage 2 latency on the same fixture. The accompanying examplelaurus/examples/sift_rerank_probe.rsruns a full(ef_search × rerank_factor × HNSW config)sweep with(Recall, latency)per cell so operators can pick the operating point for their own data shape.
Both are gated on LAURUS_REAL_BENCHMARK=1 AND the presence of the
SIFT1M .fvecs files under .cache/sift/sift/. Default CI runs are
unchanged. To enable locally:
./scripts/fetch-sift.sh --large # ~478MB
LAURUS_REAL_BENCHMARK=1 cargo test --release \
--test vector_recall_test \
hnsw_quantized_recall_at_10_with_rerank_on_sift_meets_stage2_real_data_recall_gate \
-- --nocapture
LAURUS_REAL_BENCHMARK=1 cargo bench --bench vector_search_bench \
-- "HNSW Graph Search Rerank Real"
The Issue #481 wording originally asked for “≥ 3× speedup vs the
pre-Stage-1 f32 baseline.” Cross-branch Criterion measurements on
SIFT1M-50k (median over 30 samples, same (m, ef_construction, ef_search)) gave 625 µs/query on the pre-Stage-1 f32 HNSW path
versus 323 µs/query on the Stage 2 int8 + rerank path — a 1.94×
speedup. Issue #498 reduces the real-data gate to ≥ 1.5×
accordingly, with the recall side held at the original 0.99. The
gap between the original 3× target and the measured 1.94× comes
from rerank only re-ordering candidates the int8 graph traversal
already visited — a lower ef_search does not pay back through
rerank when the candidate set itself becomes too narrow, which a
follow-up could address by widening the graph search budget
independently of ef_search (the Lucene 99 pattern).
Product Quantization with rerank (Issue #481 Stage 3)
Stage 3 adds an opt-in Product Quantization path for the HNSW
index. Each segment trains a per-field codebook of M sub-vectors
× K = 256 centroids using Lloyd k-means with k-means++
initialisation, and stores every vector as M bytes (one centroid
index per sub-vector). The search hot loop replaces the int8 SIMD
kernel with asymmetric distance computation (ADC): per-query
the searcher builds an M × K look-up table of squared distances
between the query’s sub-vectors and the codebook entries, then
scores each candidate as Σ_m lut[m][codes[m]] — M table
lookups + M − 1 adds per candidate.
PQ is enabled per field via HnswOption.quantizer:
#![allow(unused)]
fn main() {
use laurus::vector::HnswOption;
use laurus::vector::core::quantization::QuantizationMethod;
use laurus::vector::core::rerank::RerankStorageKind;
let opt = HnswOption {
dimension: 128,
quantizer: QuantizationMethod::ProductQuantization { subvector_count: 32 },
// PQ-only Recall@10 caps out around 0.78-0.92 on SIFT1M, so
// production deployments should pair PQ with the LRS1 rerank
// sidecar — same Stage 2 mechanism, just driven by PQ
// candidate generation instead of int8.
rerank_storage: Some(RerankStorageKind::F32),
..Default::default()
};
}
subvector_count must be at least 1 and divide dimension; defining
the field (creating the index, add_field, update_field) rejects any
other value (Issue #1491). Common choices for
dim = 128: M ∈ {8, 16, 32} (sub_dim 16 / 8 / 4). Larger M
trades on-disk compression for higher recall — Issue #481 Stage 3
ships only the 8-bit (K = 256) variant; the on-disk format reserves
a 4-bit (K = 16) slot for a future PR.
Minimum training size: PQ trains K = 256 k-means centroids per
sub-quantizer, so a segment with fewer than 256 vectors cannot train a
meaningful codebook. Such segments are written as Scalar8Bit
instead (the LVS1 header is self-describing, so readers dispatch on
the stored kind transparently); once the segment grows — or is merged
into a larger one — the next write trains PQ as configured. The
subvector_count check still applies regardless of segment size,
including to a subvector_count of 0. Neither the fallback nor the minimum
applies when a shared codebook is
configured: nothing is trained per segment in that case, so even tiny
per-commit segments stay on PQ.
Shared PQ codebook (Issue #631)
By default every segment write trains its own codebook from scratch — a multi-second k-means cost that recurs on every commit and every merge under the segment-per-commit layout (#634/#889). Following the FAISS / Lucene99 precedent, a codebook can instead be trained once on a representative sample and reused by every subsequent segment write, reducing the encode step to a table lookup (measured ~91-92% faster than inline training at 2 048-8 192 vectors).
Enable it by naming a codebook file on the field and training it:
[fields.embedding.Hnsw]
dimension = 128
pq_codebook_path = "embedding.pqcb"
[fields.embedding.Hnsw.quantizer.ProductQuantization]
subvector_count = 32
laurus train pq-codebook --field embedding --input vectors.jsonl --update-schema
(or --from-index in place of --input to sample vectors already
committed to the index; or fold training into index creation with
laurus create index --train-pq-codebook <jsonl>, which removes the
train-before-first-commit ordering hazard entirely — both Issue #920),
or programmatically via
Engine::train_pq_codebook
(engine.train_pq_codebook("embedding", &vectors, None); pair with
engine.sample_committed_vectors("embedding", Some(n)) for the
from-index flow). Training is CPU-bound and synchronous; thousands of
representative vectors are enough — the full corpus is not required.
Semantics:
- The segment format is unchanged. The shared codebook is still embedded inline in each segment header, so shared-codebook and inline-trained segments coexist with no migration, and the codes are byte-identical to what inline training on the same sample would produce.
pq_codebook_pathis relative to the root of the vector storage, which is where the training writes the file:store/vector/in the index directory of the CLI and the server. The directory of the field (store/vector/<field>/) is not searched. A file of that name there, such as the codebook of a fielda/bin the directory of a fielda, is not used, also when the field’s own is missing (Issue #1738).- The codebook file is resolved once, when the field’s index is
opened: when the engine is opened, when
add_fieldadds the field, and whenupdate_fieldrebuilds or recreates it (aReindexorDestructivechange, Issue #1735), which takes a file that was retrained meanwhile. Retraining while an engine is open does not otherwise hot-swap the codebook mid-session (intentional — a codebook must not change between the commits of one session), and aMetadataOnlychange, such as ofdefault_ef_search, keeps the one in use; reopen the engine or rebuild the field to pick up a new file. - Failure policy — no silent fallback. A configured but
not-yet-trained
pq_codebook_pathis lenient at open (so a schema can be created before training), but a commit that needs to encode hard-errors with the training command to run. A present but corrupt file errors at open, and fails anadd_fieldorupdate_fieldthat would open the field’s index before anything changes. A file of another geometry (dimension orsubvector_count) fails the commit, or the rebuild before it publishes, with both values named. Laurus never silently falls back to per-segment training — an invisible regression to the multi-second training cost would defeat the feature. - Cosine-metric fields L2-normalize the training sample the same way the writer normalizes indexed vectors, so the codebook basis always matches (the #794 trap).
- FastScan fields are supported too (Issue #920,
pq-fastscanfeature): aProductQuantizationFastScanfield trains and encodes against a k=16 shared codebook through the exact same commands and file format — the.pqcbheader storeskverbatim, so the two variants are distinguished by the stored value, and a k-mismatched codebook (e.g. a k=256 file configured on a FastScan field) fails the commit loudly with both values named.
On-disk format
PQ segments use the same LVS1 header as Scalar8Bit (quant_kind = 2) and carry the codebook inside the per-segment metadata block:
[ Fixed header 16 bytes ]
[ PQ params 8 bytes ] m / k / sub_dim / padding (u16 × 4)
[ Codebook m × k × sub_dim × 4 bytes ]
[ Per-vector codes num_vectors × m bytes ]
For dim = 128, M = 32, K = 256: codebook = 32 × 256 × 4 × 4 = 131 072 bytes (128 KB) per segment plus 32 bytes per vector.
Recall and speed gates (Issue #481 Stage 3)
- Kernel-level test — synthetic 5 000-vector / dim 128 / 100
queries at
(m=16, ef_construction=200, ef_search=200, rerank_factor=10, M=32):hnsw_pq_rerank_recall_at_10_meets_stage3_recall_gateasserts Recall@10 ≥ 0.95. Measured 0.9660. - Real-data test — SIFT1M-50k subsample (opt-in via
LAURUS_REAL_BENCHMARK=1, same config):hnsw_pq_rerank_recall_at_10_on_sift_meets_stage3_real_data_recall_gateasserts Recall@10 ≥ 0.95. Measured 0.9965. - Real-data speed bench —
bench_hnsw_graph_search_pq_rerank_real_data(opt-in, Criterion). Cross-branch measurement at the same SIFT1M-50k config: pre-Stage-1 f32 HNSW = 625.21 µs/query (PR #500); Stage 3 PQ + rerank = 299.54 µs/query = 2.09× speedup.
Issue #481 originally asked for ≥ 5× speedup at Recall ≥ 0.95. The PR established that target is not reachable on SIFT1M with the current implementation — both Stage 2 (#500) and this Stage 3 PR have measured speedups in the 1.9-2.1× band because rerank dominates the wall-clock once the candidate set is wide enough to recover recall. The gate was reduced to ≥ 1.5× accordingly. A follow-up could pursue the Lucene 99 pattern (independent graph search budget) and / or a 4-bit PQ variant to close the gap.
PQ → SQ → f32 three-stage rerank (Issue #673)
Stage 3’s rerank widens the PQ ADC candidate set to top_k * rerank_factor and rescores only that leading slice against the
exact f32 sidecar — anything the graph traversal found beyond that
budget is discarded. Setting ef_search wider than top_k * rerank_factor used to buy nothing beyond that budget on a PQ field;
since #673 it activates an extra int8 (SQ) stage that
re-ranks the entire ef_search-sized candidate set by a cheap
int8 kernel before the narrow exact-stage budget is carved out of
it — so the surplus the graph already computed gets a chance to
compete on a much better proxy (int8) than the PQ ADC order it
arrived in, instead of being thrown away unscored.
The int8 view is derived from the same LRS1 f32 sidecar the exact stage reads (trained once, lazily, on first use, and cached for the segment’s lifetime) — no second on-disk sidecar, no new per-field configuration, and no new query parameter. The chain activates automatically, per query, whenever all of the following hold:
- the field is PQ-quantized (
ProductQuantizationorProductQuantizationFastScan); - a rerank sidecar (
rerank_storage: Some(F32)) is loaded; rerank_factoris set on the query; andeffective_ef_search > top_k * rerank_factor— i.e. the graph traversal actually computed more candidates than the exact stage alone would consume. Withef_searchleft at the engine’s default (400for the defaultef_constructionof200, seedefault_ef_search), this holds whenevertop_k * rerank_factoris below400, such as10 * 10. When it doesn’t, for example because the query sets anef_searchno larger thantop_k * rerank_factor, the SQ stage would narrow nothing and is skipped, so the query takes the identical two-stage (PQ → f32) path it always has.
The score_basis contract (Issue #927) is unaffected either way:
the pipeline still ends in the exact f32 stage, so multi-segment
fan-out keeps treating those scores as the exact, cross-segment-
comparable basis regardless of whether an SQ stage ran ahead of it.
Float16 (Issue #623)
Float16 stores each value as an IEEE 754 half-precision number:
2 bytes per dimension, half of f32 and twice Scalar8Bit. It is
supported by HNSW, Flat and IVF fields (unlike Product Quantization,
which is HNSW-only) and by all five distance metrics.
#![allow(unused)]
fn main() {
use laurus::vector::FlatOption;
use laurus::vector::core::quantization::QuantizationMethod;
let opt = FlatOption {
dimension: 384,
quantizer: QuantizationMethod::Float16,
..Default::default()
};
}
In a schema TOML file the same choice is quantizer = "Float16" (see
Schema Format → Quantization).
Encoding
- Each value is rounded to the nearest half-precision value. Values
beyond ±65504 (the largest finite half-precision value) saturate to
±65504 instead of becoming infinite. This is the same conversion as
the
F16kind of MultiVector storage. - There is nothing to train and no per-segment parameter. The segment
uses the
LVS1header withquant_kind = 4and no metadata block; each record storesdim × 2bytes. - A merge decodes the rows and encodes them again. Re-encoding a value that is already half precision is exact, so merges do not degrade the vectors. The tests rewrite a segment ten times and no component moves, including Cosine fields, whose rows are re-normalized on every write.
Search
- The query stays f32. The distance kernels widen the stored values to f32 as they read them, so the routed search paths never decode a row into a buffer. The kernel is chosen per target: NEON on aarch64, F16C + AVX2 + FMA on x86_64 (detected at run time), and a portable kernel elsewhere, including wasm32. The kernels sum in different orders, so their results agree to within f32 rounding, not bit for bit.
- Where the rows live depends on the loading mode. With the default
mmap-backed
FileStorage(Lazy), the rows are read in place from the mapped segment file: they are not copied onto the heap, and the OS page cache keeps the hot part resident. WithEagerloading (MemoryStorage, orFileStoragewithLAURUS_NO_MMAP=1), the rows are copied into memory when the segment is loaded. On Windows, a mapped segment file that a merge deletes stays on disk until its reader is dropped; leftover files are removed on the next open. - Two paths are slower because they decode each candidate through
get_vectorinstead of scoring the row in place: a Flat search without a field name over a segment that holds several fields, and the HNSW linear-scan fallback. A search with a field name, or over a segment that holds a single field, takes the in-place kernels. - An f32 rerank sidecar
(
rerank_storage) is still allowed, but it adds little: in the measurements below, Float16 already reproduces the f32 top 10.
Changing an existing field to Float16
Changing quantizer is a
Reindex change:
Engine::update_field with reindex: true rebuilds the field’s
segments as Float16 from the values they store. A Scalar8Bit field
without an f32 sidecar stores only int8 codes, so the rebuild produces
Float16 copies of the dequantized int8 values, not the original
precision. To get full precision, the field needs the f32 sidecar
(rerank_storage = "F32") before the change, or the documents must be
ingested again.
Compatibility: laurus builds that predate Float16 cannot open an index that contains Float16 segments. They fail with
unknown vector segment quant_kind = 4, or with an unknown-variant error when they parse the schema. A server that predatesQUANTIZATION_METHOD_FLOAT16stores the field asScalar8Bitwithout an error, so check the returned schema when you talk to an older server. Servers that know Float16 reject a quantization method they do not know asINVALID_ARGUMENT(HTTP 400) instead (Issue #1459).
Measurements
Quality and size through the engine, BEIR SciFact (5,183 documents,
300 queries) and NFCorpus (3,633 documents, 323 queries) with
all-MiniLM-L6-v2 (384 dimensions), Cosine, a commit every 500
documents, measured with laurus/examples/beir_dense_probe.rs.
“Recall@10 vs f32” is the overlap with exact f32 search; nDCG@10 for
exact f32 is 0.6451 (SciFact) and 0.3159 (NFCorpus):
| Field | nDCG@10 SciFact / NFCorpus | Recall@10 vs f32 | Bytes per vector (Flat) |
|---|---|---|---|
Scalar8Bit (Flat and HNSW) | 0.6460 / 0.3165 | 0.9933 / 0.9935 | 402 |
Scalar8Bit + f32 sidecar, rerank_factor = 4 (Flat) | 0.6451 / 0.3159 | 1.0000 / 1.0000 | 402 + 1,536 |
Float16 (Flat and HNSW) | 0.6451 / 0.3159 | 1.0000 / 1.0000 | 778 |
The Scalar8Bit nDCG@10 differences from f32 have 95% confidence
intervals that contain 0. The results are the same with MemoryStorage
(Eager) and the mmap-backed FileStorage (Lazy).
Search cost, instructions per query on Apple Silicon (SciFact, one segment, top 10, one rayon thread, median of five rounds; IVF with 64 lists, 8 of them probed):
| Index | Scalar8Bit Eager | Scalar8Bit Lazy | Float16 Eager | Float16 Lazy |
|---|---|---|---|---|
| Flat | 5.14 M | 5.21 M | 6.69 M | 6.76 M |
| IVF | 0.83 M | 0.89 M | 1.05 M | 1.11 M |
| HNSW | 0.47 M | 0.49 M | 0.73 M | 0.75 M |
Both loading modes run the same kernels on the same rows. Reading the
rows in place costs 1–7% more instructions than reading them from the
heap; IVF pays the most, since its rows form one run per list.
Scalar8Bit takes 19% (IVF) to 35% (HNSW) fewer instructions per query
than Float16. Before Issue #1463, Scalar8Bit with the default
mmap-backed storage decoded every candidate into new buffers and took
three to six times the instructions of Eager. The x86 F16C kernel
was not measured.
MultiVector Storage
The quantization methods above apply to the ANN index types listed for
each in the Quantization table. A MultiVector field
has no ANN index, so quantizer does not apply to it — instead its own
storage option (Issue #1346) picks the on-disk element kind of its token
vectors:
| Kind | Rust Enum Variant | Bytes/element | Error | Size per document (300 × 128 tokens) |
|---|---|---|---|---|
| F32 (default) | MultiVectorStorage::F32 | 4 | Exact | ~150 KB |
| F16 | MultiVectorStorage::F16 | 2 | ~2⁻¹¹ relative error per element | ~75 KB |
| Int8 | MultiVectorStorage::Int8 | ~1 (dimension + 2 bytes/row total) | Bounded by the per-vector scale max(abs(vector)) / 127 | ~38 KB |
| Binary | MultiVectorStorage::Binary | 1/8 (ceil(dimension / 8) bytes/row) | Lossy: one bit per element against a field-level center (see Binary); requires Cosine | ~4.7 KB |
#![allow(unused)]
fn main() {
use laurus::{MultiVectorOption, MultiVectorStorage};
let opt = MultiVectorOption::new(128).storage(MultiVectorStorage::Int8);
}
Unlike quantizer’s per-segment global scale, Int8’s scale is
per-vector: scale = max(abs(vector)) / 127, computed independently
for each token vector, with no corpus- or segment-trained state — which is
what lets a segment merge copy rows byte-for-byte instead of
re-quantizing on every merge.
Changing storage on an existing field is a
Reindex change:
Engine::update_field with reindex: true rebuilds the field’s existing
segments under the new on-disk kind. It decodes what is stored, so it
cannot restore precision a lossy kind already dropped. A schema with no
storage key (written before this option existed) defaults to F32 and
needs no migration.
Binary
Binary stores one bit per element: 12 bytes per token vector at 96
dimensions, 32 times smaller than F32. Token vectors of a
late-interaction model are highly anisotropic — they share one dominant
direction — so the plain sign of each element would come out nearly the
same for every token. Binary stores the sign of each element’s offset
from a center instead, and decodes a row as
x_i = w_i * (bit_i ? +1 : -1)
decoded = c + x - ((x · c) / (c · c)) * c
where c is the mean token vector and w_i the mean of |v_i - c_i|,
both stored as f16. The decoded offset is projected off c: without
that, the bits’ spurious component along c acts as a query-independent
bias in MaxSim and ranking quality collapses. Queries are not binarized:
the float query vectors are scored against the stored bits directly,
without decoding the rows (see
Cost).
- The field learns
candwonce, from the first commit or merge that holds at least 2,048 token vectors (a sample of at most 16,384 of them, spread over the documents). Every later segment is encoded with them, and everyBinarysegment stores its own copy (4 bytes per dimension), so each segment decodes on its own and merges copy rows verbatim. They are never re-learned, so they do not follow a corpus that drifts afterwards. - Until then, the field writes its segments as
F16. A merge that brings at least 2,048 token vectors together learns the parameters and converts them; converting an existing field toBinarywithupdate_fieldlearns them from the stored vectors. AnF16segment that no merge reaches only costs space. BinaryrequiresDistanceMetric::Cosine: it keeps each token vector’s direction, not its magnitude. UnderCosinea decoded vector has a norm of at most 1 (up to f16 rounding), so a score stays at most the number of query vectors.- It is clearly lossy (see Measured quality), and
changing
storageaway fromBinarydoes not bring the dropped precision back.
Token pooling
pool_factor (Issue #1346) makes a field smaller by keeping fewer token
vectors per document. At index time, a document’s token vectors after the
first are clustered into max(r / pool_factor, 1) clusters (r is how
many there are) and each cluster is replaced by its mean. The stored size
and MaxSim’s cost, which grows with the stored vectors, both drop by about
the factor, and pooling combines with every storage kind.
#![allow(unused)]
fn main() {
use laurus::{MultiVectorOption, MultiVectorStorage};
let opt = MultiVectorOption::new(128)
.storage(MultiVectorStorage::Int8)
.pool_factor(2);
}
- Method. The hierarchical pooling of Clavié et al. (arXiv 2409.14683)
as Sentence Transformers and PyLate implement it: the first token vector
(
[CLS]for a ColBERT model) is kept as is, and the others are grouped by Ward agglomerative clustering on the cosine distance. laurus reproduces SciPy’s clustering; a test checks it against SciPy’s output. In aCosinefield the cluster means are re-normalized, which ranked better on BEIR than the raw means those implementations keep. - Every write is pooled once. A document is pooled after it is embedded and before the field’s writer is taken, so fresh documents, WAL recovery and text embedded by the field’s embedder are all pooled; queries are not. Each stored document records the factor it was pooled with, so merges never pool it again.
- Turning pooling on for an existing field is a Reindex. Its stored
vectors are still the original ones, so
Engine::update_fieldwithreindex: truepools them exactly as ingest would have (forF32storage; other kinds pool their decoded values, and aBinaryfield keeps the parameters it already learned). The merge pools the stored documents in parallel (one after another on WebAssembly), and ingestion waits until it is done. - Changing or turning off a factor in use is Destructive. The original token vectors are gone once a document is pooled (multi-vector values are not kept in the document store), so the field’s data is discarded and its documents must be put again.
- Cost. Pooling a document of
ntoken vectors takesO(n²)time and memory: about 3 ms for 300 vectors of 128 dimensions, and about 2 s and 290 MB for the 8,192-vector maximum (Apple M4, release build). Puts made at the same time pool their documents at the same time, outside the field’s writer. Documents pooled at once hold at most 256 MiB together (one document at the maximum, which is then pooled alone), and no more of them run at once than there are cores. A Reindex pools within its own 256 MiB, so documents put throughVectorStoredirectly whileVectorStore::rebuild_fieldruns can bring the total to 512 MiB;Engine::update_fieldholds puts back until it is done. - A
Binaryfield learns its parameters from the pooled vectors, and its 2,048-vector threshold counts pooled vectors.
Measured quality
Measured on two BEIR datasets with the
BEIR probe:
answerdotai/answerai-colbert-small-v1 (96-dimension token vectors,
about 236 tokens per document), every storage kind ingesting the same
vectors. Exhaustive ranks every document by MaxSim; BM25 → rescore
rescores the BM25 top 100. Each cell is nDCG@10, then its paired
difference from F32 with a 95% bootstrap confidence interval. The probe
commits every 500 documents, so the Binary field learns its parameters
in the first commit.
| Kind | Bytes/token (96 dims) | Size vs F32 | SciFact exhaustive | SciFact BM25 → rescore | NFCorpus exhaustive | NFCorpus BM25 → rescore |
|---|---|---|---|---|---|---|
| F32 | 384 | 1 | 0.7456 | 0.7284 | 0.3690 | 0.3458 |
| F16 | 192 | 1/2 | 0.7446 (−0.0010 [−0.0029, 0.0000]) | 0.7284 (−0.0001 [−0.0002, 0.0000]) | 0.3689 (−0.0001 [−0.0008, +0.0006]) | 0.3457 (−0.0001 [−0.0009, +0.0007]) |
| Int8 | 98 | 1/3.92 | 0.7457 (+0.0002 [−0.0038, +0.0044]) | 0.7264 (−0.0021 [−0.0052, +0.0000]) | 0.3686 (−0.0004 [−0.0043, +0.0034]) | 0.3460 (+0.0002 [−0.0034, +0.0037]) |
| Binary | 12 | 1/32 | 0.7176 (−0.0280 [−0.0481, −0.0087]) | 0.7139 (−0.0145 [−0.0297, +0.0008]) | 0.3192 (−0.0498 [−0.0626, −0.0373]) | 0.3264 (−0.0194 [−0.0279, −0.0116]) |
- Every F16 and Int8 interval contains 0, so neither shows a measurable nDCG@10 loss on these datasets. The largest point estimate is Int8’s −0.0021 on SciFact BM25 → rescore.
Binaryloses 1.5 to 5.0 points of nDCG@10. It loses less under BM25 → rescore, where BM25 has already narrowed the candidates, than when MaxSim alone ranks the whole corpus.- The plain sign of each element (what Vespa’s ColBERT binarization
stores, also 12 bytes per token) scored 0.7018 / 0.6978 / 0.3113 /
0.3202 in the same columns. Pooled over both datasets’ 623 queries,
Binaryis ahead by +0.0117 [−0.0014, +0.0254] exhaustive and +0.0110 [−0.0001, +0.0225] BM25 → rescore. The gain depends on the tokens the parameters are learned from: learning them from the leading 5, 20, 50, 100 or 500 documents instead gave +0.016 to +0.023 exhaustive, and no sample came out behind the plain sign (Issue #1346). - F16 changes the nDCG@10 of at most 1 of SciFact’s 300 queries and 18 of NFCorpus’s 323. Int8 reorders the top 10 of most queries (237 of 300 on SciFact exhaustive), but the gains and losses cancel out (6 queries up, 7 down).
- F32’s exhaustive nDCG@10 is within 0.005 of the model card’s published numbers (SciFact 0.7477, NFCorpus 0.373), which do not state how they were measured.
- On SciFact the payload is 469 MB (F32), 235 MB (F16), 120 MB (Int8)
and 14.7 MB (Binary) for 1.22 M token vectors; segment files add 24
bytes per document and 80 bytes per segment, plus 4 bytes per dimension
(384 here) per
Binarysegment. - 25 NFCorpus queries have no BM25 hit (single words such as
okrathat never occur in the corpus; the default analyzer does not stem), so BM25 → rescore scores them 0 under every kind.
With token pooling, measured the same way (the size is that of the segment files, relative to unpooled F32):
| Kind | Bytes/token (96 dims) | Size vs F32 | SciFact exhaustive | SciFact BM25 → rescore | NFCorpus exhaustive | NFCorpus BM25 → rescore |
|---|---|---|---|---|---|---|
F32, pool_factor 2 | 384 | 1/2.00 | 0.7434 (−0.0021 [−0.0106, +0.0064]) | 0.7292 (+0.0008 [−0.0069, +0.0090]) | 0.3683 (−0.0007 [−0.0034, +0.0020]) | 0.3456 (−0.0002 [−0.0026, +0.0020]) |
F32, pool_factor 3 | 384 | 1/2.99 | 0.7450 (−0.0005 [−0.0095, +0.0084]) | 0.7288 (+0.0004 [−0.0085, +0.0093]) | 0.3650 (−0.0040 [−0.0083, +0.0001]) | 0.3433 (−0.0025 [−0.0066, +0.0013]) |
F32, pool_factor 4 | 384 | 1/3.97 | 0.7483 (+0.0028 [−0.0096, +0.0149]) | 0.7292 (+0.0008 [−0.0107, +0.0121]) | 0.3642 (−0.0048 [−0.0109, +0.0008]) | 0.3415 (−0.0043 [−0.0095, +0.0008]) |
Int8, pool_factor 2 | 98 | 1/7.81 | 0.7428 (−0.0028 [−0.0097, +0.0042]) | 0.7277 (−0.0008 [−0.0077, +0.0064]) | 0.3662 (−0.0028 [−0.0072, +0.0014]) | 0.3447 (−0.0011 [−0.0051, +0.0028]) |
Int8, pool_factor 3 | 98 | 1/11.67 | 0.7458 (+0.0002 [−0.0093, +0.0095]) | 0.7296 (+0.0012 [−0.0076, +0.0100]) | 0.3647 (−0.0043 [−0.0097, +0.0009]) | 0.3431 (−0.0027 [−0.0079, +0.0020]) |
Binary, pool_factor 2 | 12 | 1/62.81 | 0.7088 (−0.0368 [−0.0555, −0.0188]) | 0.7038 (−0.0246 [−0.0404, −0.0093]) | 0.3184 (−0.0506 [−0.0640, −0.0383]) | 0.3217 (−0.0241 [−0.0328, −0.0158]) |
Binary, pool_factor 3 | 12 | 1/93.23 | 0.7091 (−0.0365 [−0.0564, −0.0176]) | 0.7006 (−0.0278 [−0.0456, −0.0106]) | 0.3113 (−0.0577 [−0.0732, −0.0431]) | 0.3202 (−0.0256 [−0.0365, −0.0155]) |
- Every interval of pooled F32 and pooled Int8 contains 0. Pooled over both datasets’ 623 queries, the difference from unpooled F32 under exhaustive ranking is −0.0014 [−0.0057, +0.0031] at factor 2, −0.0023 [−0.0071, +0.0026] at factor 3 and −0.0012 [−0.0078, +0.0056] at factor 4, and −0.0028 [−0.0069, +0.0014] for Int8 at factor 2; under BM25 → rescore it is closer to 0. NFCorpus is where the point estimates drop first (about −0.004 at factors 3 and 4).
- Pooling and Int8 multiply: factor 2 with Int8 is 1/7.8 the size of F32 with no measurable loss.
Binaryloses more with pooling: −0.0047 [−0.0120, +0.0024] under exhaustive ranking and −0.0074 [−0.0139, −0.0009] under BM25 → rescore, on top of its own loss.- Re-normalizing the cluster means matters. With the raw means that Sentence Transformers and PyLate keep, F32 at factors 2, 3 and 4 ranked 0.0033, 0.0045 and 0.0098 lower under exhaustive ranking (pooled over both datasets, every interval above 0; Issue #1346).
- Rescoring time fell about in proportion to the factor: on SciFact exhaustive, 104 ms per query unpooled and 50, 37 and 27 ms at factors 2, 3 and 4 (wall clock on a loaded machine; only the trend is meaningful).
Reproduce with make beir-storage-eval BEIR_DATASET=scifact (or
nfcorpus).
Segment Files
| Index Type | File Extension | Contents |
|---|---|---|
| HNSW | .hnsw | Graph structure, vectors, and metadata |
| Flat | .flat | Raw vectors and metadata |
| IVF | .ivf | Cluster centroids, assigned vectors, and metadata |
All three index types default to the segment-per-commit layout (see
below); the monolithic single-file layout remains available via
{Flat,Hnsw,Ivf}IndexConfig { segmented: false, .. } for direct index
users.
Segment-per-commit layout (default for all three index types)
Since #634 (HNSW) and
#889 (Flat and IVF), each
commit seals only the newly added vectors as an immutable
segment_NNNNNN.{hnsw,flat,ivf} file and registers it in an atomic,
checksummed segments.json manifest — the per-commit cost drops from
O(index) to O(new documents), with no full-corpus rework for the existing
segments:
- Search fans out over the sealed segments (newest generation first) and deduplicates same-document copies with newest-wins masking, so a re-indexed document always resolves to its latest embedding. An adaptive over-fetch — expanding the per-segment budget geometrically until enough live hits survive masking — keeps result quality stable even when a deep band of stale copies awaits a merge.
- Merging: a tiered, generation-contiguous merge policy collapses
size-similar segment runs as ingest proceeds (each vector is rewritten
O(log N) times over its lifetime), and
optimize()force-merges everything into one segment. IVF’s merge does not try to reconcile per-segment cluster ids (they carry no cross-segment meaning): it flattens the deduplicated survivors and retrains centroids from scratch over the merged union, with the cluster count re-derived adaptively for the union’s size. Flat has no f32 rerank sidecar to fall back on, so each merge dequantizes, retrains scalar-quantization parameters, and requantizes — a small amount of quantization drift accumulates across merges, unlike HNSW’s/IVF’s lossless-ish requantization path. Merges run insidecommit()after the commit’s segment and deletions are durable, so a merge that fails does not fail the commit (Issue #1500): it is logged as a warning that names the field, and the next commit that has something to commit retries it (Issue #1509). Searches keep running during a merge and read either the segments it replaces or the merged one: the merge deletes the replaced segments’ files only once every search that listed them has loaded them, so it may wait briefly for such searches (Issue #1678). - Per-segment training: HNSW’s graphs and IVF’s centroids are both
built independently per segment — IVF adapts its cluster count to each
segment’s own size (capped by the schema’s
n_clusters) rather than training a fixed count regardless of how many vectors landed in that commit. No cross-segment agreement is needed for either index type, since search fans out per segment and merges top-k results. - Deletions are logical: an index-level bitmap (
{name}.delmap) is consulted by every segment reader and physically reclaimed by merges. - Migration is zero-copy: an existing monolithic segment file is registered verbatim as the first segment on first open — one manifest write, no data movement.
- Durability: segment files and the manifest are written via temp-file + fsync + atomic rename, and the manifest carries the WAL checkpoint published only after all covered state is durable — see Persistence.
Writer retention across commits (monolithic layout only)
Retention only applies to the monolithic layout (segmented: false);
a segmented writer always starts from an empty buffer, so there is nothing
to retain. For the monolithic HNSW layout, the store keeps its writer
cached across commits (Issue #864): after a commit the writer’s
in-memory state is equivalent to the file it just wrote, so the first
upsert after a commit extends it in place instead of reloading (and
dequantizing) the whole .hnsw from storage — under commit-heavy ingest
that reload was O(index size) per cycle. The cache is dropped whenever the
index is rewritten behind the writer — auto-compaction firing inside a
commit, or an explicit optimize() — because both rebuild the file
through a fresh writer and clear the deletion bitmap, and a stale retained
writer would write the reclaimed vectors back — and whenever a commit
fails partway or its auto-compaction fails, where the writer/disk
agreement is unknown. As a bonus, a
retained writer with no pending changes skips the index rewrite entirely,
so a no-change commit() costs no .hnsw write at all. The monolithic
Flat and IVF layouts keep the previous drop-on-commit behavior, unaudited
for the same invariants — reaching for that code path today requires
opting out of the segmented default explicitly.
Code Example
use std::sync::Arc;
use laurus::{Document, Engine, Schema};
use laurus::lexical::TextOption;
use laurus::vector::HnswOption;
use laurus::vector::core::distance::DistanceMetric;
use laurus::storage::memory::MemoryStorage;
#[tokio::main]
async fn main() -> laurus::Result<()> {
let storage = Arc::new(MemoryStorage::new(Default::default()));
let schema = Schema::builder()
.add_text_field("title", TextOption::default())
.add_hnsw_field("embedding", HnswOption {
dimension: 384,
distance: DistanceMetric::Cosine,
m: 16,
ef_construction: 200,
..Default::default()
})
.build();
// With an embedder, text in vector fields is automatically embedded
let engine = Engine::builder(storage, schema)
.embedder(my_embedder)
.build()
.await?;
// Add text to the vector field — it will be embedded automatically
engine.add_document("doc-1", Document::builder()
.add_text("title", "Rust Programming")
.add_text("embedding", "Rust is a systems programming language.")
.build()
).await?;
engine.commit().await?;
Ok(())
}
Next Steps
- Search the vector index: Vector Search
- Combine with lexical search: Hybrid Search