Skip to main content

relate_planner/order/
strategy.rs

1//! Cost-based physical `MatchStrategy` selection for `MATCH` clauses (ADR-0737).
2//!
3//! Runs in `relate-planner` after `MATCH` rewrites and pattern ordering, using
4//! `PatternStats` to choose between composable physical operators:
5//! - `HashJoinJunctionSplit` vs `FrontierNfa` on mixed fixed+varlen patterns,
6//! - `HashJoinCrossClause` vs `MorselPipeline` across `MATCH ... WITH ... MATCH`,
7//! - `HashJoinTwoPattern` vs `MorselPipeline`/`Walker` on two-pattern joins,
8//! - `MorselPipeline` / `FrontierNfa` / `Walker` on remaining shapes.
9
10use std::collections::{BTreeMap, HashSet};
11
12use relate_ir::{is_agg_expr, path_pattern_vars, Clause, Expr, MatchMode, PathPattern, Projection};
13use relate_names::SmallName;
14
15use crate::stats::PatternStats;
16
17use super::estimate::{endpoint_estimate, where_conjuncts_of, Basis, Estimate};
18use super::junction::junction_split_pays;
19use super::{
20    apply_degree, apply_hop_bound, can_reverse_path, direction_cost, seed_on_rel_start, seed_rows,
21    walk_cost,
22};
23
24/// Minimum side-A / incoming row count before a hash join pays for itself.
25pub const HASH_JOIN_MIN_SIDE_ROWS: u128 = 128;
26
27/// Unmeasured cost margin gate against guess prices in two-pattern joins.
28const HASH_JOIN_GUESS_MARGIN: u128 = 2;
29
30/// Planner-selected physical execution strategy for one `MATCH` clause.
31#[derive(Debug, Clone, Copy, PartialEq, Eq)]
32pub enum MatchStrategy {
33    /// Fixed-length single-pattern morsel pipeline or batched scan/expand.
34    MorselPipeline,
35    /// Frontier NFA breadth-first traversal for variable-length / quantified patterns.
36    FrontierNfa,
37    /// Two-pattern hash join over shared node variable(s) (`MATCH (a)--(h), (b)--(h)`).
38    HashJoinTwoPattern,
39    /// Cross-clause hash join with SemiMask SIP across `MATCH ... WITH ... MATCH`.
40    HashJoinCrossClause,
41    /// Junction-split hash join separating a selective fixed leg from a var-length/QPP leg.
42    HashJoinJunctionSplit,
43    /// Per-row pattern walker (OPTIONAL, SEARCH, REPEATABLE ELEMENTS, shortestPath,
44    /// multi-pattern cartesian, or complex GPM).
45    Walker,
46}
47
48impl MatchStrategy {
49    /// Canonical display name rendered in `EXPLAIN` plan details.
50    pub fn as_str(self) -> &'static str {
51        match self {
52            Self::MorselPipeline => "MorselPipeline",
53            Self::FrontierNfa => "FrontierNfa",
54            Self::HashJoinTwoPattern => "HashJoinTwoPattern",
55            Self::HashJoinCrossClause => "HashJoinCrossClause",
56            Self::HashJoinJunctionSplit => "HashJoinJunctionSplit",
57            Self::Walker => "Walker",
58        }
59    }
60}
61
62/// Which endpoint of a cross-clause pattern is cheaper to scan from.
63#[derive(Clone, Copy, Debug, PartialEq, Eq)]
64pub enum CrossClauseSearchEnd {
65    Start,
66    End,
67}
68
69impl CrossClauseSearchEnd {
70    /// Whether the pattern should be reversed to start from the cheaper end.
71    pub fn should_reverse(self) -> bool {
72        matches!(self, Self::End)
73    }
74}
75
76/// Result of pricing a cross-clause `MATCH` pattern against nested-loop re-expansion.
77#[derive(Clone, Copy, Debug, PartialEq, Eq)]
78pub struct CrossClauseCost {
79    pub cheapest_end: CrossClauseSearchEnd,
80    pub pays: bool,
81}
82
83/// Canonical cost helper for cross-clause HashJoin vs nested-loop expansion.
84///
85/// Compares scanning `pat` once from its cheapest measured unshared endpoint plus
86/// streaming `row_count` probe rows against expanding `pat` per input row.
87pub fn evaluate_cross_clause_cost(
88    pat: &PathPattern,
89    shared_vars: &[&SmallName],
90    where_conjuncts: &[&Expr],
91    row_count: u128,
92    stats: &dyn PatternStats,
93) -> CrossClauseCost {
94    let per_row = per_row_expand_cost(pat, shared_vars, stats);
95    let nested_cost = per_row.saturating_mul(row_count);
96
97    let unbound = |_: &str| false;
98    let last = pat.nodes.len() - 1;
99    let est0 = endpoint_estimate(
100        &pat.nodes[0],
101        &unbound,
102        where_conjuncts.iter().copied(),
103        stats,
104    );
105    let est1 = endpoint_estimate(
106        &pat.nodes[last],
107        &unbound,
108        where_conjuncts.iter().copied(),
109        stats,
110    );
111
112    let rows0 = seed_rows(est0);
113    let rows1 = seed_rows(est1);
114    let can_reverse = can_reverse_path(pat, &unbound);
115    let cheapest_end = if can_reverse && rows1 < rows0 {
116        CrossClauseSearchEnd::End
117    } else {
118        CrossClauseSearchEnd::Start
119    };
120
121    let is_shared_0 = pat.nodes[0]
122        .variable
123        .as_ref()
124        .is_some_and(|v| shared_vars.contains(&v));
125    let is_shared_1 = pat.nodes[last]
126        .variable
127        .as_ref()
128        .is_some_and(|v| shared_vars.contains(&v));
129
130    let unshared_selective = [
131        (!is_shared_0, est0, rows0),
132        (can_reverse && !is_shared_1, est1, rows1),
133    ]
134    .into_iter()
135    .filter(|(eligible, est, _)| *eligible && !matches!(est.basis(), Basis::Rank))
136    .min_by_key(|(_, _, rows)| *rows)
137    .map(|(_, _, rows)| rows);
138
139    let pays = unshared_selective
140        .is_some_and(|build_rows| build_rows.saturating_add(row_count) <= nested_cost);
141
142    CrossClauseCost { cheapest_end, pays }
143}
144
145fn per_row_expand_cost(
146    pat: &PathPattern,
147    shared_vars: &[&SmallName],
148    stats: &dyn PatternStats,
149) -> u128 {
150    if pat.rels.is_empty() {
151        return 1;
152    }
153    let last = pat.nodes.len() - 1;
154    let shared_at_start = pat.nodes[0]
155        .variable
156        .as_ref()
157        .is_some_and(|v| shared_vars.contains(&v));
158    let shared_at_end = pat.nodes[last]
159        .variable
160        .as_ref()
161        .is_some_and(|v| shared_vars.contains(&v));
162
163    let (start_node, rel, seed_is_start, other_node) = if shared_at_start {
164        (
165            &pat.nodes[0],
166            &pat.rels[0],
167            seed_on_rel_start(&pat.rels[0], false),
168            &pat.nodes[1],
169        )
170    } else if shared_at_end {
171        let r = &pat.rels[last - 1];
172        (
173            &pat.nodes[last],
174            r,
175            seed_on_rel_start(r, true),
176            &pat.nodes[last - 1],
177        )
178    } else {
179        (
180            &pat.nodes[0],
181            &pat.rels[0],
182            seed_on_rel_start(&pat.rels[0], false),
183            &pat.nodes[1],
184        )
185    };
186
187    let deg = apply_hop_bound(1, start_node, rel, seed_is_start, stats);
188    if deg > 1 {
189        return deg;
190    }
191    apply_degree(1, other_node, rel, seed_is_start, stats).max(1)
192}
193
194/// Populate the per-`(part_idx, clause_idx)` `MatchStrategy` map for one stage's parts.
195pub(crate) fn plan_match_strategies(
196    parts: &[Vec<Clause>],
197    stats: &dyn PatternStats,
198) -> BTreeMap<(usize, usize), MatchStrategy> {
199    let mut strategies = BTreeMap::new();
200    for (part_idx, clauses) in parts.iter().enumerate() {
201        plan_part_strategies(part_idx, clauses, stats, &mut strategies);
202    }
203    strategies
204}
205
206fn plan_part_strategies(
207    part_idx: usize,
208    clauses: &[Clause],
209    stats: &dyn PatternStats,
210    out: &mut BTreeMap<(usize, usize), MatchStrategy>,
211) {
212    let mut scope: Vec<String> = Vec::new();
213    let mut bound: HashSet<String> = HashSet::new();
214    let mut est_rows: Option<u128> = Some(1);
215
216    for (clause_idx, clause) in clauses.iter().enumerate() {
217        if let Clause::Match {
218            optional,
219            match_mode,
220            patterns,
221            where_clause,
222            search,
223            ..
224        } = clause
225        {
226            let strategy = select_match_strategy(
227                *optional,
228                *match_mode,
229                patterns,
230                where_clause.as_ref(),
231                search.is_some(),
232                &bound,
233                est_rows,
234                stats,
235            );
236            out.insert((part_idx, clause_idx), strategy);
237        }
238        est_rows = advance_est_rows(clause, &bound, est_rows, stats);
239        let introduced = crate::rewrite::bindings_of(clause, &scope);
240        crate::rewrite::advance_scope(&mut scope, &mut bound, clause, &introduced);
241    }
242}
243
244#[allow(clippy::too_many_arguments)]
245fn select_match_strategy(
246    optional: bool,
247    match_mode: MatchMode,
248    patterns: &[PathPattern],
249    where_clause: Option<&Expr>,
250    has_search: bool,
251    bound: &HashSet<String>,
252    est_input_rows: Option<u128>,
253    stats: &dyn PatternStats,
254) -> MatchStrategy {
255    if optional || has_search || patterns.is_empty() {
256        return MatchStrategy::Walker;
257    }
258
259    let has_varlen = patterns
260        .iter()
261        .any(|p| p.rels.iter().any(|r| r.var_length || r.quantified));
262
263    if match_mode == MatchMode::RepeatableElements {
264        return if has_varlen && patterns.len() == 1 && !patterns[0].is_shortest_path_function {
265            MatchStrategy::FrontierNfa
266        } else {
267            MatchStrategy::Walker
268        };
269    }
270
271    if patterns.iter().any(|p| p.is_shortest_path_function) {
272        return MatchStrategy::Walker;
273    }
274
275    let conjuncts = where_conjuncts_of(where_clause);
276
277    // 1. Mixed fixed + varlen single pattern: cost-based JunctionSplit vs FrontierNfa.
278    // Align row-count eligibility with the executor's build-fixed (1 row) and
279    // build-varlen (>= HASH_JOIN_MIN_SIDE_ROWS) entry points so EXPLAIN never
280    // promises a junction split that 2..127 rows would decline at runtime.
281    if patterns.len() == 1 && has_varlen {
282        let rows_eligible = est_input_rows.is_none_or(|r| r == 1 || r >= HASH_JOIN_MIN_SIDE_ROWS);
283        if rows_eligible && junction_split_pays(&patterns[0], &conjuncts, bound, stats) {
284            return MatchStrategy::HashJoinJunctionSplit;
285        }
286        return MatchStrategy::FrontierNfa;
287    }
288
289    // 2. Multi-pattern two-way join: cost-based HashJoinTwoPattern vs Walker.
290    if patterns.len() == 2 {
291        if two_pattern_hash_join_pays(patterns, &conjuncts, bound, stats) {
292            return MatchStrategy::HashJoinTwoPattern;
293        }
294        return MatchStrategy::Walker;
295    }
296
297    if patterns.len() > 2 {
298        return MatchStrategy::Walker;
299    }
300
301    let pat = &patterns[0];
302    if pat.needs_gpm() {
303        return MatchStrategy::Walker;
304    }
305
306    // 3. Cross-clause HashJoin across MATCH ... WITH ... MATCH.
307    if let Some(input_rows) = est_input_rows {
308        if cross_clause_hash_join_pays(pat, &conjuncts, bound, input_rows, stats) {
309            return MatchStrategy::HashJoinCrossClause;
310        }
311    }
312
313    MatchStrategy::MorselPipeline
314}
315
316fn cross_clause_hash_join_pays(
317    pat: &PathPattern,
318    conjuncts: &[&Expr],
319    bound: &HashSet<String>,
320    input_rows: u128,
321    stats: &dyn PatternStats,
322) -> bool {
323    if input_rows < HASH_JOIN_MIN_SIDE_ROWS {
324        return false;
325    }
326    if pat.nodes.len() < 2
327        || pat.rels.is_empty()
328        || pat.rels.len() != pat.nodes.len() - 1
329        || pat.is_shortest_path_function
330        || pat.needs_gpm()
331    {
332        return false;
333    }
334    if pat.rels.iter().any(|r| {
335        r.var_length
336            || r.quantified
337            || r.variable
338                .as_ref()
339                .is_some_and(|v| v.with_str(|s| bound.contains(s)))
340    }) {
341        return false;
342    }
343    let pat_vars: HashSet<String> = path_pattern_vars(pat).map(|v| v.to_string()).collect();
344    if conjuncts
345        .iter()
346        .any(|c| !relate_ir::all_vars_satisfy(c, |v| pat_vars.contains(v)))
347    {
348        return false;
349    }
350    let mut shared: Vec<&SmallName> = Vec::new();
351    for n in &pat.nodes {
352        if let Some(v) = &n.variable {
353            if v.with_str(|s| bound.contains(s)) && !shared.contains(&v) {
354                shared.push(v);
355            }
356        }
357    }
358    if shared.is_empty() {
359        return false;
360    }
361    shared.sort();
362    evaluate_cross_clause_cost(pat, &shared, conjuncts, input_rows, stats).pays
363}
364
365fn two_pattern_hash_join_pays(
366    patterns: &[PathPattern],
367    conjuncts: &[&Expr],
368    bound: &HashSet<String>,
369    stats: &dyn PatternStats,
370) -> bool {
371    if patterns.len() != 2 {
372        return false;
373    }
374    for p in patterns {
375        if p.nodes.len() < 2
376            || p.rels.is_empty()
377            || p.rels.len() != p.nodes.len() - 1
378            || p.is_shortest_path_function
379            || p.needs_gpm()
380            || p.rels.iter().any(|r| r.var_length || r.quantified)
381        {
382            return false;
383        }
384        if path_pattern_vars(p).any(|v| v.with_str(|s| bound.contains(s))) {
385            return false;
386        }
387    }
388
389    let a_nodes: HashSet<&SmallName> = patterns[0]
390        .nodes
391        .iter()
392        .filter_map(|n| n.variable.as_ref())
393        .collect();
394    let b_nodes: HashSet<&SmallName> = patterns[1]
395        .nodes
396        .iter()
397        .filter_map(|n| n.variable.as_ref())
398        .collect();
399    let mut shared_nodes: Vec<&SmallName> = a_nodes.intersection(&b_nodes).copied().collect();
400    if shared_nodes.is_empty() {
401        return false;
402    }
403
404    let a_rels: HashSet<&SmallName> = patterns[0]
405        .rels
406        .iter()
407        .filter_map(|r| r.variable.as_ref())
408        .collect();
409    let b_rels: HashSet<&SmallName> = patterns[1]
410        .rels
411        .iter()
412        .filter_map(|r| r.variable.as_ref())
413        .collect();
414    if a_rels.intersection(&b_rels).next().is_some() {
415        return false;
416    }
417    shared_nodes.sort();
418
419    let unbound = |_: &str| false;
420    let side_a = direction_cost(&patterns[0], false, &unbound, conjuncts, stats);
421    if matches!(side_a.basis, Basis::Rank) || side_a.walked < HASH_JOIN_MIN_SIDE_ROWS {
422        return false;
423    }
424
425    let side_b = &patterns[1];
426    let per_row = per_row_expand_cost(side_b, &shared_nodes, stats);
427    let nested_cost = per_row.saturating_mul(side_a.walked);
428
429    let last = side_b.nodes.len() - 1;
430    let est0 = endpoint_estimate(&side_b.nodes[0], &unbound, conjuncts.iter().copied(), stats);
431    let est1 = endpoint_estimate(
432        &side_b.nodes[last],
433        &unbound,
434        conjuncts.iter().copied(),
435        stats,
436    );
437    let can_rev = can_reverse_path(side_b, &unbound);
438    let (best_est, best_rows) = if can_rev && seed_rows(est1) < seed_rows(est0) {
439        (est1, seed_rows(est1))
440    } else {
441        (est0, seed_rows(est0))
442    };
443
444    if matches!(best_est.basis(), Basis::Rank) {
445        best_rows.saturating_mul(HASH_JOIN_GUESS_MARGIN) <= nested_cost
446    } else {
447        best_rows.saturating_add(side_a.walked) <= nested_cost
448    }
449}
450
451fn advance_est_rows(
452    clause: &Clause,
453    bound: &HashSet<String>,
454    est_rows: Option<u128>,
455    stats: &dyn PatternStats,
456) -> Option<u128> {
457    match clause {
458        Clause::Match {
459            optional,
460            patterns,
461            where_clause,
462            ..
463        } => {
464            let conjuncts = where_conjuncts_of(where_clause.as_ref());
465            let mut rows = est_rows?;
466            let mut local_bound = bound.clone();
467            for pat in patterns {
468                let bound_fn = |name: &str| local_bound.contains(name);
469                let pat_rows = estimate_pattern_rows(pat, &bound_fn, &conjuncts, rows, stats)?;
470                rows = if *optional {
471                    rows.max(pat_rows)
472                } else {
473                    pat_rows
474                };
475                for v in path_pattern_vars(pat) {
476                    local_bound.insert(v.to_string());
477                }
478            }
479            Some(rows)
480        }
481        Clause::With {
482            items,
483            group_by,
484            limit,
485            ..
486        } => {
487            let mut rows = if is_ungrouped_agg(items, group_by.as_deref()) {
488                Some(1)
489            } else {
490                est_rows
491            };
492            if let Some(Expr::Int(n)) = limit {
493                if *n >= 0 {
494                    let lim = *n as u128;
495                    rows = Some(rows.map_or(lim, |r| r.min(lim)));
496                }
497            }
498            rows
499        }
500        Clause::Unwind { expression, .. } => {
501            let base = est_rows?;
502            match expression {
503                Expr::List(items) => Some(base.saturating_mul(items.len() as u128)),
504                _ => None,
505            }
506        }
507        Clause::Create { .. }
508        | Clause::Merge { .. }
509        | Clause::Set { .. }
510        | Clause::Remove { .. }
511        | Clause::Delete { .. }
512        | Clause::Foreach { .. }
513        | Clause::Use { .. } => est_rows,
514        _ => None,
515    }
516}
517
518fn is_ungrouped_agg(items: &[Projection], group_by: Option<&[Expr]>) -> bool {
519    let has_agg = items.iter().any(|it| is_agg_expr(&it.expr));
520    if !has_agg {
521        return false;
522    }
523    match group_by {
524        Some(keys) => keys.is_empty(),
525        None => items.iter().all(|it| is_agg_expr(&it.expr)),
526    }
527}
528
529fn estimate_pattern_rows(
530    pat: &PathPattern,
531    bound: &impl Fn(&str) -> bool,
532    conjuncts: &[&Expr],
533    input_rows: u128,
534    stats: &dyn PatternStats,
535) -> Option<u128> {
536    let first = pat.nodes.first()?;
537    let hops = pat
538        .nodes
539        .iter()
540        .zip(pat.rels.iter())
541        .map(|(node, rel)| (node, rel, seed_on_rel_start(rel, false)));
542    let start_bound = first.variable.as_ref().is_some_and(|v| v.with_str(bound));
543    if start_bound {
544        return Some(walk_cost(Estimate::Measured(input_rows), hops, stats));
545    }
546    let est = endpoint_estimate(first, bound, conjuncts.iter().copied(), stats);
547    if matches!(est.basis(), Basis::Rank) {
548        return None;
549    }
550    let walked = walk_cost(est, hops, stats);
551    Some(input_rows.saturating_mul(walked))
552}