velesdb-core 1.9.2

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
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
//! Extended tests for [`StreamIngester`] backpressure, shutdown drain,
//! and configuration defaults.

use super::ingester::{BackpressureError, StreamIngester, StreamingConfig};
use crate::collection::types::Collection;
use crate::distance::DistanceMetric;
use crate::point::Point;
use tempfile::TempDir;

/// Helper: create a test collection in a temp directory.
fn test_collection(dim: usize) -> (TempDir, Collection) {
    let dir = TempDir::new().expect("tempdir");
    let path = dir.path().join("test_ingester_coll");
    let coll = Collection::create(path, dim, DistanceMetric::Cosine).expect("create collection");
    (dir, coll)
}

/// Helper: create a point with the given id and dimension.
fn make_point(id: u64, dim: usize) -> Point {
    Point {
        id,
        vector: vec![0.1_f32; dim],
        payload: None,
        sparse_vectors: None,
    }
}

// ─────────────────────────────────────────────────────────────────────────────
// Config defaults
// ─────────────────────────────────────────────────────────────────────────────

#[test]
fn streaming_config_defaults() {
    let cfg = StreamingConfig::default();
    assert_eq!(cfg.buffer_size, 10_000);
    assert_eq!(cfg.batch_size, 128);
    assert_eq!(cfg.flush_interval_ms, 50);
}

#[test]
fn streaming_config_clone_is_identical() {
    let cfg = StreamingConfig {
        buffer_size: 42,
        batch_size: 7,
        flush_interval_ms: 100,
    };
    let cloned = cfg.clone();
    assert_eq!(cloned.buffer_size, 42);
    assert_eq!(cloned.batch_size, 7);
    assert_eq!(cloned.flush_interval_ms, 100);
}

// ─────────────────────────────────────────────────────────────────────────────
// try_send with backpressure
// ─────────────────────────────────────────────────────────────────────────────

#[tokio::test]
async fn ingester_try_send_buffer_full_error_display() {
    let (_dir, coll) = test_collection(4);
    let config = StreamingConfig {
        buffer_size: 1,
        batch_size: 1000,
        flush_interval_ms: 60_000,
    };
    let ingester = StreamIngester::new(coll, config);

    // Fill the single-slot channel
    assert!(ingester.try_send(make_point(1, 4)).is_ok());

    let err = ingester.try_send(make_point(2, 4)).unwrap_err();
    assert!(
        matches!(err, BackpressureError::BufferFull),
        "expected BufferFull, got: {err}"
    );
    // Verify Display impl
    let msg = format!("{err}");
    assert!(
        msg.contains("full"),
        "error message should mention 'full': {msg}"
    );

    ingester.shutdown().await;
}

#[tokio::test]
async fn ingester_config_accessor() {
    let (_dir, coll) = test_collection(4);
    let config = StreamingConfig {
        buffer_size: 42,
        batch_size: 7,
        flush_interval_ms: 99,
    };
    let ingester = StreamIngester::new(coll, config);

    let c = ingester.config();
    assert_eq!(c.buffer_size, 42);
    assert_eq!(c.batch_size, 7);
    assert_eq!(c.flush_interval_ms, 99);

    ingester.shutdown().await;
}

// ─────────────────────────────────────────────────────────────────────────────
// Shutdown drains pending items
// ─────────────────────────────────────────────────────────────────────────────

#[tokio::test]
async fn ingester_shutdown_drains_all_pending() {
    let (_dir, coll) = test_collection(4);
    let config = StreamingConfig {
        buffer_size: 100,
        batch_size: 10_000,        // huge — won't auto-flush by batch
        flush_interval_ms: 60_000, // huge — won't auto-flush by timer
    };
    let coll_clone = coll.clone();
    let ingester = StreamIngester::new(coll, config);

    for i in 1..=5 {
        ingester.try_send(make_point(i, 4)).expect("send ok");
    }

    // Brief yield so drain loop receives points into its channel buffer
    tokio::time::sleep(std::time::Duration::from_millis(50)).await;

    // Shutdown flushes everything
    ingester.shutdown().await;

    let results = coll_clone.get(&[1, 2, 3, 4, 5]);
    let found = results.iter().filter(|r| r.is_some()).count();
    assert_eq!(found, 5, "shutdown must flush all pending points");
}

// ─────────────────────────────────────────────────────────────────────────────
// BackpressureError variants
// ─────────────────────────────────────────────────────────────────────────────

#[test]
fn backpressure_error_not_configured_display() {
    let err = BackpressureError::NotConfigured;
    let msg = format!("{err}");
    assert!(msg.contains("not configured"));
}

#[test]
fn backpressure_error_drain_task_dead_display() {
    let err = BackpressureError::DrainTaskDead;
    let msg = format!("{err}");
    assert!(msg.contains("dead"));
}

// ─────────────────────────────────────────────────────────────────────────────
// Drain loop integration tests (moved from ingester.rs inline tests)
// ─────────────────────────────────────────────────────────────────────────────

#[tokio::test]
async fn test_stream_try_send_succeeds_when_capacity_available() {
    let (_dir, coll) = test_collection(4);
    let config = StreamingConfig {
        buffer_size: 10,
        batch_size: 100,
        flush_interval_ms: 5000,
    };
    let ingester = StreamIngester::new(coll, config);

    let result = ingester.try_send(make_point(1, 4));
    assert!(
        result.is_ok(),
        "try_send should succeed when channel has capacity"
    );

    ingester.shutdown().await;
}

#[tokio::test]
async fn test_stream_try_send_returns_buffer_full_when_at_capacity() {
    let (_dir, coll) = test_collection(4);
    let config = StreamingConfig {
        buffer_size: 2,
        batch_size: 100,
        flush_interval_ms: 60_000,
    };
    let ingester = StreamIngester::new(coll, config);

    assert!(ingester.try_send(make_point(1, 4)).is_ok());
    assert!(ingester.try_send(make_point(2, 4)).is_ok());

    let result = ingester.try_send(make_point(3, 4));
    assert!(result.is_err(), "should return error when buffer full");
    match result.unwrap_err() {
        BackpressureError::BufferFull => {}
        other => panic!("expected BufferFull, got: {other}"),
    }

    ingester.shutdown().await;
}

#[tokio::test]
async fn test_stream_drain_flushes_at_batch_size() {
    let (_dir, coll) = test_collection(4);
    let batch_size = 4;
    let config = StreamingConfig {
        buffer_size: 100,
        batch_size,
        flush_interval_ms: 60_000,
    };
    let coll_clone = coll.clone();
    let ingester = StreamIngester::new(coll, config);

    for i in 0..batch_size {
        ingester
            .try_send(make_point(i as u64 + 1, 4))
            .expect("send should succeed");
    }

    // Poll until batch-size flush completes (max 5s).
    let deadline = tokio::time::Instant::now() + std::time::Duration::from_secs(5);
    loop {
        let found_count = coll_clone.get(&[1, 2, 3, 4]).iter().flatten().count();
        if found_count == 4 {
            break;
        }
        assert!(
            tokio::time::Instant::now() < deadline,
            "timed out waiting for batch flush (found {found_count}/4)"
        );
        tokio::time::sleep(std::time::Duration::from_millis(25)).await;
    }

    let results = coll_clone.get(&[1, 2, 3, 4]);
    let found_count = results.iter().filter(|r| r.is_some()).count();
    assert_eq!(
        found_count, 4,
        "all {batch_size} points should be flushed via upsert"
    );

    ingester.shutdown().await;
}

#[tokio::test]
async fn test_stream_drain_flushes_partial_batch_after_timeout() {
    let (_dir, coll) = test_collection(4);
    let config = StreamingConfig {
        buffer_size: 100,
        batch_size: 100,
        flush_interval_ms: 50,
    };
    let coll_clone = coll.clone();
    let ingester = StreamIngester::new(coll, config);

    ingester.try_send(make_point(1, 4)).expect("send 1");
    ingester.try_send(make_point(2, 4)).expect("send 2");

    // Poll until timer-triggered partial flush completes (max 5s).
    let deadline = tokio::time::Instant::now() + std::time::Duration::from_secs(5);
    loop {
        let found_count = coll_clone.get(&[1, 2]).iter().flatten().count();
        if found_count == 2 {
            break;
        }
        assert!(
            tokio::time::Instant::now() < deadline,
            "timed out waiting for partial batch flush (found {found_count}/2)"
        );
        tokio::time::sleep(std::time::Duration::from_millis(25)).await;
    }

    let results = coll_clone.get(&[1, 2]);
    let found_count = results.iter().filter(|r| r.is_some()).count();
    assert_eq!(
        found_count, 2,
        "partial batch should be flushed after flush_interval_ms"
    );

    ingester.shutdown().await;
}

#[tokio::test]
async fn test_stream_shutdown_flushes_remaining_points() {
    let (_dir, coll) = test_collection(4);
    let config = StreamingConfig {
        buffer_size: 100,
        batch_size: 1000,
        flush_interval_ms: 60_000,
    };
    let coll_clone = coll.clone();
    let ingester = StreamIngester::new(coll, config);

    ingester.try_send(make_point(10, 4)).expect("send");
    ingester.try_send(make_point(11, 4)).expect("send");

    tokio::time::sleep(std::time::Duration::from_millis(50)).await;

    ingester.shutdown().await;

    let results = coll_clone.get(&[10, 11]);
    let found_count = results.iter().filter(|r| r.is_some()).count();
    assert_eq!(
        found_count, 2,
        "shutdown should flush remaining buffered points"
    );
}

#[tokio::test]
async fn test_stream_delta_drain_loop_routes_to_delta_when_active() {
    let (_dir, coll) = test_collection(4);
    let config = StreamingConfig {
        buffer_size: 100,
        batch_size: 4,
        flush_interval_ms: 50,
    };
    let coll_clone = coll.clone();

    coll.delta_buffer.activate();

    let ingester = StreamIngester::new(coll, config);

    for i in 1..=4 {
        ingester
            .try_send(make_point(i, 4))
            .expect("send should succeed");
    }

    // Poll until all 4 points are flushed to storage AND delta buffer (max 5s).
    let deadline = tokio::time::Instant::now() + std::time::Duration::from_secs(5);
    loop {
        let found = coll_clone.get(&[1, 2, 3, 4]).iter().flatten().count();
        if found == 4 && coll_clone.delta_buffer.len() == 4 {
            break;
        }
        assert!(
            tokio::time::Instant::now() < deadline,
            "timed out waiting for delta drain flush (storage={found}/4, delta={})",
            coll_clone.delta_buffer.len()
        );
        tokio::time::sleep(std::time::Duration::from_millis(25)).await;
    }

    let results = coll_clone.get(&[1, 2, 3, 4]);
    let found = results.iter().filter(|r| r.is_some()).count();
    assert_eq!(found, 4, "upsert should write all points to storage");

    assert_eq!(
        coll_clone.delta_buffer.len(),
        4,
        "delta buffer should contain the streamed points when active"
    );

    ingester.shutdown().await;
}

#[tokio::test]
#[allow(clippy::cast_possible_truncation)]
async fn test_stream_searchable_immediately() {
    let (_dir, coll) = test_collection(4);
    let config = StreamingConfig {
        buffer_size: 100,
        batch_size: 4,
        flush_interval_ms: 50,
    };
    let coll_clone = coll.clone();
    let ingester = StreamIngester::new(coll, config);

    for i in 1..=4u64 {
        let mut vec = vec![0.0_f32; 4];
        vec[(i as usize - 1) % 4] = 1.0;
        let p = Point {
            id: i,
            vector: vec,
            payload: None,
            sparse_vectors: None,
        };
        ingester.try_send(p).expect("send should succeed");
    }

    // Poll until all 4 points are flushed and searchable (max 5s).
    let deadline = tokio::time::Instant::now() + std::time::Duration::from_secs(5);
    loop {
        let found = coll_clone.get(&[1, 2, 3, 4]).iter().flatten().count();
        if found == 4 {
            break;
        }
        assert!(
            tokio::time::Instant::now() < deadline,
            "timed out waiting for search-ready flush (found {found}/4)"
        );
        tokio::time::sleep(std::time::Duration::from_millis(25)).await;
    }

    let query = vec![1.0, 0.0, 0.0, 0.0];
    let results = coll_clone.search(&query, 4).expect("search should succeed");
    assert!(
        !results.is_empty(),
        "inserted points should be searchable after drain"
    );
    assert_eq!(results[0].point.id, 1, "closest match should be id=1");

    ingester.shutdown().await;
}

#[tokio::test]
#[allow(clippy::cast_precision_loss)]
async fn test_stream_delta_rebuild_no_data_loss() {
    let (_dir, coll) = test_collection(4);
    let initial_points: Vec<Point> = (1..=5u64)
        .map(|i| {
            let mut vec = vec![0.0_f32; 4];
            vec[0] = i as f32;
            Point {
                id: i,
                vector: vec,
                payload: None,
                sparse_vectors: None,
            }
        })
        .collect();
    coll.upsert(initial_points).expect("upsert initial points");

    coll.delta_buffer.activate();
    assert!(coll.delta_buffer.is_active());

    let config = StreamingConfig {
        buffer_size: 100,
        batch_size: 4,
        flush_interval_ms: 50,
    };
    let coll_clone = coll.clone();
    let ingester = StreamIngester::new(coll, config);

    for i in 6..=10u64 {
        let mut vec = vec![0.0_f32; 4];
        vec[0] = i as f32;
        let p = Point {
            id: i,
            vector: vec,
            payload: None,
            sparse_vectors: None,
        };
        ingester.try_send(p).expect("send should succeed");
    }

    // Poll until all 5 streamed points are visible (max 5s), avoiding
    // a fixed sleep that is fragile under load.
    let deadline = tokio::time::Instant::now() + std::time::Duration::from_secs(5);
    loop {
        let count = coll_clone.get(&[6, 7, 8, 9, 10]).iter().flatten().count();
        if count == 5 {
            break;
        }
        assert!(
            tokio::time::Instant::now() < deadline,
            "timed out waiting for streamed points to flush (found {count}/5)"
        );
        tokio::time::sleep(std::time::Duration::from_millis(25)).await;
    }

    let query = vec![10.0, 0.0, 0.0, 0.0];
    let results = coll_clone
        .search_ids(&query, 10)
        .expect("search_ids should succeed");
    let found_ids: std::collections::HashSet<u64> = results.iter().map(|sr| sr.id).collect();

    for id in 1..=10 {
        assert!(
            found_ids.contains(&id),
            "point id={id} should be in search results"
        );
    }

    let drained = coll_clone.delta_buffer.deactivate_and_drain();
    assert!(!coll_clone.delta_buffer.is_active());
    assert_eq!(drained.len(), 5, "delta should have had 5 entries");

    ingester.shutdown().await;
}

// ─────────────────────────────────────────────────────────────────────────────
// try_send_batch (#416)
// ─────────────────────────────────────────────────────────────────────────────

#[tokio::test]
async fn try_send_batch_sends_all_points() {
    let (_dir, coll) = test_collection(4);
    let config = StreamingConfig {
        buffer_size: 100,
        batch_size: 10,
        flush_interval_ms: 50,
    };
    let coll_clone = coll.clone();
    let ingester = StreamIngester::new(coll, config);

    let points: Vec<Point> = (1..=5).map(|i| make_point(i, 4)).collect();
    let sent = ingester.try_send_batch(points).expect("batch send ok");
    assert_eq!(sent, 5);

    // Poll until all 5 points are flushed (max 5s).
    let deadline = tokio::time::Instant::now() + std::time::Duration::from_secs(5);
    loop {
        let found = coll_clone.get(&[1, 2, 3, 4, 5]).iter().flatten().count();
        if found == 5 {
            break;
        }
        assert!(
            tokio::time::Instant::now() < deadline,
            "timed out waiting for batch flush (found {found}/5)"
        );
        tokio::time::sleep(std::time::Duration::from_millis(25)).await;
    }

    ingester.shutdown().await;
}

#[tokio::test]
async fn try_send_batch_empty_vec_returns_zero() {
    let (_dir, coll) = test_collection(4);
    let config = StreamingConfig::default();
    let ingester = StreamIngester::new(coll, config);

    let sent = ingester.try_send_batch(Vec::new()).expect("empty batch ok");
    assert_eq!(sent, 0);

    ingester.shutdown().await;
}

#[tokio::test]
async fn try_send_batch_partial_on_buffer_full() {
    let (_dir, coll) = test_collection(4);
    let config = StreamingConfig {
        buffer_size: 3,
        batch_size: 1000,          // huge -- won't auto-flush by batch
        flush_interval_ms: 60_000, // huge -- won't auto-flush by timer
    };
    let ingester = StreamIngester::new(coll, config);

    let points: Vec<Point> = (1..=10).map(|i| make_point(i, 4)).collect();
    let result = ingester.try_send_batch(points);

    // Should get a BufferFull error because we tried to send 10 into a 3-slot channel.
    match result {
        Err(BackpressureError::BufferFull) => {
            // Expected: some points were sent before the channel was full.
        }
        Ok(sent) => {
            // If the drain consumed some between sends, we might succeed.
            assert!(sent <= 10);
        }
        Err(other) => panic!("expected BufferFull or Ok, got: {other}"),
    }

    ingester.shutdown().await;
}