edgevec 0.4.0

High-performance embedded vector database for Browser, Node, and Edge
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
# πŸš€ `EdgeVec`

[![CI](https://github.com/matte1782/edgevec/actions/workflows/ci.yml/badge.svg)](https://github.com/matte1782/edgevec/actions/workflows/ci.yml)
[![Performance](https://github.com/matte1782/edgevec/actions/workflows/benchmark.yml/badge.svg)](https://github.com/matte1782/edgevec/actions/workflows/benchmark.yml)
[![Crates.io](https://img.shields.io/crates/v/edgevec.svg)](https://crates.io/crates/edgevec)
[![License](https://img.shields.io/badge/License-MIT%20OR%20Apache--2.0-blue.svg)](https://github.com/matte1782/edgevec/blob/main/LICENSE-MIT)

**High-performance vector search for Browser, Node, and Edge**

> βœ… **STATUS: Alpha Release Ready** β€” All performance targets exceeded.

---

## What's New in v0.4.0

### Documentation & Quality Sprint
- **`docs/TUTORIAL.md`** β€” Complete getting started guide
- **`docs/PERFORMANCE_TUNING.md`** β€” HNSW parameter optimization
- **`docs/TROUBLESHOOTING.md`** β€” Top 10 errors and solutions
- **`docs/INTEGRATION_GUIDE.md`** β€” Third-party embedding integrations
- **`docs/MIGRATION.md`** β€” Migration from hnswlib, FAISS, Pinecone

### Benchmark Dashboard
- **Interactive visualization** at `/wasm/examples/benchmark-dashboard.html`
- EdgeVec vs hnswlib-node vs voy comparison
- Real-time performance charts with Chart.js

### Quality Infrastructure
- **Chaos Testing** β€” 15 edge case tests (empty index, max dimensions, etc.)
- **Load Testing** β€” 100k vector stress tests, sustained search load
- **P99 Latency Tracking** β€” P50/P99/P999 percentile benchmarks
- **CI Regression Detection** β€” 10% threshold enforcement

### Previous (v0.3.0)
- Soft delete API with O(1) tombstone-based deletion
- Compaction API for reclaiming space
- Full WASM bindings for soft delete operations
- Persistence format v0.3 with automatic migration

---

## What is `EdgeVec`?

`EdgeVec` is an embedded vector database built in Rust with first-class WASM support. It's designed to run anywhere: browsers, Node.js, mobile apps, and edge devices.

### Key Features

- **Sub-millisecond search** β€” 0.23ms at 100k vectors (768d, quantized)
- **HNSW Indexing** β€” O(log n) approximate nearest neighbor search
- **Scalar Quantization (SQ8)** β€” 3.6x memory compression
- **WASM-First** β€” Native browser support via WebAssembly
- **Persistent Storage** β€” `IndexedDB` in browser, file system elsewhere
- **Minimal Dependencies** β€” No C compiler required, WASM-ready
- **Tiny Bundle** β€” 227 KB gzipped (55% under 500KB target)

---

## Quick Start

### Installation

```bash
npm install edgevec
```

**For Rust users:** To achieve optimal performance, ensure your `.cargo/config.toml` includes:

```toml
[build]
rustflags = ["-C", "target-cpu=native"]
```

Without this configuration, performance will be 60-78% slower due to missing SIMD optimizations.

### Browser/Node.js Usage

```javascript
import init, { EdgeVec, EdgeVecConfig } from 'edgevec';

async function main() {
    // 1. Initialize WASM (required once)
    await init();

    // 2. Create Config and Index
    const config = new EdgeVecConfig(128);  // 128 dimensions
    config.metric = 'cosine';  // Optional: 'l2', 'cosine', or 'dot'
    const index = new EdgeVec(config);

    // 3. Insert Vectors
    const vector = new Float32Array(128).fill(0.1);
    const id = index.insert(vector);
    console.log(`Inserted vector with ID: ${id}`);

    // 4. Search
    const query = new Float32Array(128).fill(0.1);
    const results = index.search(query, 10);
    console.log("Results:", results);
    // Results: [{ id: 0, score: 0.0 }, ...]

    // 5. Save to IndexedDB (browser) or file system
    await index.save("my-vector-db");
}

main().catch(console.error);
```

### Load Existing Index

```javascript
import init, { EdgeVec } from 'edgevec';

await init();
const index = await EdgeVec.load("my-vector-db");
const results = index.search(queryVector, 10);
```

### Rust Usage

```rust,no_run
use edgevec::{HnswConfig, HnswIndex, VectorStorage};
use edgevec::persistence::{write_snapshot, MemoryBackend};

fn main() -> Result<(), Box<dyn std::error::Error>> {
    // 1. Create Config & Storage
    let config = HnswConfig::new(128);
    let mut storage = VectorStorage::new(&config, None);

    // 2. Create Index
    let mut index = HnswIndex::new(config, &storage)?;

    // 3. Insert Vectors
    let vec1 = vec![1.0; 128];
    let _id1 = index.insert(&vec1, &mut storage)?;

    // 4. Search
    let query = vec![1.0; 128];
    let results = index.search(&query, 10, &storage)?;
    println!("Found {} results", results.len());

    // 5. Save Snapshot
    let mut backend = MemoryBackend::new();
    write_snapshot(&index, &storage, &mut backend)?;

    Ok(())
}
```

### Batch Insert (Rust)

For inserting many vectors efficiently, use the batch insert API:

```rust,no_run
use edgevec::{HnswConfig, HnswIndex, VectorStorage};
use edgevec::batch::BatchInsertable;
use edgevec::error::BatchError;

fn main() -> Result<(), BatchError> {
    let config = HnswConfig::new(128);
    let mut storage = VectorStorage::new(&config, None);
    let mut index = HnswIndex::new(config, &storage).unwrap();

    // Prepare vectors as (id, data) tuples
    let vectors: Vec<(u64, Vec<f32>)> = (1..=1000)
        .map(|i| (i as u64, vec![i as f32; 128]))
        .collect();

    // Batch insert with progress tracking
    let ids = index.batch_insert(vectors, &mut storage, Some(|inserted, total| {
        println!("Progress: {}/{}", inserted, total);
    }))?;

    println!("Inserted {} vectors", ids.len());
    Ok(())
}
```

**Features:** Progress tracking, best-effort semantics, and unified error handling.

### Soft Delete (Rust)

Delete vectors without rebuilding the index (v0.3.0+):

```rust,no_run
use edgevec::{HnswConfig, HnswIndex, VectorStorage};

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let config = HnswConfig::new(128);
    let mut storage = VectorStorage::new(&config, None);
    let mut index = HnswIndex::new(config, &storage)?;

    // Insert a vector
    let vector = vec![1.0; 128];
    let id = index.insert(&vector, &mut storage)?;

    // Soft delete (O(1) operation)
    let was_deleted = index.soft_delete(id)?;
    println!("Deleted: {}", was_deleted);

    // Check deletion status
    println!("Is deleted: {}", index.is_deleted(id)?);

    // Get statistics
    println!("Live: {}, Deleted: {}", index.live_count(), index.deleted_count());
    println!("Tombstone ratio: {:.1}%", index.tombstone_ratio() * 100.0);

    // Compact when tombstones accumulate (rebuilds index)
    if index.needs_compaction() {
        let (new_index, new_storage, result) = index.compact(&mut storage)?;
        println!("Removed {} tombstones", result.tombstones_removed);
        // Use new_index and new_storage for future operations
    }

    Ok(())
}
```

### Soft Delete (JavaScript)

```javascript
import init, { EdgeVec, EdgeVecConfig } from 'edgevec';

await init();
const config = new EdgeVecConfig(128);
const index = new EdgeVec(config);

// Insert vectors
const vector = new Float32Array(128).fill(0.5);
const id = index.insert(vector);

// Soft delete
const wasDeleted = index.softDelete(id);
console.log('Deleted:', wasDeleted);

// Statistics
console.log('Live:', index.liveCount());
console.log('Deleted:', index.deletedCount());
console.log('Tombstone ratio:', index.tombstoneRatio());

// Compact when needed
if (index.needsCompaction()) {
    const result = index.compact();
    console.log(`Removed ${result.tombstones_removed} tombstones`);
}
```

| Operation | Time Complexity | Notes |
|:----------|:----------------|:------|
| `soft_delete()` | O(1) | Set tombstone byte |
| `is_deleted()` | O(1) | Read tombstone byte |
| `search()` | O(log n) | Automatically excludes tombstones |
| `compact()` | O(n log n) | Full index rebuild |

---

## Interactive Examples

Try EdgeVec directly in your browser with our NVIDIA-grade cyberpunk demo suite:

<p align="center">
  <a href="wasm/examples/index.html">
    <img src="docs/screenshot/demo-catalog.png" alt="EdgeVec Demo Catalog" width="800">
  </a>
</p>

<p align="center">
  <strong>
    <a href="wasm/examples/index.html">View All Examples</a> |
    <a href="wasm/examples/benchmark-dashboard.html">Launch Dashboard</a>
  </strong>
</p>

### Demo Gallery

<table>
<tr>
<td width="50%">
<a href="wasm/examples/benchmark-dashboard.html">
<img src="docs/screenshot/benchmark-dashboard.png" alt="Benchmark Dashboard">
</a>
<h4>Performance Dashboard</h4>
<p>Competitive analysis vs hnswlib-node & voy with interactive Chart.js visualizations</p>
</td>
<td width="50%">
<a href="wasm/examples/soft_delete.html">
<img src="docs/screenshot/soft-delete-demo.png" alt="Soft Delete Demo">
</a>
<h4>Soft Delete & Compaction</h4>
<p>RFC-001 implementation with tombstone visualization and real-time metrics</p>
</td>
</tr>
<tr>
<td width="50%">
<a href="wasm/examples/batch_insert.html">
<img src="docs/screenshot/batch-insert-demo.png" alt="Batch Insert Demo">
</a>
<h4>Batch Insert</h4>
<p>Sequential vs batch comparison with progress tracking</p>
</td>
<td width="50%">
<a href="wasm/examples/stress-test.html">
<img src="docs/screenshot/stress-test-demo.png" alt="Stress Test Demo">
</a>
<h4>Stress Test</h4>
<p>Push EdgeVec to its limits with continuous operations</p>
</td>
</tr>
</table>

### Running Locally

```bash
# Clone the repository
git clone https://github.com/matte1782/edgevec.git
cd edgevec

# IMPORTANT: Start server from project root!
python -m http.server 8080

# Open in browser (include full path)
# http://localhost:8080/wasm/examples/index.html
```

> ⚠️ **Note:** Do NOT start server from `wasm/examples/` β€” WASM module requires `/pkg/` access from root.

---

## Development Status

`EdgeVec` follows a **military-grade development protocol**. No code is written without an approved plan.

### βœ… Alpha Release Ready (v0.1.0)

**All Performance Targets Exceeded:**
- βœ… **Search Mean:** 0.23ms (4.3x under 1ms target)
- βœ… **Search P99 (estimated):** <600Β΅s (based on Mean + 2Οƒ)
- βœ… **Memory:** 832 MB for 1M vectors (17% under 1GB target)
- βœ… **Bundle Size:** 227 KB (55% under 500KB target)

**What Works Now:**
- βœ… **HNSW Indexing** β€” Sub-millisecond search at 100k scale
- βœ… **Scalar Quantization (SQ8)** β€” 3.6x memory reduction
- βœ… **SIMD Optimization** β€” AVX2/FMA for 60-78% speedup
- βœ… **Crash Recovery (WAL)** β€” Log-based replay
- βœ… **Atomic Snapshots** β€” Safe background saving
- βœ… **Browser Integration** β€” WASM Bindings + IndexedDB
- βœ… **npm Package** β€” `edgevec@0.4.0` published

**Development Progress:**
- Phase 0: Environment Setup β€” βœ… COMPLETE
- Phase 1: Architecture β€” βœ… COMPLETE
- Phase 2: Planning β€” βœ… COMPLETE
- Phase 3: Implementation β€” βœ… COMPLETE
- Phase 4: WASM Integration β€” βœ… COMPLETE
- Phase 5: Alpha Release β€” βœ… **READY**

### Future Roadmap (v0.5.0+)

1. **ARM/NEON Optimization** β€” Cross-platform SIMD verification
2. **Mobile Support** β€” iOS Safari and Android Chrome formalized
3. **CLI Tools** β€” Optional developer command-line interface
4. **Enhanced Metadata Storage** β€” Native metadata support

### Path to v1.0

EdgeVec will reach v1.0 after:
- Production usage feedback from v0.4.0/v0.5.0
- Security audit
- API stability guarantee commitment

---

## πŸ“Š Performance (Alpha Release)

### Search Latency (768-dimensional vectors, k=10)

| Scale | Float32 | Quantized (SQ8) | Target | Status |
|:------|:--------|:----------------|:-------|:-------|
| **10k vectors** | 203 Β΅s | **88 Β΅s** | <1 ms | βœ… **11x under** |
| **50k vectors** | 480 Β΅s | **167 Β΅s** | <1 ms | βœ… **6x under** |
| **100k vectors** | 572 Β΅s | **329 Β΅s** | <1 ms | βœ… **3x under** |

**Note:** Mean latencies from Criterion benchmarks (10 samples). Max observed: 622Β΅s (100k Float32). Outliers: 0-20% (mostly high mild/severe). P99 estimates are all <650Β΅s. See `docs/benchmarks/` for full analysis.

### Memory Efficiency (768-dimensional vectors)

| Mode | Memory per Vector | 1M Vectors | Compression |
|:-----|:------------------|:-----------|:------------|
| **Float32** | 3,176 bytes | 3.03 GB | Baseline |
| **Quantized (SQ8)** | 872 bytes | **832 MB** | **3.6x smaller** |

Memory per vector includes: vector storage + HNSW graph overhead (node metadata + neighbor pool).
Measured using `index.memory_usage() + storage.memory_usage()` after building 100k index.

### Bundle Size

| Package | Size (Gzipped) | Target | Status |
|:--------|:---------------|:-------|:-------|
| `edgevec@0.4.0` | **227 KB** | <500 KB | βœ… **55% under** |

### Competitive Comparison (10k vectors, 128 dimensions)

| Library | Search P50 | Insert P50 | Type | Notes |
|:--------|:-----------|:-----------|:-----|:------|
| **EdgeVec** | **0.20ms** | 0.83ms | WASM | Fastest WASM solution |
| hnswlib-node | 0.05ms | 1.56ms | Native C++ | Requires compilation |
| voy | 4.78ms | 0.03ms | WASM | KD-tree, batch-only |

**EdgeVec is 24x faster than voy** for search while both are pure WASM.
Native bindings (hnswlib-node) are faster but require C++ compilation and don't work in browsers.

[Full competitive analysis β†’](docs/benchmarks/competitive_analysis.md)

### Key Advantages

- βœ… **Sub-millisecond search** at 100k scale
- βœ… **Fastest pure-WASM solution** β€” 24x faster than voy
- βœ… **Zero network latency** β€” runs 100% locally (browser, Node, edge)
- βœ… **Privacy-preserving** β€” no data leaves the device
- βœ… **Tiny bundle** β€” 227 KB gzipped
- βœ… **No compilation required** β€” unlike native bindings

### Test Environment

- **Hardware:** AMD Ryzen 7 5700U, 16GB RAM
- **OS:** Windows 11
- **Rust:** 1.94.0-nightly (2025-12-05)
- **Criterion:** 0.5.x
- **Compiler flags:** `-C target-cpu=native` (AVX2 SIMD enabled)

[Full benchmarks β†’](docs/benchmarks/)

---

## Development Protocol

### The Agents

| Agent | Role |
|:------|:-----|
| **META_ARCHITECT** | System design, data layouts |
| **PLANNER** | Roadmaps, weekly task plans |
| **`RUST_ENGINEER`** | Core Rust implementation |
| **`WASM_SPECIALIST`** | WASM bindings, browser integration |
| **`BENCHMARK_SCIENTIST`** | Performance testing |
| **HOSTILE_REVIEWER** | Quality gate (has veto power) |
| **DOCWRITER** | Documentation, README |

---

## Development Environment

### Local CI Simulation

Before pushing changes, run the local CI simulation to catch issues:

```bash
# Run full CI check with timing validation
cargo xtask ci-check

# Run pre-release validation (CI + docs + publish dry-run)
cargo xtask pre-release
```

The `ci-check` command:
- Sets CI environment variables (`RUSTFLAGS`, `PROPTEST_CASES`, `NUM_VECTORS`)
- Runs formatting, clippy, tests, and WASM checks
- Validates each step completes within CI timeout limits

**Timing Budgets (xtask / CI timeout):**
| Step | Local Limit | CI Timeout | Typical |
|:-----|:------------|:-----------|:--------|
| Formatting | 30s | 5min | <1s |
| Clippy | 180s | 10min | ~20s |
| Tests | 600s | 30min | ~50s |
| WASM Check | 120s | 10min | <1s |

If a step exceeds its local limit, the build fails to catch performance regressions before CI.

### Environment Variables

| Variable | Local Default | CI Value | Purpose |
|:---------|:--------------|:---------|:--------|
| `RUSTFLAGS` | (native) | `-C target-cpu=x86-64-v2` | Prevent SIGILL on CI runners |
| `PROPTEST_CASES` | 256 | 32 | Reduce proptest runtime |
| `NUM_VECTORS` | 10000 | 1000 | Reduce integration test runtime |

### Building

```bash
# Standard build
cargo build --release

# WASM build
wasm-pack build --release

# Run tests
cargo test --all

# Run benchmarks
cargo bench
```

### Release Process

See [CONTRIBUTING.md](./CONTRIBUTING.md) for the full release process, including:
- [Release Checklist]./docs/RELEASE_CHECKLIST.md
- [Rollback Procedures]./docs/ROLLBACK_PROCEDURES.md

---

## Origins

`EdgeVec` builds upon lessons learned from [binary_semantic_cache](../binary_semantic_cache/), a high-performance semantic caching library. Specifically:

**Salvaged (MIT Licensed):**
- Hamming distance implementation (~10 lines)
- Binary quantization math (~100 lines)

**Built Fresh:**
- HNSW graph indexing
- WASM-native architecture
- `IndexedDB` persistence
- Everything else

---

## Acknowledgments

- Thanks to the **Reddit community** for identifying a potential alignment issue in the persistence layer, which led to improved safety via `bytemuck` in v0.2.1.
- Thanks to the **Hacker News community** for feedback on competitive positioning and benchmarking.

---

## License

Licensed under either of:

* Apache License, Version 2.0 ([LICENSE-APACHE]./LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0)
* MIT license ([LICENSE-MIT]./LICENSE-MIT or http://opensource.org/licenses/MIT)

at your option.

### Contribution

Unless you explicitly state otherwise, any contribution intentionally submitted
for inclusion in the work by you, as defined in the Apache-2.0 license, shall be
dual licensed as above, without any additional terms or conditions.

---

<div align="center">

**Built with πŸ¦€ Rust + πŸ•ΈοΈ WebAssembly**

*Correctness by Construction*

</div>