All my work / AI infrastructure · by Ravindra Sawant

Nearline

HNSW-style vector search index from scratch, measured against exact search.

Python 3.11+ · NumPy 416 lines of core code source on GitHub ↗ CI status

4/4 core requirements 7 tests passing 2/2 benchmark targets

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) or diverse (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 uses allow_pickle=False and validates shapes, ids, entry and every reference.

Requirements → tests

ReqPriRequirement Proven byStatus
FR-01P0Ingest unique IDs + finite fixed-dim float32 vectors; normalize; reject zero norm/dupes/shapeT01pass
FR-02P0Exact top-k + multilayer graph insertion: seeded levels, greedy descent, bounded beam searchT02, T03pass
FR-03P0Tunable M / efConstruction / efSearch; top-k with scores + visit diagnostics; ID tie breakT01, T03pass
FR-04P0Persist vectors + adjacency; load with version/dims/reference validation; build statsT04pass
FR-05P1Tombstone deletion, metadata post-filter with underfill flag, offline rebuildT05pass
TestWhat it provesResult
T01Exact top-k on hand-computed 2-D examples, ties, negative cosine, k > population; reject NaN/zero/dupespass
T02Deterministic 100-node graph: degree caps, layer references, no self edges, entry level, reachabilitypass
T03Approximate vs exact over held-out queries for several M/ef; recall distributionpass
T04Save/load roundtrip; dangling references, truncated arrays and pickled payloads rejectedpass
T05Deleted nearest result traversable but never returned; filter underfill; rebuild = exact live baselinepass

Benchmark

Target (hypothesis from the spec)GoalActual
recall@10 >= 0.90 on at least one seeded clustered workload>= 0.901.0 (M=16, ef=16, diverse)met
simple-pruning MVP alone reaches recall >= 0.90>= 0.900.9885 (worst query 0.0)met
  • best_recall@10 = 1.0
  • best_config = M=16 ef=16 diverse
  • simple_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   # bench

More 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

Distributed systems

  • Quorum Deterministic Raft consensus simulator with fault injection and an always-on invariant checker
  • Tandem Collaborative text editor on a sequence CRDT: offline edits, any delivery order, always converges
  • Burrow Minimal Linux container runtime in Go: namespaces, pivot_root, cgroup v2 limits

← See all my work: apps, ML/AI and systems