Skip to content

Latest commit

 

History

History
163 lines (131 loc) · 12.1 KB

README.md

File metadata and controls

163 lines (131 loc) · 12.1 KB

Vector IDB

IndexedDB as a Vector Database — store embeddings and search by exact cosine similarity directly in the browser with zero runtime dependencies.

Live Demo Architecture Research License: Apache-2.0

idb-vector wraps IndexedDB for client-side vector storage and exact top-k retrieval, inspired by vector search systems like Polymath and Pinecone. It supports exact cursor scans (query), caller-indexed candidate filtering (queryCandidates), opt-in in-memory packed snapshots (createSnapshot), opt-in int8 bounded-rerank side-stores (buildSideStore / querySideStore), and geometry utilities (diagnose / fitWhitening). Background context: IndexedDB as a Vector Database.

Important

Critical Contract & Caveats

  • Top-level vectorPath only: vectorPath must name one top-level property holding an Array of finite, non-zero numbers. A dotted name such as "nested.vector" is refused at construction with a TypeError (the library reads record[vectorPath] literally rather than resolving an IndexedDB key path), and "__proto__" is refused for the same reason.
  • Pre-transaction validation & Float64 bounds: insert(), update(), query(), queryCandidates(), querySideStore(), and snapshot.query() validate inputs and Float64 squared-magnitude limits (~2.2e-162 underflow / ~1.34e154 overflow) before opening a transaction; refused calls write nothing.
  • Strict option allow-lists (no silent filter drops): query() accepts only limit (default 10) and threshold ([-1, 1]). Passing index, range, or predicate to query() throws a TypeError pointing to queryCandidates().
  • Caller-owned schema & offline demo boundary: VectorDB opens existing databases at their own version and never upgrades schemas or creates custom indexes. The Wikipedia demo works offline after loading (~35–39 MB first download), while reloading the page still requires networking.

Quick Start

npm install idb-vector
import { VectorDB } from "idb-vector";

const db = new VectorDB({
  dbName: "vectorDB",     // optional (default "vectorDB")
  objectStore: "vectors", // optional (default "vectors")
  vectorPath: "embedding",
});

// Insert records (validates vector synchronously before opening a transaction)
const key1 = await db.insert({ embedding: [1, 2, 3], text: "First passage" });
const key2 = await db.insert({ embedding: [2, 3, 4], text: "Second passage" });

// Exact cosine similarity scan across the store (default limit: 10)
const matches = await db.query([1, 2, 3], { limit: 20 });

// Filter via caller-owned IndexedDB indexes and/or a pre-ranking predicate
const { results, info } = await db.queryCandidates([1, 2, 3], {
  limit: 10,
  threshold: 0.5,
  // index: "category",
  // range: IDBKeyRange.only("news"),
  predicate: (record) => record.text.length > 0,
});

await db.update(key2, { embedding: [2, 3, 4], text: "Updated passage" });
await db.delete(key1);
await db.close(); // release IndexedDB connection cleanly

Optional Accelerators & Geometry Utilities

import { diagnose, fitWhitening } from "idb-vector";

// 1. In-memory packed Float64 snapshot (for repeated queries on a frozen corpus)
const snapshot = await db.createSnapshot({ maxBytes: 128 * 1024 * 1024 });
const snapRes = await snapshot.query([1, 2, 3], { limit: 10 }); // { mode, results, skipped }
await snapshot.refresh();
snapshot.close();

// 2. Caller-owned int8 side-store with corpus-wide epoch & bounded exact Float64 rerank
const getEpoch = async (idb) => readCorpusEpochFromYourMetadataStore(idb);
const stats = await db.buildSideStore({ sideStore: "codes", getEpoch });
const sideRes = await db.querySideStore([1, 2, 3], {
  sideStore: "codes",
  getEpoch,
  epoch: stats.epoch,
  candidateBudget: 100,
  limit: 10,
});

// 3. Opt-in coordinate-variance screen & Cholesky whitening (test on a separate DB)
const report = diagnose([[10, 1], [20, 2], [30, 4], [40, 3]]);
const whitening = fitWhitening([[10, 1], [20, 2], [30, 4], [40, 3]]);

Architecture

flowchart LR
  App["Browser Application"] --> DB["VectorDB API (index.js)"]
  DB --> Write["Write Boundary (sync snapshot and null-proto copy)"]
  Write -->|"tx complete"| IDB["IndexedDB Store (caller schema and vectors)"]
  DB --> Exact["Exact Scan (query and queryCandidates)"]
  Exact -->|"Single readonly tx and hoisted norm"| IDB
  Exact --> TopK["SortedArray Top-K (utils/sortedarray.js)"]
  DB --> Snap["Packed Snapshot (utils/packed-snapshot.js)"]
  Snap -->|"Bounded Float64 blocks or live fallback"| IDB
  DB --> Side["Int8 Side-Store (utils/side-store.js)"]
  Side -->|"Epoch check and bounded Float64 rerank"| IDB
  App -.->|"Optional preprocessing"| Geo["Geometry Tools (utils/geometry.js)"]
Loading

Capabilities

  • Exact Cosine Search & Snapshot Isolation: query() runs inside a single readonly IndexedDB transaction with a hoisted query vector norm, keeping scores bit-for-bit identical while avoiding redundant per-record norm work.
  • Candidate Queries with Disclosure: queryCandidates() narrows scans via your own IDBIndex / IDBKeyRange and pre-ranking predicate filters, returning { results, info } with recordsRead, recordsScored, candidateSetComplete, and fullScanRequired.
  • Fail-Closed Contract: Invalid vectors, mismatched dimensions, or malformed records stored by older code or another connection reject and name the offending key instead of silently poisoning top-k with NaN or 0 scores.
  • Packed Snapshots (createSnapshot): Packs numeric-key Float64 vectors into contiguous memory blocks within an explicit maxBytes budget and falls back cleanly to a live cursor on overflow or unsupported keys.
  • Int8 Code Side-Store (buildSideStore / querySideStore): Uses 1-byte/dimension affine codes only for candidate selection on non-resident unfiltered corpora, reranking top candidates from exact Float64 originals under ADR 0001 epoch guarantees.
  • Geometry Diagnostics & Whitening (diagnose / fitWhitening): Heuristic coordinate-variance screen and explicit opt-in O(n d² + d³) Cholesky whitening. Off by default and never mutates stored vectors automatically.

API Overview

Export / Method Role Key Options / Return Shape
new VectorDB(options) Open/init store at top-level vectorPath vectorPath (required), dbName, objectStore
db.insert(obj, key?) Validate & store record snapshot Resolves on tx complete with key
db.update(key, obj) Validate & update record Checks in-line keyPath match when configured
db.delete(key) Delete record by key Resolves on tx complete
db.query(vec, opts?) Exact full-store cosine search limit (default 10), threshold ([-1, 1])
db.queryCandidates(vec, opts?) Exact search over caller indexes/filter index, range, predicate, limit, threshold -> { results, info }
db.createSnapshot({ maxBytes }) Opt-in in-memory Float64 cache snapshot.query, refresh, close, mode, reason, bytes
db.buildSideStore / querySideStore Opt-in int8 bounded exact rerank Requires caller getEpoch(db) & epoch; optional eligibleKeys, candidateBudget
diagnose / fitWhitening Optional geometry screen & Cholesky whitening Returns variance metrics / { transform, inverse }
db.close() / db.objectStore Connection lifecycle & escape hatch Idempotent close; further ops throw InvalidStateError

Live Demo & Architecture Research

  • Offline Wikipedia Search Demo: Open the live demo to explicitly load 250 or 2,000 real Wikipedia passages into IndexedDB, encode unseen questions locally with quantized all-MiniLM-L6-v2 (no API key), and keep searching with networking disabled.
    • First load downloads ~35–39 MB (model + ONNX WASM runtime); reloading the page still requires networking.
    • See demo/README.md for integrity verification and reproduction, and demo/compute/README.md for the separate JS/WASM-SIMD/WebGPU compute lab.
  • Architecture Research Report: Read the HTML report covering IndexedDB access patterns, HNSW, WebGPU, and anisotropy with evidence labels, citations, contradictions, and dated publication notes.
    • Source lives in research/architecture.md; rebuild self-contained research/index.html (via committed marked 17.0.4) with npm ci && npm run build:research.
    • Verify in Chromium with npm run test:research (add -- --links for external citations) or the 300 s bounded npm run gate:research; screenshots and a JSON receipt go to .cache/research-evidence/.

Documentation Index

Document Covers
Core API & Validation Contract VectorDB methods, vectorPath rules, Float64 bounds, queryCandidates(), read strategy & lifecycle
Packed Snapshots, Side-Store & Geometry createSnapshot({ maxBytes }), buildSideStore / querySideStore, diagnose() & fitWhitening()
Demo, Research & Benchmarks Wikipedia demo, loopback servers, research build/verify, browser test drivers & real-vector suite
ADR 0001: Side-Store Contract Key identity, corpus-wide epoch pinning, eligibleKeys equivalence & 12 contract invariants
Test Tier Speed Budgets test:fast, test:middle, full merged gate, gate:research 300 s bound & packed-stress split
Wikipedia Demo Guide Offline boundary, bundled assets, SHA-256 integrity trust root & reproduction commands
Compute & Storage Lab Synthetic comparison across IndexedDB cursor, JS, WASM-SIMD & WebGPU (does not alter library)
Architecture Research Source IndexedDB access patterns, HNSW, WebGPU & anisotropy analysis (published to /research/)
Browser Benchmark Analysis 1k / 10k / 100k IndexedDB benchmark results, failure modes & disk cleanup guidance
Packed Snapshot Report In-memory Float64 snapshot format, memory bounds, live fallback & whitening measurements
Side-Store Query Report End-to-end int8 side-store vs packed snapshot & selective-filter exact-scan benchmarks

Development Commands

npm start                  # serve Wikipedia demo on 127.0.0.1 (loopback only; no LAN/remote access)
npm run demo               # serve synthetic vector & metadata-index demo on loopback
npm run test:fast          # pure fast unit tests (no Chromium, no child processes or sockets)
npm run test:middle        # integration-shaped unit tests (server routing, staging, packlist)
npm test                   # full Chromium contract & demo drivers + test:middle
npm run build:research     # rebuild self-contained research/index.html from research/architecture.md
npm run test:research      # verify research page in Chromium (receipts in .cache/research-evidence/)

See Demo, Research & Benchmarks for individual browser test scripts, microbenchmarks (measure, measure:candidates, measure:packed-snapshot), and the research-only real-vector suite (real:prepare, real:embed, real:measure).

Limitations

idb-vector is a lightweight wrapper over IndexedDB designed for straightforward browser integration and caller-managed schemas. It does not bundle built-in approximate nearest-neighbour (ANN/HNSW) indexing, automatic background index synchronization, or multi-node storage. Licensed under Apache-2.0.