ruvector/crates/ruvector-core/tests
rUv e2350b759f
fix(core): HNSW correctness fixes, k=0 guard, sorted results, cross-integration helpers (v2.2.3) (#502)
* fix(core): correctness + safety fixes in HNSW/flat index + cross-integration helpers (v2.2.3)

Correctness fixes:
- hnsw: `DistanceFn::eval` now clamps distance to 0.0 — prevents hnsw_rs
  internal BinaryHeap assertion panic when floating-point rounding yields a
  marginally-negative cosine/euclidean distance for near-identical vectors
- hnsw: `set_ef_search` was a silent no-op; now correctly writes to
  `config.ef_search` so callers can tune recall at query time
- hnsw: `search_with_ef` clamps `ef_search` to `max(ef_search, k)` to
  prevent silent under-recall when ef_search < k (hnsw_rs constraint)
- hnsw: `search_with_ef` now explicitly returns an empty slice for k=0
  instead of forwarding to hnsw_rs which may panic
- hnsw: `search_with_ef` returns early (empty slice) when index is empty
  to avoid hnsw_rs BinaryHeap `.peek().unwrap()` panic on zero-element index
- hnsw: results are now explicitly sorted by ascending distance; hnsw_rs
  does not guarantee this order in all code paths
- hnsw: deserialization rebuilds the HNSW graph in index order
  (sorted by idx) and uses an O(n) HashMap lookup instead of O(n^2)
  linear search over the vectors vec during restore
- flat: added k=0 guard (returns empty slice, no panic)
- flat: switched sort to `sort_unstable_by` with a `partial_cmp` fallback
  to handle NaN distances gracefully and improve throughput on large sets

API improvement:
- types: `HnswConfig::default()` now uses `max_elements=1_000_000` (was
  10_000_000) and `m=16/ef_construction=100` to avoid excessive upfront
  memory allocation in the common case; large-index callers can still
  set `max_elements` explicitly

New module:
- integration: `FannAdapter` and `SemanticSearchAdapter` — thin wrappers
  that make ruvector-core directly usable from ruv-FANN (layer-embedding
  storage + retrieval) and sparc (semantic file search by embedding query).
  Includes `normalize()` and `cosine_similarity()` free-standing utilities.

Tests (4 new integration, 3 new unit):
- test_hnsw_search_k_zero: k=0 returns empty, no panic
- test_hnsw_results_sorted_ascending: verifies window[i].score <= window[i+1].score
- test_hnsw_set_ef_search_updates_config: set_ef_search writes through to config
- test_hnsw_search_with_ef_clamps_to_k: ef < k still returns results
- flat: test_flat_index_k_zero, test_flat_index_results_sorted
- integration: FannAdapter and SemanticSearchAdapter roundtrip tests

Version bump: 2.2.2 → 2.2.3

Co-Authored-By: claude-flow <ruv@ruv.net>

* style: cargo fmt ruvector-core
2026-05-23 03:37:35 -04:00
..
advanced_features_integration.rs fix(ci): Fix formatting and workflow permission issues 2025-12-26 22:11:57 +00:00
concurrent_tests.rs fix: Resolve test compilation errors with VectorId type and imports 2025-11-26 17:27:57 +00:00
embeddings_test.rs fix(ci): Fix formatting and workflow permission issues 2025-12-26 22:11:57 +00:00
hnsw_integration_test.rs fix(core): HNSW correctness fixes, k=0 guard, sorted results, cross-integration helpers (v2.2.3) (#502) 2026-05-23 03:37:35 -04:00
integration_tests.rs fix: Resolve test compilation errors with VectorId type and imports 2025-11-26 17:27:57 +00:00
property_tests.rs Test and validate core functionality (#54) 2025-12-06 09:36:47 -05:00
README.md feat: Complete ALL Ruvector phases - production-ready vector database 2025-11-19 14:37:21 +00:00
stress_tests.rs fix: Resolve test compilation errors with VectorId type and imports 2025-11-26 17:27:57 +00:00
test_memory_pool.rs style: apply rustfmt across entire codebase 2026-01-28 17:00:26 +00:00
test_quantization.rs style: apply rustfmt across entire codebase 2026-01-28 17:00:26 +00:00
test_simd_correctness.rs style: apply rustfmt across entire codebase 2026-01-28 17:00:26 +00:00
unit_tests.rs fix: Resolve CI build failures 2025-11-26 15:25:47 +00:00

Ruvector Core Test Suite

Overview

This directory contains a comprehensive Test-Driven Development (TDD) test suite following the London School approach. The test suite covers unit tests, integration tests, property-based tests, stress tests, and concurrent access tests.

Test Files

1. unit_tests.rs - Unit Tests with Mocking (London School)

Comprehensive unit tests using mockall for mocking dependencies:

  • Distance Metric Tests: Tests for all 4 distance metrics (Euclidean, Cosine, Dot Product, Manhattan)

    • Self-distance verification
    • Symmetry properties
    • Orthogonal and parallel vector cases
    • Dimension mismatch error handling
  • Quantization Tests: Tests for scalar and binary quantization

    • Round-trip reconstruction accuracy
    • Distance calculation correctness
    • Sign preservation (binary quantization)
    • Hamming distance validation
  • Storage Layer Tests: Tests for VectorStorage

    • Insert with explicit and auto-generated IDs
    • Metadata handling
    • Dimension validation
    • Batch operations
    • Delete operations
    • Error cases (non-existent vectors, dimension mismatches)
  • VectorDB Tests: High-level API tests

    • Empty database operations
    • Insert/delete with len() tracking
    • Search functionality
    • Metadata filtering
    • Batch insert operations

2. integration_tests.rs - End-to-End Integration Tests

Full workflow tests that verify all components work together:

  • Complete Workflows: Insert + search + retrieve with metadata
  • Large Batch Operations: 10K+ vector batch insertions
  • Persistence: Database save and reload verification
  • Mixed Operations: Combined insert, delete, and search operations
  • Distance Metrics: Tests for all 4 metrics end-to-end
  • HNSW Configurations: Different HNSW parameter combinations
  • Metadata Filtering: Complex filtering scenarios
  • Error Handling: Dimension validation, wrong query dimensions

3. property_tests.rs - Property-Based Tests (proptest)

Mathematical property verification using proptest:

  • Distance Metric Properties:

    • Self-distance is zero
    • Symmetry: d(a,b) = d(b,a)
    • Triangle inequality: d(a,c) ≤ d(a,b) + d(b,c)
    • Non-negativity
    • Scale invariance (cosine)
    • Translation invariance (Euclidean)
  • Quantization Properties:

    • Round-trip reconstruction bounds
    • Sign preservation (binary)
    • Self-distance is zero
    • Symmetry
    • Distance bounds
  • Batch Operations:

    • Consistency between batch and individual operations
  • Dimension Handling:

    • Mismatch error detection
    • Success on matching dimensions

4. stress_tests.rs - Scalability and Performance Stress Tests

Tests that push the system to its limits:

  • Million Vector Insertion (ignored by default): Insert 1M vectors in batches
  • Concurrent Queries: 10 threads × 100 queries each
  • Concurrent Mixed Operations: Simultaneous readers and writers
  • Memory Pressure: Large 2048-dimensional vectors
  • Error Recovery: Invalid operations don't crash the system
  • Repeated Operations: Same operation executed many times
  • Extreme Parameters: k values larger than database size

5. concurrent_tests.rs - Thread-Safety Tests

Multi-threaded access patterns:

  • Concurrent Reads: Multiple threads reading simultaneously
  • Concurrent Writes: Non-overlapping writes from multiple threads
  • Mixed Read/Write: Concurrent reads and writes
  • Delete and Insert: Simultaneous deletes and inserts
  • Search and Insert: Searching while inserting
  • Batch Atomicity: Verifying batch operations are atomic
  • Read-Write Consistency: Ensuring no data corruption
  • Metadata Updates: Concurrent metadata modifications

Benchmarks

6. benches/quantization_bench.rs - Quantization Performance

Criterion benchmarks for quantization operations:

  • Scalar quantization encode/decode/distance
  • Binary quantization encode/decode/distance
  • Compression ratio comparisons

7. benches/batch_operations.rs - Batch Operation Performance

Criterion benchmarks for batch operations:

  • Batch insert at various scales (100, 1K, 10K)
  • Individual vs batch insert comparison
  • Parallel search performance
  • Batch delete operations

Running Tests

Run All Tests

cargo test --package ruvector-core

Run Specific Test Suites

# Unit tests only
cargo test --test unit_tests

# Integration tests only
cargo test --test integration_tests

# Property tests only
cargo test --test property_tests

# Concurrent tests only
cargo test --test concurrent_tests

# Stress tests (including ignored tests)
cargo test --test stress_tests -- --ignored --test-threads=1

Run Benchmarks

# Distance metrics (existing)
cargo bench --bench distance_metrics

# HNSW search (existing)
cargo bench --bench hnsw_search

# Quantization (new)
cargo bench --bench quantization_bench

# Batch operations (new)
cargo bench --bench batch_operations

Generate Coverage Report

# Install tarpaulin if not already installed
cargo install cargo-tarpaulin

# Generate HTML coverage report
cargo tarpaulin --out Html --output-dir target/coverage

# Open coverage report
open target/coverage/index.html

Test Coverage Goals

  • Target: 90%+ code coverage
  • Focus Areas:
    • Distance calculations
    • Index operations
    • Storage layer
    • Error handling paths
    • Edge cases

Known Issues

As of the current implementation, there are pre-existing compilation errors in the codebase that prevent some tests from running:

  1. HNSW Index: DataId::new construction issues in src/index/hnsw.rs
  2. AgenticDB: Missing Encode/Decode trait implementations for ReflexionEpisode

These issues exist in the main codebase and need to be fixed before the full test suite can execute.

Test Organization

Tests are organized by purpose and scope:

  1. Unit Tests: Test individual components in isolation with mocking
  2. Integration Tests: Test component interactions and workflows
  3. Property Tests: Test mathematical properties and invariants
  4. Stress Tests: Test performance limits and edge cases
  5. Concurrent Tests: Test thread-safety and concurrent access patterns

Dependencies

Test dependencies (in Cargo.toml):

[dev-dependencies]
criterion = { workspace = true }
proptest = { workspace = true }
mockall = { workspace = true }
tempfile = "3.13"
tracing-subscriber = { workspace = true }

Contributing

When adding new tests:

  1. Follow the existing structure and naming conventions
  2. Add tests to the appropriate file (unit, integration, property, etc.)
  3. Document the test purpose clearly
  4. Ensure tests are deterministic and don't depend on timing
  5. Use tempdir() for database paths in tests
  6. Clean up resources properly

CI/CD Integration

Recommended CI pipeline:

test:
  script:
    - cargo test --all-features
    - cargo tarpaulin --out Xml
  coverage: '/\d+\.\d+% coverage/'

bench:
  script:
    - cargo bench --no-run

Performance Expectations

Based on stress tests:

  • Insert: ~10K vectors/second (batch mode)
  • Search: ~1K queries/second (k=10, HNSW)
  • Concurrent: 10+ threads without performance degradation
  • Memory: ~4KB per 384-dim vector (uncompressed)

Additional Resources