relate-executor 1.0.1

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
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
//! The contracted kernels' predicate programs (ADR-0473): 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 **at most one**
//! property predicate (`<var>.<key> <op> <row-invariant bound>` or
//! `<var>.<key> IS [NOT] NULL`). A second predicate on the same variable, or
//! any conjunct shape outside the vocabulary (functions over the row, `OR`,
//! `NOT`, property maps, comparisons of two properties), declines the whole
//! clause — the per-row walker keeps it, answers identical (the differential
//! tests pin that). The one-predicate bound is what keeps the monomorphic
//! table closed: three program kinds, three instantiations of every kernel
//! loop, no filter-axis template grid (ADR-0473's rejection).
//!
//! The bound is evaluated **lazily, once per stage**: a stage with no
//! candidates never evaluates it, 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 relate_core::{NodeId, Result, Value};
use relate_ir::{var_prop_named, BinaryOp, Expr, NodePattern, UnaryOp};
use relate_names::{NamedToken, SmallName, Token};

use crate::ctx::ExecCtx;
use crate::eval::{binary_pure, eval, expr_vars, is_nondeterministic, orient};
use crate::overlay::ExecGraph;
use crate::row::Row;

use super::super::agg_fold::is_pred_op;

/// 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 },
}

/// 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,
}

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.
    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.
    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.
    fn admits(
        &self,
        prepared: &mut Option<Self::Prepared>,
        ctx: ExecCtx<'_>,
        node: NodeId,
    ) -> Result<bool>;
}

/// Labels only.
#[derive(Clone, Copy)]
pub(crate) struct LabelsOnly<'a> {
    pattern: &'a NodePattern,
}

/// Labels plus one property comparison.
#[derive(Clone, Copy)]
pub(crate) struct PropCmp<'a> {
    pattern: &'a NodePattern,
    key: &'a NamedToken,
    op: BinaryOp,
    bound: &'a Expr,
}

/// Labels plus one null check.
#[derive(Clone, Copy)]
pub(crate) struct PropNull<'a> {
    pattern: &'a NodePattern,
    key: &'a NamedToken,
    is_null: bool,
}

impl<'a> NodePred for LabelsOnly<'a> {
    type Prepared = InternedLabels<'a>;

    fn prepare(&self, ctx: ExecCtx<'_>) -> Result<Self::Prepared> {
        Ok(InternedLabels::resolve(ctx, self.pattern))
    }

    fn admits(
        &self,
        prepared: &mut Option<Self::Prepared>,
        ctx: ExecCtx<'_>,
        node: NodeId,
    ) -> Result<bool> {
        if prepared.is_none() {
            *prepared = Some(self.prepare(ctx)?);
        }
        let prepared = prepared.as_ref().expect("prepared before the label check");
        Ok(prepared.admits(ctx.graph, node))
    }
}

/// The prepared comparison: the bound's value, evaluated once per run,
/// plus the interned labels (checked before the comparison) — and the
/// check itself, over the prepared facts alone.
pub(crate) struct CmpPrepared<'a> {
    labels: InternedLabels<'a>,
    key: &'a NamedToken,
    op: BinaryOp,
    value: Value,
}

impl CmpPrepared<'_> {
    /// The comparison check: the label conjunction first, then the
    /// canonical property read against the once-evaluated bound.
    fn admits(&self, ctx: ExecCtx<'_>, node: NodeId) -> Result<bool> {
        if !self.labels.admits(ctx.graph, node) {
            return Ok(false);
        }
        // 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);
        }
        Ok(binary_pure(self.op, have, self.value.clone())?.truthy() == Some(true))
    }
}

impl<'a> NodePred for PropCmp<'a> {
    type Prepared = CmpPrepared<'a>;

    fn prepare(&self, ctx: ExecCtx<'_>) -> Result<Self::Prepared> {
        // The bound is variable-free by the decoder, so the empty row it
        // cannot read is inert — the same evaluation the per-row path
        // makes against each matched row, minus the row it never reads.
        let value = eval(
            ctx.graph,
            &Row::new(),
            self.bound,
            ctx.params,
            ctx.cypher_version,
        )?;
        Ok(CmpPrepared {
            labels: InternedLabels::resolve(ctx, self.pattern),
            key: self.key,
            op: self.op,
            value,
        })
    }

    fn admits(
        &self,
        prepared: &mut Option<Self::Prepared>,
        ctx: ExecCtx<'_>,
        node: NodeId,
    ) -> Result<bool> {
        if prepared.is_none() {
            *prepared = Some(self.prepare(ctx)?);
        }
        let prepared = prepared.as_ref().expect("prepared before the comparison");
        prepared.admits(ctx, node)
    }
}

impl<'a> NodePred for PropNull<'a> {
    type Prepared = PreparedNull<'a>;

    fn prepare(&self, ctx: ExecCtx<'_>) -> Result<Self::Prepared> {
        Ok(PreparedNull {
            labels: InternedLabels::resolve(ctx, self.pattern),
            key: self.key,
            is_null: self.is_null,
        })
    }

    fn admits(
        &self,
        prepared: &mut Option<Self::Prepared>,
        ctx: ExecCtx<'_>,
        node: NodeId,
    ) -> Result<bool> {
        if prepared.is_none() {
            *prepared = Some(self.prepare(ctx)?);
        }
        let prepared = prepared.as_ref().expect("prepared before the null check");
        prepared.admits(ctx, node)
    }
}

/// The prepared null check: the interned labels plus the key and the
/// written polarity — the check itself reads only the property.
pub(crate) struct PreparedNull<'a> {
    labels: InternedLabels<'a>,
    key: &'a NamedToken,
    is_null: bool,
}

impl PreparedNull<'_> {
    /// The null check: the label conjunction first, then the property
    /// read's presence compared to the written polarity.
    fn admits(&self, ctx: ExecCtx<'_>, node: NodeId) -> Result<bool> {
        if !self.labels.admits(ctx.graph, node) {
            return Ok(false);
        }
        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)
    }
}

/// The monomorphic admission of one [`NodeTarget`] — the one runtime
/// dispatch per stage: the caller passes it to its kernel loop, after
/// which every per-candidate check inside the loop is
/// [`NodePred::admits`], statically dispatched and inlined. The three
/// arms are the whole vocabulary; a program outside them is
/// unconstructible (the decoder declines before a stage exists).
#[derive(Clone, Copy)]
pub(crate) enum Admission<'a> {
    Bare(LabelsOnly<'a>),
    Cmp(PropCmp<'a>),
    Null(PropNull<'a>),
}

/// The [`Admission`] wrapper's prepared form — the small enum that folds
/// the three kinds' prepared forms into one, so a kernel loop holds one
/// `Option<AdmissionPrepared>` beside one `Admission` and never
/// re-dispatches per candidate.
pub(crate) enum AdmissionPrepared<'a> {
    Bare(InternedLabels<'a>),
    Cmp(CmpPrepared<'a>),
    Null(PreparedNull<'a>),
}

impl AdmissionPrepared<'_> {
    /// The prepared form's check — the variant's own, over its prepared
    /// facts.
    fn admits(&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),
        }
    }
}

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

    fn prepare(&self, ctx: ExecCtx<'_>) -> Result<Self::Prepared> {
        Ok(match self {
            Admission::Bare(pred) => AdmissionPrepared::Bare(pred.prepare(ctx)?),
            Admission::Cmp(pred) => AdmissionPrepared::Cmp(pred.prepare(ctx)?),
            Admission::Null(pred) => AdmissionPrepared::Null(pred.prepare(ctx)?),
        })
    }

    fn admits(
        &self,
        prepared: &mut Option<Self::Prepared>,
        ctx: ExecCtx<'_>,
        node: NodeId,
    ) -> Result<bool> {
        if prepared.is_none() {
            *prepared = Some(self.prepare(ctx)?);
        }
        let prepared = prepared
            .as_ref()
            .expect("the wrapper prepares before the check");
        prepared.admits(ctx, node)
    }
}

impl<'a> Admission<'a> {
    /// The dispatched admission of `target`'s compiled program.
    pub(crate) fn of(target: &'a NodeTarget<'a>) -> Admission<'a> {
        let pattern = target.pattern;
        match &target.prog {
            Prog::Bare => Admission::Bare(LabelsOnly { pattern }),
            Prog::Cmp { key, op, bound } => Admission::Cmp(PropCmp {
                pattern,
                key,
                op: *op,
                bound,
            }),
            Prog::Null { key, is_null } => Admission::Null(PropNull {
                pattern,
                key,
                is_null: *is_null,
            }),
        }
    }
}

/// 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,
    }
}

/// Whether the bound expression may evaluate once per clause instead of
/// per row: no variables at all (so no row can change it), no
/// nondeterministic call (`rand()` may differ per row), and no
/// scope-bearing variant (a subquery hides its internals from the walk).
pub(crate) fn bound_is_row_invariant(bound: &Expr) -> bool {
    let mut named = std::collections::HashSet::new();
    expr_vars(bound, &mut named);
    named.is_empty()
        && !bound.any(&mut |expr| {
            matches!(expr, Expr::Function { name, .. }
                if name.with_str(is_nondeterministic))
                || expr.is_scope_bearing()
        })
}

#[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 { .. }));
    }
}