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
//! The route's one guard: the patterns ADR-0186's Decision sends to BFS.

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

use relate_core::Value;
use relate_ir::{
    label_expr_vars, pattern_prop_key, Expr, MatchMode, NodePattern, PathMode, PathPattern,
    PathSelector, PatternElement, QuantifiedPathPattern, RelPattern,
};
use relate_names::NamedToken;

use crate::eval::{bound_is_row_invariant, bytecode::NodeBytecode, expr_vars};
use crate::row::{row_bound, Row};
use crate::shortest::followable;

use super::super::selector::resolve_gpm_count;
use super::super::{ElementFilter, GpmFilters};
use crate::pattern_walk::RelFilter;
use crate::shortest::CommonEndNodes;

/// Which shortest-path spelling a routed pattern is: the one fact the
/// element decode cannot read off the lowered pattern. The function and
/// expression forms reject a same-node pair, the keyword selectors keep
/// their closed trails (51N23), and only the expression form stops a fan
/// at its first productive layer.
#[derive(Clone, Copy, PartialEq, Eq)]
pub(super) enum Spelling {
    KeywordSelector,
    Function,
    Expression,
}

impl Spelling {
    /// The `MATCH`-clause spelling: the function forms carry the flag, a
    /// keyword selector does not. The expression form is stamped by its
    /// own entry ([`super::fold_shortest_route`]), which hands
    /// [`Spelling::Expression`] to the one driver.
    pub(super) fn of(path: &PathPattern) -> Self {
        if path.is_shortest_path_function {
            Spelling::Function
        } else {
            Spelling::KeywordSelector
        }
    }

    /// 51N23's runtime policy.
    pub(super) fn common_end_nodes(self) -> CommonEndNodes {
        match self {
            Spelling::KeywordSelector => CommonEndNodes::Allowed,
            Spelling::Function | Spelling::Expression => CommonEndNodes::Forbidden,
        }
    }

    /// The expression form keeps only the global shortest: an origin's
    /// deeper layers are longer than its own shortest, so they cannot win.
    pub(super) fn first_layer_only(self) -> bool {
        self == Spelling::Expression
    }

    /// Whether a clause-level `WHERE` conjunct that reads the path filters
    /// the *search* (the function and expression forms, as live
    /// `shortestPath()` plans it) or only the selected paths afterwards (a
    /// keyword selector).
    pub(super) fn filters_search_by_clause_where(self) -> bool {
        self != Spelling::KeywordSelector
    }

    /// The hop ceiling an unbounded relationship takes: only the expression
    /// form carries one (the walk's flat default); the clause spellings keep
    /// the pattern's own bound.
    fn unbounded_ceiling(self) -> Option<u32> {
        (self == Spelling::Expression).then_some(crate::pattern_walk::DEFAULT_MAX_HOPS)
    }
}

/// What a pair partition keeps of its trails when the selector counts more
/// than one (ADR-0607): the `k` shortest trails, or every trail of the `k`
/// shortest distinct lengths. A selector that fits the single-path or
/// all-shortest searches carries none.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum Keep {
    Paths(usize),
    Groups(usize),
}

/// What a routed pattern's selector asks of a partition: the one shortest
/// trail, every shortest trail, or a count above one (ADR-0607).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum Selection {
    Single,
    AllShortest,
    Count(Keep),
}

impl Selection {
    /// All-path selector (every shortest trail) rather than single-path.
    pub(super) fn all(self) -> bool {
        self == Selection::AllShortest
    }

    /// The count the length-class walk answers, if this is one.
    pub(super) fn counted(self) -> Option<Keep> {
        match self {
            Selection::Count(keep) => Some(keep),
            Selection::Single | Selection::AllShortest => None,
        }
    }
}

/// How one inner boundary node of a 1-hop QPP evaluates its predicates.
#[derive(Clone, Debug)]
pub(super) enum InnerPlan {
    /// Bare node or static labels only — no property map or inline `WHERE`.
    LabelsOnly,
    /// Property entries and/or inline `WHERE` compiled to flat bytecode (ADR-0720).
    Bytecode(NodeBytecode),
    /// Predicates outside the bytecode vocabulary (e.g. outer row variable
    /// references) or dynamic label expression; evaluated via general tree eval.
    Fallback,
}

#[cfg(test)]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum InnerPlanKind {
    LabelsOnly,
    Bytecode,
    Fallback,
}

#[cfg(test)]
impl InnerPlan {
    pub(crate) fn kind(&self) -> InnerPlanKind {
        match self {
            Self::LabelsOnly => InnerPlanKind::LabelsOnly,
            Self::Bytecode(_) => InnerPlanKind::Bytecode,
            Self::Fallback => InnerPlanKind::Fallback,
        }
    }
}

/// An inner boundary node pattern paired with its compiled evaluation plan.
#[derive(Clone)]
pub(super) struct InnerNode<'p> {
    pub(super) pattern: &'p NodePattern,
    pub(super) plan: InnerPlan,
}

impl<'p> InnerNode<'p> {
    fn new(pattern: &'p NodePattern) -> Self {
        Self {
            plan: compile_inner_node_plan(pattern),
            pattern,
        }
    }
}

/// Inner boundary node patterns and compiled plans of a 1-hop quantified path
/// pattern `((head)-[rel]-(tail)){m,n}`.
#[derive(Clone)]
pub(super) struct QppInner<'p> {
    pub(super) head: InnerNode<'p>,
    pub(super) tail: InnerNode<'p>,
}

/// The three elements of a routed pattern and its selector kind.
pub(super) struct Shape<'p> {
    pub start: &'p NodePattern,
    pub rel: &'p RelPattern,
    /// The rel's resolved type filter (LABS-801) — the pattern-level
    /// table's entry for this exact element, found in the same pass that
    /// decoded the shape, never re-derived or re-sniffed.
    pub filter: &'p RelFilter,
    pub end: &'p NodePattern,
    /// Inner node patterns when the routed hop is a general 1-hop QPP with
    /// inner labels, predicates, or group variables (`None` for plain
    /// var-length hops).
    pub qpp_inner: Option<QppInner<'p>>,
    /// The var-length bounds: the rel's own `*m..n` (legacy element shape)
    /// or the quantifier's `{m,n}` (the quantified element every var-length
    /// spelling lowers to, LABS-661) — the inner rel is a plain one-hop.
    pub min: u32,
    pub max: Option<u32>,
    /// What the selector keeps of a partition.
    pub selection: Selection,
    /// The shortest-path spelling this pattern was written with.
    pub spelling: Spelling,
    /// The match mode the guard admitted — always
    /// [`MatchMode::DifferentRelationships`] (the guard declines every
    /// other), carried so the route's unbounded cap reads the admitted
    /// mode instead of restating the admission.
    pub match_mode: MatchMode,
}

/// The one guard: the selectors, match and path modes, and pattern shape of
/// ADR-0186's Decision, an empty incoming used-relationship set, and row
/// bindings the search can honor. `None` keeps the pattern on GPM.
///
/// A path-level `WHERE` does not send the pattern to GPM: an inline one, and
/// a clause-level one of the function spellings, rides the search (see
/// [`super::filters::PathFilter`]); a keyword selector's clause-level one
/// is a post-filter of the selected paths.
pub(super) fn route_shape<'p>(
    path: &'p PathPattern,
    filters: &'p GpmFilters,
    match_mode: MatchMode,
    used: &UsedSet,
    row: &Row,
    params: &BTreeMap<String, Value>,
    spelling: Spelling,
) -> Option<Shape<'p>> {
    // The route takes the `None`, `WALK` and `TRAIL` path modes only — the
    // vocabulary decoded once, here. An explicit `WALK` (whose longer
    // answers may reuse a relationship) stays on GPM: the length-class
    // walk enumerates trails, so a count selector declines it (ADR-0607).
    let explicit_walk = match path.mode {
        Some(PathMode::Walk) => true,
        None | Some(PathMode::Trail) => false,
        Some(_) => return None,
    };
    if match_mode != MatchMode::DifferentRelationships || !used.is_empty() {
        return None;
    }
    let selection = match path.selector.as_ref()? {
        PathSelector::AnyShortest => Selection::Single,
        PathSelector::AllShortest => Selection::AllShortest,
        // The count may arrive as a parameter: the plan cache's
        // auto-parameterization turns a literal `SHORTEST 1` into one, so
        // it resolves through the canonical count helper. A count that
        // does not resolve (or is zero) stays on GPM, which owns the
        // selector's count errors.
        PathSelector::Shortest {
            count: Some(count),
            group,
        } => {
            let n = resolve_gpm_count(Some(count), 1, params).ok()?;
            counted(n, *group)?
        }
        // `ANY k` keeps the `k` shortest, as `SHORTEST k` does (the
        // selector's own reading); `ANY` alone stays on GPM.
        PathSelector::Any(Some(count)) => {
            let n = resolve_gpm_count(Some(count), 1, params).ok()?;
            counted(n, false)?
        }
        PathSelector::Shortest { .. } | PathSelector::Any(_) | PathSelector::All => return None,
    };
    if explicit_walk && selection.counted().is_some() {
        return None;
    }
    let hop = routed_hop(path, filters, selection, spelling, match_mode, row)?;
    if hop.min > 1
        || hop.rel.where_clause.is_some()
        || !followable(hop.start, hop.rel, hop.end)
        || hop
            .rel
            .variable
            .as_ref()
            .is_some_and(|v| v.with_str(row_bound(row)))
    {
        return None;
    }
    // GPM checks the end node with the relationship variable already bound;
    // an endpoint map that reads it (or the path variable) stays on GPM.
    // Text render: the late-binding list compares against the String
    // variable sets of the filter walk.
    let late: Vec<String> = hop
        .rel
        .variable
        .as_ref()
        .map(|v| v.to_string())
        .into_iter()
        .chain(path.path_names().map(|name| name.to_string()))
        .collect();
    let endpoint_ok = |np: &NodePattern| {
        let mut vars = HashSet::new();
        if let Some(props) = &np.properties {
            expr_vars(props, &mut vars);
        }
        np.variable
            .as_ref()
            .is_none_or(|v| matches!(row.get_name(v), None | Some(Value::Node(_))))
            && !late.iter().any(|v| vars.contains(v.as_str()))
    };
    // The start's inline WHERE keeps GPM: GPM checks it once at the start
    // binding, before the relationship variable exists, and the route binds
    // no start predicate of its own.
    // The end's inline WHERE rides the route's path filter instead
    // ([`super::filters::PathFilter`]): GPM checks it at every arrival with
    // the relationship variable bound but no path name bound yet, and the
    // route answers the same predicate against each bound trail — so a
    // WHERE that names a path variable keeps GPM's spelling of the check.
    // A predicate whose reading cannot complete against a bound trail (a
    // later pattern's variable) declines in `Route::try_new`.
    let end_where_ok = hop.end.where_clause.as_ref().is_none_or(|predicate| {
        let mut vars = HashSet::new();
        expr_vars(predicate, &mut vars);
        path.path_names()
            .all(|name| name.with_str(|text| !vars.contains(text)))
    });
    (endpoint_ok(hop.start)
        && hop.start.where_clause.is_none()
        && endpoint_ok(hop.end)
        && end_where_ok)
        .then_some(hop)
}

/// The routed var-length hop of a three-element pattern decoded into the
/// route's one [`Shape`] (F-1-10): the outer nodes, the traversed rel, its
/// resolved filter (LABS-801), and the effective bounds — one decoded
/// unit, never a positional tuple the caller reassembles field-for-field.
/// The selector's `all` fact arrives decided — the one fact the element
/// decode cannot read off the pattern. Every var-length spelling lowers to
/// the quantified element (LABS-661) — `-[r:T*m..n]-` arrives as
/// `[Node, Quantified([anon, one-hop rel, anon]), Node]` with the bounds on
/// the quantifier — so that shape decodes first (the shared
/// `implicit_var_length_rel` decoder); the plain var-length `Relationship`
/// element (hand-built or planner-IR-diagnostic plans) remains the legacy
/// arm.
fn routed_hop<'p>(
    path: &'p PathPattern,
    filters: &'p GpmFilters,
    selection: Selection,
    spelling: Spelling,
    match_mode: MatchMode,
    row: &Row,
) -> Option<Shape<'p>> {
    let [PatternElement::Node(start), rel_element, PatternElement::Node(end)] =
        path.elements.as_slice()
    else {
        return None;
    };
    // The rel element's resolved filter sits at its own index in the
    // pattern-level table (LABS-801) — the shape decode and the filter
    // lookup read one position, so they cannot disagree. The arms differ
    // only in where the rel, its filter, inner QPP nodes and bounds come from.
    let (rel, filter, qpp_inner, min, max) = match (rel_element, &filters.filters[1]) {
        (PatternElement::Quantified(qpp), ElementFilter::Group(inner)) => {
            let ElementFilter::Rel(filter) = &inner[1] else {
                return None;
            };
            if let Some(rel) = qpp.implicit_var_length_rel() {
                (rel, filter, None, qpp.min, qpp.max)
            } else {
                let (rel, inner) = qpp_hop(path, start, end, qpp, filter, selection, row)?;
                (rel, filter, Some(inner), qpp.min, qpp.max)
            }
        }
        (PatternElement::Relationship(rel), ElementFilter::Rel(filter)) if rel.var_length => {
            (rel, filter, None, rel.min_hops, rel.max_hops)
        }
        _ => return None,
    };
    Some(Shape {
        start,
        rel,
        filter,
        end,
        qpp_inner,
        min,
        max: max.or(spelling.unbounded_ceiling()),
        selection,
        spelling,
        match_mode,
    })
}

/// Match and validate a general 1-hop QPP element `((head)-[rel]-(tail)){m,n}`
/// eligible for shortest-route search with interior pruning.
fn qpp_hop<'p>(
    path: &'p PathPattern,
    start: &'p NodePattern,
    end: &'p NodePattern,
    qpp: &'p QuantifiedPathPattern,
    _filter: &'p RelFilter,
    selection: Selection,
    row: &Row,
) -> Option<(&'p RelPattern, QppInner<'p>)> {
    if !matches!(selection, Selection::Single | Selection::AllShortest)
        || qpp.subpath_variable.is_some()
        || qpp.where_clause.is_some()
    {
        return None;
    }
    let [PatternElement::Node(head), PatternElement::Relationship(rel), PatternElement::Node(tail)] =
        qpp.elements.as_slice()
    else {
        return None;
    };
    if rel.var_length
        || rel.where_clause.is_some()
        || rel.properties.is_some()
        || !qpp_inner_compatible(path, start, rel, end, head, tail, row)
    {
        return None;
    }
    let head = InnerNode::new(head);
    let tail = InnerNode::new(tail);
    Some((rel, QppInner { head, tail }))
}

/// Compile a 1-hop QPP inner node pattern into its [`InnerPlan`].
fn compile_inner_node_plan(np: &NodePattern) -> InnerPlan {
    if !np.has_static_labels() {
        return InnerPlan::Fallback;
    }
    let has_predicates = np.where_clause.is_some()
        || match &np.properties {
            Some(Expr::Map(m)) => !m.is_empty(),
            Some(_) => true,
            None => false,
        };
    if !has_predicates {
        return InnerPlan::LabelsOnly;
    }
    let map_entries: Vec<(NamedToken, &Expr)> = match &np.properties {
        None => Vec::new(),
        Some(Expr::Map(entries)) => {
            let mut out = Vec::with_capacity(entries.len());
            for (key, value) in entries {
                if !bound_is_row_invariant(value) {
                    return InnerPlan::Fallback;
                }
                out.push((pattern_prop_key(&np.prop_keys, key), value));
            }
            out
        }
        Some(_) => return InnerPlan::Fallback,
    };
    match NodeBytecode::compile_entries_and_exprs(
        np.variable.as_ref(),
        map_entries,
        np.where_clause.as_ref(),
    ) {
        Some(code) => InnerPlan::Bytecode(code),
        None => InnerPlan::Fallback,
    }
}

/// Whether an inner node pattern's expressions (properties, inline WHERE,
/// and label expression) read only its own variable or variables already bound in `row`.
fn reads_only_own_or_bound(np: &NodePattern, row: &Row) -> bool {
    let mut vars = HashSet::new();
    if let Some(props) = &np.properties {
        expr_vars(props, &mut vars);
    }
    if let Some(w) = &np.where_clause {
        expr_vars(w, &mut vars);
    }
    if let Some(le) = &np.label_expr {
        label_expr_vars(le, &mut vars);
    }
    let bound = row_bound(row);
    vars.iter().all(|name| {
        np.variable.as_ref().is_some_and(|v| v == name.as_str()) || bound(name.as_str())
    })
}

/// Whether `head` and `tail` of a 1-hop QPP are self-contained single-node
/// patterns whose group variables do not collide with each other, the outer
/// pattern, or the incoming row.
fn qpp_inner_compatible(
    path: &PathPattern,
    start: &NodePattern,
    rel: &RelPattern,
    end: &NodePattern,
    head: &NodePattern,
    tail: &NodePattern,
    row: &Row,
) -> bool {
    if head.variable.is_some() && head.variable == tail.variable {
        return false;
    }
    let collides = |v: &relate_names::SmallName| {
        start.variable.as_ref() == Some(v)
            || rel.variable.as_ref() == Some(v)
            || end.variable.as_ref() == Some(v)
            || path.path_names().any(|p| p == v)
            || v.with_str(row_bound(row))
    };
    for np in [head, tail] {
        if np.variable.as_ref().is_some_and(collides) || !reads_only_own_or_bound(np, row) {
            return false;
        }
    }
    true
}

/// The route's reading of a resolved selector count and `GROUPS` flag. One
/// answer is the single-path search, one group the all-shortest search, and
/// a larger count the length-class walk; zero stays on GPM.
fn counted(n: usize, group: bool) -> Option<Selection> {
    match (n, group) {
        (0, _) => None,
        (1, false) => Some(Selection::Single),
        (1, true) => Some(Selection::AllShortest),
        (n, true) => Some(Selection::Count(Keep::Groups(n))),
        (n, false) => Some(Selection::Count(Keep::Paths(n))),
    }
}