Build your own vector database
Building the index (Algorithm 1)·22 min

Connect + shrink a neighborhood

0 / 1
# grade this stage (from your course directory)
npx theinference test --stage connect-and-shrink --watch

Isolate the trickiest mechanical part of INSERT — the link manager — so you can get it green before wiring the full loop. connect adds bidirectional edges between the new node and its selected neighbors, then shrinks any neighbor that overflowed its capacity by re-selecting its neighborhood with the heuristic.

What to build

Your task

Implement runConnect

Implement HNSW.connect(layer, newId, selected, Mmax). Add newId ↔ nb for each selected nb; if nb now has more than Mmax neighbors, re-select its list down to Mmax with the heuristic (keeping pruned connections, so a node never loses its last link). The adapter returns the updated adjacency for the touched nodes.

tests/adapters.ts
export function runConnect(
  vectors: number[][], layer: number, newId: number,
  existingAdj: number[][], selected: number[], Mmax: number,
): number[][] {
  // returns FIXED-WIDTH rows: [nodeId, n0, n1, ...] padded with -1 to (1 + Mmax),
  // neighbors sorted ascending, rows sorted by node id, for each touched node
}
Fixed-width rows

Each returned row is [nodeId, ...neighbors] padded with -1 to length 1 + Mmax, so the harness can flatten a rectangular matrix. Sort each node's neighbors ascending and the rows by node id — that makes the comparison deterministic.

How it's graded

Adapter mode: the updated adjacency for touched nodes is compared exactly to the reference on a small hand-built graph with one over-capacity neighbor that must shrink.