selene-db-graph 1.2.0

In-memory property-graph storage core (ArcSwap + imbl CoW, label/typed indexes, write funnel) for selene-db.
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
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
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
//! Exact JSON search over graph node properties.
//!
//! This module is the JSON correctness oracle and small-corpus path. It scans
//! the current graph snapshot for JSON-valued node properties and returns node
//! candidates whose stored JSON matches the requested exact predicate.

use std::collections::BinaryHeap;
use std::time::Duration;

use selene_core::{
    CancellationCause, CancellationChecker, DbString, JsonPathSelector, JsonValue, JsonValueRef,
    NodeId, Value,
};

use crate::error::{GraphError, GraphResult};
use crate::graph::SeleneGraph;
use crate::shared::SharedGraph;
use crate::store::RowIndex;

#[path = "json_search/parallel.rs"]
mod parallel;

pub(crate) const JSON_SEARCH_CANCEL_STRIDE: usize = 1024;
pub(crate) const JSON_SEARCH_PARALLEL_CHUNK_ROWS: usize = 2048;
#[cfg(not(test))]
pub(crate) const JSON_SEARCH_PARALLEL_MIN_ROWS: u64 = 16_384;
#[cfg(test)]
pub(crate) const JSON_SEARCH_PARALLEL_MIN_ROWS: u64 = 8;
/// Maximum selector count accepted by GQL JSON path search procedures.
pub const JSON_PATH_SELECTOR_LIMIT: usize = 64;

/// One JSON-containment node hit.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct JsonContainmentHit {
    /// Matched node id.
    pub node_id: NodeId,
}

/// One JSON path-existence node hit.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct JsonPathHit {
    /// Matched node id.
    pub node_id: NodeId,
}

/// One JSON path-containment node hit.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct JsonPathContainmentHit {
    /// Matched node id.
    pub node_id: NodeId,
}

/// One JSON path-value node hit.
#[derive(Clone, Debug, PartialEq)]
pub struct JsonPathValueHit {
    /// Matched node id.
    pub node_id: NodeId,
    /// JSON value selected by the requested path.
    pub value: JsonValue,
}

/// Error returned by checked JSON search APIs.
#[derive(Debug, thiserror::Error)]
pub enum JsonSearchError {
    /// Graph storage or consistency failure.
    #[error(transparent)]
    Graph(#[from] GraphError),
    /// Caller requested cooperative cancellation.
    #[error("JSON search cancelled")]
    Cancelled,
    /// Statement deadline elapsed.
    #[error("JSON search timed out after {elapsed:?}")]
    Timeout {
        /// Wall-clock duration since the deadline elapsed.
        elapsed: Duration,
    },
}

impl JsonSearchError {
    pub(crate) fn into_graph_error(self) -> GraphError {
        match self {
            Self::Graph(error) => error,
            Self::Cancelled | Self::Timeout { .. } => GraphError::Inconsistent {
                reason: format!("disabled JSON-search checker returned {self}"),
            },
        }
    }
}

impl From<CancellationCause> for JsonSearchError {
    fn from(cause: CancellationCause) -> Self {
        match cause {
            CancellationCause::Cancelled => Self::Cancelled,
            CancellationCause::Timeout { elapsed } => Self::Timeout { elapsed },
        }
    }
}

impl SeleneGraph {
    /// Exhaustively find JSON-valued node properties containing `candidate`.
    pub fn exact_json_contains_nodes(
        &self,
        label: &DbString,
        property: &DbString,
        candidate: &JsonValue,
        k: usize,
    ) -> GraphResult<Vec<JsonContainmentHit>> {
        self.exact_json_contains_nodes_checked(
            label,
            property,
            candidate,
            k,
            CancellationChecker::disabled(),
        )
        .map_err(JsonSearchError::into_graph_error)
    }

    /// Exhaustively find JSON-valued node properties with cancellation checks.
    pub fn exact_json_contains_nodes_checked(
        &self,
        label: &DbString,
        property: &DbString,
        candidate: &JsonValue,
        k: usize,
        checker: CancellationChecker<'_>,
    ) -> Result<Vec<JsonContainmentHit>, JsonSearchError> {
        checker.check()?;
        if k == 0 {
            return Ok(Vec::new());
        }
        let Some(label_rows) = self.nodes_with_label(label) else {
            return Ok(Vec::new());
        };
        if parallel::should_parallelize_json_scan(label_rows, k) {
            let scan = parallel::JsonScan::new(self, label, property);
            return parallel::contains_nodes(scan, candidate, k, label_rows, checker);
        }

        let mut top_k = JsonContainmentTopK::new(k);
        let mut rows_since_check = 0usize;
        for raw_row in label_rows.iter() {
            rows_since_check += 1;
            if rows_since_check >= JSON_SEARCH_CANCEL_STRIDE {
                checker.check()?;
                rows_since_check = 0;
            }
            if !self.node_store.is_alive(raw_row) {
                continue;
            }
            let row = RowIndex::new(raw_row);
            let node_id = self
                .node_id_for_row(row)
                .ok_or_else(|| GraphError::Inconsistent {
                    reason: format!(
                        "label index row {raw_row} for {} has no node id",
                        label.as_str()
                    ),
                })?;
            let properties = self
                .node_store
                .properties
                .get(raw_row as usize)
                .ok_or_else(|| GraphError::Inconsistent {
                    reason: format!(
                        "JSON search row {raw_row} for {} has no property row",
                        label.as_str()
                    ),
                })?;
            let Some(Value::Json(value)) = properties.get(property) else {
                continue;
            };
            if value.contains(candidate) {
                top_k.push(node_id);
            }
        }
        Ok(top_k.into_hits())
    }

    /// Exhaustively find JSON-valued node properties where `path` exists.
    pub fn exact_json_path_exists_nodes(
        &self,
        label: &DbString,
        property: &DbString,
        path: &[JsonPathSelector],
        k: usize,
    ) -> GraphResult<Vec<JsonPathHit>> {
        self.exact_json_path_exists_nodes_checked(
            label,
            property,
            path,
            k,
            CancellationChecker::disabled(),
        )
        .map_err(JsonSearchError::into_graph_error)
    }

    /// Exhaustively find JSON-valued node properties with path-existence checks.
    pub fn exact_json_path_exists_nodes_checked(
        &self,
        label: &DbString,
        property: &DbString,
        path: &[JsonPathSelector],
        k: usize,
        checker: CancellationChecker<'_>,
    ) -> Result<Vec<JsonPathHit>, JsonSearchError> {
        checker.check()?;
        if k == 0 || path.is_empty() {
            return Ok(Vec::new());
        }
        let Some(label_rows) = self.nodes_with_label(label) else {
            return Ok(Vec::new());
        };
        if parallel::should_parallelize_json_scan(label_rows, k) {
            let scan = parallel::JsonScan::new(self, label, property);
            return parallel::path_exists_nodes(scan, path, k, label_rows, checker);
        }

        let mut top_k = JsonContainmentTopK::new(k);
        let mut rows_since_check = 0usize;
        for raw_row in label_rows.iter() {
            rows_since_check += 1;
            if rows_since_check >= JSON_SEARCH_CANCEL_STRIDE {
                checker.check()?;
                rows_since_check = 0;
            }
            if !self.node_store.is_alive(raw_row) {
                continue;
            }
            let row = RowIndex::new(raw_row);
            let node_id = self
                .node_id_for_row(row)
                .ok_or_else(|| GraphError::Inconsistent {
                    reason: format!(
                        "label index row {raw_row} for {} has no node id",
                        label.as_str()
                    ),
                })?;
            let properties = self
                .node_store
                .properties
                .get(raw_row as usize)
                .ok_or_else(|| GraphError::Inconsistent {
                    reason: format!(
                        "JSON search row {raw_row} for {} has no property row",
                        label.as_str()
                    ),
                })?;
            let Some(Value::Json(value)) = properties.get(property) else {
                continue;
            };
            if value.path_exists(path) {
                top_k.push(node_id);
            }
        }
        Ok(top_k.into_path_hits())
    }

    /// Exhaustively find JSON-valued node properties whose selected path
    /// contains `candidate`.
    pub fn exact_json_path_contains_nodes(
        &self,
        label: &DbString,
        property: &DbString,
        path: &[JsonPathSelector],
        candidate: &JsonValue,
        k: usize,
    ) -> GraphResult<Vec<JsonPathContainmentHit>> {
        self.exact_json_path_contains_nodes_checked(
            label,
            property,
            path,
            candidate,
            k,
            CancellationChecker::disabled(),
        )
        .map_err(JsonSearchError::into_graph_error)
    }

    /// Exhaustively find JSON path containment matches with cancellation checks.
    pub fn exact_json_path_contains_nodes_checked(
        &self,
        label: &DbString,
        property: &DbString,
        path: &[JsonPathSelector],
        candidate: &JsonValue,
        k: usize,
        checker: CancellationChecker<'_>,
    ) -> Result<Vec<JsonPathContainmentHit>, JsonSearchError> {
        checker.check()?;
        if k == 0 || path.is_empty() {
            return Ok(Vec::new());
        }
        let Some(label_rows) = self.nodes_with_label(label) else {
            return Ok(Vec::new());
        };
        if parallel::should_parallelize_json_scan(label_rows, k) {
            let scan = parallel::JsonScan::new(self, label, property);
            return parallel::path_contains_nodes(scan, path, candidate, k, label_rows, checker);
        }

        let mut top_k = JsonContainmentTopK::new(k);
        let mut rows_since_check = 0usize;
        for raw_row in label_rows.iter() {
            rows_since_check += 1;
            if rows_since_check >= JSON_SEARCH_CANCEL_STRIDE {
                checker.check()?;
                rows_since_check = 0;
            }
            if !self.node_store.is_alive(raw_row) {
                continue;
            }
            let row = RowIndex::new(raw_row);
            let node_id = self
                .node_id_for_row(row)
                .ok_or_else(|| GraphError::Inconsistent {
                    reason: format!(
                        "label index row {raw_row} for {} has no node id",
                        label.as_str()
                    ),
                })?;
            let properties = self
                .node_store
                .properties
                .get(raw_row as usize)
                .ok_or_else(|| GraphError::Inconsistent {
                    reason: format!(
                        "JSON search row {raw_row} for {} has no property row",
                        label.as_str()
                    ),
                })?;
            let Some(Value::Json(value)) = properties.get(property) else {
                continue;
            };
            if value.path_contains(path, candidate) {
                top_k.push(node_id);
            }
        }
        Ok(top_k.into_path_containment_hits())
    }

    /// Exhaustively find JSON-valued node properties where `path` selects a value.
    pub fn exact_json_path_value_nodes(
        &self,
        label: &DbString,
        property: &DbString,
        path: &[JsonPathSelector],
        k: usize,
    ) -> GraphResult<Vec<JsonPathValueHit>> {
        self.exact_json_path_value_nodes_checked(
            label,
            property,
            path,
            k,
            CancellationChecker::disabled(),
        )
        .map_err(JsonSearchError::into_graph_error)
    }

    /// Exhaustively find JSON path values with cancellation checks.
    pub fn exact_json_path_value_nodes_checked(
        &self,
        label: &DbString,
        property: &DbString,
        path: &[JsonPathSelector],
        k: usize,
        checker: CancellationChecker<'_>,
    ) -> Result<Vec<JsonPathValueHit>, JsonSearchError> {
        checker.check()?;
        if k == 0 || path.is_empty() {
            return Ok(Vec::new());
        }
        let Some(label_rows) = self.nodes_with_label(label) else {
            return Ok(Vec::new());
        };
        if parallel::should_parallelize_json_scan(label_rows, k) {
            let scan = parallel::JsonScan::new(self, label, property);
            return parallel::path_value_nodes(scan, path, k, label_rows, checker);
        }

        let mut top_k = JsonPathValueTopK::new(k);
        let mut rows_since_check = 0usize;
        for raw_row in label_rows.iter() {
            rows_since_check += 1;
            if rows_since_check >= JSON_SEARCH_CANCEL_STRIDE {
                checker.check()?;
                rows_since_check = 0;
            }
            if !self.node_store.is_alive(raw_row) {
                continue;
            }
            let row = RowIndex::new(raw_row);
            let node_id = self
                .node_id_for_row(row)
                .ok_or_else(|| GraphError::Inconsistent {
                    reason: format!(
                        "label index row {raw_row} for {} has no node id",
                        label.as_str()
                    ),
                })?;
            let properties = self
                .node_store
                .properties
                .get(raw_row as usize)
                .ok_or_else(|| GraphError::Inconsistent {
                    reason: format!(
                        "JSON search row {raw_row} for {} has no property row",
                        label.as_str()
                    ),
                })?;
            let Some(Value::Json(value)) = properties.get(property) else {
                continue;
            };
            let Some(value) = value.path_value_ref(path) else {
                continue;
            };
            top_k.push(node_id, value);
        }
        Ok(top_k.into_hits())
    }
}

impl SharedGraph {
    /// Exhaustively find JSON-valued node properties in the current snapshot.
    pub fn exact_json_contains_nodes(
        &self,
        label: &DbString,
        property: &DbString,
        candidate: &JsonValue,
        k: usize,
    ) -> GraphResult<Vec<JsonContainmentHit>> {
        self.read()
            .exact_json_contains_nodes(label, property, candidate, k)
    }

    /// Exhaustively find JSON-valued node properties with cancellation checks.
    pub fn exact_json_contains_nodes_checked(
        &self,
        label: &DbString,
        property: &DbString,
        candidate: &JsonValue,
        k: usize,
        checker: CancellationChecker<'_>,
    ) -> Result<Vec<JsonContainmentHit>, JsonSearchError> {
        self.read()
            .exact_json_contains_nodes_checked(label, property, candidate, k, checker)
    }

    /// Exhaustively find JSON-valued node properties where `path` exists.
    pub fn exact_json_path_exists_nodes(
        &self,
        label: &DbString,
        property: &DbString,
        path: &[JsonPathSelector],
        k: usize,
    ) -> GraphResult<Vec<JsonPathHit>> {
        self.read()
            .exact_json_path_exists_nodes(label, property, path, k)
    }

    /// Exhaustively find JSON-valued node properties with path-existence checks.
    pub fn exact_json_path_exists_nodes_checked(
        &self,
        label: &DbString,
        property: &DbString,
        path: &[JsonPathSelector],
        k: usize,
        checker: CancellationChecker<'_>,
    ) -> Result<Vec<JsonPathHit>, JsonSearchError> {
        self.read()
            .exact_json_path_exists_nodes_checked(label, property, path, k, checker)
    }

    /// Exhaustively find JSON-valued node properties whose selected path
    /// contains `candidate`.
    pub fn exact_json_path_contains_nodes(
        &self,
        label: &DbString,
        property: &DbString,
        path: &[JsonPathSelector],
        candidate: &JsonValue,
        k: usize,
    ) -> GraphResult<Vec<JsonPathContainmentHit>> {
        self.read()
            .exact_json_path_contains_nodes(label, property, path, candidate, k)
    }

    /// Exhaustively find JSON path containment matches with cancellation checks.
    pub fn exact_json_path_contains_nodes_checked(
        &self,
        label: &DbString,
        property: &DbString,
        path: &[JsonPathSelector],
        candidate: &JsonValue,
        k: usize,
        checker: CancellationChecker<'_>,
    ) -> Result<Vec<JsonPathContainmentHit>, JsonSearchError> {
        self.read()
            .exact_json_path_contains_nodes_checked(label, property, path, candidate, k, checker)
    }

    /// Exhaustively find JSON-valued node properties where `path` selects a value.
    pub fn exact_json_path_value_nodes(
        &self,
        label: &DbString,
        property: &DbString,
        path: &[JsonPathSelector],
        k: usize,
    ) -> GraphResult<Vec<JsonPathValueHit>> {
        self.read()
            .exact_json_path_value_nodes(label, property, path, k)
    }

    /// Exhaustively find JSON path values with cancellation checks.
    pub fn exact_json_path_value_nodes_checked(
        &self,
        label: &DbString,
        property: &DbString,
        path: &[JsonPathSelector],
        k: usize,
        checker: CancellationChecker<'_>,
    ) -> Result<Vec<JsonPathValueHit>, JsonSearchError> {
        self.read()
            .exact_json_path_value_nodes_checked(label, property, path, k, checker)
    }
}

struct JsonContainmentTopK {
    k: usize,
    nodes: BinaryHeap<NodeId>,
}

impl JsonContainmentTopK {
    fn new(k: usize) -> Self {
        Self {
            k,
            nodes: BinaryHeap::new(),
        }
    }

    fn push(&mut self, node_id: NodeId) {
        if self.k == 0 {
            return;
        }
        if self.nodes.len() < self.k {
            self.nodes.push(node_id);
            return;
        }
        let Some(mut max_node_id) = self.nodes.peek_mut() else {
            return;
        };
        if node_id < *max_node_id {
            *max_node_id = node_id;
        }
    }

    fn into_hits(self) -> Vec<JsonContainmentHit> {
        self.nodes
            .into_sorted_vec()
            .into_iter()
            .map(|node_id| JsonContainmentHit { node_id })
            .collect()
    }

    fn into_path_hits(self) -> Vec<JsonPathHit> {
        self.nodes
            .into_sorted_vec()
            .into_iter()
            .map(|node_id| JsonPathHit { node_id })
            .collect()
    }

    fn into_path_containment_hits(self) -> Vec<JsonPathContainmentHit> {
        self.nodes
            .into_sorted_vec()
            .into_iter()
            .map(|node_id| JsonPathContainmentHit { node_id })
            .collect()
    }
}

struct JsonPathValueCandidate {
    node_id: NodeId,
    value: JsonValue,
}

impl PartialEq for JsonPathValueCandidate {
    fn eq(&self, other: &Self) -> bool {
        self.node_id == other.node_id
    }
}

impl Eq for JsonPathValueCandidate {}

impl PartialOrd for JsonPathValueCandidate {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for JsonPathValueCandidate {
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        self.node_id.cmp(&other.node_id)
    }
}

struct JsonPathValueTopK {
    k: usize,
    nodes: BinaryHeap<JsonPathValueCandidate>,
}

impl JsonPathValueTopK {
    fn new(k: usize) -> Self {
        Self {
            k,
            nodes: BinaryHeap::new(),
        }
    }

    fn push(&mut self, node_id: NodeId, value: JsonValueRef<'_>) {
        self.push_with(node_id, || value.to_owned_json_value());
    }

    fn push_owned(&mut self, node_id: NodeId, value: JsonValue) {
        self.push_with(node_id, || value);
    }

    fn push_with(&mut self, node_id: NodeId, value: impl FnOnce() -> JsonValue) {
        if self.k == 0 {
            return;
        }
        if self.nodes.len() < self.k {
            self.nodes.push(JsonPathValueCandidate {
                node_id,
                value: value(),
            });
            return;
        }
        let Some(mut max_node) = self.nodes.peek_mut() else {
            return;
        };
        if node_id < max_node.node_id {
            *max_node = JsonPathValueCandidate {
                node_id,
                value: value(),
            };
        }
    }

    fn into_hits(self) -> Vec<JsonPathValueHit> {
        self.nodes
            .into_sorted_vec()
            .into_iter()
            .map(|hit| JsonPathValueHit {
                node_id: hit.node_id,
                value: hit.value,
            })
            .collect()
    }
}

#[cfg(test)]
mod tests;