velesdb-core 1.9.3

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
//! TDD tests for metadata-only collections (EPIC-CORE-002).
//!
//! These tests define the expected behavior for collections
//! that store metadata without vectors.
#![allow(deprecated)] // Tests use legacy Collection.

use crate::collection::CollectionType;
use crate::error::Error;
use crate::point::Point;
use crate::Database;
use serde_json::json;
use tempfile::tempdir;

// =============================================================================
// AC1: CollectionType enum
// =============================================================================

#[test]
fn test_collection_type_metadata_only_exists() {
    // CollectionType::MetadataOnly should exist
    let ct = CollectionType::MetadataOnly;
    assert!(ct.is_metadata_only());
}

#[test]
fn test_collection_type_vector_exists() {
    use crate::distance::DistanceMetric;
    use crate::quantization::StorageMode;

    // CollectionType::Vector should contain dimension, metric, storage_mode
    let ct = CollectionType::Vector {
        dimension: 768,
        metric: DistanceMetric::Cosine,
        storage_mode: StorageMode::Full,
    };

    match ct {
        CollectionType::Vector {
            dimension,
            metric,
            storage_mode,
        } => {
            assert_eq!(dimension, 768);
            assert_eq!(metric, DistanceMetric::Cosine);
            assert_eq!(storage_mode, StorageMode::Full);
        }
        CollectionType::MetadataOnly | CollectionType::Graph { .. } => {
            panic!("Expected Vector variant")
        }
    }
}

// =============================================================================
// AC2: Database::create_collection_typed API
// =============================================================================

#[test]
fn test_create_metadata_only_collection() {
    let dir = tempdir().unwrap();
    let db = Database::open(dir.path()).unwrap();

    // Create a metadata-only collection
    db.create_collection_typed("products", &CollectionType::MetadataOnly)
        .unwrap();

    // Verify it exists
    let collections = db.list_collections();
    assert!(collections.contains(&"products".to_string()));

    // Verify we can get it
    let coll = db.get_collection("products").unwrap();
    assert!(coll.is_metadata_only());
}

#[test]
fn test_create_vector_collection_typed() {
    use crate::distance::DistanceMetric;
    use crate::quantization::StorageMode;

    let dir = tempdir().unwrap();
    let db = Database::open(dir.path()).unwrap();

    // Create a vector collection using the typed API
    db.create_collection_typed(
        "embeddings",
        &CollectionType::Vector {
            dimension: 768,
            metric: DistanceMetric::Cosine,
            storage_mode: StorageMode::Full,
        },
    )
    .unwrap();

    let coll = db.get_collection("embeddings").unwrap();
    assert!(!coll.is_metadata_only());
    assert_eq!(coll.config().dimension, 768);
}

// =============================================================================
// AC3: Upsert without vector on metadata-only collections
// =============================================================================

#[test]
fn test_metadata_only_upsert_without_vector() {
    let dir = tempdir().unwrap();
    let db = Database::open(dir.path()).unwrap();

    db.create_collection_typed("products", &CollectionType::MetadataOnly)
        .unwrap();

    let coll = db.get_collection("products").unwrap();

    // Upsert points without vectors (metadata-only point)
    let result = coll.upsert_metadata(vec![
        Point::metadata_only(
            1,
            json!({
                "code_produit": "PROD001",
                "pays": "France",
                "nom_produit": "Séjour Paris",
                "prix": 1500.0
            }),
        ),
        Point::metadata_only(
            2,
            json!({
                "code_produit": "PROD002",
                "pays": "Espagne",
                "nom_produit": "Circuit Andalousie",
                "prix": 2000.0
            }),
        ),
    ]);

    assert!(result.is_ok());
    assert_eq!(coll.len(), 2);
}

#[test]
fn test_metadata_only_rejects_vector() {
    let dir = tempdir().unwrap();
    let db = Database::open(dir.path()).unwrap();

    db.create_collection_typed("products", &CollectionType::MetadataOnly)
        .unwrap();

    let coll = db.get_collection("products").unwrap();

    // Attempt to upsert a point WITH a vector should fail
    let result = coll.upsert(vec![Point::new(
        1,
        vec![0.1; 768],
        Some(json!({"title": "Test"})),
    )]);

    assert!(result.is_err());
    match result.unwrap_err() {
        Error::VectorNotAllowed(collection_name) => {
            assert_eq!(collection_name, "products");
        }
        e => panic!("Expected VectorNotAllowed error, got: {e:?}"),
    }
}

// =============================================================================
// AC4: Supported operations on metadata-only collections
// =============================================================================

#[test]
fn test_metadata_only_get_by_id() {
    let dir = tempdir().unwrap();
    let db = Database::open(dir.path()).unwrap();

    db.create_collection_typed("products", &CollectionType::MetadataOnly)
        .unwrap();

    let coll = db.get_collection("products").unwrap();

    coll.upsert_metadata(vec![Point::metadata_only(
        42,
        json!({"name": "Test Product", "price": 99.99}),
    )])
    .unwrap();

    // Get by ID should work
    let results = coll.get(&[42]);
    assert_eq!(results.len(), 1);
    assert!(results[0].is_some());

    let point = results[0].as_ref().unwrap();
    assert_eq!(point.id, 42);
    assert!(point.vector.is_empty()); // No vector
    assert!(point.payload.is_some());
}

#[test]
fn test_metadata_only_delete() {
    let dir = tempdir().unwrap();
    let db = Database::open(dir.path()).unwrap();

    db.create_collection_typed("products", &CollectionType::MetadataOnly)
        .unwrap();

    let coll = db.get_collection("products").unwrap();

    coll.upsert_metadata(vec![
        Point::metadata_only(1, json!({"name": "Product 1"})),
        Point::metadata_only(2, json!({"name": "Product 2"})),
    ])
    .unwrap();

    assert_eq!(coll.len(), 2);

    // Delete should work
    coll.delete(&[1]).unwrap();
    assert_eq!(coll.len(), 1);
}

#[test]
fn test_metadata_only_count() {
    let dir = tempdir().unwrap();
    let db = Database::open(dir.path()).unwrap();

    db.create_collection_typed("products", &CollectionType::MetadataOnly)
        .unwrap();

    let coll = db.get_collection("products").unwrap();

    assert_eq!(coll.len(), 0);
    assert!(coll.is_empty());

    coll.upsert_metadata(vec![
        Point::metadata_only(1, json!({"name": "A"})),
        Point::metadata_only(2, json!({"name": "B"})),
        Point::metadata_only(3, json!({"name": "C"})),
    ])
    .unwrap();

    assert_eq!(coll.len(), 3);
    assert!(!coll.is_empty());
}

#[test]
fn test_metadata_only_search_returns_error() {
    let dir = tempdir().unwrap();
    let db = Database::open(dir.path()).unwrap();

    db.create_collection_typed("products", &CollectionType::MetadataOnly)
        .unwrap();

    let coll = db.get_collection("products").unwrap();

    coll.upsert_metadata(vec![Point::metadata_only(1, json!({"name": "Test"}))])
        .unwrap();

    // search() MUST return an explicit error
    let query_vector = vec![0.1; 768];
    let result = coll.search(&query_vector, 10);

    assert!(result.is_err());
    match result.unwrap_err() {
        Error::SearchNotSupported(collection_name) => {
            assert_eq!(collection_name, "products");
        }
        e => panic!("Expected SearchNotSupported error, got: {e:?}"),
    }
}

// =============================================================================
// AC5: No HNSW index created for metadata-only
// =============================================================================

#[test]
fn test_metadata_only_no_hnsw_file() {
    let dir = tempdir().unwrap();
    let db = Database::open(dir.path()).unwrap();

    db.create_collection_typed("products", &CollectionType::MetadataOnly)
        .unwrap();

    let coll = db.get_collection("products").unwrap();

    coll.upsert_metadata(vec![Point::metadata_only(1, json!({"name": "Test"}))])
        .unwrap();

    coll.flush().unwrap();

    // HNSW index file should NOT exist
    let hnsw_path = dir.path().join("products").join("hnsw.bin");
    assert!(
        !hnsw_path.exists(),
        "HNSW index should not be created for metadata-only collections"
    );
}

// =============================================================================
// AC6: Memory efficiency (no dummy vectors)
// =============================================================================

#[test]
#[allow(clippy::cast_precision_loss)]
fn test_metadata_only_memory_efficient() {
    let dir = tempdir().unwrap();
    let db = Database::open(dir.path()).unwrap();

    db.create_collection_typed("products", &CollectionType::MetadataOnly)
        .unwrap();

    let coll = db.get_collection("products").unwrap();

    // Insert 100 metadata-only points
    let points: Vec<_> = (0..100_u64)
        .map(|i| {
            let price = (i as f64) * 10.0; // Safe: i < 100, no precision loss
            Point::metadata_only(
                i,
                json!({
                    "id": i,
                    "name": format!("Product {i}"),
                    "price": price
                }),
            )
        })
        .collect();

    coll.upsert_metadata(points).unwrap();

    // No vector storage file should be created or should be minimal
    let vectors_path = dir.path().join("products").join("vectors.bin");
    if vectors_path.exists() {
        let size = std::fs::metadata(&vectors_path).unwrap().len();
        // Should be essentially empty (just header, not 768*4*100 = 307KB)
        assert!(
            size < 1000,
            "Vector storage should be minimal for metadata-only, got {size} bytes"
        );
    }
}

// =============================================================================
// Persistence: reopen metadata-only collection
// =============================================================================

#[test]
fn test_metadata_only_persistence() {
    let dir = tempdir().unwrap();

    // Create and populate
    {
        let db = Database::open(dir.path()).unwrap();
        db.create_collection_typed("products", &CollectionType::MetadataOnly)
            .unwrap();

        let coll = db.get_collection("products").unwrap();
        coll.upsert_metadata(vec![
            Point::metadata_only(1, json!({"name": "Product 1"})),
            Point::metadata_only(2, json!({"name": "Product 2"})),
        ])
        .unwrap();
        coll.flush().unwrap();
    }

    // Reopen and verify
    {
        let db = Database::open(dir.path()).unwrap();
        // Load existing collections from disk
        db.load_collections().unwrap();

        let coll = db.get_collection("products").unwrap();
        assert!(coll.is_metadata_only());
        assert_eq!(coll.len(), 2);

        let results = coll.get(&[1, 2]);
        assert!(results[0].is_some());
        assert!(results[1].is_some());
    }
}

// =============================================================================
// AC9: execute_query on metadata collections via Database::execute_query
// =============================================================================

#[test]
fn test_execute_query_on_metadata_collection() {
    use crate::velesql::Parser;

    let dir = tempdir().unwrap();
    let db = Database::open(dir.path()).unwrap();

    db.create_metadata_collection("meta_items").unwrap();
    let coll = db.get_metadata_collection("meta_items").unwrap();

    // Insert a few items
    let points: Vec<Point> = (1u64..=5)
        .map(|i| Point::metadata_only(i, json!({"name": format!("item_{}", i)})))
        .collect();
    coll.upsert(points).unwrap();
    drop(coll);

    // Execute VelesQL SELECT via Database::execute_query
    let query_str = "SELECT * FROM meta_items LIMIT 5";
    let parsed = Parser::parse(query_str).unwrap();
    let results = db
        .execute_query(&parsed, &std::collections::HashMap::new())
        .unwrap();

    assert_eq!(results.len(), 5, "execute_query should return all 5 items");
}