relate-planner 1.5.0

Bind OpenCypher AST to a logical plan
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
//! Cost-based physical `MatchStrategy` selection for `MATCH` clauses (ADR-0737).
//!
//! Runs in `relate-planner` after `MATCH` rewrites and pattern ordering, using
//! `PatternStats` to choose between composable physical operators:
//! - `HashJoinJunctionSplit` vs `FrontierNfa` on mixed fixed+varlen patterns,
//! - `HashJoinCrossClause` vs `MorselPipeline` across `MATCH ... WITH ... MATCH`,
//! - `HashJoinTwoPattern` vs `MorselPipeline`/`Walker` on two-pattern joins,
//! - `MorselPipeline` / `FrontierNfa` / `Walker` on remaining shapes.

use std::collections::{BTreeMap, HashSet};

use relate_ir::{is_agg_expr, path_pattern_vars, Clause, Expr, MatchMode, PathPattern, Projection};
use relate_names::SmallName;

use crate::stats::PatternStats;

use super::estimate::{endpoint_estimate, where_conjuncts_of, Basis, Estimate};
use super::junction::junction_split_pays;
use super::{
    apply_degree, apply_hop_bound, can_reverse_path, direction_cost, seed_on_rel_start, seed_rows,
    walk_cost,
};

/// Minimum side-A / incoming row count before a hash join pays for itself.
pub const HASH_JOIN_MIN_SIDE_ROWS: u128 = 128;

/// Unmeasured cost margin gate against guess prices in two-pattern joins.
const HASH_JOIN_GUESS_MARGIN: u128 = 2;

/// Planner-selected physical execution strategy for one `MATCH` clause.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MatchStrategy {
    /// Fixed-length single-pattern morsel pipeline or batched scan/expand.
    MorselPipeline,
    /// Frontier NFA breadth-first traversal for variable-length / quantified patterns.
    FrontierNfa,
    /// Two-pattern hash join over shared node variable(s) (`MATCH (a)--(h), (b)--(h)`).
    HashJoinTwoPattern,
    /// Cross-clause hash join with SemiMask SIP across `MATCH ... WITH ... MATCH`.
    HashJoinCrossClause,
    /// Junction-split hash join separating a selective fixed leg from a var-length/QPP leg.
    HashJoinJunctionSplit,
    /// Per-row pattern walker (OPTIONAL, SEARCH, REPEATABLE ELEMENTS, shortestPath,
    /// multi-pattern cartesian, or complex GPM).
    Walker,
}

impl MatchStrategy {
    /// Canonical display name rendered in `EXPLAIN` plan details.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::MorselPipeline => "MorselPipeline",
            Self::FrontierNfa => "FrontierNfa",
            Self::HashJoinTwoPattern => "HashJoinTwoPattern",
            Self::HashJoinCrossClause => "HashJoinCrossClause",
            Self::HashJoinJunctionSplit => "HashJoinJunctionSplit",
            Self::Walker => "Walker",
        }
    }
}

/// Which endpoint of a cross-clause pattern is cheaper to scan from.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum CrossClauseSearchEnd {
    Start,
    End,
}

impl CrossClauseSearchEnd {
    /// Whether the pattern should be reversed to start from the cheaper end.
    pub fn should_reverse(self) -> bool {
        matches!(self, Self::End)
    }
}

/// Result of pricing a cross-clause `MATCH` pattern against nested-loop re-expansion.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct CrossClauseCost {
    pub cheapest_end: CrossClauseSearchEnd,
    pub pays: bool,
}

/// Canonical cost helper for cross-clause HashJoin vs nested-loop expansion.
///
/// Compares scanning `pat` once from its cheapest measured unshared endpoint plus
/// streaming `row_count` probe rows against expanding `pat` per input row.
pub fn evaluate_cross_clause_cost(
    pat: &PathPattern,
    shared_vars: &[&SmallName],
    where_conjuncts: &[&Expr],
    row_count: u128,
    stats: &dyn PatternStats,
) -> CrossClauseCost {
    let per_row = per_row_expand_cost(pat, shared_vars, stats);
    let nested_cost = per_row.saturating_mul(row_count);

    let unbound = |_: &str| false;
    let last = pat.nodes.len() - 1;
    let est0 = endpoint_estimate(
        &pat.nodes[0],
        &unbound,
        where_conjuncts.iter().copied(),
        stats,
    );
    let est1 = endpoint_estimate(
        &pat.nodes[last],
        &unbound,
        where_conjuncts.iter().copied(),
        stats,
    );

    let rows0 = seed_rows(est0);
    let rows1 = seed_rows(est1);
    let can_reverse = can_reverse_path(pat, &unbound);
    let cheapest_end = if can_reverse && rows1 < rows0 {
        CrossClauseSearchEnd::End
    } else {
        CrossClauseSearchEnd::Start
    };

    let is_shared_0 = pat.nodes[0]
        .variable
        .as_ref()
        .is_some_and(|v| shared_vars.contains(&v));
    let is_shared_1 = pat.nodes[last]
        .variable
        .as_ref()
        .is_some_and(|v| shared_vars.contains(&v));

    let unshared_selective = [
        (!is_shared_0, est0, rows0),
        (can_reverse && !is_shared_1, est1, rows1),
    ]
    .into_iter()
    .filter(|(eligible, est, _)| *eligible && !matches!(est.basis(), Basis::Rank))
    .min_by_key(|(_, _, rows)| *rows)
    .map(|(_, _, rows)| rows);

    let pays = unshared_selective
        .is_some_and(|build_rows| build_rows.saturating_add(row_count) <= nested_cost);

    CrossClauseCost { cheapest_end, pays }
}

fn per_row_expand_cost(
    pat: &PathPattern,
    shared_vars: &[&SmallName],
    stats: &dyn PatternStats,
) -> u128 {
    if pat.rels.is_empty() {
        return 1;
    }
    let last = pat.nodes.len() - 1;
    let shared_at_start = pat.nodes[0]
        .variable
        .as_ref()
        .is_some_and(|v| shared_vars.contains(&v));
    let shared_at_end = pat.nodes[last]
        .variable
        .as_ref()
        .is_some_and(|v| shared_vars.contains(&v));

    let (start_node, rel, seed_is_start, other_node) = if shared_at_start {
        (
            &pat.nodes[0],
            &pat.rels[0],
            seed_on_rel_start(&pat.rels[0], false),
            &pat.nodes[1],
        )
    } else if shared_at_end {
        let r = &pat.rels[last - 1];
        (
            &pat.nodes[last],
            r,
            seed_on_rel_start(r, true),
            &pat.nodes[last - 1],
        )
    } else {
        (
            &pat.nodes[0],
            &pat.rels[0],
            seed_on_rel_start(&pat.rels[0], false),
            &pat.nodes[1],
        )
    };

    let deg = apply_hop_bound(1, start_node, rel, seed_is_start, stats);
    if deg > 1 {
        return deg;
    }
    apply_degree(1, other_node, rel, seed_is_start, stats).max(1)
}

/// Populate the per-`(part_idx, clause_idx)` `MatchStrategy` map for one stage's parts.
pub(crate) fn plan_match_strategies(
    parts: &[Vec<Clause>],
    stats: &dyn PatternStats,
) -> BTreeMap<(usize, usize), MatchStrategy> {
    let mut strategies = BTreeMap::new();
    for (part_idx, clauses) in parts.iter().enumerate() {
        plan_part_strategies(part_idx, clauses, stats, &mut strategies);
    }
    strategies
}

fn plan_part_strategies(
    part_idx: usize,
    clauses: &[Clause],
    stats: &dyn PatternStats,
    out: &mut BTreeMap<(usize, usize), MatchStrategy>,
) {
    let mut scope: Vec<String> = Vec::new();
    let mut bound: HashSet<String> = HashSet::new();
    let mut est_rows: Option<u128> = Some(1);

    for (clause_idx, clause) in clauses.iter().enumerate() {
        if let Clause::Match {
            optional,
            match_mode,
            patterns,
            where_clause,
            search,
            ..
        } = clause
        {
            let strategy = select_match_strategy(
                *optional,
                *match_mode,
                patterns,
                where_clause.as_ref(),
                search.is_some(),
                &bound,
                est_rows,
                stats,
            );
            out.insert((part_idx, clause_idx), strategy);
        }
        est_rows = advance_est_rows(clause, &bound, est_rows, stats);
        let introduced = crate::rewrite::bindings_of(clause, &scope);
        crate::rewrite::advance_scope(&mut scope, &mut bound, clause, &introduced);
    }
}

#[allow(clippy::too_many_arguments)]
fn select_match_strategy(
    optional: bool,
    match_mode: MatchMode,
    patterns: &[PathPattern],
    where_clause: Option<&Expr>,
    has_search: bool,
    bound: &HashSet<String>,
    est_input_rows: Option<u128>,
    stats: &dyn PatternStats,
) -> MatchStrategy {
    if optional || has_search || patterns.is_empty() {
        return MatchStrategy::Walker;
    }

    let has_varlen = patterns
        .iter()
        .any(|p| p.rels.iter().any(|r| r.var_length || r.quantified));

    if match_mode == MatchMode::RepeatableElements {
        return if has_varlen && patterns.len() == 1 && !patterns[0].is_shortest_path_function {
            MatchStrategy::FrontierNfa
        } else {
            MatchStrategy::Walker
        };
    }

    if patterns.iter().any(|p| p.is_shortest_path_function) {
        return MatchStrategy::Walker;
    }

    let conjuncts = where_conjuncts_of(where_clause);

    // 1. Mixed fixed + varlen single pattern: cost-based JunctionSplit vs FrontierNfa.
    // Align row-count eligibility with the executor's build-fixed (1 row) and
    // build-varlen (>= HASH_JOIN_MIN_SIDE_ROWS) entry points so EXPLAIN never
    // promises a junction split that 2..127 rows would decline at runtime.
    if patterns.len() == 1 && has_varlen {
        let rows_eligible = est_input_rows.is_none_or(|r| r == 1 || r >= HASH_JOIN_MIN_SIDE_ROWS);
        if rows_eligible && junction_split_pays(&patterns[0], &conjuncts, bound, stats) {
            return MatchStrategy::HashJoinJunctionSplit;
        }
        return MatchStrategy::FrontierNfa;
    }

    // 2. Multi-pattern two-way join: cost-based HashJoinTwoPattern vs Walker.
    if patterns.len() == 2 {
        if two_pattern_hash_join_pays(patterns, &conjuncts, bound, stats) {
            return MatchStrategy::HashJoinTwoPattern;
        }
        return MatchStrategy::Walker;
    }

    if patterns.len() > 2 {
        return MatchStrategy::Walker;
    }

    let pat = &patterns[0];
    if pat.needs_gpm() {
        return MatchStrategy::Walker;
    }

    // 3. Cross-clause HashJoin across MATCH ... WITH ... MATCH.
    if let Some(input_rows) = est_input_rows {
        if cross_clause_hash_join_pays(pat, &conjuncts, bound, input_rows, stats) {
            return MatchStrategy::HashJoinCrossClause;
        }
    }

    MatchStrategy::MorselPipeline
}

fn cross_clause_hash_join_pays(
    pat: &PathPattern,
    conjuncts: &[&Expr],
    bound: &HashSet<String>,
    input_rows: u128,
    stats: &dyn PatternStats,
) -> bool {
    if input_rows < HASH_JOIN_MIN_SIDE_ROWS {
        return false;
    }
    if pat.nodes.len() < 2
        || pat.rels.is_empty()
        || pat.rels.len() != pat.nodes.len() - 1
        || pat.is_shortest_path_function
        || pat.needs_gpm()
    {
        return false;
    }
    if pat.rels.iter().any(|r| {
        r.var_length
            || r.quantified
            || r.variable
                .as_ref()
                .is_some_and(|v| v.with_str(|s| bound.contains(s)))
    }) {
        return false;
    }
    let pat_vars: HashSet<String> = path_pattern_vars(pat).map(|v| v.to_string()).collect();
    if conjuncts
        .iter()
        .any(|c| !relate_ir::all_vars_satisfy(c, |v| pat_vars.contains(v)))
    {
        return false;
    }
    let mut shared: Vec<&SmallName> = Vec::new();
    for n in &pat.nodes {
        if let Some(v) = &n.variable {
            if v.with_str(|s| bound.contains(s)) && !shared.contains(&v) {
                shared.push(v);
            }
        }
    }
    if shared.is_empty() {
        return false;
    }
    shared.sort();
    evaluate_cross_clause_cost(pat, &shared, conjuncts, input_rows, stats).pays
}

fn two_pattern_hash_join_pays(
    patterns: &[PathPattern],
    conjuncts: &[&Expr],
    bound: &HashSet<String>,
    stats: &dyn PatternStats,
) -> bool {
    if patterns.len() != 2 {
        return false;
    }
    for p in patterns {
        if p.nodes.len() < 2
            || p.rels.is_empty()
            || p.rels.len() != p.nodes.len() - 1
            || p.is_shortest_path_function
            || p.needs_gpm()
            || p.rels.iter().any(|r| r.var_length || r.quantified)
        {
            return false;
        }
        if path_pattern_vars(p).any(|v| v.with_str(|s| bound.contains(s))) {
            return false;
        }
    }

    let a_nodes: HashSet<&SmallName> = patterns[0]
        .nodes
        .iter()
        .filter_map(|n| n.variable.as_ref())
        .collect();
    let b_nodes: HashSet<&SmallName> = patterns[1]
        .nodes
        .iter()
        .filter_map(|n| n.variable.as_ref())
        .collect();
    let mut shared_nodes: Vec<&SmallName> = a_nodes.intersection(&b_nodes).copied().collect();
    if shared_nodes.is_empty() {
        return false;
    }

    let a_rels: HashSet<&SmallName> = patterns[0]
        .rels
        .iter()
        .filter_map(|r| r.variable.as_ref())
        .collect();
    let b_rels: HashSet<&SmallName> = patterns[1]
        .rels
        .iter()
        .filter_map(|r| r.variable.as_ref())
        .collect();
    if a_rels.intersection(&b_rels).next().is_some() {
        return false;
    }
    shared_nodes.sort();

    let unbound = |_: &str| false;
    let side_a = direction_cost(&patterns[0], false, &unbound, conjuncts, stats);
    if matches!(side_a.basis, Basis::Rank) || side_a.walked < HASH_JOIN_MIN_SIDE_ROWS {
        return false;
    }

    let side_b = &patterns[1];
    let per_row = per_row_expand_cost(side_b, &shared_nodes, stats);
    let nested_cost = per_row.saturating_mul(side_a.walked);

    let last = side_b.nodes.len() - 1;
    let est0 = endpoint_estimate(&side_b.nodes[0], &unbound, conjuncts.iter().copied(), stats);
    let est1 = endpoint_estimate(
        &side_b.nodes[last],
        &unbound,
        conjuncts.iter().copied(),
        stats,
    );
    let can_rev = can_reverse_path(side_b, &unbound);
    let (best_est, best_rows) = if can_rev && seed_rows(est1) < seed_rows(est0) {
        (est1, seed_rows(est1))
    } else {
        (est0, seed_rows(est0))
    };

    if matches!(best_est.basis(), Basis::Rank) {
        best_rows.saturating_mul(HASH_JOIN_GUESS_MARGIN) <= nested_cost
    } else {
        best_rows.saturating_add(side_a.walked) <= nested_cost
    }
}

fn advance_est_rows(
    clause: &Clause,
    bound: &HashSet<String>,
    est_rows: Option<u128>,
    stats: &dyn PatternStats,
) -> Option<u128> {
    match clause {
        Clause::Match {
            optional,
            patterns,
            where_clause,
            ..
        } => {
            let conjuncts = where_conjuncts_of(where_clause.as_ref());
            let mut rows = est_rows?;
            let mut local_bound = bound.clone();
            for pat in patterns {
                let bound_fn = |name: &str| local_bound.contains(name);
                let pat_rows = estimate_pattern_rows(pat, &bound_fn, &conjuncts, rows, stats)?;
                rows = if *optional {
                    rows.max(pat_rows)
                } else {
                    pat_rows
                };
                for v in path_pattern_vars(pat) {
                    local_bound.insert(v.to_string());
                }
            }
            Some(rows)
        }
        Clause::With {
            items,
            group_by,
            limit,
            ..
        } => {
            let mut rows = if is_ungrouped_agg(items, group_by.as_deref()) {
                Some(1)
            } else {
                est_rows
            };
            if let Some(Expr::Int(n)) = limit {
                if *n >= 0 {
                    let lim = *n as u128;
                    rows = Some(rows.map_or(lim, |r| r.min(lim)));
                }
            }
            rows
        }
        Clause::Unwind { expression, .. } => {
            let base = est_rows?;
            match expression {
                Expr::List(items) => Some(base.saturating_mul(items.len() as u128)),
                _ => None,
            }
        }
        Clause::Create { .. }
        | Clause::Merge { .. }
        | Clause::Set { .. }
        | Clause::Remove { .. }
        | Clause::Delete { .. }
        | Clause::Foreach { .. }
        | Clause::Use { .. } => est_rows,
        _ => None,
    }
}

fn is_ungrouped_agg(items: &[Projection], group_by: Option<&[Expr]>) -> bool {
    let has_agg = items.iter().any(|it| is_agg_expr(&it.expr));
    if !has_agg {
        return false;
    }
    match group_by {
        Some(keys) => keys.is_empty(),
        None => items.iter().all(|it| is_agg_expr(&it.expr)),
    }
}

fn estimate_pattern_rows(
    pat: &PathPattern,
    bound: &impl Fn(&str) -> bool,
    conjuncts: &[&Expr],
    input_rows: u128,
    stats: &dyn PatternStats,
) -> Option<u128> {
    let first = pat.nodes.first()?;
    let hops = pat
        .nodes
        .iter()
        .zip(pat.rels.iter())
        .map(|(node, rel)| (node, rel, seed_on_rel_start(rel, false)));
    let start_bound = first.variable.as_ref().is_some_and(|v| v.with_str(bound));
    if start_bound {
        return Some(walk_cost(Estimate::Measured(input_rows), hops, stats));
    }
    let est = endpoint_estimate(first, bound, conjuncts.iter().copied(), stats);
    if matches!(est.basis(), Basis::Rank) {
        return None;
    }
    let walked = walk_cost(est, hops, stats);
    Some(input_rows.saturating_mul(walked))
}