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
//! The contracted kernels' structural matcher (ADR-0473): the plan-time
//! recognizer that decides, linear in pattern size, whether a `MATCH`
//! clause's patterns are one of the contracted families — and compiles
//! everything the kernel runs on. Everything it cannot prove it declines,
//! and the per-row walker keeps the clause unchanged, answers identical.
//!
//! The two traversal families (ADR-0473 §Decision):
//!
//! - **Unrolled fixed-k chain** — one pattern of 2..=4 fixed single hops
//!   with per-hop predicate programs. The planner has already oriented the
//!   path's selective end to `nodes[0]` (ADR-0218's `reverse_path`), so
//!   the kernel's scan segment sits there and the hops walk forward as
//!   written.
//! - **Hub-star** — exactly two patterns, each 1..=2 fixed single hops,
//!   sharing exactly one **hub** node variable at an end of both patterns
//!   (the q19/q01/q26 family), optionally sharing a **terminal** variable
//!   at the opposite ends (a bounded cycle — q30's shared creator). The
//!   kernel enumerates hub candidates and expands both sides per hub,
//!   intersecting locally.
//!
//! The scan-shaped single node is the third family, and it already runs as
//! the scan-filter chain (`exec/batch.rs`, LABS-359): the chain kernel's
//! scan segment is that chain over id slots, so what this matcher
//! recognizes is the two traversal families, each with its scan segment
//! inside.
//!
//! Structural proofs shared by both families ([`plain_pattern`]): no GPM
//! features, no named path, no var-length or quantified hop, static type
//! lists, and a static label conjunction per node.
//! Variable proofs: no repeated rel variable (the walker's pre-bound
//! reconciliation semantics), no node variable repetition beyond the
//! hub/terminal sharing the hub-star family is defined by. Predicate
//! proofs: every flattened `WHERE` conjunct references one pattern node
//! variable and compiles into `program` (`Prog::Cmp`, `Prog::Null`, or
//! `Prog::Bytecode`, ADR-0720).

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

use relate_ir::{
    pattern_node_anchor_variables, single_var_of, Direction, Expr, MatchMode, NodePattern,
    PathPattern, PatternElement, RelPattern,
};
use relate_names::SmallName;
use relate_planner::seed_on_rel_start;

use crate::row::Row;

use super::program::{compile_node, NodeTarget};

/// The most hops an exact `*k` pattern may unroll before declining to the
/// general walker or frontier NFA (guarding against OOM on massive `*1000000` hops).
pub(crate) const MAX_UNROLL_HOPS: usize = 32;

/// One matched family with everything its kernel runs on.
pub(crate) enum Contract<'a> {
    /// (a) The unrolled fixed-k chain — boxed: a contract is built once
    /// per clause and matched once, never in a hot loop, and the compiled
    /// programs carry `String`s and `Expr`s that dwarf the enum's tags.
    Chain(Box<Chain<'a>>),
}

impl Contract<'_> {
    /// The rung this contract runs (LABS-1117): the chain with its hop
    /// count. The one derivation both the runtime
    /// engagement record and the PROFILE fact read.
    pub(crate) fn rung(&self) -> crate::metrics::KernelRung {
        match self {
            Contract::Chain(chain) => crate::metrics::KernelRung::Chain {
                hops: chain.hops.len(),
            },
        }
    }
}

/// One hop of a kernel's walk: the rel pattern, the traversal direction in
/// the kernel's walk order, the target node's admission, and the
/// degree-estimator's facts (the hop's seed-side node pattern and whether
/// the driving end rides the rel's start side at this hop).
pub(crate) struct Hop<'a> {
    pub(crate) rel: &'a RelPattern,
    /// The traversal direction of this hop in walk order (a walk against
    /// the written direction flips it).
    pub(crate) traverse: Direction,
    /// The hop's arrival node (the end the walk arrives at).
    pub(crate) target: NodeTarget<'a>,
    /// The hop's seed-side node pattern (the end the walk leaves).
    pub(crate) seed: &'a NodePattern,
    /// Whether the driving seed rides the rel's start side at this hop —
    /// the degree estimator's one derived fact (LABS-426's tail choice).
    pub(crate) seed_on_start: bool,
    /// When Some(slot), the target node variable was already bound earlier in the
    /// same pattern at `slot`, making this hop an ExpandInto rather than an Expand.
    pub(crate) expand_into: Option<usize>,
}

impl Hop<'_> {
    /// This hop scaled from the driving end by the planner's degree tail:
    /// `rows` rows sitting at the hop's seed side become the hop's
    /// arrival-side row estimate. A hop the walk model cannot price (an
    /// untyped rel, an unlabeled seed side) rides the any-label tail
    /// instead of passing the rows through (LABS-991).
    pub(crate) fn scaled_from_seed(
        &self,
        rows: u128,
        stats: &dyn relate_planner::PatternStats,
    ) -> u128 {
        relate_planner::apply_hop_bound(rows, self.seed, self.rel, self.seed_on_start, stats)
    }
}

/// The chain contract: the scan segment's subject plus the unrolled hops.
pub(crate) struct Chain<'a> {
    /// The scan segment's subject — `nodes[0]`, the planner-oriented
    /// selective end (ADR-0218's `reverse_path`).
    pub(crate) start: NodeTarget<'a>,
    /// Hops in walk order; hop `j`'s target is `nodes[j + 1]`.
    pub(crate) hops: Vec<Hop<'a>>,
}

impl Chain<'_> {
    /// The final hop and the hops before it. The compile enforces at least
    /// 1 hop, so the split states an invariant.
    pub(crate) fn split_last_hop(&self) -> (&Hop<'_>, &[Hop<'_>]) {
        self.hops
            .split_last()
            .expect("the compile enforces at least 1 hop")
    }
}

/// Recognize a contracted family over the planned patterns — the
/// plan-time half of engagement (ADR-0473). `None` declines: the shape is
/// not one of the families, the driving row carries bindings (a mid-statement
/// clause keeps the walker's per-row semantics), or the mode is not
/// `DIFFERENT RELATIONSHIPS` (relationship uniqueness would not apply).
///
/// Linear in pattern size: one pass over nodes and rels per pattern, plus
/// one pass over the conjuncts. Nothing here reads the graph.
pub(crate) fn compile<'a>(
    patterns: &'a [PathPattern],
    match_mode: MatchMode,
    row: &Row,
    conjuncts: &[Expr],
) -> Option<Contract<'a>> {
    if match_mode != MatchMode::DifferentRelationships || !row.is_empty() {
        return None;
    }
    match patterns.len() {
        1 => compile_chain(&patterns[0], conjuncts).map(|c| Contract::Chain(Box::new(c))),
        _ => None,
    }
}

/// The rel-spelling facts the pattern gates share: no quantified
/// spelling, no inline property map, no inline `WHERE`. `plain_pattern`
/// declines var-length hops outright; `unroll_fixed` expands the exact
/// `*k` subset — both consult this one predicate for the spelling facts
/// they share, never a second derivation.
fn rel_plain(rel: &RelPattern) -> bool {
    !rel.quantified && rel.properties.is_none() && rel.where_clause.is_none()
}

/// The per-pattern proofs both families share. Every condition is a proof,
/// not a heuristic: a shape the kernels' loops cannot reproduce exactly
/// keeps the per-row walker.
fn plain_pattern(path: &PathPattern) -> Option<()> {
    // GPM-only features (path modes, selectors, pattern/element WHERE),
    // the shapes that clear the compact form, and named paths.
    if path.needs_gpm() || path.is_shortest_path_function || path.has_path_name() {
        return None;
    }
    if path.nodes.len() != path.rels.len() + 1 {
        return None;
    }
    for node in &path.nodes {
        // An inline element predicate is GPM (caught above; re-stated for
        // the compact form). A property map is compiled — the planner
        // folds every `WHERE var.key = value` into one, so declining maps
        // would decline the family's own queries.
        if node.where_clause.is_some() {
            return None;
        }
        // A dynamic label expression keeps the walker's label evaluation.
        if !node.has_static_labels() {
            return None;
        }
    }
    for rel in &path.rels {
        // Var-length and quantified hops keep the recursive walker; a
        // rel property map keeps the walker's `rel_edge_ok`; a non-1
        // bound is a quantified spelling. A static single type keeps the
        // `types` list the kernel's adjacency reads (the synthesized
        // `type_expr` of every typed rel, like the nodes' `label_expr`);
        // a dynamic — or disjunctive — type expression keeps the walker,
        // and the single-type bound is what the degree estimator prices.
        if rel.var_length
            || !rel_plain(rel)
            || !rel
                .type_expr
                .as_ref()
                .is_none_or(|expr| expr.is_static_conjunction())
            || rel.min_hops != 1
            || rel.max_hops.is_some_and(|max| max != 1)
        {
            return None;
        }
    }
    Some(())
}

/// The patterns the chain count fold compiles: the lone pattern's
/// exact-`*k` unrolling ([`unroll_fixed`]) when it has one, the written
/// patterns otherwise. The count fold is the one consumer — the rows
/// kernel and the existence probe compile the written patterns, and the
/// `*k` spelling reaches only this fold; the caller holds the returned
/// value for the compile's lifetime.
pub(crate) fn chain_spelling(patterns: &[PathPattern]) -> Cow<'_, [PathPattern]> {
    let [only] = patterns else {
        return Cow::Borrowed(patterns);
    };
    unroll_fixed(only).map_or(Cow::Borrowed(patterns), |unrolled| {
        Cow::Owned(vec![unrolled])
    })
}

/// The pattern with every exact `*k` relationship spelled out as `k`
/// anonymous single hops (`(a)-[:R*3]->(b)` becomes
/// `(a)-[:R]->()-[:R]->()-[:R]->(b)`), or `None` when no relationship is
/// var-length or a spelling is not exactly unrollable: a named variable
/// (it binds a list), a property map or inline `WHERE` (the shared
/// `rel_plain` facts), a quantified, ranged or zero-length hop, or an
/// unrolled hop count past the chain bound. The unrolled pattern has the same
/// default-mode (trail) semantics — one relationship per hop, pairwise
/// distinct.
///
/// It lives here, beside [`rel_plain`] and [`plain_pattern`]: the three
/// are the pattern-spelling gates, and this one shares its rel-spelling
/// facts with the proof that declines var-length outright. Its consumer
/// is [`chain_spelling`], which preprocesses the exact-`*k` spelling
/// into a fixed-hop pattern for the chain count fold's compile —
/// `compile` itself never calls it. The walker-facing var-length semantics stay
/// `relate-front`'s `quantify_var_length` (ADR-0471), which lowers the
/// parser's spellings into these bounds.
pub(super) fn unroll_fixed(path: &PathPattern) -> Option<PathPattern> {
    if !path.rels.iter().any(|rel| rel.var_length) || path.rels.len() + 1 != path.nodes.len() {
        return None;
    }
    // The per-rel unroll counts, derived once: the total (not each `k`
    // alone: one fixed hop beside a `*4` unrolls past the bound a lone
    // `*4` does not) must land in the chain's own range — one gate
    // before any allocation.
    let copies: Vec<u32> = path.rels.iter().map(fixed_copies).collect::<Option<_>>()?;
    let total = copies
        .iter()
        .fold(0usize, |sum, &c| sum.saturating_add(c as usize));
    if !(1..=MAX_UNROLL_HOPS).contains(&total) {
        return None;
    }
    let mut nodes = vec![path.nodes[0].clone()];
    let mut rels = Vec::new();
    for ((rel, next), &count) in path.rels.iter().zip(&path.nodes[1..]).zip(&copies) {
        // `count - 1` anonymous hops, then the written end node — the
        // unrolled chain's real shape, no loop index special-casing the
        // last copy (`fixed_copies` guarantees `count >= 1`).
        let mut single = rel.clone();
        single.var_length = false;
        single.min_hops = 1;
        single.max_hops = Some(1);
        for _ in 0..count - 1 {
            rels.push(single.clone());
            nodes.push(NodePattern::anonymous());
        }
        rels.push(single);
        nodes.push(next.clone());
    }
    // The built pattern is closed with the same shape proof the compile
    // applies, so "unrolled implies chain-shaped" holds at the return,
    // never by the downstream compile's grace (no behaviour change:
    // `compile` already applies exactly this proof to this pattern).
    let mut elements = vec![PatternElement::Node(nodes[0].clone())];
    for (rel, node) in rels.iter().zip(&nodes[1..]) {
        elements.push(PatternElement::Relationship(rel.clone()));
        elements.push(PatternElement::Node(node.clone()));
    }
    let unrolled = PathPattern {
        elements,
        nodes,
        rels,
        ..path.clone()
    };
    plain_pattern(&unrolled).is_some().then_some(unrolled)
}

/// One rel's fixed-hop count when the spelling unrolls exactly: `k` for a
/// var-length hop, `1` for a fixed one, `None` for a spelling that does
/// not unroll — a zero-length hop (`*0`, which would unroll to nothing
/// and silently drop its end node's variable, labels and property map), a
/// named variable (it binds a list), a ranged hop (max not the exact
/// `k`), or the shared `rel_plain` facts.
fn fixed_copies(rel: &RelPattern) -> Option<u32> {
    if !rel.var_length {
        return Some(1);
    }
    let k = rel.min_hops;
    (k != 0 && rel.max_hops == Some(k) && rel.variable.is_none() && rel_plain(rel)).then_some(k)
}

/// Group every `WHERE` conjunct by the single pattern node variable it
/// references (ADR-0720). A conjunct naming zero variables, multiple
/// variables, or a variable outside the patterns' node variables declines
/// (`None`), keeping the per-row walker.
fn node_exprs<'c>(
    patterns: &[PathPattern],
    conjuncts: &'c [Expr],
) -> Option<BTreeMap<SmallName, Vec<&'c Expr>>> {
    let node_vars = node_var_set(patterns);
    let mut grouped: BTreeMap<SmallName, Vec<&'c Expr>> = BTreeMap::new();
    for conjunct in conjuncts {
        let var = single_var_of(conjunct)?;
        if !node_vars.contains(&var) {
            return None;
        }
        grouped.entry(var).or_default().push(conjunct);
    }
    Some(grouped)
}

/// The set of node variable names across `patterns`.
fn node_var_set(patterns: &[PathPattern]) -> HashSet<SmallName> {
    patterns
        .iter()
        .flat_map(pattern_node_anchor_variables)
        .collect()
}

/// No rel variable repeats — within a pattern (the walker's pre-bound
/// reconciliation in `bind_trail`), across the pair (the same
/// reconciliation), or against any node variable. A named rel binds one
/// relationship; the kernels bind one rel per hop and cannot reproduce a
/// repeated name's reconciliation.
fn rel_vars_unique(patterns: &[PathPattern]) -> bool {
    let mut seen: HashSet<&SmallName> = HashSet::new();
    let node_vars = node_var_set(patterns);
    for path in patterns {
        for rel in &path.rels {
            if let Some(var) = rel.variable.as_ref() {
                if !seen.insert(var) || node_vars.contains(var) {
                    return false;
                }
            }
        }
    }
    true
}

/// The chain family: one pattern, fixed single hops (k >= 1), every
/// node variable occurring at most once per slot or repeating an earlier slot (cycles / ExpandInto),
/// every conjunct compiled.
pub(crate) fn compile_chain<'a>(path: &'a PathPattern, conjuncts: &[Expr]) -> Option<Chain<'a>> {
    plain_pattern(path)?;
    if path.rels.is_empty() || path.rels.len() > MAX_UNROLL_HOPS {
        return None;
    }
    // Track node variable bindings: a variable repeating an earlier node
    // is an ExpandInto hop targeting that earlier node slot.
    let mut node_var_slots: BTreeMap<&SmallName, usize> = BTreeMap::new();
    if let Some(var) = path.nodes[0].variable.as_ref() {
        node_var_slots.insert(var, 0);
    }
    let mut expand_intos: Vec<Option<usize>> = Vec::with_capacity(path.rels.len());
    for (j, node) in path.nodes[1..].iter().enumerate() {
        if let Some(var) = node.variable.as_ref() {
            if let Some(&prev_slot) = node_var_slots.get(var) {
                expand_intos.push(Some(prev_slot));
            } else {
                node_var_slots.insert(var, j + 1);
                expand_intos.push(None);
            }
        } else {
            expand_intos.push(None);
        }
    }
    if !rel_vars_unique(std::slice::from_ref(path)) {
        return None;
    }
    let grouped = node_exprs(std::slice::from_ref(path), conjuncts)?;
    let start = compile_node(&path.nodes[0], &grouped)?;
    let hops = path
        .rels
        .iter()
        .enumerate()
        .map(|(j, rel)| {
            Some(Hop {
                rel,
                // The chain walks the pattern as written, from the
                // planner-oriented selective end.
                traverse: rel.direction,
                target: compile_node(&path.nodes[j + 1], &grouped)?,
                seed: &path.nodes[j],
                seed_on_start: seed_on_rel_start(rel, false),
                expand_into: expand_intos[j],
            })
        })
        .collect::<Option<Vec<_>>>()?;
    Some(Chain { start, hops })
}