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
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
//! Junction-split HashJoin and SemiMask SIP operator over Var-Length / Frontier NFA legs.
//!
//! Splits a single path pattern at junction node `c` separating a fixed leg `L_fixed`
//! and a var-length/QPP leg `L_var`. Depending on which leg is selective, builds a
//! charged [`JunctionBuildTable`] keyed on `c` and streams the probe leg directly into
//! the output sink without uncharged intermediate row buffers (ADR-0555, ADR-0737).

use std::collections::HashSet;
use std::rc::Rc;

use relate_core::{NodeId, Result};
use relate_ir::{path_pattern_vars, Expr, MatchMode, PathPattern};
use relate_names::SmallName;
use relate_planner::{
    can_reverse_varlen_leg, detect_junction_split, junction_legs_have_cross_inline_refs,
    reverse_varlen_leg, split_junction_legs, MatchStrategy,
};

use crate::ctx::ExecCtx;
use crate::exec::expand::match_resolved_path;
use crate::exec::graph_stats::{element_estimate, GraphStats};
use crate::exec::match_clause::MatchClauseInputs;
use crate::exec::one_path::{match_one_path, PathFilters};
use crate::exec::pattern_policies::{MatchReduce, MatchTail};
use crate::exec::profiling::count_hash_join;
use crate::exec::pushdown::{flatten_and_owned, match_scope, MatchCap, Residual};
use crate::exec::rider::{BindingSink, Rider};
use crate::exec::sink::SinkProjection;
use crate::hash_seed::IdMap;
use crate::overlay::{ExecGraph, RetainedTotal};
use crate::pattern_walk::UsedRels;
use crate::row::Row;
use crate::UsedSet;

use super::semi_mask::SemiMask;
use super::{downstream_projection, internal_vars_unused_downstream, min_side_rows, row_node_id};

/// Check if relationship types between two legs are explicit, non-empty, and disjoint.
fn legs_rel_types_disjoint(fixed: &PathPattern, var: &PathPattern) -> bool {
    let mut fixed_types = HashSet::new();
    for r in &fixed.rels {
        if r.types.is_empty() || r.type_expr.is_some() {
            return false;
        }
        for name in r.type_names() {
            fixed_types.insert(name);
        }
    }
    let mut var_types = HashSet::new();
    for r in &var.rels {
        if r.types.is_empty() || r.type_expr.is_some() {
            return false;
        }
        for name in r.type_names() {
            var_types.insert(name);
        }
    }
    fixed_types.is_disjoint(&var_types)
}

fn expr_references_any(expr: &Expr, vars: &HashSet<String>) -> bool {
    let mut used = HashSet::new();
    crate::eval::expr_vars(expr, &mut used);
    used.iter().any(|v| vars.contains(v))
}

fn is_multiplicity_downstream(
    build_leg: &PathPattern,
    junction_var: &SmallName,
    conjuncts: &[Expr],
    projection: Option<&SinkProjection<'_>>,
    reduce: Option<&MatchReduce<'_>>,
) -> bool {
    if build_leg.has_path_name() {
        return false;
    }
    let internal: HashSet<String> = path_pattern_vars(build_leg)
        .filter(|v| *v != junction_var)
        .map(|v| v.to_string())
        .collect();
    internal_vars_unused_downstream(
        &internal,
        conjuncts,
        downstream_projection(projection, reduce),
    )
}

/// Charged hash build table keyed by the junction node id, shared across both
/// build-varlen and build-fixed junction-split orientations.
struct JunctionBuildTable {
    multiplicity_only: bool,
    disjoint_rels: bool,
    counts: IdMap<NodeId, u64>,
    by_key: IdMap<NodeId, Vec<(Row, UsedSet)>>,
    charge: RetainedTotal,
    build_rows: u64,
}

impl JunctionBuildTable {
    fn new(graph: &ExecGraph<'_>, multiplicity_only: bool, disjoint_rels: bool) -> Result<Self> {
        Ok(Self {
            multiplicity_only,
            disjoint_rels,
            counts: IdMap::default(),
            by_key: IdMap::default(),
            charge: graph.retain_bytes(0)?,
            build_rows: 0,
        })
    }

    fn insert(
        &mut self,
        graph: &ExecGraph<'_>,
        key: NodeId,
        row: Row,
        used: UsedSet,
    ) -> Result<()> {
        self.build_rows += 1;
        if self.multiplicity_only {
            let existed = self.counts.contains_key(&key);
            *self.counts.entry(key).or_default() += 1;
            if !existed {
                self.charge
                    .add_bytes(graph, crate::workspace::map_entries_bytes(1))?;
            }
        } else {
            self.charge.add_row(graph, row.values())?;
            let existed = self.by_key.contains_key(&key);
            self.by_key.entry(key).or_default().push((row, used));
            if !existed {
                self.charge
                    .add_bytes(graph, crate::workspace::map_entries_bytes(1))?;
            }
        }
        Ok(())
    }

    fn is_empty(&self) -> bool {
        self.build_rows == 0
    }

    fn distinct_keys(&self) -> Vec<NodeId> {
        if self.multiplicity_only {
            self.counts.keys().copied().collect()
        } else {
            self.by_key.keys().copied().collect()
        }
    }

    fn distinct_len(&self) -> u64 {
        if self.multiplicity_only {
            self.counts.len() as u64
        } else {
            self.by_key.len() as u64
        }
    }

    /// Probe `key` with one matched row from the opposite leg, check relationship
    /// disjointness, merge bindings, and emit through `tail` into `out`.
    /// Returns `Ok(true)` when `cap` is now full.
    fn emit_matches(
        &self,
        graph: &ExecGraph<'_>,
        key: NodeId,
        probe_row: &Row,
        rel_disjoint: impl Fn(&UsedSet) -> bool,
        emit: &mut EmitState<'_, '_, '_>,
    ) -> Result<bool> {
        if self.multiplicity_only {
            if let Some(&count) = self.counts.get(&key) {
                for _ in 0..count {
                    if emit.push(graph, probe_row.clone())? {
                        return Ok(true);
                    }
                }
            }
        } else if let Some(matching_rows) = self.by_key.get(&key) {
            for (b_row, b_used) in matching_rows {
                if !self.disjoint_rels && !rel_disjoint(b_used) {
                    continue;
                }
                let mut merged = probe_row.clone();
                for (k, v) in b_row.iter() {
                    if !merged.contains_key(k) {
                        merged.insert(k.to_string(), v.clone());
                    }
                }
                if emit.push(graph, merged)? {
                    return Ok(true);
                }
            }
        }
        Ok(false)
    }
}

/// Output accumulator shared by both probe sinks, charging every emitted row.
struct EmitState<'out, 'cap, 'tail> {
    tail: MatchTail<'tail>,
    cap: Option<&'out mut MatchCap<'cap>>,
    out: &'out mut Vec<Row>,
    out_charge: RetainedTotal,
}

impl EmitState<'_, '_, '_> {
    fn push(&mut self, graph: &ExecGraph<'_>, row: Row) -> Result<bool> {
        if let Some(finished) = self.tail.finish_row(graph, row, self.cap.as_deref_mut())? {
            self.out_charge.add_row(graph, finished.values())?;
            self.out.push(finished);
            if self.halted() {
                return Ok(true);
            }
        }
        Ok(false)
    }

    fn halted(&self) -> bool {
        self.cap.as_ref().is_some_and(|c| c.full())
    }
}

struct VarlenProbeSink<'a, 'out, 'cap, 'tail> {
    junction_var: &'a SmallName,
    semi_mask: &'a SemiMask,
    table: &'a JunctionBuildTable,
    emit: EmitState<'out, 'cap, 'tail>,
}

impl BindingSink for VarlenProbeSink<'_, '_, '_, '_> {
    fn offer(&mut self, graph: &ExecGraph<'_>, fixed_row: Row, used: &UsedRels) -> Result<()> {
        let c_id = row_node_id(&fixed_row, self.junction_var);
        if !self.semi_mask.contains(c_id) {
            return Ok(());
        }
        let _ = self.table.emit_matches(
            graph,
            c_id,
            &fixed_row,
            |b_used| used.is_disjoint(b_used),
            &mut self.emit,
        )?;
        Ok(())
    }

    fn halted(&self) -> bool {
        self.emit.halted()
    }
}

/// Bundled state for one validated junction-split execution.
struct JunctionSplitJob<'a, 'cap, 'cap_data, 'proj, 'red> {
    ctx: ExecCtx<'a>,
    fixed_leg: PathPattern,
    var_leg: PathPattern,
    fixed_on_left: bool,
    junction_var: &'a SmallName,
    match_mode: MatchMode,
    disjoint_rels: bool,
    conjuncts: Vec<Expr>,
    fixed_conjuncts: Vec<Expr>,
    var_conjuncts: Vec<Expr>,
    cap: Option<&'cap mut MatchCap<'cap_data>>,
    projection: Option<&'proj SinkProjection<'proj>>,
    reduce: Option<&'red MatchReduce<'red>>,
}

impl JunctionSplitJob<'_, '_, '_, '_, '_> {
    /// Build the selective `fixed_leg` into a charged [`JunctionBuildTable`],
    /// then stream `var_leg` exclusively from the matched junction nodes.
    fn exec_build_fixed(mut self, seed_input: &Row, out: &mut Vec<Row>) -> Result<bool> {
        let unbound = |_: &str| false;
        if !self.fixed_on_left {
            if !can_reverse_varlen_leg(&self.var_leg, &unbound) {
                return Ok(false);
            }
            reverse_varlen_leg(&mut self.var_leg);
        }

        let stats = GraphStats::new(self.ctx.graph.base(), self.ctx.params);
        let last_fixed = self.fixed_leg.nodes.len() - 1;
        let est0 = element_estimate(
            &stats,
            &self.fixed_leg,
            &unbound,
            self.fixed_conjuncts.iter(),
            0,
        );
        let est1 = element_estimate(
            &stats,
            &self.fixed_leg,
            &unbound,
            self.fixed_conjuncts.iter(),
            last_fixed,
        );
        if est1.rows < est0.rows && relate_planner::can_reverse_path(&self.fixed_leg, &unbound) {
            relate_planner::reverse_path(&mut self.fixed_leg);
        }

        let multiplicity_only = self.disjoint_rels
            && is_multiplicity_downstream(
                &self.fixed_leg,
                self.junction_var,
                &self.conjuncts,
                self.projection,
                self.reduce,
            );
        let mut table =
            JunctionBuildTable::new(self.ctx.graph, multiplicity_only, self.disjoint_rels)?;

        let fixed_filters = PathFilters::resolve(self.ctx.graph, &self.fixed_leg, self.match_mode);
        let fixed_patterns = [self.fixed_leg.clone()];
        let fixed_scope = match_scope(self.ctx.graph, seed_input, &fixed_patterns);
        let fixed_residual = Residual {
            conjuncts: &self.fixed_conjuncts,
            scope: &fixed_scope,
        };
        let junction_var = self.junction_var;
        let graph = self.ctx.graph;
        let mut build_sink = |row: Row, used: UsedSet| -> Result<bool> {
            let key = row_node_id(&row, junction_var);
            table.insert(graph, key, row, used)?;
            Ok(false)
        };
        let mut build_rider = Rider::Stream(&mut build_sink);
        let _ = match_one_path(
            self.ctx,
            &self.fixed_leg,
            &fixed_filters,
            seed_input.clone(),
            UsedSet::default(),
            self.match_mode,
            &fixed_residual,
            Some(&mut build_rider),
            MatchTail::Carry,
        )?;

        #[cfg(test)]
        super::HASH_JOIN_ENGAGED.with(|c| c.set(c.get() + 1));

        if table.is_empty() {
            count_hash_join(crate::metrics::HashJoinCounters {
                build_rows: 0,
                probe_rows: 0,
                semi_mask_rejected: 0,
            });
            return Ok(true);
        }

        let junction_ids = table.distinct_keys();
        let var_filters = PathFilters::resolve(self.ctx.graph, &self.var_leg, self.match_mode);
        let var_patterns = [self.var_leg.clone()];
        let mut emit = EmitState {
            tail: MatchTail::Finish {
                reduce: self.reduce,
            },
            cap: self.cap,
            out,
            out_charge: self.ctx.graph.retain_bytes(0)?,
        };
        let mut probe_rows: u64 = 0;

        for junction_id in junction_ids {
            self.ctx.graph.cancel_tick()?;
            if emit.halted() {
                break;
            }
            let mut seed_row = seed_input.clone();
            seed_row.insert(
                self.junction_var.to_string(),
                self.ctx.graph.node_value(junction_id),
            );
            let var_scope = match_scope(self.ctx.graph, &seed_row, &var_patterns);
            let var_residual = Residual {
                conjuncts: &self.var_conjuncts,
                scope: &var_scope,
            };
            let mut probe_sink = |v_row: Row, v_used: UsedSet| -> Result<bool> {
                probe_rows += 1;
                table.emit_matches(
                    graph,
                    junction_id,
                    &v_row,
                    |f_used| v_used.is_disjoint(f_used),
                    &mut emit,
                )
            };
            let mut probe_rider = Rider::Stream(&mut probe_sink);
            let _ = match_one_path(
                self.ctx,
                &self.var_leg,
                &var_filters,
                seed_row,
                UsedSet::default(),
                self.match_mode,
                &var_residual,
                Some(&mut probe_rider),
                MatchTail::Carry,
            )?;
        }

        count_hash_join(crate::metrics::HashJoinCounters {
            build_rows: table.build_rows,
            probe_rows,
            semi_mask_rejected: 0,
        });
        Ok(true)
    }

    /// Build `var_leg` into a charged [`JunctionBuildTable`] + [`SemiMask`],
    /// then stream `fixed_leg` over `rows` probing the table.
    fn exec_build_varlen(self, rows: &[Row], out: &mut Vec<Row>) -> Result<bool> {
        let fixed_filters = PathFilters::resolve(self.ctx.graph, &self.fixed_leg, self.match_mode);
        let PathFilters::Classic { rels, plans } = &fixed_filters else {
            return Ok(false);
        };

        let multiplicity_only = self.disjoint_rels
            && is_multiplicity_downstream(
                &self.var_leg,
                self.junction_var,
                &self.conjuncts,
                self.projection,
                self.reduce,
            );
        let mut table =
            JunctionBuildTable::new(self.ctx.graph, multiplicity_only, self.disjoint_rels)?;

        let var_filters = PathFilters::resolve(self.ctx.graph, &self.var_leg, self.match_mode);
        let var_patterns = [self.var_leg.clone()];
        let var_scope = match_scope(self.ctx.graph, &Row::new(), &var_patterns);
        let var_residual = Residual {
            conjuncts: &self.var_conjuncts,
            scope: &var_scope,
        };
        let junction_var = self.junction_var;
        let graph = self.ctx.graph;
        let mut build_sink = |row: Row, used: UsedSet| -> Result<bool> {
            let key = row_node_id(&row, junction_var);
            table.insert(graph, key, row, used)?;
            Ok(false)
        };
        let mut build_rider = Rider::Stream(&mut build_sink);
        let _ = match_one_path(
            self.ctx,
            &self.var_leg,
            &var_filters,
            Row::new(),
            UsedSet::default(),
            self.match_mode,
            &var_residual,
            Some(&mut build_rider),
            MatchTail::Carry,
        )?;

        if table.is_empty() {
            count_hash_join(crate::metrics::HashJoinCounters {
                build_rows: 0,
                probe_rows: rows.len() as u64,
                semi_mask_rejected: 0,
            });
            return Ok(true);
        }

        #[cfg(test)]
        super::HASH_JOIN_ENGAGED.with(|c| c.set(c.get() + 1));

        let ids = table.distinct_keys();
        let semi_mask = Rc::new(SemiMask::from_rows(&ids, |id| **id)?);

        let fixed_patterns = [self.fixed_leg.clone()];
        let fixed_scope = match_scope(self.ctx.graph, &Row::new(), &fixed_patterns);
        let fixed_residual = Residual {
            conjuncts: &self.fixed_conjuncts,
            scope: &fixed_scope,
        };

        let mut sink = VarlenProbeSink {
            junction_var: self.junction_var,
            semi_mask: &semi_mask,
            table: &table,
            emit: EmitState {
                tail: MatchTail::Finish {
                    reduce: self.reduce,
                },
                cap: self.cap,
                out,
                out_charge: self.ctx.graph.retain_bytes(0)?,
            },
        };

        for row in rows {
            self.ctx.graph.cancel_tick()?;
            if sink.halted() {
                break;
            }
            match_resolved_path(
                self.ctx,
                &self.fixed_leg,
                rels,
                plans,
                &fixed_residual,
                row.clone(),
                UsedSet::default(),
                &mut sink,
            )?;
        }

        count_hash_join(crate::metrics::HashJoinCounters {
            build_rows: table.distinct_len(),
            probe_rows: rows.len() as u64,
            semi_mask_rejected: semi_mask.rejected(),
        });
        Ok(true)
    }
}

/// Attempt to engage junction-split HashJoin + SemiMask over a mixed fixed+varlen pattern.
pub(crate) fn try_junction_split_hash_join(
    ctx: ExecCtx<'_>,
    rows: &[Row],
    clause: MatchClauseInputs<'_>,
    cap: Option<&mut MatchCap<'_>>,
    projection: Option<&SinkProjection<'_>>,
    reduce: Option<&MatchReduce<'_>>,
    planned_strategy: Option<MatchStrategy>,
) -> Result<Option<Vec<Row>>> {
    let MatchClauseInputs {
        optional,
        match_mode,
        patterns,
        where_clause,
    } = clause;

    if optional || patterns.len() != 1 || rows.is_empty() {
        return Ok(None);
    }
    if match_mode == MatchMode::RepeatableElements {
        return Ok(None);
    }

    #[cfg(test)]
    if super::HASH_JOIN_DISABLED.with(std::cell::Cell::get) {
        return Ok(None);
    }

    let pattern = &patterns[0];
    if let Some(w) = where_clause {
        let pat_vars: HashSet<String> = path_pattern_vars(pattern).map(|v| v.to_string()).collect();
        if !relate_ir::all_vars_satisfy(w, |v| pat_vars.contains(v)) {
            return Ok(None);
        }
    }

    let Some(split) = detect_junction_split(pattern) else {
        return Ok(None);
    };

    let junction_var = pattern.nodes[split.index]
        .variable
        .as_ref()
        .expect("detect_junction_split guarantees a named junction node");
    let (fixed_leg, var_leg) = split_junction_legs(pattern, split);

    let fixed_vars: HashSet<String> = path_pattern_vars(&fixed_leg)
        .filter(|v| *v != junction_var)
        .map(|v| v.to_string())
        .collect();
    let var_vars: HashSet<String> = path_pattern_vars(&var_leg)
        .filter(|v| *v != junction_var)
        .map(|v| v.to_string())
        .collect();

    if junction_legs_have_cross_inline_refs(&fixed_leg, &var_leg, &fixed_vars, &var_vars) {
        return Ok(None);
    }

    let conjuncts = where_clause.map(flatten_and_owned).unwrap_or_default();
    for c in &conjuncts {
        if expr_references_any(c, &var_vars) && expr_references_any(c, &fixed_vars) {
            return Ok(None);
        }
    }

    for r in rows {
        for v in &var_vars {
            if r.get_name(&SmallName::from(v.as_str())).is_some() {
                return Ok(None);
            }
        }
    }

    let var_conjuncts: Vec<Expr> = conjuncts
        .iter()
        .filter(|c| !expr_references_any(c, &fixed_vars))
        .cloned()
        .collect();
    let fixed_conjuncts: Vec<Expr> = conjuncts
        .iter()
        .filter(|c| !expr_references_any(c, &var_vars))
        .cloned()
        .collect();
    let disjoint_rels = legs_rel_types_disjoint(&fixed_leg, &var_leg);

    let job = JunctionSplitJob {
        ctx,
        fixed_leg,
        var_leg,
        fixed_on_left: split.fixed_on_left,
        junction_var,
        match_mode,
        disjoint_rels,
        conjuncts,
        fixed_conjuncts,
        var_conjuncts,
        cap,
        projection,
        reduce,
    };

    let planner_selected = planned_strategy == Some(MatchStrategy::HashJoinJunctionSplit);
    if planner_selected
        && rows.len() == 1
        && rows[0].get_name(junction_var).is_none()
        && !fixed_vars
            .iter()
            .any(|v| rows[0].get_name(&SmallName::from(v.as_str())).is_some())
    {
        let mut out = Vec::new();
        return Ok(job.exec_build_fixed(&rows[0], &mut out)?.then_some(out));
    }

    #[cfg(test)]
    let forced = super::HASH_JOIN_FORCED.with(std::cell::Cell::get);
    #[cfg(not(test))]
    let forced = false;

    if !forced && rows.len() < min_side_rows() {
        return Ok(None);
    }

    let mut out = Vec::new();
    Ok(job.exec_build_varlen(rows, &mut out)?.then_some(out))
}