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
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
//! Composable HashJoin and SemiMasker SIP differential parity and PROFILE plan-shape tests.

use std::collections::BTreeMap;

use relate_core::Value;

use super::{take_hash_join_engagements, with_hash_join_disabled};
use crate::exec::test_support::{exec_cypher, profiled, try_exec_cypher_params};
use crate::graph::Graph;

/// Build a multi-hop graph:
/// Side A: (a:A)-[:RA]->(b:B)-[:RAB]->(h:H)
/// Side B: (c:C)-[:RC]->(d:D)-[:RCD]->(h:H)
fn build_multi_hop_graph(hubs: usize, branches_per_hub: usize) -> Graph {
    let g = Graph::default();
    g.begin_write().unwrap();
    let node = |label: &str, id: i64| {
        g.create_node(
            vec![label.into()],
            BTreeMap::from([("id".into(), Value::Int(id))]),
        )
        .unwrap()
    };

    let mut hub_nodes = Vec::new();
    for i in 0..hubs {
        hub_nodes.push(node("H", i as i64));
    }

    let mut counter = 0i64;
    for &h in &hub_nodes {
        for _ in 0..branches_per_hub {
            counter += 1;
            let a = node("A", counter);
            let b = node("B", counter);
            g.create_rel(a, b, "RA".into(), BTreeMap::new()).unwrap();
            g.create_rel(b, h, "RAB".into(), BTreeMap::new()).unwrap();

            let c = node("C", counter);
            let d = node("D", counter);
            g.create_rel(c, d, "RC".into(), BTreeMap::new()).unwrap();
            g.create_rel(d, h, "RCD".into(), BTreeMap::new()).unwrap();
        }
    }
    g.commit_write();
    g
}

#[test]
fn multi_hop_two_pattern_join_parity() {
    // 20 hubs * 8 branches = 160 side-A rows (>= 128 minimum)
    let g = build_multi_hop_graph(20, 8);
    let query = "MATCH (a:A)-[:RA]->(b:B)-[:RAB]->(h:H), (c:C)-[:RC]->(d:D)-[:RCD]->(h) \
                 RETURN h.id AS hub, a.id AS aid, c.id AS cid ORDER BY hub, aid, cid";

    let _ = take_hash_join_engagements();
    let joined = exec_cypher(&g, query);
    assert_eq!(
        take_hash_join_engagements(),
        1,
        "multi-hop hash join engaged"
    );

    let nested = with_hash_join_disabled(|| {
        let _ = take_hash_join_engagements();
        let r = exec_cypher(&g, query);
        assert_eq!(take_hash_join_engagements(), 0, "hash join disabled");
        r
    });

    assert_eq!(
        joined.rows, nested.rows,
        "exact parity between hash join and nested loop"
    );
    assert!(!joined.rows.is_empty());
}

#[test]
fn multi_key_join_parity_and_rel_uniqueness() {
    let g = Graph::default();
    g.begin_write().unwrap();
    let node = |label: &str, id: i64| {
        g.create_node(
            vec![label.into()],
            BTreeMap::from([("id".into(), Value::Int(id))]),
        )
        .unwrap()
    };

    let hubs = 20;
    let mut h1_nodes = Vec::new();
    let mut h2_nodes = Vec::new();
    for i in 0..hubs {
        h1_nodes.push(node("H1", i as i64));
        h2_nodes.push(node("H2", i as i64));
    }

    // 20 * 10 = 200 side A rows
    let mut counter = 0i64;
    for i in 0..hubs {
        let h1 = h1_nodes[i];
        let h2 = h2_nodes[i];
        for _ in 0..10 {
            counter += 1;
            let a = node("A", counter);
            g.create_rel(a, h1, "R1".into(), BTreeMap::new()).unwrap();
            g.create_rel(a, h2, "R2".into(), BTreeMap::new()).unwrap();

            let b = node("B", counter);
            g.create_rel(b, h1, "R3".into(), BTreeMap::new()).unwrap();
            g.create_rel(b, h2, "R4".into(), BTreeMap::new()).unwrap();
        }
    }
    g.commit_write();

    // Two patterns, each 2 hops, sharing both h1 and h2
    let query = "MATCH (h1:H1)<-[:R1]-(a:A)-[:R2]->(h2:H2), \
                       (h1:H1)<-[:R3]-(b:B)-[:R4]->(h2:H2) \
                 RETURN h1.id AS h1_id, h2.id AS h2_id, a.id AS aid, b.id AS bid \
                 ORDER BY h1_id, h2_id, aid, bid";

    let _ = take_hash_join_engagements();
    let joined = exec_cypher(&g, query);
    assert_eq!(
        take_hash_join_engagements(),
        1,
        "multi-key hash join engaged"
    );

    let nested = with_hash_join_disabled(|| exec_cypher(&g, query));
    assert_eq!(joined.rows, nested.rows, "exact parity on multi-key join");
    assert!(!joined.rows.is_empty());
}

#[test]
fn semi_mask_sip_effectiveness_and_profile_metrics() {
    let g = Graph::default();
    g.begin_write().unwrap();
    let node = |label: &str, id: i64| {
        g.create_node(
            vec![label.into()],
            BTreeMap::from([("id".into(), Value::Int(id))]),
        )
        .unwrap()
    };

    // 200 hubs for side A, 10 A nodes per hub = 2000 side A rows
    let hubs = 200;
    let mut hub_nodes = Vec::new();
    let mut counter = 0i64;
    for i in 0..hubs {
        let h = node("Hub", i as i64);
        hub_nodes.push(h);
        for _ in 0..10 {
            counter += 1;
            let a = node("A", counter);
            g.create_rel(a, h, "TO_HUB".into(), BTreeMap::new())
                .unwrap();
        }
    }

    // Side B has:
    // 200 hubs * 10 = 2000 matching B nodes wired to hubs
    // 1000 non-matching B nodes wired to non-hub nodes
    for &h in &hub_nodes {
        for _ in 0..10 {
            counter += 1;
            let b = node("B", counter);
            g.create_rel(b, h, "FROM_B".into(), BTreeMap::new())
                .unwrap();
        }
    }
    for i in 0..1000 {
        counter += 1;
        let non_hub = node("Hub", (100_000 + i) as i64);
        let b = node("B", counter);
        g.create_rel(b, non_hub, "FROM_B".into(), BTreeMap::new())
            .unwrap();
    }
    g.commit_write();

    let query = "MATCH (a:A)-[:TO_HUB]->(h:Hub), (b:B)-[:FROM_B]->(h:Hub) \
                 RETURN h.id AS hid, a.id AS aid, b.id AS bid ORDER BY hid, aid, bid";

    let _ = take_hash_join_engagements();
    let records = profiled(&g, query);
    assert_eq!(take_hash_join_engagements(), 1, "hash join engaged");

    let hj_rec = records.iter().find(|r| r.hash_join.build_rows > 0);
    assert!(
        hj_rec.is_some(),
        "PROFILE record contains hash_join metrics"
    );
    let hj = hj_rec.unwrap().hash_join;
    assert!(
        hj.build_rows >= 1000,
        "build_rows >= 1000, got {}",
        hj.build_rows
    );
    assert!(hj.probe_rows > 0, "probe_rows > 0, got {}", hj.probe_rows);
    assert!(
        hj.semi_mask_rejected > 0,
        "semi_mask_rejected > 0, got {}",
        hj.semi_mask_rejected
    );

    let res = exec_cypher(&g, query);
    let nested_res = with_hash_join_disabled(|| exec_cypher(&g, query));
    assert_eq!(res.rows, nested_res.rows, "results match nested loop");
    assert_eq!(res.rows.len(), 20_000);
}

#[test]
fn syntactic_perturbations_stay_engaged() {
    let g = build_multi_hop_graph(20, 10); // 200 rows

    // 1. Base query
    let query_base = "MATCH (a:A)-[:RA]->(b:B)-[:RAB]->(h:H), (c:C)-[:RC]->(d:D)-[:RCD]->(h) \
                      RETURN h.id AS hid, a.id AS aid, c.id AS cid ORDER BY hid, aid, cid";
    // 2. WHERE with NOT / OR keeping all rows
    let query_where = "MATCH (a:A)-[:RA]->(b:B)-[:RAB]->(h:H), (c:C)-[:RC]->(d:D)-[:RCD]->(h) \
                       WHERE h.id >= 0 OR NOT (h.id < 0) \
                       RETURN h.id AS hid, a.id AS aid, c.id AS cid ORDER BY hid, aid, cid";
    // 3. Parameterized predicate keeping all rows
    let query_param = "MATCH (a:A)-[:RA]->(b:B)-[:RAB]->(h:H), (c:C)-[:RC]->(d:D)-[:RCD]->(h) \
                       WHERE h.id >= $min_id \
                       RETURN h.id AS hid, a.id AS aid, c.id AS cid ORDER BY hid, aid, cid";

    for (desc, q) in [
        ("base query", query_base),
        ("WHERE with OR / NOT", query_where),
    ] {
        let _ = take_hash_join_engagements();
        let res = exec_cypher(&g, q);
        assert_eq!(
            take_hash_join_engagements(),
            1,
            "query '{desc}' engaged hash join"
        );
        let disabled_res = with_hash_join_disabled(|| exec_cypher(&g, q));
        assert_eq!(res.rows, disabled_res.rows, "parity on '{desc}'");
    }

    let params = BTreeMap::from([("min_id".to_string(), Value::Int(0))]);
    let _ = take_hash_join_engagements();
    let res = try_exec_cypher_params(&g, query_param, &params).unwrap();
    assert_eq!(
        take_hash_join_engagements(),
        1,
        "parameterized query engaged hash join"
    );
    let disabled_res =
        with_hash_join_disabled(|| try_exec_cypher_params(&g, query_param, &params).unwrap());
    assert_eq!(res.rows, disabled_res.rows, "parity on parameterized query");
}

#[test]
fn multiplicity_semi_join_subsumes_adr_0713() {
    let g = Graph::default();
    g.begin_write().unwrap();
    let node = |label: &str, id: i64| {
        g.create_node(
            vec![label.into()],
            BTreeMap::from([("id".into(), Value::Int(id))]),
        )
        .unwrap()
    };

    // 200 persons (hubs).
    // Each person has 2 matching interests (multiplicity = 2).
    let persons: Vec<_> = (0..200).map(|i| node("Person", i as i64)).collect();
    let int1 = node("Interest", 1);
    let int2 = node("Interest", 2);
    for &p in &persons {
        g.create_rel(p, int1, "HAS".into(), BTreeMap::new())
            .unwrap();
        g.create_rel(p, int2, "HAS".into(), BTreeMap::new())
            .unwrap();
    }
    // Each person lives in a city:
    for (i, &p) in persons.iter().enumerate() {
        let city = node("City", (100 + i) as i64);
        g.create_rel(p, city, "LIVES".into(), BTreeMap::new())
            .unwrap();
    }
    g.commit_write();

    // Query: side A matches (p:Person)-[:HAS]->(i:Interest), but 'i' is NOT returned or used downstream!
    // Downstream only returns p.id and c.id.
    let query = "MATCH (p:Person)-[:HAS]->(i:Interest), (p)-[:LIVES]->(c:City) \
                 RETURN p.id AS pid, c.id AS cid ORDER BY pid, cid";

    let _ = take_hash_join_engagements();
    let res = exec_cypher(&g, query);
    assert_eq!(
        take_hash_join_engagements(),
        1,
        "multiplicity hash join engaged"
    );

    let nested_res = with_hash_join_disabled(|| exec_cypher(&g, query));
    assert_eq!(res.rows, nested_res.rows, "exact parity with nested loop");
    // 200 persons * 2 matching interests = 400 rows (preserving bag semantics!)
    assert_eq!(res.rows.len(), 400);
}

#[test]
fn multiplicity_declines_when_rel_types_overlap() {
    let g = Graph::default();
    g.begin_write().unwrap();
    let node = |label: &str, id: i64| {
        g.create_node(
            vec![label.into()],
            BTreeMap::from([("id".into(), Value::Int(id))]),
        )
        .unwrap()
    };
    let persons: Vec<_> = (0..200).map(|i| node("Person", i as i64)).collect();
    for &p in &persons {
        let o1 = node("Other", 1);
        let o2 = node("Other", 2);
        // Overlapping rel type :CONNECTED on both sides!
        g.create_rel(p, o1, "CONNECTED".into(), BTreeMap::new())
            .unwrap();
        g.create_rel(p, o2, "CONNECTED".into(), BTreeMap::new())
            .unwrap();
    }
    g.commit_write();

    let query = "MATCH (p:Person)-[:CONNECTED]->(o1:Other), (p)-[:CONNECTED]->(o2:Other) \
                 RETURN p.id AS pid, o2.id AS o2id ORDER BY pid, o2id";
    let res = exec_cypher(&g, query);
    let nested_res = with_hash_join_disabled(|| exec_cypher(&g, query));
    assert_eq!(res.rows, nested_res.rows, "parity when rel types overlap");
}

#[test]
fn multiplicity_declines_when_rel_is_untyped() {
    let g = Graph::default();
    g.begin_write().unwrap();
    let node = |label: &str, id: i64| {
        g.create_node(
            vec![label.into()],
            BTreeMap::from([("id".into(), Value::Int(id))]),
        )
        .unwrap()
    };
    let persons: Vec<_> = (0..200).map(|i| node("Person", i as i64)).collect();
    for &p in &persons {
        let i1 = node("Interest", 1);
        let c1 = node("City", 1);
        g.create_rel(p, i1, "HAS".into(), BTreeMap::new()).unwrap();
        g.create_rel(p, c1, "LIVES".into(), BTreeMap::new())
            .unwrap();
    }
    g.commit_write();

    // Untyped relationship -[]-> on side A!
    let query = "MATCH (p:Person)-[]->(i:Interest), (p)-[:LIVES]->(c:City) \
                 RETURN p.id AS pid, c.id AS cid ORDER BY pid, cid";
    let res = exec_cypher(&g, query);
    let nested_res = with_hash_join_disabled(|| exec_cypher(&g, query));
    assert_eq!(res.rows, nested_res.rows, "parity when rel is untyped");
}

#[test]
fn multiplicity_declines_when_residual_references_side_a_non_join_var() {
    let g = Graph::default();
    g.begin_write().unwrap();
    let node = |label: &str, id: i64| {
        g.create_node(
            vec![label.into()],
            BTreeMap::from([("id".into(), Value::Int(id))]),
        )
        .unwrap()
    };
    let persons: Vec<_> = (0..200).map(|i| node("Person", i as i64)).collect();
    for &p in &persons {
        let i1 = node("Interest", 1);
        let i2 = node("Interest", 2);
        g.create_rel(p, i1, "HAS".into(), BTreeMap::new()).unwrap();
        g.create_rel(p, i2, "HAS".into(), BTreeMap::new()).unwrap();
        let c1 = node("City", 1);
        g.create_rel(p, c1, "LIVES".into(), BTreeMap::new())
            .unwrap();
    }
    g.commit_write();

    // WHERE references side A non-join var 'i'
    let query = "MATCH (p:Person)-[:HAS]->(i:Interest), (p)-[:LIVES]->(c:City) \
                 WHERE i.id = 1 \
                 RETURN p.id AS pid, c.id AS cid ORDER BY pid, cid";
    let res = exec_cypher(&g, query);
    let nested_res = with_hash_join_disabled(|| exec_cypher(&g, query));
    assert_eq!(
        res.rows, nested_res.rows,
        "parity when residual references non-join var"
    );
}

#[test]
fn multiplicity_declines_when_downstream_is_fold_or_filter() {
    let g = Graph::default();
    g.begin_write().unwrap();
    let node = |label: &str, id: i64| {
        g.create_node(
            vec![label.into()],
            BTreeMap::from([("id".into(), Value::Int(id))]),
        )
        .unwrap()
    };
    let persons: Vec<_> = (0..200).map(|i| node("Person", i as i64)).collect();
    for &p in &persons {
        let i1 = node("Interest", 1);
        let c1 = node("City", 1);
        g.create_rel(p, i1, "HAS".into(), BTreeMap::new()).unwrap();
        g.create_rel(p, c1, "LIVES".into(), BTreeMap::new())
            .unwrap();
    }
    g.commit_write();

    // Downstream aggregation fold reads side A's non-join var 'i'
    let query = "MATCH (p:Person)-[:HAS]->(i:Interest), (p)-[:LIVES]->(c:City) \
                 RETURN p.id AS pid, count(i) AS cnt ORDER BY pid";
    let res = exec_cypher(&g, query);
    let nested_res = with_hash_join_disabled(|| exec_cypher(&g, query));
    assert_eq!(
        res.rows, nested_res.rows,
        "parity when downstream folds non-join var"
    );
}

#[test]
fn profile_limit_reports_hash_join_metrics() {
    let g = build_multi_hop_graph(20, 8);
    let query = "MATCH (a:A)-[:RA]->(b:B)-[:RAB]->(h:H), (c:C)-[:RC]->(d:D)-[:RCD]->(h) \
                 RETURN h.id AS hub, a.id AS aid, c.id AS cid ORDER BY hub, aid, cid";
    let _ = take_hash_join_engagements();
    let records = profiled(&g, query);
    assert_eq!(take_hash_join_engagements(), 1, "hash join engaged");
    let hj_rec = records.iter().find(|r| r.hash_join.build_rows > 0);
    assert!(
        hj_rec.is_some(),
        "PROFILE records contain hash_join metrics"
    );
    let hj = hj_rec.unwrap().hash_join;
    assert_eq!(hj.build_rows, 160);
}

#[test]
fn the_join_streams_a_fan_out_independent_of_the_hub_index() {
    use crate::ctx::ExecCtx;
    use crate::exec::batch_tail::BATCH_ROWS;
    use crate::exec::hash_join::try_hash_join;
    use crate::exec::pattern_policies::Matched;
    use crate::exec::pushdown::Residual;
    use crate::exec::test_support::{build, clauses_of};
    use crate::overlay::ExecGraph;
    use crate::row::{Row, RowNames};
    use crate::UsedSet;
    use relate_core::tokens::{workspace_meter, LedgerGuard};
    use relate_ir::{Clause, MatchMode, PathPattern};

    const SIDE_A_ROWS: usize = 128;
    const SIDE_B_ROWS: usize = 32;

    let measure = |hubs: usize| -> (usize, u64) {
        assert_eq!(SIDE_A_ROWS % hubs, 0);
        let mut labels: Vec<&[&str]> = vec![&["H"][..]; hubs];
        labels.resize(hubs + SIDE_B_ROWS, &["B"][..]);
        let rels: Vec<(usize, usize, &str)> = (0..SIDE_B_ROWS)
            .map(|b| (hubs + b, b % hubs, "RB"))
            .collect();
        let built = build(&labels, &rels);
        let view = ExecGraph::read(&built.graph);
        let params = BTreeMap::new();
        let ctx = ExecCtx::new(&view, &params);
        let clauses = clauses_of("MATCH (a:A)-[:RA]->(h:H), (b:B)-[:RB]->(h) RETURN count(*) AS c");
        let patterns: Vec<PathPattern> = match clauses.into_iter().next() {
            Some(Clause::Match { patterns, .. }) => patterns,
            _ => panic!("the fixture opens with the comma-pair MATCH"),
        };
        let names = RowNames::new(&["h".to_string()]);
        let a_rows: Matched = (0..SIDE_A_ROWS)
            .map(|i| {
                let hub = built.nodes[i % hubs];
                (
                    Row::from_names(&names, vec![view.node_value(hub)]),
                    UsedSet::default(),
                )
            })
            .collect();
        let base = Row::new();
        let residual = Residual::empty();
        let mut ledger = crate::test_support::roomy_ledger();
        let guard = LedgerGuard::install(&mut ledger);
        let _ = take_hash_join_engagements();
        let mut stream = try_hash_join(
            ctx,
            &patterns,
            MatchMode::DifferentRelationships,
            &base,
            &a_rows,
            &residual,
        )
        .expect("the join runs infallibly")
        .expect("the join takes the pair");
        assert_eq!(take_hash_join_engagements(), 1, "the join engaged");
        assert!(!stream.is_held(), "the join hands back a produced stream");
        assert!(stream.probe().is_empty(), "no merged row is in hand");
        let mut rows = 0usize;
        while let Some(batch) = stream.next_batch().expect("the join is infallible") {
            let count = batch.into_iter().count();
            assert!(count <= BATCH_ROWS, "a batch is bounded");
            rows += count;
        }
        let (_, peak, _) = workspace_meter().expect("a ledger is installed");
        drop(guard);
        (rows, peak)
    };

    let (four_hubs, at_four_hubs) = measure(4);
    let (one_hub, at_one_hub) = measure(1);
    assert_eq!(four_hubs, SIDE_A_ROWS * SIDE_B_ROWS / 4);
    assert_eq!(one_hub, SIDE_A_ROWS * SIDE_B_ROWS);
    assert!(at_four_hubs > 0, "the side-A index is charged");
    assert!(
        at_one_hub <= at_four_hubs,
        "the fan-out per hub grew 4x ({four_hubs} -> {one_hub} rows) \
         but the retained total rose: {at_one_hub} vs {at_four_hubs}"
    );
}