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
use super::far_probe::take_far_equality_materializations;
use super::far_probe::take_far_node_index_rejects;
use super::far_probe::take_far_range_materializations;
use super::test_support::exec_autocommit;
use super::test_support::exec_cypher;
use super::*;
use crate::graph::Graph;

fn far_node_index_graph() -> Graph {
    let g = Graph::default();
    exec_autocommit(&g, "CREATE RANGE INDEX b_code FOR (b:B) ON (b.code)").unwrap();
    exec_autocommit(&g, "CREATE TEXT INDEX b_name FOR (b:B) ON (b.name)").unwrap();
    exec_autocommit(&g, "CREATE RANGE INDEX p_id FOR (p:P) ON (p.id)").unwrap();
    exec_autocommit(&g, "CREATE RANGE INDEX t_name FOR (t:T) ON (t.name)").unwrap();
    g.begin_write().unwrap();
    let a = g
        .create_node(
            vec!["A".into()],
            BTreeMap::from([("id".into(), Value::Int(1))]),
        )
        .unwrap();
    for (code, name) in [(1, "matching text"), (2, "other"), (3, "another")] {
        let b = g
            .create_node(
                vec!["B".into()],
                BTreeMap::from([
                    ("code".into(), Value::Int(code)),
                    ("loose".into(), Value::Int(code % 2)),
                    ("name".into(), Value::String(name.into())),
                ]),
            )
            .unwrap();
        g.create_rel(a, b, "R".into(), BTreeMap::new()).unwrap();
    }
    // A second P ties the label counts (P == F == 2), which keeps the
    // first pattern at its index-0 start via ADR-0351's leftmost
    // tie-break; the second pattern's bound, unlabeled `f` stays at
    // index 0 through the row-bound estimate (a bound element enumerates
    // exactly one candidate) — without it, `t:T` at 2 would beat the
    // unlabeled element's whole-graph estimate and displace the start.
    let p = g
        .create_node(
            vec!["P".into()],
            BTreeMap::from([("id".into(), Value::Int(7))]),
        )
        .unwrap();
    g.create_node(
        vec!["P".into()],
        BTreeMap::from([("id".into(), Value::Int(8))]),
    )
    .unwrap();
    for (i, tag) in ["wanted", "other"].into_iter().enumerate() {
        let f = g
            .create_node(
                vec!["F".into()],
                BTreeMap::from([("id".into(), Value::Int(i as i64))]),
            )
            .unwrap();
        let t = g
            .create_node(
                vec!["T".into()],
                BTreeMap::from([("name".into(), Value::String(tag.into()))]),
            )
            .unwrap();
        g.create_rel(f, p, "MEMBER".into(), BTreeMap::new())
            .unwrap();
        g.create_rel(f, t, "TAGGED".into(), BTreeMap::new())
            .unwrap();
    }
    g.commit_write();
    g
}

#[test]
fn far_node_range_index_prefilters_forced_neighbors() {
    let g = far_node_index_graph();
    let _ = take_far_node_index_rejects();
    let r = exec_cypher(
        &g,
        "MATCH (a:A {id: 1})-[:R]->(b:B) \
         WHERE b.code = 1 RETURN b.name AS name",
    );
    assert_eq!(r.rows, vec![vec![Value::String("matching text".into())]]);
    // The compound start selection (LABS-351) starts the walk at the
    // indexed `b` seek — the prefilter's forced-neighbor arm never runs
    // on this plan (0 rejects); the prefilter's coverage stays pinned by
    // the comma-joined and range/text prefilter-arming shapes below.
    assert_eq!(take_far_node_index_rejects(), 0);
}

#[test]
fn far_node_text_index_prefilters_forced_neighbors() {
    let g = far_node_index_graph();
    let _ = take_far_node_index_rejects();
    let r = exec_cypher(
        &g,
        "MATCH (a:A {id: 1})-[:R]->(b:B) \
         WHERE b.name CONTAINS 'matching' RETURN b.code AS code",
    );
    assert_eq!(r.rows, vec![vec![Value::Int(1)]]);
    // The compound start selection (LABS-351) starts the walk at the
    // indexed `b` seek — the prefilter's forced-neighbor arm never runs
    // on this plan (0 rejects); the prefilter's coverage stays pinned by
    // the comma-joined and range/text prefilter-arming shapes below.
    assert_eq!(take_far_node_index_rejects(), 0);
}

#[test]
fn far_node_index_prefilters_a_comma_joined_second_pattern() {
    const QUERY: &str = "MATCH (f:F)-[:MEMBER]->(p:P), (f)-[:TAGGED]->(t:T) \
         WHERE p.id = 7 AND t.name = 'wanted' RETURN f.id AS id";
    let g = far_node_index_graph();
    let _ = take_far_node_index_rejects();
    let r = exec_cypher(&g, QUERY);
    assert_eq!(r.rows, vec![vec![Value::Int(0)]]);
    // ADR-0351: the first pattern's cheapest element is `p:P` (1 node),
    // so the pivoted plan starts there; with the row-bound estimate
    // (a bound element enumerates exactly one candidate) the second
    // pattern's bound `f` scores 1 and keeps its index-0 start, and the
    // pivoted first pattern's backward walk arms one prefilter rejection.
    // The prefilter's coverage on the original index-0 plan is pinned
    // with the start choice disabled below.
    assert_eq!(take_far_node_index_rejects(), 1);
    // The disabled run returns its results; the A/B assertions live
    // outside the closure, in the same frame as the pivoted ones.
    let (plain_rows, plain_rejects) = super::pivot::with_pivot_disabled(|| {
        let _ = take_far_node_index_rejects();
        let r = exec_cypher(&g, QUERY);
        (r.rows, take_far_node_index_rejects())
    });
    assert_eq!(plain_rows, vec![vec![Value::Int(0)]]);
    assert_eq!(plain_rejects, 1);
}

#[test]
fn far_node_without_a_declared_index_prefilters_from_the_lazy_postings() {
    let g = far_node_index_graph();
    let _ = take_far_node_index_rejects();
    let r = exec_cypher(
        &g,
        "MATCH (a:A {id: 1})-[:R]->(b:B) \
         WHERE b.loose = 1 RETURN b.code AS code ORDER BY code",
    );
    assert_eq!(r.rows, vec![vec![Value::Int(1)], vec![Value::Int(3)]]);
    // ADR-0614: the undeclared (B, loose) pair serves the probe from
    // the lazy equality postings, so the prefilter arms — the loose-0
    // neighbour is rejected by the probe, not left to the residual
    // path. (Pre-ADR-0614 this pinned the opposite: no declared pair,
    // no probe, the residual path.)
    assert_eq!(take_far_node_index_rejects(), 1);
}

/// The residual path stays for a probe the postings cannot serve: a
/// comparison window on the undeclared pair — the lazy postings answer
/// equalities only, so the prefilter cannot arm and the walk checks the
/// predicate per candidate (0 rejects, the same rows).
#[test]
fn far_node_comparison_window_without_an_index_stays_on_the_residual_path() {
    let g = far_node_index_graph();
    let _ = take_far_node_index_rejects();
    let r = exec_cypher(
        &g,
        "MATCH (a:A {id: 1})-[:R]->(b:B) \
         WHERE b.loose > 0 RETURN b.code AS code ORDER BY code",
    );
    assert_eq!(r.rows, vec![vec![Value::Int(1)], vec![Value::Int(3)]]);
    assert_eq!(take_far_node_index_rejects(), 0);
}

/// `(cid, length)` comments linked to one indexed person, plus unlinked
/// comments long enough to inflate the range estimate.
fn person_comment_graph(linked: &[(i64, i64)], unlinked_long: usize) -> Graph {
    let g = Graph::default();
    exec_autocommit(
        &g,
        "CREATE RANGE INDEX person_first FOR (p:Person) ON (p.firstName)",
    )
    .unwrap();
    exec_autocommit(
        &g,
        "CREATE RANGE INDEX person_last FOR (p:Person) ON (p.lastName)",
    )
    .unwrap();
    exec_autocommit(
        &g,
        "CREATE RANGE INDEX comment_length FOR (c:Comment) ON (c.length)",
    )
    .unwrap();
    g.begin_write().unwrap();
    let person = g
        .create_node(
            vec!["Person".into()],
            BTreeMap::from([
                ("firstName".into(), Value::String("Alfredo".into())),
                ("lastName".into(), Value::String("Gomez".into())),
            ]),
        )
        .unwrap();
    for &(cid, length) in linked {
        let comment = g
            .create_node(
                vec!["Comment".into()],
                BTreeMap::from([
                    ("cid".into(), Value::Int(cid)),
                    ("length".into(), Value::Int(length)),
                ]),
            )
            .unwrap();
        g.create_rel(comment, person, "commentHasCreator".into(), BTreeMap::new())
            .unwrap();
    }
    for i in 0..unlinked_long {
        g.create_node(
            vec!["Comment".into()],
            BTreeMap::from([
                ("cid".into(), Value::Int(10_000 + i as i64)),
                ("length".into(), Value::Int(500)),
            ]),
        )
        .unwrap();
    }
    g.commit_write();
    g
}

/// The far-range bound rides a function call on purpose: the runtime
/// funnel — and this probe's cardinality — resolves it through `eval`,
/// while the plan-time ladder's `range_rows` declines function-call
/// bounds (`Expr::seek_value` resolves literals and parameters only,
/// ADR-0486), so the start stays on the equality side and the far probe
/// is the machinery under test. A literal bound would price the window
/// in the ladder and displace the start onto the comment side (ADR-0486,
/// pinned in `pivot_tests`).
const LONG_COMMENT_QUERY: &str = "MATCH (p:Person)<-[:commentHasCreator]-(c:Comment) \
     WHERE p.firstName = 'Alfredo' AND p.lastName = 'Gomez' AND c.length > toInteger('100') \
     RETURN c.cid AS cid ORDER BY cid";

#[test]
fn broad_far_range_stays_on_the_residual_path() {
    let mut linked = vec![(1, 150)];
    linked.extend((2..=28).map(|cid| (cid, 10)));
    let g = person_comment_graph(&linked, 40);
    let _ = take_far_range_materializations();
    let _ = take_far_node_index_rejects();
    let _ = take_neighbor_walks();
    let r = exec_cypher(&g, LONG_COMMENT_QUERY);
    assert_eq!(r.rows, vec![vec![Value::Int(1)]]);
    assert_eq!(take_far_range_materializations(), 0);
    assert_eq!(take_far_node_index_rejects(), 0);
    assert_eq!(take_neighbor_walks(), 28);
}

#[test]
fn selective_far_range_materializes_and_rejects_neighbors() {
    let mut linked = vec![(1, 150), (2, 180)];
    linked.extend((3..=2_002).map(|cid| (cid, 10)));
    let g = person_comment_graph(&linked, 0);
    let _ = take_far_range_materializations();
    let _ = take_far_node_index_rejects();
    let r = exec_cypher(&g, LONG_COMMENT_QUERY);
    assert_eq!(r.rows, vec![vec![Value::Int(1)], vec![Value::Int(2)]]);
    assert_eq!(take_far_range_materializations(), 1);
    assert_eq!(take_far_node_index_rejects(), 2_000);
}

#[test]
fn empty_far_estimate_does_not_expand() {
    let linked: Vec<_> = (1..=3).map(|cid| (cid, 10)).collect();
    let g = person_comment_graph(&linked, 0);
    let _ = take_neighbor_walks();
    let r = exec_cypher(
        &g,
        "MATCH (p:Person)<-[:commentHasCreator]-(c:Comment) \
         WHERE p.firstName = 'Alfredo' AND p.lastName = 'Gomez' AND c.length = -1 \
         RETURN c.cid AS cid",
    );
    assert!(r.rows.is_empty());
    assert_eq!(take_neighbor_walks(), 0);
}

#[test]
fn repeated_small_frontiers_materialize_once_their_total_catches_the_estimate() {
    let g = Graph::default();
    exec_autocommit(&g, "CREATE RANGE INDEX tag_name FOR (t:Tag) ON (t.name)").unwrap();
    exec_autocommit(
        &g,
        "CREATE RANGE INDEX person_last FOR (p:Person) ON (p.lastName)",
    )
    .unwrap();
    g.begin_write().unwrap();
    let tag = g
        .create_node(
            vec!["Tag".into()],
            BTreeMap::from([("name".into(), Value::String("Norah".into()))]),
        )
        .unwrap();
    for pid in 1..=10 {
        let person = g
            .create_node(
                vec!["Person".into()],
                BTreeMap::from([
                    ("pid".into(), Value::Int(pid)),
                    (
                        "lastName".into(),
                        Value::String(if pid == 10 { "Gurung" } else { "Other" }.into()),
                    ),
                ]),
            )
            .unwrap();
        let forum = g
            .create_node(vec!["Forum".into()], BTreeMap::new())
            .unwrap();
        g.create_rel(forum, tag, "forumHasTag".into(), BTreeMap::new())
            .unwrap();
        g.create_rel(forum, person, "hasModerator".into(), BTreeMap::new())
            .unwrap();
    }
    for extra in 11..=13 {
        g.create_node(
            vec!["Person".into()],
            BTreeMap::from([
                ("pid".into(), Value::Int(extra)),
                ("lastName".into(), Value::String("Gurung".into())),
            ]),
        )
        .unwrap();
    }
    g.commit_write();
    let _ = take_far_node_index_rejects();
    let r = exec_cypher(
        &g,
        "MATCH (t:Tag)<-[:forumHasTag]-(f:Forum)-[:hasModerator]->(p:Person) \
         WHERE t.name = 'Norah' AND p.lastName = 'Gurung' RETURN p.pid AS pid",
    );
    assert_eq!(r.rows, vec![vec![Value::Int(10)]]);
    // The compound start selection (LABS-351) starts at the
    // equality-indexed endpoint (both `t.name` and `p.lastName` carry
    // hits ~1), so the far-node estimate never materializes on this
    // plan (0 rejects); its dedup behavior stays pinned by the
    // comma-joined prefilter shapes.
    assert_eq!(take_far_node_index_rejects(), 0);
}

/// Twenty `M` memories mention two `E` entities (ten each); no index, so a
/// `WHERE r.user = ...` far-node seek is served from the lazy equality
/// postings, which have no count without building the bucket.
fn lazy_equality_graph() -> Graph {
    let g = Graph::default();
    g.begin_write().unwrap();
    let entities: Vec<_> = (0..2)
        .map(|k| {
            g.create_node(
                vec!["E".into()],
                BTreeMap::from([("key".into(), Value::Int(k))]),
            )
            .unwrap()
        })
        .collect();
    for i in 0..20_i64 {
        let m = g
            .create_node(
                vec!["M".into()],
                BTreeMap::from([
                    ("id".into(), Value::Int(i)),
                    ("user".into(), Value::String(format!("u{}", i % 4).into())),
                ]),
            )
            .unwrap();
        g.create_rel(
            m,
            entities[(i % 2) as usize],
            "MENTIONS".into(),
            BTreeMap::new(),
        )
        .unwrap();
    }
    g.commit_write();
    g
}

#[test]
fn far_node_lazy_equality_seek_waits_for_the_frontier() {
    // The aggregate carries `e` into the second MATCH, so no one-hop fold
    // serves it: each input row prepares its own far probe. Each `e` has
    // ten neighbors, fewer than the twenty `M` ids the label count bounds
    // the bucket by, so the probe filters the walked neighbors and never
    // builds the `user` bucket. Unpriced, it built the bucket per row.
    const QUERY: &str = "UNWIND [0, 1, 2, 3] AS b MATCH (m:M {id: b})-[:MENTIONS]->(e:E) \
         WITH e, count(*) AS c \
         MATCH (e)<-[:MENTIONS]-(r:M) WHERE r.user = 'u0' \
         RETURN r.id AS id ORDER BY id";
    let g = lazy_equality_graph();
    let _ = take_far_equality_materializations();
    let r = exec_cypher(&g, QUERY);
    let expected: Vec<Vec<Value>> = (0..20).step_by(4).map(|i| vec![Value::Int(i)]).collect();
    assert_eq!(r.rows, expected);
    assert_eq!(take_far_equality_materializations(), 0);
}

#[test]
fn equality_row_estimate_counts_the_bucket() {
    let g = far_node_index_graph();
    assert_eq!(
        g.pattern_equality_rows("B", "code", &Value::Int(1)),
        Some(1)
    );
    assert_eq!(
        g.pattern_equality_rows("B", "code", &Value::Int(9)),
        Some(0)
    );
    assert_eq!(g.pattern_equality_rows("B", "loose", &Value::Int(1)), None);
}