sqlitegraph 2.2.2

Embedded graph database with full ACID transactions, HNSW vector search, dual backend support, and comprehensive graph algorithms library
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
# HNSW Development Rules & Process

**Date**: 2025-12-19
**Scope**: HNSW Vector Integration Development
**Status**: ACTIVE - Must be followed strictly

---

## ๐Ÿšซ **ABSOLUTE PROHIBITIONS**

1. **NO MOCKS** - Ever. No exceptions.
2. **NO STUBS** - Ever. No exceptions.
3. **NO PLACEHOLDERS** - Use real implementations only
4. **NO SIMULATION** - Real data and real behavior only
5. **NO PASS/FALLBACK** - Implement actual functionality
6. **NO ASSUMPTIONS** - Research, verify, then implement
7. **NO GUESSING** - Use proven algorithms and tested approaches

---

## โœ… **MANDATORY REQUIREMENTS**

### 1. **File Organization Rules**

```rust
// Every source file must be โ‰ค 1,000 LOC
// Every file must have comprehensive documentation
// Every public method must have doc comments
// Every function call must be traceable
// Every variable name must be meaningful
// Every error condition must be handled
```

### 2. **TDD Workflow Rules**

```
1. Write FAILING test first
2. Write MINIMAL code to make test pass
3. Refactor ONLY after test passes
4. NO code without corresponding test
5. Integration tests before implementation
6. Regression tests for every feature
```

### 3. **Documentation Requirements**

```rust
/// HNSW Vector Search Module
///
/// This module provides high-performance vector search capabilities
/// using Hierarchical Navigable Small World (HNSW) algorithm.
///
/// ## Architecture
/// - Separates index construction from search operations
/// - Uses SIMD-optimized distance calculations
/// - Supports both SQLite and Native V2 backends
///
/// ## Performance Characteristics
/// - Search: O(log N) average case
/// - Insert: O(log N) with dynamic updates
/// - Memory: 2-3x vector size overhead
///
/// ## Usage Examples
/// ```rust
/// let hnsw = HnswIndex::new(config)?;
/// hnsw.insert(vector, id)?;
/// let results = hnsw.search(query, k)?;
/// ```
pub struct HnswIndex {
    /// Core HNSW data structure
    /// Stores layered graph with connections
    layers: Vec<HnswLayer>,

    /// Entry point for searches
    /// ID of the node at top layer
    entry_point: u64,

    /// HNSW algorithm parameters
    /// Number of connections per layer
    config: HnswConfig,
}
```

### 4. **TodoWrite Tool Usage Rules**

```
For EVERY source file created:
1. Create specific TodoWrite for that file
2. Track all tasks for that file in its TodoWrite
3. Mark tasks as in_progress before starting
4. Mark tasks as completed only when DONE
5. No generic todos - file-specific only
```

### 5. **Integration Rules**

```
1. Must use existing SQLiteGraph patterns
2. Must follow SQLiteGraph error handling
3. Must use SQLiteGraph trait abstractions
4. Must maintain API consistency
5. No external dependencies without review
```

---

## ๐Ÿ—๏ธ **Module Structure Rules**

### 1. **Folder Organization**
```
sqlitegraph/src/hnsw/
โ”œโ”€โ”€ mod.rs                 # Public API, โ‰ค 1,000 LOC
โ”œโ”€โ”€ index.rs              # HNSW index management, โ‰ค 1,000 LOC
โ”œโ”€โ”€ search.rs             # Search algorithms, โ‰ค 1,000 LOC
โ”œโ”€โ”€ construction.rs       # Index construction, โ‰ค 1,000 LOC
โ”œโ”€โ”€ distance.rs           # SIMD distance calculations, โ‰ค 1,000 LOC
โ”œโ”€โ”€ storage.rs            # Vector storage abstraction, โ‰ค 1,000 LOC
โ”œโ”€โ”€ config.rs             # Configuration types, โ‰ค 1,000 LOC
โ”œโ”€โ”€ errors.rs             # HNSW-specific errors, โ‰ค 1,000 LOC
โ””โ”€โ”€ tests/
    โ”œโ”€โ”€ integration.rs    # Integration tests
    โ”œโ”€โ”€ regression.rs     # Regression tests
    โ””โ”€โ”€ performance.rs    # Performance benchmarks
```

### 2. **File Size Enforcement**
```
- Every .rs file โ‰ค 1,000 LOC (including comments/tests)
- No exceptions to 1,000 LOC limit
- Split files if exceeding limit
- Each file must have single responsibility
```

### 3. **Separation of Concerns**
```
index.rs        - Index lifecycle management
search.rs       - Search algorithm implementation
construction.rs - Index building algorithms
distance.rs     - Distance metric calculations only
storage.rs      - Abstract storage interface only
config.rs       - Configuration and parameters only
errors.rs       - Error types and handling only
```

---

## ๐Ÿงช **Testing Requirements**

### 1. **Test-Driven Development Sequence**
```rust
// STEP 1: Write failing test
#[test]
fn test_hnsw_basic_search() {
    let hnsw = HnswIndex::new(test_config());
    // Test will fail - no implementation yet
    assert!(hnsw.search(&test_vector(), 10).is_ok());
}

// STEP 2: Implement minimal code
pub struct HnswIndex {
    // Minimal implementation to pass test
}

// STEP 3: Run test - it should pass
// STEP 4: Refactor and improve
```

### 2. **Integration Test Requirements**
```rust
// Before ANY implementation, write integration tests
#[test]
fn test_sqlitegraph_hnsw_integration() {
    let graph = SqliteGraph::open_in_memory().unwrap();
    // Test the complete integration workflow
    let result = graph.add_entity_embedding(1, test_vector()).unwrap();
    assert!(result.is_ok());
}
```

### 3. **Regression Test Requirements**
```rust
// Every feature must have regression tests
#[test]
fn test_hnsw_search_regression_2024_12_19() {
    // Specific test that catches known regressions
    // Must be updated if behavior intentionally changes
    let hnsw = setup_regression_test();
    let results = hnsw.search(&REGRESSION_QUERY, 10).unwrap();
    assert_eq!(results.len(), REGRESSION_EXPECTED_RESULTS);
}
```

---

## ๐Ÿ”ง **Implementation Rules**

### 1. **No Assumptions Rule**
```rust
// โŒ WRONG - Assuming hnsw-rs API exists
extern crate hnsw_rs;

// โœ… RIGHT - Research and verify first
use hnsw_rs::HnswIndex; // Only if crate actually exists and is verified

// โŒ WRONG - Assuming algorithm works
fn search_hnsw(query: &[f32]) -> Vec<u64> {
    // Magic implementation without understanding
}

// โœ… RIGHT - Understand algorithm first
fn search_hnsw(query: &[f32]) -> Result<Vec<u64>, HnswError> {
    // Implementation based on HNSW research papers
    // With proper error handling and edge cases
}
```

### 2. **No Mocks Rule**
```rust
// โŒ WRONG - Using mocks
#[cfg(test)]
mod mock_hnsw {
    pub struct MockHnswIndex;
    impl MockHnswIndex {
        pub fn search(&self, _query: &[f32]) -> Vec<u64> {
            vec![1, 2, 3] // Fake return
        }
    }
}

// โœ… RIGHT - Use real implementations
#[test]
fn test_hnsw_search() {
    let hnsw = HnswIndex::new(test_config()).unwrap();
    hnsw.insert(test_vector(), 1).unwrap();
    let results = hnsw.search(test_query(), 10).unwrap();
    assert!(!results.is_empty());
}
```

### 3. **Real Data Only Rule**
```rust
// โŒ WRONG - Fake/test data
let fake_embedding = vec![0.1, 0.2, 0.3];

// โœ… RIGHT - Real embeddings or realistic test data
let real_embedding = generate_test_embedding(768); // Actually generates
```

---

## ๐Ÿ“ **Documentation Requirements**

### 1. **Module Documentation**
```rust
//! Hierarchical Navigable Small World (HNSW) Vector Search
//!
//! This module provides production-ready HNSW implementation with:
//! - SIMD-optimized distance calculations
//! - Multi-threaded index construction
//! - Dynamic updates without full rebuilds
//! - Memory-mapped persistence
//!
//! # Quick Start
//!
//! ```rust
//! use sqlitegraph::hnsw::{HnswIndex, HnswConfig};
//!
//! let config = HnswConfig::builder()
//!     .dimension(768)
//!     .m_connections(16)
//!     .ef_construction(200)
//!     .build()?;
//!
//! let mut hnsw = HnswIndex::new(config)?;
//! hnsw.insert(embedding, id)?;
//! let results = hnsw.search(query, 10)?;
//! # Ok::<(), Box<dyn std::error::Error>>(())
//! ```
```

### 2. **Function Documentation**
```rust
/// Insert a vector into the HNSW index
///
/// This method inserts a new vector with the specified identifier into the HNSW
/// structure. The insertion process follows the HNSW algorithm:
///
/// 1. Determine appropriate layers for the new node
/// 2. Search for neighbors in each layer
/// 3. Establish connections following M parameter constraints
/// 4. Update entry point if necessary
///
/// # Arguments
///
/// * `vector` - The vector to insert, must match configured dimension
/// * `id` - Unique identifier for this vector
///
/// # Returns
///
/// Returns `Ok(())` on successful insertion or `HnswError` if:
/// - Vector dimension doesn't match configuration
/// - ID already exists in index
/// - Index construction failed
///
/// # Examples
///
/// ```rust
/// let embedding = vec![0.1; 768];
/// hnsw.insert(embedding, 42)?;
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
///
/// # Performance
///
/// - Time Complexity: O(log N) average case
/// - Memory Impact: O(M) new connections
/// - Thread Safety: Requires exclusive access
///
/// # Panics
///
/// Panics if vector length doesn't match configured dimension
pub fn insert(&mut self, vector: Vec<f32>, id: u64) -> Result<(), HnswError> {
    // Implementation
}
```

### 3. **Type Documentation**
```rust
/// HNSW algorithm configuration parameters
///
/// This struct defines all parameters that control HNSW behavior.
/// These parameters significantly impact search quality, construction time,
/// and memory usage.
///
/// # Fields
///
/// * `dimension` - Vector dimension count (must match all vectors)
/// * `m` - Number of bi-directional links for each node (default: 16)
/// * `ef_construction` - Size of dynamic candidate list during construction (default: 200)
/// * `ml` - Maximum number of layers in the index (default: 16)
/// * `distance_metric` - Distance calculation method (default: Cosine)
///
/// # Default Configuration
///
/// The default configuration provides good performance for most use cases:
/// - Balanced search quality vs speed
/// - Reasonable memory usage (~2.5x vector size)
/// - Fast construction time
///
/// # Examples
///
/// ```rust
/// let config = HnswConfig::builder()
///     .dimension(512)
///     .m_connections(32)        // Higher M for better recall
///     .ef_construction(400)     // Higher ef for better construction
///     .distance_metric(DistanceMetric::Euclidean)
///     .build()?;
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[derive(Debug, Clone, PartialEq)]
pub struct HnswConfig {
    /// Vector dimension count
    /// Must match all vectors inserted into the index
    pub dimension: usize,

    /// Number of connections per node (M parameter)
    /// Typical range: 5-48, higher values improve recall but increase memory
    pub m: usize,

    /// Construction ef parameter
    /// Controls dynamic candidate list size during index building
    pub ef_construction: usize,

    /// Maximum number of layers
    /// Calculated as floor(-ln(N) * ml_scale) where N is data size
    pub ml: u8,

    /// Distance metric for similarity calculation
    pub distance_metric: DistanceMetric,
}
```

---

## ๐Ÿ”„ **Workflow Requirements**

### 1. **Development Branch Rules**
```bash
# Create development branch
git checkout -b feature/hnsw-integration

# Work ONLY on this branch
# No commits to main/development until feature complete

# Merge only after:
# - All tests pass
# - Code review complete
# - Documentation complete
# - Performance benchmarks meet targets
```

### 2. **File Creation Sequence**
```
For each new file:
1. Create TodoWrite for the file
2. Write integration test FIRST
3. Write failing unit test
4. Implement minimal code
5. Make test pass
6. Add comprehensive documentation
7. Mark TodoWrite task as completed
8. Commit with descriptive message
```

### 3. **TodoWrite Usage Pattern**
```rust
// Before creating file
TodoWrite::todos(vec![
    TodoItem {
        content: "Create hnsw/mod.rs with public API".to_string(),
        status: "pending".to_string(),
        active_form: "Creating hnsw module structure".to_string(),
    }
]);

// When starting work
TodoWrite::todos(vec![
    TodoItem {
        content: "Create hnsw/mod.rs with public API".to_string(),
        status: "in_progress".to_string(),
        active_form: "Implementing hnsw module structure".to_string(),
    }
]);

// When complete
TodoWrite::todos(vec![
    TodoItem {
        content: "Create hnsw/mod.rs with public API".to_string(),
        status: "completed".to_string(),
        active_form: "Completed hnsw module structure".to_string(),
    }
]);
```

---

## โœ… **Compliance Checklist**

Before committing ANY code, verify:

- [ ] No mocks, stubs, or placeholders
- [ ] All code โ‰ค 1,000 LOC per file
- [ ] Comprehensive documentation for all public APIs
- [ ] Tests written BEFORE implementation
- [ ] Integration tests pass
- [ ] Regression tests pass
- [ ] No assumptions about external APIs
- [ ] Real data used in tests
- [ ] TodoWrite updated for file
- [ ] Single responsibility per file
- [ ] Proper error handling throughout
- [ ] Performance benchmarks passing

---

## ๐Ÿšซ **Immediate Failure Conditions**

ANY violation of these rules results in:
1. Immediate stop of development
2. Code review failure
3. Required refactoring before proceeding
4. Documentation of the violation

---

**Status**: These rules are active and must be followed for ALL HNSW development work.

**Last Updated**: 2025-12-19
**Next Review**: As needed during development