All my work / AI infrastructure · by Ravindra Sawant
Nearline
HNSW-style vector search index from scratch, measured against exact search.
Verified 2026-11-28; CI re-runs the acceptance tests on every push.
The problem
Embedding search trades exact nearest-neighbour accuracy for speed. This is an HNSW-inspired multilayer proximity graph written from scratch and measured against exact brute force.
What I found
- The PRD's simple 'keep the closest neighbours' pruning reached 0.93-0.99 mean recall@10, but individual queries scored 0.0 - the graph had no bridge edges between clusters.
- Adding the HNSW diversity heuristic fixed it: recall@10 of 1.0 at efSearch 64, at roughly 4x the build time.
- Indexes persist as NPZ + JSON with allow_pickle=False; loading validates shapes, ids and every graph reference, and rejects pickled payloads.
Architecture
add(id, vec) ─► validate + L2-normalize ─► level ~ floor(-ln(U)·mL), mL = 1/ln(M), capped
─► greedy descent (ef=1) on layers above the node's level
─► per layer ≤ level: bounded best-first search (ef_construction) ─► select M neighbors
─► add reverse links, prune overflowing lists (cap M, 2M at layer 0) ─► maybe new entry point
search(q, k, ef) ─► greedy descent to layer 1 ─► base-layer beam search (ef ≥ k) ─► drop tombstones / filter
exact(q, k) ─► V @ q over live vectors ─► lexsort(-score, id)
- Distance =
1 − score, heap entries(distance, node)→ deterministic ties. - Neighbor selection:
simple(PRD MVP: keep the closest) ordiverse(HNSW heuristic: keep a candidate only if it is closer to the base than to any already-selected neighbor, then backfill). Simple pruning can strand clustered data (no bridge edges);check()reports unreachable nodes and the benchmark shows the recall gap. - Persistence:
index.npz(vectors, ids, levels, deleted, CSR adjacency per layer) +meta.json; written to a temp directory then swapped in. Load usesallow_pickle=Falseand validates shapes, ids, entry and every reference.
Requirements → tests
| Req | Pri | Requirement | Proven by | Status |
|---|---|---|---|---|
| FR-01 | P0 | Ingest unique IDs + finite fixed-dim float32 vectors; normalize; reject zero norm/dupes/shape | T01 | pass |
| FR-02 | P0 | Exact top-k + multilayer graph insertion: seeded levels, greedy descent, bounded beam search | T02, T03 | pass |
| FR-03 | P0 | Tunable M / efConstruction / efSearch; top-k with scores + visit diagnostics; ID tie break | T01, T03 | pass |
| FR-04 | P0 | Persist vectors + adjacency; load with version/dims/reference validation; build stats | T04 | pass |
| FR-05 | P1 | Tombstone deletion, metadata post-filter with underfill flag, offline rebuild | T05 | pass |
| Test | What it proves | Result |
|---|---|---|
| T01 | Exact top-k on hand-computed 2-D examples, ties, negative cosine, k > population; reject NaN/zero/dupes | pass |
| T02 | Deterministic 100-node graph: degree caps, layer references, no self edges, entry level, reachability | pass |
| T03 | Approximate vs exact over held-out queries for several M/ef; recall distribution | pass |
| T04 | Save/load roundtrip; dangling references, truncated arrays and pickled payloads rejected | pass |
| T05 | Deleted nearest result traversable but never returned; filter underfill; rebuild = exact live baseline | pass |
Benchmark
| Target (hypothesis from the spec) | Goal | Actual | |
|---|---|---|---|
| recall@10 >= 0.90 on at least one seeded clustered workload | >= 0.90 | 1.0 (M=16, ef=16, diverse) | met |
| simple-pruning MVP alone reaches recall >= 0.90 | >= 0.90 | 0.9885 (worst query 0.0) | met |
best_recall@10= 1.0best_config= M=16 ef=16 diversesimple_best_recall@10= 0.9885
quick run · 2026-11-28T23:57:21+00:00 · Uniform random 128-d data shows distance concentration: recall drops sharply.
Design questions
What does efSearch control?
The size of the dynamic candidate list at the base layer: larger ef explores more candidates, trading latency for recall. It must be at least k here.
Why multiple layers?
Sparse upper layers give long-range hops to reach the right region quickly; the dense base layer refines locally. Graph quality and entry selection matter.
What do M and efConstruction trade?
Higher M adds edges (memory, build time) and usually recall; higher efConstruction finds better neighbors at build time but builds slower.
Why normalize for cosine?
Cosine is the dot product of unit vectors; without normalization magnitude changes the ranking.
How do filters and deletes interact with ANN?
Post-filtering can underfill top-k; pre-filtered or filter-aware traversal improves filtered recall. Tombstones keep navigation intact but need periodic rebuilds.
Limitations
- Single writer, read-after-build; no quantization or sharding
- Python traversal can be slower than vectorized exact search at small N
Run it
git clone https://github.com/ravirs/nearline.git && cd nearline
pip install -r requirements.txt
PYTHONPATH=src python -m minivec demo # demo
PYTHONPATH=src python -m pytest -q # test
PYTHONPATH=src python benchmarks/bench.py --quick # benchMore systems I've built from scratch
Storage & data systems
- Strata LSM-tree key-value storage engine: WAL, SSTables with Bloom filters, atomic manifest, compaction
- Tidelog Kafka-style durable partitioned log broker: CRC'd records, offsets, generation-fenced consumer groups
- Floe Iceberg-style table format: immutable Parquet, manifests, snapshots, time travel, compare-and-swap commits
- Flint Spark-style batch engine: lazy lineage, stage planning, shuffles, broadcast and salted skew joins
- Watermark Event-time stream processor: windows, watermarks, lateness, exactly-once checkpoints
- Warden Data governance catalog: explainable grants, row filters, column masks, lineage impact
- SnapshotDB MVCC transaction engine: snapshot isolation, the write-skew anomaly, a serializable mode
AI infrastructure
- KVPager Paged KV cache with copy-on-write forks and prefix reuse (PagedAttention-style)
- Batchwise LLM inference scheduler simulator: static vs continuous vs chunked-prefill batching
- Steadyhand Durable AI agent runtime: allowlisted tools, approvals, budgets, crash recovery, replay
- Toolgate Model Context Protocol gateway: curated tools, signed identity, tenant policy, approvals, audit