relate-executor 1.5.0

In-memory graph and Cypher physical executor
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
//! Differential tests for the Vortex store against the graph it was built
//! from: the sorted `(key,row)` side-file against the compact records' point
//! reads, and the seam's point read against the same rows.

use std::collections::BTreeMap;
use std::sync::Arc;

use relate_core::{NodeId, Value};

use super::*;

struct Row {
    labels: Vec<&'static str>,
    props: Vec<(&'static str, Val)>,
}

struct Seeded {
    graph: Graph,
    ids: Vec<NodeId>,
    data: Vec<Row>,
}

/// Six nodes: every one carries `N`; ids 1 and 3 also carry `M`. Ids 4 and 6
/// carry no `name` (the nullable-column shape); two `x` values repeat.
fn sample() -> Vec<Row> {
    vec![
        Row {
            labels: vec!["N"],
            props: vec![("x", Val::Int(1)), ("name", Val::Str("a".into()))],
        },
        Row {
            labels: vec!["N", "M"],
            props: vec![("x", Val::Int(2)), ("name", Val::Str("b".into()))],
        },
        Row {
            labels: vec!["N"],
            props: vec![("x", Val::Int(2)), ("name", Val::Str("b".into()))],
        },
        Row {
            labels: vec!["N", "M"],
            props: vec![("x", Val::Int(3))],
        },
        Row {
            labels: vec!["N"],
            props: vec![("x", Val::Int(1)), ("name", Val::Str("a".into()))],
        },
        Row {
            labels: vec!["N"],
            props: vec![("x", Val::Int(2))],
        },
    ]
}

fn seed() -> Seeded {
    let graph = Graph::default();
    let data = sample();
    let mut ids = Vec::new();
    graph.begin_write().unwrap();
    for row in &data {
        let labels = row.labels.iter().map(|l| l.to_string()).collect();
        let mut props: BTreeMap<String, Value> = BTreeMap::new();
        for (key, val) in &row.props {
            let value = to_value(val.clone())
                .unwrap_or_else(|| panic!("sample property {key} does not convert to a Value"));
            props.insert(key.to_string(), value);
        }
        assert_eq!(
            props.len(),
            row.props.len(),
            "the seed lost a property on conversion"
        );
        ids.push(graph.create_node(labels, props).unwrap());
    }
    graph.commit_write();
    Seeded { graph, ids, data }
}

fn prop(row: &Row, key: &str) -> Val {
    row.props
        .iter()
        .find(|(k, _)| *k == key)
        .map(|(_, v)| v.clone())
        .unwrap_or(Val::Null)
}

fn sorted(mut ids: Vec<NodeId>) -> Vec<NodeId> {
    ids.sort_unstable();
    ids
}

fn store_of(seeded: &Seeded) -> VortexStore {
    VortexStore::from_graph(&seeded.graph, seeded.graph.commit_ts()).unwrap()
}

/// The compact records' answer for `(key, value)`: every id whose public
/// point read equals the value.
fn recorded(seeded: &Seeded, key: &str, value: &Value) -> Vec<NodeId> {
    let ts = seeded.graph.commit_ts();
    let mut ids: Vec<NodeId> = seeded
        .ids
        .iter()
        .copied()
        .filter(|id| seeded.graph.node_prop_at(*id, ts, key).as_ref() == Some(value))
        .collect();
    ids.sort_unstable();
    ids
}

/// The sorted `(key,row)` side-file answers exactly what the compact
/// records' point reads answer for the same `(key, value)` on the same graph.
#[test]
fn side_file_matches_the_compact_records() {
    let seeded = seed();
    let store = store_of(&seeded);
    let kx = seeded.graph.interned_id("x").unwrap();
    let kn = seeded.graph.interned_id("name").unwrap();

    for value in [1i64, 2, 3, 4] {
        assert_eq!(
            sorted(store.seek(kx, &Val::Int(value))),
            recorded(&seeded, "x", &Value::Int(value)),
            "x = {value}"
        );
    }
    for value in ["a", "b", "z"] {
        assert_eq!(
            sorted(store.seek(kn, &Val::Str(value.into()))),
            recorded(&seeded, "name", &Value::String(Arc::from(value))),
            "name = {value}"
        );
    }

    // The batched key check is the union of the same single-value answers.
    let mut want: Vec<NodeId> = recorded(&seeded, "x", &Value::Int(1))
        .into_iter()
        .chain(recorded(&seeded, "x", &Value::Int(3)))
        .collect();
    want.sort_unstable();
    assert_eq!(sorted(store.member(kx, &[Val::Int(1), Val::Int(3)])), want);
}

/// Point reads decode ints and strings the same way, whichever chunk the
/// row falls in.
#[test]
fn point_reads_decode_strings_and_ints() {
    let seeded = seed();
    let store = store_of(&seeded);
    let ts = seeded.graph.commit_ts();
    let kx = seeded.graph.interned_id("x").unwrap();
    let kn = seeded.graph.interned_id("name").unwrap();

    for (index, row) in seeded.data.iter().enumerate() {
        let id = seeded.ids[index];
        let want_int = match prop(row, "x") {
            Val::Int(int) => Some(Value::Int(int)),
            _ => None,
        };
        let want_name = match prop(row, "name") {
            Val::Str(name) => Some(Value::String(Arc::from(name))),
            _ => None,
        };
        assert_eq!(PropStore::point(&store, ts, id, kx), want_int);
        assert_eq!(PropStore::point(&store, ts, id, kn), want_name);
    }
}

/// The store lives in the shared [`Graph`] and answers the seam exactly as
/// the compact records did before it was attached.
#[test]
fn store_attaches_to_the_shared_graph() {
    fn assert_send_sync<T: Send + Sync>() {}
    assert_send_sync::<VortexStore>();

    let seeded = seed();
    let ts = seeded.graph.commit_ts();
    let kx = seeded.graph.interned_id("x").unwrap();
    let kn = seeded.graph.interned_id("name").unwrap();
    // Captured BEFORE any store exists — the A/B's truth. Afterwards
    // `Graph::point` routes through the attached store, so comparing the
    // graph against that store would compare it with itself.
    let recorded: Vec<_> = seeded
        .ids
        .iter()
        .map(|id| {
            (
                PropStore::point(&seeded.graph, ts, *id, kx),
                PropStore::point(&seeded.graph, ts, *id, kn),
            )
        })
        .collect();
    let store = Arc::new(VortexStore::from_graph(&seeded.graph, ts).unwrap());
    assert!(
        seeded.graph.attach_prop_store(store.clone()),
        "a store is already attached"
    );
    for (index, id) in seeded.ids.iter().enumerate() {
        let want = &recorded[index];
        assert_eq!(
            &(
                PropStore::point(store.as_ref(), ts, *id, kx),
                PropStore::point(store.as_ref(), ts, *id, kn),
            ),
            want,
            "the store answers as the compact records"
        );
        assert_eq!(
            &(
                PropStore::point(&seeded.graph, ts, *id, kx),
                PropStore::point(&seeded.graph, ts, *id, kn),
            ),
            want,
            "the attached graph answers as the compact records"
        );
    }
}

/// A cold column under N racing readers decodes once (fill-once): every
/// thread sees the same values, and the store is `Send + Sync` enough to
/// share as an `Arc` across spawned threads.
#[test]
fn concurrent_cold_point_reads_agree() {
    let seeded = seed();
    let store = Arc::new(VortexStore::from_graph(&seeded.graph, seeded.graph.commit_ts()).unwrap());
    let kx = seeded.graph.interned_id("x").unwrap();
    let handles: Vec<_> = (0..8)
        .map(|_| {
            let store = Arc::clone(&store);
            let ids = seeded.ids.clone();
            std::thread::spawn(move || {
                ids.iter()
                    .map(|id| PropStore::point(store.as_ref(), 0, *id, kx))
                    .collect::<Vec<Option<Value>>>()
            })
        })
        .collect();
    let results: Vec<Vec<Option<Value>>> = handles.into_iter().map(|h| h.join().unwrap()).collect();
    for other in &results[1..] {
        assert_eq!(&results[0], other);
    }
}

#[test]
fn the_row_space_admission_refuses_a_sparse_id_space() {
    // Dense: n live ids end at n-1.
    let dense: Vec<NodeId> = (0..1000).collect();
    assert_eq!(super::build::row_space(&dense).unwrap(), 1000);
    // Sparse: one id far past the live count trips the bound (the bound
    // tolerates deletion gaps of 4x plus 64k headroom).
    let sparse = vec![0, 1, 2, (1 << 20) + 7];
    assert!(super::build::row_space(&sparse).is_err());
}

#[test]
fn the_dense_structure_admission_refuses_an_over_budget_product() {
    // A real graph's product sits far below the budget.
    assert!(super::build::admit_dense(100_000, 16).is_ok());
    // The crafted sparse-keys shape — keys meeting rows — trips it.
    let rows = 1 << 20;
    let keys = 1 << 20;
    assert!(super::build::admit_dense(rows, keys).is_err());
}

#[test]
fn point_batch_matches_scalar_point_reads() {
    let seeded = seed();
    let store = Arc::new(store_of(&seeded));
    assert!(seeded.graph.attach_prop_store(store.clone()));
    let ts = seeded.graph.commit_ts();
    let kx = seeded.graph.interned_id("x").unwrap();
    let kn = seeded.graph.interned_id("name").unwrap();

    let mut out_x = vec![None; seeded.ids.len()];
    let mut out_name = vec![None; seeded.ids.len()];

    store.point_batch(ts, &seeded.ids, kx, &mut out_x);
    store.point_batch(ts, &seeded.ids, kn, &mut out_name);

    for (i, &id) in seeded.ids.iter().enumerate() {
        assert_eq!(
            out_x[i],
            store.point(ts, id, kx),
            "point_batch vs point for x on node {id}"
        );
        assert_eq!(
            out_name[i],
            store.point(ts, id, kn),
            "point_batch vs point for name on node {id}"
        );
    }

    // Nodes 3 and 5 (0-indexed) have missing name -> out_name[i] is None
    assert_eq!(out_name[3], None);
    assert_eq!(out_name[5], None);

    // Test with delta overlay
    seeded.graph.begin_write().unwrap();
    seeded
        .graph
        .set_property_node(seeded.ids[0], "x", Value::Int(99));
    seeded.graph.set_property_node(
        seeded.ids[0],
        "name",
        Value::String(Arc::from("delta_updated")),
    );
    seeded.graph.delete_node(seeded.ids[1], false).unwrap();
    seeded.graph.commit_write();

    let new_ts = seeded.graph.commit_ts();
    let mut out_x_new = vec![None; seeded.ids.len()];
    let mut out_name_new = vec![None; seeded.ids.len()];
    store.point_batch(new_ts, &seeded.ids, kx, &mut out_x_new);
    store.point_batch(new_ts, &seeded.ids, kn, &mut out_name_new);

    // Node 0 updated
    assert_eq!(out_x_new[0], Some(Value::Int(99)));
    assert_eq!(
        out_name_new[0],
        Some(Value::String(Arc::from("delta_updated")))
    );
    // Node 1 deleted
    assert_eq!(out_x_new[1], None);
    assert_eq!(out_name_new[1], None);
}

#[test]
fn filter_range_clears_non_matching_bits() {
    let seeded = seed();
    let store = store_of(&seeded);
    let ts = seeded.graph.commit_ts();
    let kx = seeded.graph.interned_id("x").unwrap();
    let kn = seeded.graph.interned_id("name").unwrap();

    // Sample data:
    // id 0: x=1, name="a"
    // id 1: x=2, name="b"
    // id 2: x=2, name="b"
    // id 3: x=3, no name
    // id 4: x=1, name="a"
    // id 5: x=2, no name

    // Test 1: x == 2 -> expected ids: 1, 2, 5
    let mut mask = [0b111111u64];
    let res = store.filter_range(ts, &seeded.ids, kx, BinaryOp::Eq, &Value::Int(2), &mut mask);
    assert_eq!(res, Some(()));
    assert_eq!(mask[0], (1 << 1) | (1 << 2) | (1 << 5));

    // Test 2: x > 1 -> expected ids: 1, 2, 3, 5
    let mut mask = [0b111111u64];
    let res = store.filter_range(ts, &seeded.ids, kx, BinaryOp::Gt, &Value::Int(1), &mut mask);
    assert_eq!(res, Some(()));
    assert_eq!(mask[0], (1 << 1) | (1 << 2) | (1 << 3) | (1 << 5));

    // Test 3: x <= 1 -> expected ids: 0, 4
    let mut mask = [0b111111u64];
    let res = store.filter_range(
        ts,
        &seeded.ids,
        kx,
        BinaryOp::Lte,
        &Value::Int(1),
        &mut mask,
    );
    assert_eq!(res, Some(()));
    assert_eq!(mask[0], (1 << 0) | (1 << 4));

    // Test 4: name == "a" -> expected ids: 0, 4
    let mut mask = [0b111111u64];
    let res = store.filter_range(
        ts,
        &seeded.ids,
        kn,
        BinaryOp::Eq,
        &Value::String(Arc::from("a")),
        &mut mask,
    );
    assert_eq!(res, Some(()));
    assert_eq!(mask[0], (1 << 0) | (1 << 4));

    // Test 5: name != "a" -> expected ids: 1, 2 (missing name at 3 and 5 are null, which drop!)
    let mut mask = [0b111111u64];
    let res = store.filter_range(
        ts,
        &seeded.ids,
        kn,
        BinaryOp::Neq,
        &Value::String(Arc::from("a")),
        &mut mask,
    );
    assert_eq!(res, Some(()));
    assert_eq!(mask[0], (1 << 1) | (1 << 2));

    // Test 6: null literal clears all active bits
    let mut mask = [0b111111u64];
    let res = store.filter_range(ts, &seeded.ids, kx, BinaryOp::Eq, &Value::Null, &mut mask);
    assert_eq!(res, Some(()));
    assert_eq!(mask[0], 0);
}

#[test]
fn folds_masked_computes_exact_extrema_and_count() {
    let seeded = seed();
    let store = store_of(&seeded);
    let ts = seeded.graph.commit_ts();
    let kx = seeded.graph.interned_id("x").unwrap();

    // Select ids 0 (x=1), 1 (x=2), 3 (x=3) -> mask bits 0, 1, 3 set
    let mask = [(1 << 0) | (1 << 1) | (1 << 3)];
    let wants = [PropFold::Count, PropFold::Min, PropFold::Max];
    let folds = store
        .folds_masked(ts, &seeded.ids, &mask, kx, &wants)
        .unwrap();

    assert_eq!(folds, vec![Value::Int(3), Value::Int(1), Value::Int(3)]);

    // Select only id 1 (x=2) and 2 (x=2)
    let mask2 = [(1 << 1) | (1 << 2)];
    let folds2 = store
        .folds_masked(ts, &seeded.ids, &mask2, kx, &wants)
        .unwrap();
    assert_eq!(folds2, vec![Value::Int(2), Value::Int(2), Value::Int(2)]);
}

#[test]
fn grouped_counts_masked_computes_exact_groups() {
    let seeded = seed();
    let store = store_of(&seeded);
    let ts = seeded.graph.commit_ts();
    let kx = seeded.graph.interned_id("x").unwrap();

    // Select all ids: x=1 (2 times), x=2 (3 times), x=3 (1 time)
    let mask = [0b111111u64];
    let mut groups = store
        .grouped_counts_masked(ts, &seeded.ids, &mask, kx)
        .unwrap();
    groups.sort_by_key(|(val, _)| match val {
        Value::Int(i) => *i,
        _ => 0,
    });

    assert_eq!(
        groups,
        vec![(Value::Int(1), 2), (Value::Int(2), 3), (Value::Int(3), 1),]
    );

    // Select subset: ids 0 (x=1) and 1 (x=2)
    let mask_sub = [(1 << 0) | (1 << 1)];
    let mut groups_sub = store
        .grouped_counts_masked(ts, &seeded.ids, &mask_sub, kx)
        .unwrap();
    groups_sub.sort_by_key(|(val, _)| match val {
        Value::Int(i) => *i,
        _ => 0,
    });

    assert_eq!(groups_sub, vec![(Value::Int(1), 1), (Value::Int(2), 1)]);
}