velesdb-core 7.0.0

High-performance vector database engine written in Rust
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
//! Tests for `distance` module

use super::distance::*;

#[test]
fn test_cosine_similarity() {
    let a = vec![1.0, 0.0, 0.0];
    let b = vec![1.0, 0.0, 0.0];
    let similarity = DistanceMetric::Cosine.calculate(&a, &b);
    assert!((similarity - 1.0).abs() < 1e-6);

    let c = vec![0.0, 1.0, 0.0];
    let similarity = DistanceMetric::Cosine.calculate(&a, &c);
    assert!(similarity.abs() < 1e-6);
}

#[test]
fn test_euclidean_distance() {
    let a = vec![0.0, 0.0, 0.0];
    let b = vec![3.0, 4.0, 0.0];
    let distance = DistanceMetric::Euclidean.calculate(&a, &b);
    assert!((distance - 5.0).abs() < 1e-6);
}

#[test]
fn test_dot_product() {
    let a = vec![1.0, 2.0, 3.0];
    let b = vec![4.0, 5.0, 6.0];
    let product = DistanceMetric::DotProduct.calculate(&a, &b);
    assert!((product - 32.0).abs() < 1e-6);
}

#[test]
fn test_higher_is_better() {
    // Cosine: higher similarity = more similar
    assert!(DistanceMetric::Cosine.higher_is_better());

    // DotProduct: higher product = more similar
    assert!(DistanceMetric::DotProduct.higher_is_better());

    // Euclidean: lower distance = more similar
    assert!(!DistanceMetric::Euclidean.higher_is_better());
}

#[test]
fn test_metric_serialization() {
    // Test that metrics can be serialized/deserialized
    let metric = DistanceMetric::Cosine;
    let json = serde_json::to_string(&metric).unwrap();
    let deserialized: DistanceMetric = serde_json::from_str(&json).unwrap();
    assert_eq!(metric, deserialized);

    let metric = DistanceMetric::Euclidean;
    let json = serde_json::to_string(&metric).unwrap();
    let deserialized: DistanceMetric = serde_json::from_str(&json).unwrap();
    assert_eq!(metric, deserialized);

    let metric = DistanceMetric::DotProduct;
    let json = serde_json::to_string(&metric).unwrap();
    let deserialized: DistanceMetric = serde_json::from_str(&json).unwrap();
    assert_eq!(metric, deserialized);

    let metric = DistanceMetric::Hamming;
    let json = serde_json::to_string(&metric).unwrap();
    let deserialized: DistanceMetric = serde_json::from_str(&json).unwrap();
    assert_eq!(metric, deserialized);

    let metric = DistanceMetric::Jaccard;
    let json = serde_json::to_string(&metric).unwrap();
    let deserialized: DistanceMetric = serde_json::from_str(&json).unwrap();
    assert_eq!(metric, deserialized);
}

// =========================================================================
// TDD Tests for Hamming Distance
// =========================================================================

#[test]
fn test_hamming_distance_identical() {
    // Identical binary vectors should have distance 0
    let a = vec![1.0, 0.0, 1.0, 0.0];
    let b = vec![1.0, 0.0, 1.0, 0.0];
    let distance = DistanceMetric::Hamming.calculate(&a, &b);
    assert!(
        (distance - 0.0).abs() < 1e-6,
        "Identical vectors: distance = 0"
    );
}

#[test]
fn test_hamming_distance_completely_different() {
    // Completely different binary vectors
    let a = vec![1.0, 1.0, 1.0, 1.0];
    let b = vec![0.0, 0.0, 0.0, 0.0];
    let distance = DistanceMetric::Hamming.calculate(&a, &b);
    assert!(
        (distance - 4.0).abs() < 1e-6,
        "All bits differ: distance = 4"
    );
}

#[test]
fn test_hamming_distance_partial() {
    // Some bits differ
    let a = vec![1.0, 0.0, 1.0, 0.0];
    let b = vec![1.0, 1.0, 0.0, 0.0];
    let distance = DistanceMetric::Hamming.calculate(&a, &b);
    assert!((distance - 2.0).abs() < 1e-6, "2 bits differ: distance = 2");
}

#[test]
fn test_hamming_higher_is_better() {
    // Hamming: lower distance = more similar
    assert!(!DistanceMetric::Hamming.higher_is_better());
}

// =========================================================================
// TDD Tests for Jaccard Similarity
// =========================================================================

#[test]
fn test_jaccard_similarity_identical() {
    // Identical sets should have similarity 1.0
    let a = vec![1.0, 0.0, 1.0, 1.0];
    let b = vec![1.0, 0.0, 1.0, 1.0];
    let similarity = DistanceMetric::Jaccard.calculate(&a, &b);
    assert!(
        (similarity - 1.0).abs() < 1e-6,
        "Identical sets: similarity = 1.0"
    );
}

#[test]
fn test_jaccard_similarity_disjoint() {
    // Disjoint sets should have similarity 0.0
    let a = vec![1.0, 1.0, 0.0, 0.0];
    let b = vec![0.0, 0.0, 1.0, 1.0];
    let similarity = DistanceMetric::Jaccard.calculate(&a, &b);
    assert!(
        (similarity - 0.0).abs() < 1e-6,
        "Disjoint sets: similarity = 0.0"
    );
}

#[test]
fn test_jaccard_similarity_partial_overlap() {
    // Partial overlap: intersection=2, union=4, similarity=0.5
    let a = vec![1.0, 1.0, 1.0, 0.0];
    let b = vec![1.0, 1.0, 0.0, 1.0];
    let similarity = DistanceMetric::Jaccard.calculate(&a, &b);
    assert!(
        (similarity - 0.5).abs() < 1e-6,
        "Partial overlap: similarity = 0.5"
    );
}

#[test]
fn test_jaccard_similarity_empty_sets() {
    // Both empty sets - defined as 1.0 (identical)
    let a = vec![0.0, 0.0, 0.0, 0.0];
    let b = vec![0.0, 0.0, 0.0, 0.0];
    let similarity = DistanceMetric::Jaccard.calculate(&a, &b);
    assert!(
        (similarity - 1.0).abs() < 1e-6,
        "Empty sets: similarity = 1.0"
    );
}

#[test]
fn test_jaccard_higher_is_better() {
    // Jaccard: higher similarity = more similar
    assert!(DistanceMetric::Jaccard.higher_is_better());
}

// =========================================================================
// TDD Tests for sort_results (QW-1 Refactoring)
// =========================================================================

#[test]
fn test_sort_results_cosine_descending() {
    let mut results = vec![(1, 0.7), (2, 0.9), (3, 0.8)];
    DistanceMetric::Cosine.sort_results(&mut results);
    assert_eq!(results[0].0, 2); // Highest first
    assert_eq!(results[1].0, 3);
    assert_eq!(results[2].0, 1);
}

#[test]
fn test_sort_results_euclidean_ascending() {
    let mut results = vec![(1, 5.0), (2, 2.0), (3, 3.0)];
    DistanceMetric::Euclidean.sort_results(&mut results);
    assert_eq!(results[0].0, 2); // Lowest first
    assert_eq!(results[1].0, 3);
    assert_eq!(results[2].0, 1);
}

#[test]
fn test_sort_results_dot_product_descending() {
    let mut results = vec![(1, 10.0), (2, 30.0), (3, 20.0)];
    DistanceMetric::DotProduct.sort_results(&mut results);
    assert_eq!(results[0].0, 2); // Highest first
}

#[test]
fn test_sort_results_hamming_ascending() {
    let mut results = vec![(1, 4.0), (2, 1.0), (3, 2.0)];
    DistanceMetric::Hamming.sort_results(&mut results);
    assert_eq!(results[0].0, 2); // Lowest first
}

#[test]
fn test_sort_results_jaccard_descending() {
    let mut results = vec![(1, 0.3), (2, 0.9), (3, 0.5)];
    DistanceMetric::Jaccard.sort_results(&mut results);
    assert_eq!(results[0].0, 2); // Highest first
}

#[test]
fn test_sort_results_handles_nan() {
    let mut results = vec![(1, f32::NAN), (2, 0.5), (3, 0.8)];
    // Should not panic with NaN values
    DistanceMetric::Cosine.sort_results(&mut results);
    assert!(results[0].1.is_nan()); // positive NaN is the max under total_cmp (descending)
    assert_eq!(results[1].0, 3); // 0.8
    assert_eq!(results[2].0, 2); // 0.5
}

#[test]
fn test_sort_results_empty_input_does_not_panic() {
    let mut results: Vec<(u64, f32)> = vec![];
    // Empty input is the trivial boundary case: sort_results must not panic
    // (e.g. must not assume a non-empty slice / index results[0]).
    DistanceMetric::Cosine.sort_results(&mut results);
}

#[test]
fn test_parse_aliases() {
    assert_eq!(
        DistanceMetric::parse_alias("cosine"),
        Some(DistanceMetric::Cosine)
    );
    assert_eq!(
        DistanceMetric::parse_alias("L2"),
        Some(DistanceMetric::Euclidean)
    );
    assert_eq!(
        DistanceMetric::parse_alias("inner"),
        Some(DistanceMetric::DotProduct)
    );
    assert_eq!(
        DistanceMetric::parse_alias("hamming"),
        Some(DistanceMetric::Hamming)
    );
    assert_eq!(
        DistanceMetric::parse_alias("jaccard"),
        Some(DistanceMetric::Jaccard)
    );
    assert_eq!(DistanceMetric::parse_alias("unknown"), None);
}

#[test]
fn test_canonical_names_and_from_str() {
    use std::str::FromStr;

    assert_eq!(DistanceMetric::Cosine.canonical_name(), "cosine");
    assert_eq!(DistanceMetric::Euclidean.canonical_name(), "euclidean");
    assert_eq!(DistanceMetric::DotProduct.canonical_name(), "dot");
    assert_eq!(DistanceMetric::Hamming.canonical_name(), "hamming");
    assert_eq!(DistanceMetric::Jaccard.canonical_name(), "jaccard");

    assert_eq!(
        DistanceMetric::from_str("dotproduct").unwrap(),
        DistanceMetric::DotProduct
    );
    assert!(DistanceMetric::from_str("invalid").is_err());
}

#[test]
fn test_parse_ip_alias() {
    use std::str::FromStr;

    // "ip" (inner product) is a common alias for DotProduct in ML ecosystems
    assert_eq!(
        DistanceMetric::from_str("ip").unwrap(),
        DistanceMetric::DotProduct
    );
    assert_eq!(
        DistanceMetric::from_str("IP").unwrap(),
        DistanceMetric::DotProduct
    );
    assert_eq!(
        DistanceMetric::parse_alias("ip"),
        Some(DistanceMetric::DotProduct)
    );
    assert_eq!(
        DistanceMetric::parse_alias("  IP  "),
        Some(DistanceMetric::DotProduct)
    );
}

// ---------------------------------------------------------------------------
// Score contract (`score_range` / `clamp_score`)
// ---------------------------------------------------------------------------

/// The declared range must match what `calculate` can actually produce.
///
/// These two travelled separately once: `transform_score` on the HNSW path
/// floored cosine at 0.0 while `calculate` returned the real cosine, so the
/// same document scored differently depending on which path ranked it.
#[test]
fn score_range_matches_what_calculate_produces() {
    let aligned = vec![1.0_f32, 0.0, 0.0];
    let opposed = vec![-1.0_f32, 0.0, 0.0];

    let cosine = DistanceMetric::Cosine.calculate(&aligned, &opposed);
    let (low, high) = DistanceMetric::Cosine
        .score_range()
        .expect("cosine is a bounded metric");
    assert!(
        (cosine - low).abs() < 1e-6,
        "opposed vectors must reach the declared floor {low}, got {cosine}"
    );
    assert!((high - 1.0).abs() < f32::EPSILON);

    // Jaccard over non-negative weights cannot go below zero.
    let disjoint_a = vec![1.0_f32, 0.0];
    let disjoint_b = vec![0.0_f32, 1.0];
    let jaccard = DistanceMetric::Jaccard.calculate(&disjoint_a, &disjoint_b);
    let (j_low, j_high) = DistanceMetric::Jaccard
        .score_range()
        .expect("jaccard is a bounded metric");
    assert!((j_low - 0.0).abs() < f32::EPSILON);
    assert!((j_high - 1.0).abs() < f32::EPSILON);
    assert!(jaccard >= j_low && jaccard <= j_high);
}

/// Cosine keeps its sign; Jaccard keeps its floor.
#[test]
fn clamp_score_respects_each_metrics_own_floor() {
    assert!((DistanceMetric::Cosine.clamp_score(-0.5) + 0.5).abs() < f32::EPSILON);
    assert!(DistanceMetric::Jaccard.clamp_score(-0.5).abs() < f32::EPSILON);
}

/// Drift past a boundary is absorbed; a value inside the range is untouched.
#[test]
fn clamp_score_absorbs_boundary_drift_without_moving_interior_values() {
    assert!((DistanceMetric::Cosine.clamp_score(1.000_001) - 1.0).abs() < f32::EPSILON);
    assert!((DistanceMetric::Cosine.clamp_score(-1.000_001) + 1.0).abs() < f32::EPSILON);
    assert!((DistanceMetric::Cosine.clamp_score(0.25) - 0.25).abs() < f32::EPSILON);
}

/// An unbounded metric is passed through, not squeezed into someone's range.
#[test]
fn clamp_score_leaves_unbounded_metrics_alone() {
    for metric in [
        DistanceMetric::Euclidean,
        DistanceMetric::Hamming,
        DistanceMetric::DotProduct,
    ] {
        assert!(
            metric.score_range().is_none(),
            "{metric:?} is unbounded and must declare no range"
        );
        for value in [-42.0_f32, 0.0, 1.5, 9_000.0] {
            assert!(
                (metric.clamp_score(value) - value).abs() < f32::EPSILON,
                "{metric:?} must pass {value} through unchanged"
            );
        }
    }
}

/// On in-contract input, a bounded metric's `calculate` already lands inside
/// its declared range, so the clamp is the identity.
///
/// "In contract" differs per metric and that is the point: cosine is defined
/// for any real vector, so an anti-correlated pair belongs in its set;
/// Jaccard is defined over set-like (non-negative) weights, so it gets
/// non-negative pairs. See
/// [`jaccard_calculate_escapes_its_declared_range_on_negative_weights`] for
/// what happens outside that contract.
#[test]
fn clamp_score_is_the_identity_on_real_calculate_output() {
    let cosine_pairs: [(&[f32], &[f32]); 4] = [
        (&[1.0, 0.0, 0.0], &[1.0, 0.0, 0.0]),
        (&[1.0, 0.0, 0.0], &[-1.0, 0.0, 0.0]),
        (&[1.0, 2.0, 3.0], &[3.0, 2.0, 1.0]),
        (&[0.0, 0.0, 0.0], &[0.0, 0.0, 0.0]),
    ];
    let jaccard_pairs: [(&[f32], &[f32]); 4] = [
        (&[1.0, 0.0, 0.0], &[1.0, 0.0, 0.0]),
        (&[1.0, 0.0, 0.0], &[0.0, 1.0, 0.0]),
        (&[1.0, 2.0, 3.0], &[3.0, 2.0, 1.0]),
        (&[0.0, 0.0, 0.0], &[0.0, 0.0, 0.0]),
    ];

    for (metric, pairs) in [
        (DistanceMetric::Cosine, cosine_pairs),
        (DistanceMetric::Jaccard, jaccard_pairs),
    ] {
        for (a, b) in pairs {
            let raw = metric.calculate(a, b);
            let clamped = metric.clamp_score(raw);
            assert!(
                (raw - clamped).abs() < f32::EPSILON,
                "{metric:?} produced {raw} on {a:?} vs {b:?}, outside its declared range"
            );
        }
    }
}

/// Jaccard's kernels do not enforce their own range on out-of-contract input.
///
/// `jaccard_scalar` is `intersection / union` with no clamp, where
/// `cosine_scalar` ends in `.clamp(-1.0, 1.0)` — the asymmetry is visible in
/// the same file. Feed a negative weight (meaningless for a set-like metric,
/// but nothing rejects it at insert) and `calculate` returns -1.0 while the
/// HNSW graph path, which goes through `transform_score` -> `clamp_score`,
/// returns 0.0. That is the same shape of path disagreement this module's
/// score contract exists to prevent, one metric over.
///
/// Closing it means clamping inside the Jaccard kernels on all three ISAs
/// (scalar, AVX2/AVX-512, NEON); this test pins the current behaviour so the
/// gap is a live, named fact rather than a silent one, and fails loudly the
/// moment someone fixes it.
#[test]
fn jaccard_calculate_escapes_its_declared_range_on_negative_weights() {
    let positive = vec![1.0_f32, 0.0, 0.0];
    let negative = vec![-1.0_f32, 0.0, 0.0];

    let raw = DistanceMetric::Jaccard.calculate(&positive, &negative);
    let (low, _) = DistanceMetric::Jaccard
        .score_range()
        .expect("jaccard is bounded");

    assert!(
        raw < low,
        "expected the known unclamped kernel output below the declared floor {low}, got {raw}"
    );
    // The declared contract still holds wherever `clamp_score` is applied,
    // which is what every score-producing path now routes through.
    assert!((DistanceMetric::Jaccard.clamp_score(raw) - low).abs() < f32::EPSILON);
}