iridium-db 0.4.0

A high-performance vector-graph hybrid storage and indexing engine
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
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
use std::path::{Path, PathBuf};
use std::sync::Mutex;

use crate::features::query;
use crate::features::runtime;
use crate::features::storage::api as storage_api;

use super::{DriverConfig, DriverError, MutationOptions, Result, RowCursor};

pub struct RustDriver {
    config: DriverConfig,
    injected_store: Option<std::sync::Arc<dyn alloy_storage::BlobStore>>,
    state: Mutex<DriverState>,
}

pub(super) struct DriverState {
    pub(super) handle: Option<storage_api::StorageHandle>,
    pub(super) ingest_session_active: bool,
    pub(super) seen_mutations: std::collections::HashSet<String>,
    pub(super) seen_mutation_order: std::collections::VecDeque<String>,
}

pub fn embedded_driver(config: DriverConfig) -> Result<RustDriver> {
    RustDriver::new(config)
}

pub fn embedded_driver_with_store(
    config: DriverConfig,
    store: std::sync::Arc<dyn alloy_storage::BlobStore>,
) -> Result<RustDriver> {
    RustDriver::new_with_store(config, store)
}

impl RustDriver {
    pub fn new(config: DriverConfig) -> Result<Self> {
        if config.execute_params.morsel_size == 0 {
            return Err(DriverError::InvalidConfig(
                "execute_params.morsel_size must be > 0".to_string(),
            ));
        }
        if config.execute_params.scan_end_exclusive <= config.execute_params.scan_start {
            return Err(DriverError::InvalidConfig(
                "execute_params.scan_end_exclusive must be > scan_start".to_string(),
            ));
        }
        if config.idempotency_cache_capacity == 0 {
            return Err(DriverError::InvalidConfig(
                "idempotency_cache_capacity must be > 0".to_string(),
            ));
        }
        Ok(Self {
            config,
            injected_store: None,
            state: Mutex::new(DriverState {
                handle: None,
                ingest_session_active: false,
                seen_mutations: std::collections::HashSet::new(),
                seen_mutation_order: std::collections::VecDeque::new(),
            }),
        })
    }

    pub fn new_with_store(
        config: DriverConfig,
        store: std::sync::Arc<dyn alloy_storage::BlobStore>,
    ) -> Result<Self> {
        if config.execute_params.morsel_size == 0 {
            return Err(DriverError::InvalidConfig(
                "execute_params.morsel_size must be > 0".to_string(),
            ));
        }
        if config.execute_params.scan_end_exclusive <= config.execute_params.scan_start {
            return Err(DriverError::InvalidConfig(
                "execute_params.scan_end_exclusive must be > scan_start".to_string(),
            ));
        }
        if config.idempotency_cache_capacity == 0 {
            return Err(DriverError::InvalidConfig(
                "idempotency_cache_capacity must be > 0".to_string(),
            ));
        }
        Ok(Self {
            config,
            injected_store: Some(store),
            state: Mutex::new(DriverState {
                handle: None,
                ingest_session_active: false,
                seen_mutations: std::collections::HashSet::new(),
                seen_mutation_order: std::collections::VecDeque::new(),
            }),
        })
    }

    pub fn query(&self, query_text: &str) -> Result<runtime::RowStream> {
        if self.config.execution_mode != runtime::ExecutionMode::Native {
            return Err(DriverError::InvalidConfig(
                "query text execution is only available in native mode; use query_serialized_plan in plexus mode"
                    .to_string(),
            ));
        }
        let ast = query::parse(query_text)?;
        let typed = query::validate(&ast, &query::Catalog)?;
        let plan = runtime::explain(&typed)?;
        self.with_store_handle(|handle| {
            Ok(runtime::execute(
                &plan,
                &self.config.execute_params,
                handle,
            )?)
        })
    }

    pub fn query_serialized_plan(&self, serialized_plan: &[u8]) -> Result<runtime::RowStream> {
        if self.config.execution_mode != runtime::ExecutionMode::Plexus {
            return Err(DriverError::InvalidConfig(
                "serialized plan execution requires plexus mode".to_string(),
            ));
        }
        self.with_store_handle(|handle| {
            Ok(runtime::execute_serialized_plan(
                serialized_plan,
                &self.config.execute_params,
                handle,
            )?)
        })
    }

    #[cfg(feature = "rhodium-backend")]
    pub fn describe_compiled_plan_cache(
        &self,
        serialized_plan: &[u8],
    ) -> Result<rhodium_cache::core::storage::blob::CompiledPlanCacheDescriptor> {
        Ok(runtime::describe_compiled_plan_cache(
            serialized_plan,
            None,
        )?)
    }

    #[cfg(feature = "rhodium-backend")]
    pub fn get_compiled_plan_with_options(
        &self,
        descriptor: &rhodium_cache::core::storage::blob::CompiledPlanCacheDescriptor,
        options: storage_api::BlobReadOptions,
    ) -> Result<Option<storage_api::BlobGetResult>> {
        self.with_store_handle(|handle| {
            Ok(storage_api::get_compiled_plan_with_options(
                handle, descriptor, options,
            )?)
        })
    }

    pub fn query_stream(&self, query_text: &str) -> Result<RowCursor> {
        let rows = self.query(query_text)?;
        Ok(RowCursor {
            rows: rows.rows,
            index: 0,
        })
    }

    pub fn explain(&self, query_text: &str) -> Result<runtime::ExplainPlan> {
        if self.config.execution_mode != runtime::ExecutionMode::Native {
            return Err(DriverError::InvalidConfig(
                "explain(query_text) is only available in native mode".to_string(),
            ));
        }
        let ast = query::parse(query_text)?;
        let typed = query::validate(&ast, &query::Catalog)?;
        Ok(runtime::explain(&typed)?)
    }

    pub fn ingest_node(&self, node_id: u64, version: u64, adjacency: &[u64]) -> Result<()> {
        self.ingest_node_with_options(node_id, version, adjacency, &MutationOptions::default())
    }

    pub fn ingest_node_with_options(
        &self,
        node_id: u64,
        version: u64,
        adjacency: &[u64],
        options: &MutationOptions,
    ) -> Result<()> {
        self.with_ingest_handle(options, |handle| {
            storage_api::put_full_node(handle, node_id, version, adjacency)
        })
    }

    pub fn ingest_edge(&self, node_id: u64, version: u64, payload: &[u8]) -> Result<()> {
        self.ingest_edge_with_options(node_id, version, payload, &MutationOptions::default())
    }

    pub fn ingest_edge_with_options(
        &self,
        node_id: u64,
        version: u64,
        payload: &[u8],
        options: &MutationOptions,
    ) -> Result<()> {
        self.with_ingest_handle(options, |handle| {
            let delta = storage_api::encode_delta(node_id, version, payload);
            storage_api::put_edge_delta(handle, &delta)
        })
    }

    pub fn ingest_vector(&self, node_id: u64, version: u64, values: &[f32]) -> Result<()> {
        self.ingest_vector_with_options(node_id, version, values, &MutationOptions::default())
    }

    pub fn ingest_vector_with_options(
        &self,
        node_id: u64,
        version: u64,
        values: &[f32],
        options: &MutationOptions,
    ) -> Result<()> {
        self.with_ingest_handle(options, |handle| {
            let payload = storage_api::encode_vector_payload_f32(
                1,
                storage_api::VectorMetric::Cosine,
                values,
                false,
            );
            let delta = storage_api::encode_delta(node_id, version, &payload);
            storage_api::put_vector_delta(handle, &delta)
        })
    }

    pub fn ingest_nodes_batch(&self, nodes: &[(u64, u64, Vec<u64>)]) -> Result<()> {
        self.ingest_nodes_batch_with_options(nodes, &MutationOptions::default())
    }

    pub fn ingest_nodes_batch_with_options(
        &self,
        nodes: &[(u64, u64, Vec<u64>)],
        options: &MutationOptions,
    ) -> Result<()> {
        self.with_ingest_handle(options, |handle| {
            for (node_id, version, adjacency) in nodes {
                storage_api::put_full_node(handle, *node_id, *version, adjacency)?;
            }
            Ok(())
        })
    }

    pub fn ingest_edges_batch(&self, edges: &[(u64, u64, Vec<u8>)]) -> Result<()> {
        self.ingest_edges_batch_with_options(edges, &MutationOptions::default())
    }

    pub fn ingest_edges_batch_with_options(
        &self,
        edges: &[(u64, u64, Vec<u8>)],
        options: &MutationOptions,
    ) -> Result<()> {
        self.with_ingest_handle(options, |handle| {
            let mut deltas = Vec::with_capacity(edges.len());
            for (node_id, version, payload) in edges {
                deltas.push(storage_api::encode_delta(*node_id, *version, payload));
            }
            storage_api::put_edge_deltas_batch(handle, &deltas)
        })
    }

    pub fn create_bitmap_index(&self, index_name: &str, field_path: &str) -> Result<()> {
        self.create_bitmap_index_with_options(index_name, field_path, &MutationOptions::default())
    }

    pub fn create_bitmap_index_with_options(
        &self,
        index_name: &str,
        field_path: &str,
        options: &MutationOptions,
    ) -> Result<()> {
        self.with_ingest_handle(options, |handle| {
            storage_api::create_bitmap_index(handle, index_name, field_path)
        })
    }

    pub fn list_bitmap_indexes(&self) -> Result<Vec<(String, String)>> {
        self.with_store_handle(|handle| {
            Ok(storage_api::list_bitmap_indexes(handle)
                .into_iter()
                .map(|desc| (desc.index_name, desc.field_path))
                .collect())
        })
    }

    pub fn bitmap_add_posting(
        &self,
        index_name: &str,
        value_key: &str,
        node_id: u64,
    ) -> Result<()> {
        self.bitmap_add_posting_with_options(
            index_name,
            value_key,
            node_id,
            &MutationOptions::default(),
        )
    }

    pub fn bitmap_add_posting_with_options(
        &self,
        index_name: &str,
        value_key: &str,
        node_id: u64,
        options: &MutationOptions,
    ) -> Result<()> {
        self.with_ingest_handle(options, |handle| {
            storage_api::bitmap_add_posting(handle, index_name, value_key, node_id)
        })
    }

    pub fn begin_ingest(&self) -> Result<()> {
        let mut guard = self.state_guard()?;
        let _ = self.ensure_handle(&mut guard)?;
        guard.ingest_session_active = true;
        Ok(())
    }

    pub fn finish_ingest(&self) -> Result<()> {
        let mut guard = self.state_guard()?;
        if let Some(handle) = guard.handle.as_mut() {
            storage_api::flush(handle)?;
        }
        guard.ingest_session_active = false;
        Ok(())
    }

    pub fn put_blob(&self, blob_id: &str, bytes: &[u8]) -> Result<()> {
        self.with_store_handle(|handle| {
            storage_api::put_blob(handle, blob_id, bytes)?;
            Ok(())
        })
    }

    pub fn put_blob_with_options(
        &self,
        blob_id: &str,
        bytes: &[u8],
        options: storage_api::BlobPutOptions,
    ) -> Result<storage_api::BlobPutResult> {
        self.with_store_handle(|handle| {
            Ok(storage_api::put_blob_with_options(
                handle, blob_id, bytes, options,
            )?)
        })
    }

    pub fn get_blob(&self, blob_id: &str) -> Result<Option<Vec<u8>>> {
        self.with_store_handle(|handle| Ok(storage_api::get_blob(handle, blob_id)?))
    }

    pub fn get_blob_with_options(
        &self,
        blob_id: &str,
        options: storage_api::BlobReadOptions,
    ) -> Result<Option<storage_api::BlobGetResult>> {
        self.with_store_handle(|handle| {
            Ok(storage_api::get_blob_with_options(
                handle, blob_id, options,
            )?)
        })
    }

    pub fn has_blob(&self, blob_id: &str) -> Result<bool> {
        self.with_store_handle(|handle| Ok(storage_api::has_blob(handle, blob_id)?))
    }

    pub fn delete_blob(&self, blob_id: &str) -> Result<()> {
        self.with_store_handle(|handle| {
            storage_api::delete_blob(handle, blob_id)?;
            Ok(())
        })
    }

    pub fn has_blobs(&self, blob_ids: &[String]) -> Result<Vec<bool>> {
        self.with_store_handle(|handle| Ok(storage_api::has_blobs(handle, blob_ids)?))
    }

    pub fn delete_blobs(&self, blob_ids: &[String]) -> Result<usize> {
        self.with_store_handle(|handle| Ok(storage_api::delete_blobs(handle, blob_ids)?))
    }

    pub fn list_blob_prefix(
        &self,
        namespace: &str,
        prefix: &str,
        limit: usize,
    ) -> Result<Vec<String>> {
        self.with_store_handle(|handle| {
            Ok(storage_api::list_blob_prefix(
                handle, namespace, prefix, limit,
            )?)
        })
    }

    pub fn delete_blob_prefix(
        &self,
        namespace: &str,
        prefix: &str,
        batch_limit: usize,
    ) -> Result<storage_api::BlobPrefixDeleteResult> {
        self.with_store_handle(|handle| {
            Ok(storage_api::delete_blob_prefix(
                handle,
                namespace,
                prefix,
                batch_limit,
            )?)
        })
    }

    fn with_ingest_handle<F>(&self, options: &MutationOptions, op: F) -> Result<()>
    where
        F: FnOnce(&mut storage_api::StorageHandle) -> storage_api::Result<()>,
    {
        let mut guard = self.state_guard()?;
        let idempotency_key = validated_idempotency_key(options)?;
        let ingest_session_active = guard.ingest_session_active;
        let _ = self.ensure_handle(&mut guard)?;
        if let Some(key) = idempotency_key.as_deref() {
            if guard.seen_mutations.contains(key) {
                return Ok(());
            }
        }
        let handle = self.ensure_handle(&mut guard)?;
        op(handle)?;
        if !ingest_session_active {
            storage_api::flush(handle)?;
        }
        if let Some(key) = idempotency_key {
            remember_mutation_key(&mut guard, &self.config, key);
        }
        Ok(())
    }

    fn with_store_handle<F, T>(&self, op: F) -> Result<T>
    where
        F: FnOnce(&mut storage_api::StorageHandle) -> Result<T>,
    {
        let mut guard = self.state_guard()?;
        let handle = self.ensure_handle(&mut guard)?;
        op(handle)
    }

    pub(super) fn state_guard(&self) -> Result<std::sync::MutexGuard<'_, DriverState>> {
        self.state
            .lock()
            .map_err(|_| DriverError::Internal("driver state mutex poisoned".to_string()))
    }

    pub(super) fn ensure_handle<'a>(
        &self,
        state: &'a mut DriverState,
    ) -> Result<&'a mut storage_api::StorageHandle> {
        if state.handle.is_none() {
            let mut handle = if let Some(store) = self.injected_store.clone() {
                open_store_in_data_dir_with_store(&self.config.data_dir, store)?
            } else {
                open_store_in_data_dir(&self.config.data_dir, self.config.blob_backend)?
            };
            storage_api::recover_from_wal(&mut handle)?;
            if self.config.persist_idempotency_keys {
                load_idempotency_cache_from_disk(state, &self.config)?;
            }
            state.handle = Some(handle);
        }
        state
            .handle
            .as_mut()
            .ok_or_else(|| DriverError::Internal("store handle unavailable".to_string()))
    }
}

fn open_store_in_data_dir_with_store(
    data_dir: &Path,
    store: std::sync::Arc<dyn alloy_storage::BlobStore>,
) -> storage_api::Result<storage_api::StorageHandle> {
    let wal_dir = data_dir.join("wal");
    let manifest_path = data_dir.join("ir.manifest");
    let sstable_dir = data_dir.join("sst");
    storage_api::open_store_with_injected_blob_store(
        storage_api::StorageConfig {
            buffer_pool_pages: 1024,
            wal_dir,
            wal_segment_max_bytes: 1 << 20,
            manifest_path,
            sstable_dir,
        },
        store,
    )
}

fn open_store_in_data_dir(
    data_dir: &Path,
    blob_backend: storage_api::BlobBackend,
) -> storage_api::Result<storage_api::StorageHandle> {
    let wal_dir = data_dir.join("wal");
    let manifest_path = data_dir.join("ir.manifest");
    let sstable_dir = data_dir.join("sst");
    storage_api::open_store_with_blob_backend(
        storage_api::StorageConfig {
            buffer_pool_pages: 1024,
            wal_dir,
            wal_segment_max_bytes: 1 << 20,
            manifest_path,
            sstable_dir,
        },
        blob_backend,
    )
}

fn validated_idempotency_key(options: &MutationOptions) -> Result<Option<String>> {
    let Some(raw) = &options.idempotency_key else {
        return Ok(None);
    };
    let trimmed = raw.trim();
    if trimmed.is_empty() {
        return Err(DriverError::InvalidConfig(
            "idempotency_key must not be empty when provided".to_string(),
        ));
    }
    Ok(Some(trimmed.to_string()))
}

fn remember_mutation_key(state: &mut DriverState, config: &DriverConfig, key: String) {
    remember_mutation_key_in_memory(state, config, key.clone());
    if config.persist_idempotency_keys {
        let _ = append_idempotency_key_to_disk(config, &key);
    }
}

fn remember_mutation_key_in_memory(state: &mut DriverState, config: &DriverConfig, key: String) {
    if !state.seen_mutations.insert(key.clone()) {
        return;
    }
    state.seen_mutation_order.push_back(key);
    while state.seen_mutations.len() > config.idempotency_cache_capacity {
        if let Some(evicted) = state.seen_mutation_order.pop_front() {
            state.seen_mutations.remove(&evicted);
        }
    }
}

fn idempotency_store_path(config: &DriverConfig) -> PathBuf {
    config.data_dir.join("idempotency.keys")
}

fn append_idempotency_key_to_disk(config: &DriverConfig, key: &str) -> std::io::Result<()> {
    let path = idempotency_store_path(config);
    if let Some(parent) = path.parent() {
        std::fs::create_dir_all(parent)?;
    }
    use std::io::Write;
    let mut file = std::fs::OpenOptions::new()
        .create(true)
        .append(true)
        .open(path)?;
    writeln!(file, "{}", key)?;
    file.flush()?;
    Ok(())
}

fn load_idempotency_cache_from_disk(state: &mut DriverState, config: &DriverConfig) -> Result<()> {
    let path = idempotency_store_path(config);
    let text = match std::fs::read_to_string(path) {
        Ok(text) => text,
        Err(err) if err.kind() == std::io::ErrorKind::NotFound => return Ok(()),
        Err(err) => {
            return Err(DriverError::Internal(format!(
                "idempotency load failed: {}",
                err
            )))
        }
    };
    for line in text.lines() {
        let key = line.trim();
        if key.is_empty() {
            continue;
        }
        remember_mutation_key_in_memory(state, config, key.to_string());
    }
    Ok(())
}