vantadb 0.1.4

VantaDB: An embedded persistent memory and vector retrieval engine for local-first AI applications.
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
use crate::error::Result;
use crate::node::UnifiedNode;
use crate::query::PhysicalOperator;
use crate::storage::StorageEngine;

// ─── Physical Scan Operator ──────────────────────────────────

pub struct PhysicalScan<'a> {
    storage: &'a StorageEngine,
    entity: String,
    records: Vec<(Vec<u8>, Vec<u8>)>,
    cursor: usize,
}

impl<'a> PhysicalScan<'a> {
    pub fn new(storage: &'a StorageEngine, entity: String) -> Self {
        Self {
            storage,
            entity,
            records: Vec::new(),
            cursor: 0,
        }
    }
}

impl PhysicalOperator for PhysicalScan<'_> {
    fn open(&mut self) -> Result<()> {
        let parts: Vec<&str> = self.entity.split('#').collect();
        if parts.len() == 2 {
            if let Ok(id) = parts[1].parse::<u64>() {
                self.records.clear();
                let key = id.to_le_bytes();
                if let Some(val) = self
                    .storage
                    .backend
                    .get(crate::backend::BackendPartition::Default, &key)?
                {
                    self.records.push((key.to_vec(), val));
                }
                self.cursor = 0;
                return Ok(());
            }
        }

        self.records = self
            .storage
            .backend
            .scan(crate::backend::BackendPartition::Default)?;
        self.cursor = 0;
        Ok(())
    }

    fn next(&mut self) -> Result<Option<UnifiedNode>> {
        while self.cursor < self.records.len() {
            let (key_bytes, _val_bytes) = &self.records[self.cursor];
            self.cursor += 1;

            let id = u64::from_le_bytes(key_bytes.as_slice().try_into().map_err(|_| {
                crate::error::VantaError::SerializationError(
                    "Invalid node ID key bytes".to_string(),
                )
            })?);

            if self.storage.is_deleted(id)? {
                continue;
            }

            if let Some(node) = self.storage.get(id)? {
                // Si la entidad tiene una almohadilla, se valida el ID específico que ya filtramos en open,
                // por lo tanto, devolvemos el nodo directamente.
                if self.entity.contains('#') || self.entity == "*" {
                    return Ok(Some(node));
                }
                if let Some(crate::node::FieldValue::String(t)) = node.relational.get("type") {
                    if t == &self.entity {
                        return Ok(Some(node));
                    }
                }
            }
        }
        Ok(None)
    }

    fn close(&mut self) -> Result<()> {
        self.records.clear();
        Ok(())
    }
}

// ─── Physical Filter Operator ────────────────────────────────

pub struct PhysicalFilter<'a> {
    child: Box<dyn PhysicalOperator + 'a>,
    field: String,
    op: crate::query::RelOp,
    value: crate::node::FieldValue,
}

impl<'a> PhysicalFilter<'a> {
    pub fn new(
        child: Box<dyn PhysicalOperator + 'a>,
        field: String,
        op: crate::query::RelOp,
        value: crate::node::FieldValue,
    ) -> Self {
        Self {
            child,
            field,
            op,
            value,
        }
    }
}

impl PhysicalOperator for PhysicalFilter<'_> {
    fn open(&mut self) -> Result<()> {
        self.child.open()
    }

    fn next(&mut self) -> Result<Option<UnifiedNode>> {
        while let Some(node) = self.child.next()? {
            if evaluate_condition(&node, &self.field, &self.op, &self.value) {
                return Ok(Some(node));
            }
        }
        Ok(None)
    }

    fn close(&mut self) -> Result<()> {
        self.child.close()
    }
}

fn evaluate_condition(
    node: &UnifiedNode,
    field: &str,
    op: &crate::query::RelOp,
    expected: &crate::node::FieldValue,
) -> bool {
    if let Some(actual) = node.relational.get(field) {
        match (actual, expected) {
            (crate::node::FieldValue::String(a), crate::node::FieldValue::String(e)) => match op {
                crate::query::RelOp::Eq => a == e,
                crate::query::RelOp::Neq => a != e,
                crate::query::RelOp::Gt => a > e,
                crate::query::RelOp::Gte => a >= e,
                crate::query::RelOp::Lt => a < e,
                crate::query::RelOp::Lte => a <= e,
            },
            (crate::node::FieldValue::Int(a), crate::node::FieldValue::Int(e)) => match op {
                crate::query::RelOp::Eq => a == e,
                crate::query::RelOp::Neq => a != e,
                crate::query::RelOp::Gt => a > e,
                crate::query::RelOp::Gte => a >= e,
                crate::query::RelOp::Lt => a < e,
                crate::query::RelOp::Lte => a <= e,
            },
            (crate::node::FieldValue::Float(a), crate::node::FieldValue::Float(e)) => match op {
                crate::query::RelOp::Eq => a == e,
                crate::query::RelOp::Neq => a != e,
                crate::query::RelOp::Gt => a > e,
                crate::query::RelOp::Gte => a >= e,
                crate::query::RelOp::Lt => a < e,
                crate::query::RelOp::Lte => a <= e,
            },
            (crate::node::FieldValue::Bool(a), crate::node::FieldValue::Bool(e)) => match op {
                crate::query::RelOp::Eq => a == e,
                crate::query::RelOp::Neq => a != e,
                _ => false,
            },
            (crate::node::FieldValue::Null, crate::node::FieldValue::Null) => match op {
                crate::query::RelOp::Eq => true,
                crate::query::RelOp::Neq => false,
                _ => false,
            },
            _ => false,
        }
    } else {
        matches!(op, crate::query::RelOp::Neq)
    }
}

// ─── Physical Vector Search Operator ─────────────────────────

pub struct PhysicalVectorSearch<'a> {
    storage: &'a StorageEngine,
    #[allow(dead_code)]
    query_vec_text: String,
    min_score: f32,
    results: Vec<u64>,
    cursor: usize,
}

impl<'a> PhysicalVectorSearch<'a> {
    pub fn new(storage: &'a StorageEngine, query_text: String, min_score: f32) -> Self {
        Self {
            storage,
            query_vec_text: query_text,
            min_score,
            results: Vec::new(),
            cursor: 0,
        }
    }
}

impl PhysicalOperator for PhysicalVectorSearch<'_> {
    fn open(&mut self) -> Result<()> {
        self.results.clear();
        self.cursor = 0;

        #[allow(unused_mut)]
        let mut vector: Option<Vec<f32>> = None;

        #[cfg(feature = "remote-inference")]
        {
            let llm = crate::llm::LlmClient::new();
            if let Ok(vec) = llm.generate_embedding(&self.query_vec_text) {
                vector = Some(vec);
            }
        }

        if let Some(vec) = vector {
            let neighbors = {
                let index = self.storage.hnsw.load();
                let vs = self.storage.vector_store.read();
                index.search_nearest(&vec, None, None, 0, 5, Some(&vs))
            };
            for (id, score) in neighbors {
                if score >= self.min_score {
                    self.results.push(id);
                }
            }
        }

        Ok(())
    }

    fn next(&mut self) -> Result<Option<UnifiedNode>> {
        while self.cursor < self.results.len() {
            let id = self.results[self.cursor];
            self.cursor += 1;

            if self.storage.is_deleted(id)? {
                continue;
            }

            if let Some(node) = self.storage.get(id)? {
                return Ok(Some(node));
            }
        }
        Ok(None)
    }

    fn close(&mut self) -> Result<()> {
        self.results.clear();
        Ok(())
    }
}

// ─── Physical Project Operator ───────────────────────────────

pub struct PhysicalProject<'a> {
    child: Box<dyn PhysicalOperator + 'a>,
    fields: Vec<String>,
}

impl<'a> PhysicalProject<'a> {
    pub fn new(child: Box<dyn PhysicalOperator + 'a>, fields: Vec<String>) -> Self {
        Self { child, fields }
    }
}

impl PhysicalOperator for PhysicalProject<'_> {
    fn open(&mut self) -> Result<()> {
        self.child.open()
    }

    fn next(&mut self) -> Result<Option<UnifiedNode>> {
        if let Some(mut node) = self.child.next()? {
            let mut projected = std::collections::BTreeMap::new();
            for field in &self.fields {
                if let Some(val) = node.relational.remove(field) {
                    projected.insert(field.clone(), val);
                }
            }
            node.relational = projected;
            return Ok(Some(node));
        }
        Ok(None)
    }

    fn close(&mut self) -> Result<()> {
        self.child.close()
    }
}

// ─── Physical Limit Operator ─────────────────────────────────

pub struct PhysicalLimit<'a> {
    child: Box<dyn PhysicalOperator + 'a>,
    limit: usize,
    count: usize,
}

impl<'a> PhysicalLimit<'a> {
    pub fn new(child: Box<dyn PhysicalOperator + 'a>, limit: usize) -> Self {
        Self {
            child,
            limit,
            count: 0,
        }
    }
}

impl PhysicalOperator for PhysicalLimit<'_> {
    fn open(&mut self) -> Result<()> {
        self.child.open()?;
        self.count = 0;
        Ok(())
    }

    fn next(&mut self) -> Result<Option<UnifiedNode>> {
        if self.count >= self.limit {
            return Ok(None);
        }
        if let Some(node) = self.child.next()? {
            self.count += 1;
            return Ok(Some(node));
        }
        Ok(None)
    }

    fn close(&mut self) -> Result<()> {
        self.child.close()
    }
}

// ─── Physical Sort Operator ──────────────────────────────────

pub struct PhysicalSort<'a> {
    child: Box<dyn PhysicalOperator + 'a>,
    field: String,
    desc: bool,
    nodes: Vec<UnifiedNode>,
    cursor: usize,
}

impl<'a> PhysicalSort<'a> {
    pub fn new(child: Box<dyn PhysicalOperator + 'a>, field: String, desc: bool) -> Self {
        Self {
            child,
            field,
            desc,
            nodes: Vec::new(),
            cursor: 0,
        }
    }
}

impl PhysicalOperator for PhysicalSort<'_> {
    fn open(&mut self) -> Result<()> {
        self.child.open()?;
        self.nodes.clear();
        self.cursor = 0;

        while let Some(node) = self.child.next()? {
            self.nodes.push(node);
        }

        let field = &self.field;
        let desc = self.desc;
        self.nodes.sort_by(|a, b| {
            let a_val = a.relational.get(field);
            let b_val = b.relational.get(field);
            let cmp = match (a_val, b_val) {
                (
                    Some(crate::node::FieldValue::String(av)),
                    Some(crate::node::FieldValue::String(bv)),
                ) => av.cmp(bv),
                (
                    Some(crate::node::FieldValue::Int(av)),
                    Some(crate::node::FieldValue::Int(bv)),
                ) => av.cmp(bv),
                (
                    Some(crate::node::FieldValue::Float(av)),
                    Some(crate::node::FieldValue::Float(bv)),
                ) => av.partial_cmp(bv).unwrap_or(std::cmp::Ordering::Equal),
                (
                    Some(crate::node::FieldValue::Bool(av)),
                    Some(crate::node::FieldValue::Bool(bv)),
                ) => av.cmp(bv),
                (None, Some(_)) => std::cmp::Ordering::Less,
                (Some(_), None) => std::cmp::Ordering::Greater,
                (None, None) => std::cmp::Ordering::Equal,
                _ => std::cmp::Ordering::Equal,
            };
            if desc {
                cmp.reverse()
            } else {
                cmp
            }
        });

        Ok(())
    }

    fn next(&mut self) -> Result<Option<UnifiedNode>> {
        if self.cursor < self.nodes.len() {
            let node = self.nodes[self.cursor].clone();
            self.cursor += 1;
            return Ok(Some(node));
        }
        Ok(None)
    }

    fn close(&mut self) -> Result<()> {
        self.nodes.clear();
        self.child.close()
    }
}

// ─── Physical Vector Refine Operator (Brute Force Sim Check) ───

pub struct PhysicalVectorRefine<'a> {
    child: Box<dyn PhysicalOperator + 'a>,
    #[allow(dead_code)]
    query_vec_text: String,
    min_score: f32,
    query_vector: Option<crate::node::VectorRepresentations>,
}

impl<'a> PhysicalVectorRefine<'a> {
    pub fn new(child: Box<dyn PhysicalOperator + 'a>, query_text: String, min_score: f32) -> Self {
        Self {
            child,
            query_vec_text: query_text,
            min_score,
            query_vector: None,
        }
    }
}

impl PhysicalOperator for PhysicalVectorRefine<'_> {
    fn open(&mut self) -> Result<()> {
        self.child.open()?;
        self.query_vector = None;

        #[cfg(feature = "remote-inference")]
        {
            let llm = crate::llm::LlmClient::new();
            if let Ok(vec) = llm.generate_embedding(&self.query_vec_text) {
                self.query_vector = Some(crate::node::VectorRepresentations::Full(vec));
            }
        }
        Ok(())
    }

    fn next(&mut self) -> Result<Option<UnifiedNode>> {
        let q_vec = match &self.query_vector {
            Some(v) => v,
            None => return self.child.next(),
        };

        while let Some(node) = self.child.next()? {
            if let Some(sim) = node.vector.cosine_similarity(q_vec) {
                if sim >= self.min_score {
                    return Ok(Some(node));
                }
            }
        }
        Ok(None)
    }

    fn close(&mut self) -> Result<()> {
        self.query_vector = None;
        self.child.close()
    }
}