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
//! The contracted kernels' predicate programs (ADR-0473, ADR-0720): the closed
//! vocabulary a node's admission check compiles to, and the monomorphic
//! dispatch that keeps every per-candidate check a static, inlined call —
//! never a per-row `dyn Fn`.
//!
//! One program is a pattern's static label conjunction plus:
//! - zero property predicates (`Prog::Bare`),
//! - a single `<var>.<key> <op> <row-invariant bound>` (`Prog::Cmp`) or
//!   `<var>.<key> IS [NOT] NULL` (`Prog::Null`) kept on the zero-overhead
//!   fast path, or
//! - any multi-predicate conjunction, multi-entry property map, two-property
//!   comparison on the same node, or boolean `AND`/`OR`/`NOT` expression over
//!   the node's own properties compiled to flat stack bytecode
//!   (`Prog::Bytecode`, ADR-0720).
//!
//! Any conjunct shape outside that single-node vocabulary (functions over the
//! row, multi-variable predicates, non-row-invariant bounds) declines the
//! whole clause — the per-row walker keeps it, answers identical (the
//! differential tests pin that).
//!
//! Bounds are evaluated **lazily, once per stage**: a stage with no
//! candidates never evaluates them, which is the per-row path's behavior (an
//! empty candidate set never reaches `residual_ok`). Error parity otherwise
//! follows the scan-filter chain's stated caveat (`exec/batch.rs`): rows
//! kept and dropped are identical, but a pathological `WHERE` whose
//! conjuncts error on disjoint candidate subsets can surface a different
//! conjunct's message than the walk order would.

use std::collections::BTreeMap;

use relate_core::{NodeId, Result, Value};
use relate_ir::{
    is_pred_op, pattern_prop_key, var_prop_named, BinaryOp, Expr, NodePattern, UnaryOp,
};
use relate_names::{NamedToken, SmallName, Token};

use crate::ctx::ExecCtx;
use crate::eval::bytecode::{NodeBytecode, PreparedBytecode};
use crate::eval::{binary_pure, bound_is_row_invariant, eval, orient, predicate_value_holds};
use crate::overlay::ExecGraph;
use crate::row::Row;

/// One node's compiled property predicate: the bound stays an expression
/// until the stage prepares it (the lazy, once-per-stage evaluation).
#[derive(Clone, Debug)]
pub(crate) enum Prog {
    /// Labels only — no property predicate.
    Bare,
    /// `<var>.<key> <op> <bound>` with a row-invariant, deterministic
    /// bound. The comparison is the shared [`binary`] — the one canonical
    /// evaluator, three-valued logic included (a null operand makes the
    /// comparison null, and a `WHERE` keeps only `true`).
    Cmp {
        key: NamedToken,
        op: BinaryOp,
        bound: Expr,
    },
    /// `<var>.<key> IS [NOT] NULL` — answered from the property read
    /// alone; nothing can error.
    Null { key: NamedToken, is_null: bool },
    /// Multi-predicate, multi-entry property map, or boolean `OR`/`NOT`
    /// expression over the node's own properties, compiled to flat stack
    /// bytecode (ADR-0720).
    Bytecode(NodeBytecode),
}

/// One pattern node plus its compiled program: what a kernel stage admits
/// candidates against.
pub(crate) struct NodeTarget<'a> {
    pub(crate) pattern: &'a NodePattern,
    pub(crate) prog: Prog,
    pub(crate) bytecode: Option<NodeBytecode>,
}

impl NodeTarget<'_> {
    /// Whether the node admits every node: no label, dynamic label
    /// expression, property map, inline element `WHERE`, or compiled
    /// predicate.
    pub(crate) fn unfiltered(&self) -> bool {
        self.pattern.labels.is_empty()
            && self.pattern.label_expr.is_none()
            && self.pattern.properties.is_none()
            && self.pattern.where_clause.is_none()
            && matches!(self.prog, Prog::Bare)
    }
}

/// The interned form of a pattern's static label conjunction, resolved
/// once per stage ([`NodePred::prepare`]): one interner lookup per label,
/// never per candidate (ADR-0473 — the per-candidate string interning was
/// the measured gap between the first kernel cut and the speed-of-light
/// kernels). A label nothing in the committed store ever carried has no
/// id — no committed node can carry it either, so its check fails without
/// a store read; a write scratch's overlay is the exception (write-path
/// labels stay strings there, interned only at commit), and its nodes
/// answer through the string arm instead.
pub(crate) struct InternedLabels<'a> {
    labels: &'a [(SmallName, Token)],
    ids: Vec<Option<u32>>,
}

impl InternedLabels<'_> {
    /// Read the ids the planner resolved onto `pattern` (ADR-0541); an
    /// unresolved plan falls back to the interner lookup, a label the plan
    /// saw as never interned has no id.
    pub(crate) fn resolve<'a>(ctx: ExecCtx<'_>, pattern: &'a NodePattern) -> InternedLabels<'a> {
        InternedLabels {
            labels: &pattern.labels,
            ids: pattern
                .labels
                .iter()
                .map(|(label, token)| {
                    token.id_or_else(|| {
                        label.with_str(|text| ctx.graph.base().interned_label_id(text))
                    })
                })
                .collect(),
        }
    }

    /// The static label conjunction and visibility check — `node_ok`'s two
    /// label arms for an unbound variable: every pattern label present
    /// (`None` for an invisible node fails exactly like an absent label),
    /// and a pattern with no labels at all checking bare visibility.
    #[inline]
    pub(crate) fn admits(&self, graph: &ExecGraph<'_>, node: NodeId) -> bool {
        if self.labels.is_empty() {
            return graph.node_exists(node);
        }
        self.labels
            .iter()
            .zip(&self.ids)
            .all(|((label, _), id)| match id {
                Some(id) => matches!(
                    label.with_str(|text| graph.node_has_label_id(node, *id, text)),
                    Some(true)
                ),
                // A label the base interner never recorded can still ride
                // a write scratch: write-path labels stay strings in the
                // overlay, interned only at commit, so the string arm of
                // `node_has_label` serves them. Without a scratch nothing
                // can carry an uninterned label, so the check fails
                // without a store read.
                None => {
                    label.with_str(|text| graph.node_has_uninterned_label(node, text)) == Some(true)
                }
            })
    }
}

/// The per-candidate admission check, monomorphized (ADR-0473). A kernel
/// loop is generic over `P`; the stage dispatches once (one `match` over
/// the compiled [`Prog`]) and every candidate's check inside the loop is
/// this trait's method — statically dispatched and inlined, never a
/// per-row `dyn Fn`.
///
/// The check order is the walker's own, and that order is what keeps an
/// erroring bound's *presence* identical to the per-row path's: the label
/// conjunction first (`node_ok`'s arms — a candidate the labels reject
/// never reaches the predicate, exactly as `match_node` runs `node_ok`
/// before `residual_ok`), then the property predicate, with the
/// row-invariant bound evaluated lazily — once, at the first candidate
/// that reaches the comparison. A candidate set that never reaches the
/// comparison never evaluates the bound, the per-row path's behavior for
/// a `WHERE` whose rows all stop earlier.
pub(crate) trait NodePred: Copy {
    /// The per-run prepared form: the bound's value, evaluated at most
    /// once per stage.
    type Prepared;

    /// Evaluate the row-invariant bound. Called only from
    /// [`NodePred::admits`]'s lazy path (and once per run).
    fn prepare(&self, ctx: ExecCtx<'_>) -> Result<Self::Prepared>;

    /// Whether `node` admits, over the prepared facts alone.
    fn check(&self, prepared: &mut Self::Prepared, ctx: ExecCtx<'_>, node: NodeId) -> Result<bool>;

    /// Whether `node` admits: the prepared slot filled at the first
    /// candidate that reaches the check — the lazy once-per-stage
    /// evaluation, spelled here once so no impl carries the preamble.
    fn admits(
        &self,
        prepared: &mut Option<Self::Prepared>,
        ctx: ExecCtx<'_>,
        node: NodeId,
    ) -> Result<bool> {
        if prepared.is_none() {
            *prepared = Some(self.prepare(ctx)?);
        }
        self.check(
            prepared.as_mut().expect("prepared before the check"),
            ctx,
            node,
        )
    }
}

/// A property-only check run after [`InternedLabels::admits`] has cleared the
/// node's static label conjunction.
pub(crate) trait PropCheck {
    fn check_props(&mut self, ctx: ExecCtx<'_>, node: NodeId) -> Result<bool>;
}

/// Shared label-gated wrapper for every property-bearing prepared predicate:
/// checks the interned label conjunction once before delegating to the
/// property check, so no prepared variant duplicates the label guard.
pub(crate) struct PreparedPred<'a, C> {
    labels: InternedLabels<'a>,
    check: C,
}

impl<C: PropCheck> PreparedPred<'_, C> {
    fn admits(&mut self, ctx: ExecCtx<'_>, node: NodeId) -> Result<bool> {
        if !self.labels.admits(ctx.graph, node) {
            return Ok(false);
        }
        self.check.check_props(ctx, node)
    }
}

/// The prepared comparison check: the bound's value, evaluated once per run.
pub(crate) struct CmpCheck<'a> {
    key: &'a NamedToken,
    op: BinaryOp,
    value: Value,
}

impl PropCheck for CmpCheck<'_> {
    fn check_props(&mut self, ctx: ExecCtx<'_>, node: NodeId) -> Result<bool> {
        // A null bound makes every comparison null, and a `WHERE` drops
        // null — the shortcut is `binary`'s own null arm, without paying
        // the property read.
        if self.value.is_null() {
            return Ok(false);
        }
        // The canonical property read: a missing property is null, and a
        // null operand is `binary`'s null arm again.
        let have = ctx
            .graph
            .node_prop_resolved(node, self.key)
            .unwrap_or(Value::Null);
        if have.is_null() {
            return Ok(false);
        }
        predicate_value_holds(&binary_pure(self.op, have, self.value.clone())?)
    }
}

/// The prepared null check: the property key and written polarity.
pub(crate) struct NullCheck<'a> {
    key: &'a NamedToken,
    is_null: bool,
}

impl PropCheck for NullCheck<'_> {
    fn check_props(&mut self, ctx: ExecCtx<'_>, node: NodeId) -> Result<bool> {
        let is_null = ctx
            .graph
            .node_prop_resolved(node, self.key)
            .is_none_or(|value: Value| value.is_null());
        Ok(is_null == self.is_null)
    }
}

impl PropCheck for PreparedBytecode<'_> {
    fn check_props(&mut self, ctx: ExecCtx<'_>, node: NodeId) -> Result<bool> {
        self.admits(ctx, node)
    }
}

/// The compiled program's prepared form — the small enum holding the stage's
/// resolved facts (interned labels and any evaluated bound or bytecode
/// stack), with per-candidate check inlined via [`Self::admits`].
pub(crate) enum AdmissionPrepared<'a> {
    Bare(InternedLabels<'a>),
    Cmp(PreparedPred<'a, CmpCheck<'a>>),
    Null(PreparedPred<'a, NullCheck<'a>>),
    Bytecode(PreparedPred<'a, PreparedBytecode<'a>>),
}

impl AdmissionPrepared<'_> {
    /// The prepared form's check — the variant's own, over its prepared
    /// facts.
    fn admits(&mut self, ctx: ExecCtx<'_>, node: NodeId) -> Result<bool> {
        match self {
            AdmissionPrepared::Bare(labels) => Ok(labels.admits(ctx.graph, node)),
            AdmissionPrepared::Cmp(prepared) => prepared.admits(ctx, node),
            AdmissionPrepared::Null(prepared) => prepared.admits(ctx, node),
            AdmissionPrepared::Bytecode(prepared) => prepared.admits(ctx, node),
        }
    }
}

impl<'a> NodePred for &'a NodeTarget<'a> {
    type Prepared = AdmissionPrepared<'a>;

    fn prepare(&self, ctx: ExecCtx<'_>) -> Result<Self::Prepared> {
        let labels = InternedLabels::resolve(ctx, self.pattern);
        Ok(match &self.prog {
            Prog::Bare => AdmissionPrepared::Bare(labels),
            Prog::Cmp { key, op, bound } => {
                let value = eval(ctx.graph, &Row::new(), bound, ctx.params)?;
                AdmissionPrepared::Cmp(PreparedPred {
                    labels,
                    check: CmpCheck {
                        key,
                        op: *op,
                        value,
                    },
                })
            }
            Prog::Null { key, is_null } => AdmissionPrepared::Null(PreparedPred {
                labels,
                check: NullCheck {
                    key,
                    is_null: *is_null,
                },
            }),
            Prog::Bytecode(code) => AdmissionPrepared::Bytecode(PreparedPred {
                labels,
                check: code.prepare(ctx)?,
            }),
        })
    }

    fn check(&self, prepared: &mut Self::Prepared, ctx: ExecCtx<'_>, node: NodeId) -> Result<bool> {
        prepared.admits(ctx, node)
    }
}

/// One node's compiled admission (ADR-0473 + ADR-0720): zero or one simple
/// predicate compiles to `Prog::Bare` / `Prog::Cmp` / `Prog::Null` for zero
/// overhead; multi-predicate conjunctions, multi-entry property maps, or
/// boolean `OR`/`NOT` expressions compile to `Prog::Bytecode(NodeBytecode)`.
///
/// An inline element `WHERE` or dynamic label expression declines here —
/// `NodeTarget` reads neither, so riding one would silently drop the check.
/// Every kernel family (chains, hub-stars, and the frontier boundary matcher)
/// compiles node targets through this one function.
pub(crate) fn compile_node<'a>(
    pattern: &'a NodePattern,
    grouped: &BTreeMap<SmallName, Vec<&Expr>>,
) -> Option<NodeTarget<'a>> {
    if pattern.where_clause.is_some() || !pattern.has_static_labels() {
        return None;
    }
    let conjuncts = pattern
        .variable
        .as_ref()
        .and_then(|var| grouped.get(var))
        .map(Vec::as_slice)
        .unwrap_or(&[]);
    let map_entries: Vec<(NamedToken, &Expr)> = match &pattern.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 None;
                }
                out.push((pattern_prop_key(&pattern.prop_keys, key), value));
            }
            out
        }
        // A non-map property expression stays with the walker's `map_from_expr`.
        Some(_) => return None,
    };
    let prog = match (map_entries.as_slice(), conjuncts) {
        ([], []) => Prog::Bare,
        ([(key, value)], []) => Prog::Cmp {
            key: key.clone(),
            op: BinaryOp::Eq,
            bound: (*value).clone(),
        },
        ([], [only]) => {
            if let Some((_, prog)) = decode_conjunct(only) {
                prog
            } else {
                Prog::Bytecode(NodeBytecode::compile_entries_and_exprs(
                    pattern.variable.as_ref(),
                    std::iter::empty(),
                    std::iter::once(*only),
                )?)
            }
        }
        _ => Prog::Bytecode(NodeBytecode::compile_entries_and_exprs(
            pattern.variable.as_ref(),
            map_entries,
            conjuncts.iter().copied(),
        )?),
    };
    let bytecode = match &prog {
        Prog::Bare => None,
        Prog::Bytecode(code) => Some(code.clone()),
        Prog::Cmp { key, op, bound } => Some(NodeBytecode::from_cmp(key.clone(), *op, bound)?),
        Prog::Null { key, is_null } => Some(NodeBytecode::from_null(key.clone(), *is_null)?),
    };
    Some(NodeTarget {
        pattern,
        prog,
        bytecode,
    })
}

/// Decode one flattened `WHERE` conjunct into the kernels' vocabulary:
/// the conjunct's variable plus its compiled [`Prog`]. `None` declines —
/// the shape is outside the vocabulary, and the caller keeps the per-row
/// path for the whole clause.
///
/// The one canonical decode of a property conjunct against a
/// row-invariant bound: the mirror policy is the shared `orient`
/// (a property on the right of a symmetric comparison flips the operator;
/// a property on the right of an operand-asymmetric one — `IN`, the string
/// predicates — declines), and the bound's row-invariance, determinism,
/// and scope-freedom are proven here once. The scan-filter chain's gate
/// (`exec/batch.rs`) reads the same proof for its own bounds.
pub(crate) fn decode_conjunct(expr: &Expr) -> Option<(String, Prog)> {
    match expr {
        Expr::Unary { op, expr } => {
            let is_null = match op {
                UnaryOp::IsNull => true,
                UnaryOp::IsNotNull => false,
                _ => return None,
            };
            let (var, key) = var_prop_named(expr)?;
            Some((var.to_string(), Prog::Null { key, is_null }))
        }
        Expr::Binary { op, left, right } if is_pred_op(*op) => {
            let ((var, key), other, op) = orient(var_prop_named, left, right, *op)?;
            if !bound_is_row_invariant(other) {
                return None;
            }
            Some((
                var.to_string(),
                Prog::Cmp {
                    key,
                    op,
                    bound: other.clone(),
                },
            ))
        }
        _ => None,
    }
}

#[cfg(test)]
mod tests {
    use relate_front::parse_and_lower;
    use relate_ir::Clause;

    use super::*;

    /// The flattened `WHERE` conjuncts of a planned single-clause `MATCH`.
    fn where_conjuncts(cypher: &str) -> Vec<Expr> {
        let query = parse_and_lower(cypher).unwrap();
        let plan = relate_planner::plan(query, &mut |_| false).unwrap();
        match &plan.parts[0][0] {
            Clause::Match {
                where_clause: Some(w),
                ..
            } => crate::exec::pushdown::flatten_and_owned(w),
            other => panic!("not a MATCH with WHERE: {other:?}"),
        }
    }

    fn decoded(cypher: &str) -> Vec<Option<(String, Prog)>> {
        where_conjuncts(cypher)
            .iter()
            .map(decode_conjunct)
            .collect()
    }

    fn is_bare(prog: &Prog) -> bool {
        matches!(prog, Prog::Bare)
    }

    // The vocabulary: every comparison operator the shared pred-op table
    // admits decodes, mirrored comparisons orient, and null checks decode.
    #[test]
    fn comparison_and_null_conjuncts_decode() {
        let cases = decoded(
            "MATCH (n) WHERE n.k > 1 AND n.s CONTAINS 'x' AND n.t STARTS WITH 'a' \
             AND n.l IN [1, 2] AND n.z IS NOT NULL RETURN n",
        );
        assert_eq!(cases.len(), 5);
        for case in &cases {
            assert!(case.is_some(), "every conjunct decodes: {case:?}");
        }
        let Some((var, Prog::Cmp { op, .. })) = &cases[0] else {
            panic!("first conjunct is a comparison");
        };
        assert_eq!(var, "n");
        assert_eq!(*op, BinaryOp::Gt);
        let Some((_, Prog::Null { is_null, .. })) = &cases[4] else {
            panic!("last conjunct is a null check");
        };
        assert!(!*is_null);
    }

    #[test]
    fn mirrored_comparisons_orient_instead_of_declining() {
        let cases = decoded("MATCH (n) WHERE 1 < n.k RETURN n");
        let Some((var, Prog::Cmp { op, .. })) = &cases[0] else {
            panic!("a mirrored comparison orients");
        };
        assert_eq!(var, "n");
        assert_eq!(*op, BinaryOp::Gt, "1 < n.k is n.k > 1");
    }

    // The declines: two properties compared (bound not row-invariant), a
    // function over the row, OR, NOT, a nondeterministic bound, a
    // parameterized bound stays (row-invariant), and a property on the
    // right of an operand-asymmetric comparison.
    #[test]
    fn out_of_vocabulary_conjuncts_decline() {
        let declines = [
            "MATCH (n) WHERE n.a > n.b RETURN n",
            "MATCH (n) WHERE size(n.k) > 3 RETURN n",
            "MATCH (n) WHERE n.k > 1 OR n.j < 2 RETURN n",
            "MATCH (n) WHERE NOT n.k > 1 RETURN n",
            "MATCH (n) WHERE n.k > toInteger(rand()) RETURN n",
            "MATCH (n) WHERE [1] IN n.k RETURN n",
        ];
        for cypher in declines {
            for case in decoded(cypher) {
                assert!(case.is_none(), "{cypher} declines: {case:?}");
            }
        }
        // A parameter bound is row-invariant: it decodes.
        for case in decoded("MATCH (n) WHERE n.k > $min RETURN n") {
            assert!(case.is_some(), "a parameter bound decodes");
        }
    }

    #[test]
    fn bare_and_clone_shapes() {
        assert!(is_bare(&Prog::Bare));
        // Prog is Clone (the matcher stores it beside its pattern).
        let prog = Prog::Cmp {
            key: ("k".into(), Token::Unresolved),
            op: BinaryOp::Eq,
            bound: Expr::Int(1),
        };
        assert!(matches!(prog.clone(), Prog::Cmp { .. }));
    }
}