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
//! Flat stack-based bytecode evaluator for single-node predicates (ADR-0720).
//!
//! Compiles arbitrary boolean combinations (`AND`, `OR`, `NOT`), comparisons
//! (`relate_ir::is_pred_op`, including mirrored comparisons and two-property
//! comparisons on the same node), null checks (`IS [NOT] NULL`), and
//! multi-entry property maps over a single node variable into a flat
//! `Vec<Op>` program. Row-invariant bounds are evaluated lazily once per stage
//! on the first candidate that reaches the program, and a stage-owned
//! `Vec<Value>` stack is reused across candidates (zero per-candidate stack
//! allocation). Every binary and unary operation delegates to the canonical
//! `eval::binary_pure` and `eval::unary` implementations.

use std::borrow::Cow;

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

use crate::ctx::ExecCtx;
use crate::eval::{
    binary_pure, bound_is_row_invariant, eval, flip_cmp, predicate_value_holds, unary,
};
use crate::row::Row;

/// Maximum instruction count admitted by a single compiled node predicate.
/// Expressions exceeding this budget decline cleanly to the general walker.
const MAX_BYTECODE_OPS: usize = 512;

/// Maximum AST recursion depth admitted during bytecode compilation.
/// Deeply nested expressions decline cleanly to the general walker.
const MAX_BYTECODE_DEPTH: usize = 32;

/// One instruction of a single-node predicate program.
#[derive(Clone, Copy, Debug)]
enum Op {
    /// Push `graph.node_prop_resolved(node, &keys[idx]).unwrap_or(Value::Null)`.
    LoadProp(u16),
    /// Push `prepared_consts[idx].clone()`.
    LoadConst(u16),
    /// Pop `(lhs, rhs)` and push `binary_pure(op, lhs, rhs)?`.
    Binary(BinaryOp),
    /// Pop `v` and push `unary(op, v)?`.
    Unary(UnaryOp),
}

/// A compiled single-node predicate program over one variable.
#[derive(Clone, Debug)]
pub(crate) struct NodeBytecode {
    ops: Vec<Op>,
    keys: Vec<NamedToken>,
    consts: Vec<Expr>,
}

/// Stage-prepared state for [`NodeBytecode`]: structurally paired with its
/// bytecode program, holding once-evaluated row-invariant constants plus a
/// reusable evaluation stack.
pub(crate) struct PreparedBytecode<'a> {
    code: Cow<'a, NodeBytecode>,
    consts: Vec<Value>,
    stack: Vec<Value>,
    prop_buffers: Vec<Vec<Option<Value>>>,
}

enum Operand<'e> {
    Prop(NamedToken),
    Bound(&'e Expr),
}

fn operand<'e>(var: &SmallName, expr: &'e Expr) -> Option<Operand<'e>> {
    if let Some((v, key)) = var_prop_named(expr) {
        if v == var {
            Some(Operand::Prop(key))
        } else {
            None
        }
    } else if bound_is_row_invariant(expr) {
        Some(Operand::Bound(expr))
    } else {
        None
    }
}

type PreparedParts = (Vec<Value>, Vec<Value>, Vec<Vec<Option<Value>>>);

impl NodeBytecode {
    /// Compile a list of `(key, value)` property-map equality entries plus
    /// optional additional conjuncts (all over `var`) into one [`NodeBytecode`].
    ///
    /// `var` may be `None` when the node pattern is anonymous and only
    /// property-map entries are present; if any `conjuncts` are supplied
    /// without a variable name, compilation declines (`None`).
    pub(crate) fn compile_entries_and_exprs<'a>(
        var: Option<&SmallName>,
        entries: impl IntoIterator<Item = (NamedToken, &'a Expr)>,
        conjuncts: impl IntoIterator<Item = &'a Expr>,
    ) -> Option<Self> {
        let mut code = Self {
            ops: Vec::new(),
            keys: Vec::new(),
            consts: Vec::new(),
        };
        let mut count = 0usize;
        for (key, value) in entries {
            code.emit_prop_cmp(key, BinaryOp::Eq, value)?;
            code.chain_and(&mut count)?;
        }
        for expr in conjuncts {
            let var = var?;
            code.emit_bool(var, expr, 0)?;
            code.chain_and(&mut count)?;
        }
        (count > 0).then_some(code)
    }

    /// Compile a single comparison predicate into bytecode.
    pub(crate) fn from_cmp(key: NamedToken, op: BinaryOp, bound: &Expr) -> Option<Self> {
        let mut code = Self {
            ops: Vec::new(),
            keys: Vec::new(),
            consts: Vec::new(),
        };
        code.emit_prop_cmp(key, op, bound)?;
        Some(code)
    }

    /// Compile a single null-check predicate into bytecode.
    pub(crate) fn from_null(key: NamedToken, is_null: bool) -> Option<Self> {
        let mut code = Self {
            ops: Vec::new(),
            keys: Vec::new(),
            consts: Vec::new(),
        };
        let k = code.intern_key(key)?;
        code.push_op(Op::LoadProp(k))?;
        code.push_op(Op::Unary(if is_null {
            UnaryOp::IsNull
        } else {
            UnaryOp::IsNotNull
        }))?;
        Some(code)
    }

    fn prepare_parts(&self, ctx: ExecCtx<'_>) -> Result<PreparedParts> {
        let empty = Row::new();
        let mut consts = Vec::with_capacity(self.consts.len());
        for expr in &self.consts {
            consts.push(eval(ctx.graph, &empty, expr, ctx.params)?);
        }
        let mut prop_buffers = Vec::with_capacity(self.keys.len());
        for _ in 0..self.keys.len() {
            prop_buffers.push(Vec::new());
        }
        Ok((consts, Vec::with_capacity(8), prop_buffers))
    }

    /// Lazily evaluate all row-invariant constant operands once per stage.
    pub(crate) fn prepare(&self, ctx: ExecCtx<'_>) -> Result<PreparedBytecode<'_>> {
        let (consts, stack, prop_buffers) = self.prepare_parts(ctx)?;
        Ok(PreparedBytecode {
            code: Cow::Borrowed(self),
            consts,
            stack,
            prop_buffers,
        })
    }

    /// Prepare a stage-owned [`PreparedBytecode`] directly from an owned [`NodeBytecode`].
    pub(crate) fn prepare_owned(self, ctx: ExecCtx<'_>) -> Result<PreparedBytecode<'static>> {
        let (consts, stack, prop_buffers) = self.prepare_parts(ctx)?;
        Ok(PreparedBytecode {
            code: Cow::Owned(self),
            consts,
            stack,
            prop_buffers,
        })
    }

    fn push_op(&mut self, op: Op) -> Option<()> {
        if self.ops.len() >= MAX_BYTECODE_OPS {
            return None;
        }
        self.ops.push(op);
        Some(())
    }

    fn chain_and(&mut self, count: &mut usize) -> Option<()> {
        if *count > 0 {
            self.push_op(Op::Binary(BinaryOp::And))?;
        }
        *count += 1;
        Some(())
    }

    fn intern_key(&mut self, key: NamedToken) -> Option<u16> {
        if let Some(pos) = self.keys.iter().position(|(name, _)| *name == key.0) {
            return Some(u16::try_from(pos).expect("keys length is bounded by u16::MAX on push"));
        }
        let idx = u16::try_from(self.keys.len()).ok()?;
        self.keys.push(key);
        Some(idx)
    }

    fn push_const(&mut self, expr: Expr) -> Option<u16> {
        let idx = u16::try_from(self.consts.len()).ok()?;
        self.consts.push(expr);
        Some(idx)
    }

    fn emit_prop_cmp(&mut self, key: NamedToken, op: BinaryOp, bound: &Expr) -> Option<()> {
        if !bound_is_row_invariant(bound) {
            return None;
        }
        let k = self.intern_key(key)?;
        let c = self.push_const(bound.clone())?;
        self.push_op(Op::LoadProp(k))?;
        self.push_op(Op::LoadConst(c))?;
        self.push_op(Op::Binary(op))
    }

    fn emit_bool(&mut self, var: &SmallName, expr: &Expr, depth: usize) -> Option<()> {
        if depth >= MAX_BYTECODE_DEPTH {
            return None;
        }
        match expr {
            Expr::Binary {
                op: op @ (BinaryOp::And | BinaryOp::Or),
                left,
                right,
            } => {
                self.emit_bool(var, left, depth + 1)?;
                self.emit_bool(var, right, depth + 1)?;
                self.push_op(Op::Binary(*op))
            }
            Expr::Unary {
                op: UnaryOp::Not,
                expr: inner,
            } => {
                self.emit_bool(var, inner, depth + 1)?;
                self.push_op(Op::Unary(UnaryOp::Not))
            }
            Expr::Unary {
                op: op @ (UnaryOp::IsNull | UnaryOp::IsNotNull),
                expr: inner,
            } => {
                let (v, key) = var_prop_named(inner)?;
                if v != var {
                    return None;
                }
                let k = self.intern_key(key)?;
                self.push_op(Op::LoadProp(k))?;
                self.push_op(Op::Unary(*op))
            }
            Expr::Binary { op, left, right } if is_pred_op(*op) => {
                match (operand(var, left)?, operand(var, right)?) {
                    (Operand::Prop(lk), Operand::Prop(rk)) => {
                        let lk_idx = self.intern_key(lk)?;
                        let rk_idx = self.intern_key(rk)?;
                        self.push_op(Op::LoadProp(lk_idx))?;
                        self.push_op(Op::LoadProp(rk_idx))?;
                        self.push_op(Op::Binary(*op))
                    }
                    (Operand::Prop(k), Operand::Bound(b)) => self.emit_prop_cmp(k, *op, b),
                    (Operand::Bound(b), Operand::Prop(k)) => {
                        let oriented_op = flip_cmp(*op)?;
                        self.emit_prop_cmp(k, oriented_op, b)
                    }
                    (Operand::Bound(_), Operand::Bound(_)) => None,
                }
            }
            _ => None,
        }
    }
}

impl PreparedBytecode<'_> {
    fn eval_program(
        ops: &[Op],
        consts: &[Value],
        stack: &mut Vec<Value>,
        mut load_prop: impl FnMut(u16) -> Value,
    ) -> Result<bool> {
        stack.clear();
        for &op in ops {
            match op {
                Op::LoadProp(idx) => {
                    stack.push(load_prop(idx));
                }
                Op::LoadConst(idx) => {
                    stack.push(consts[idx as usize].clone());
                }
                Op::Binary(bin_op) => {
                    let rhs = stack.pop().expect("bytecode stack underflow (rhs)");
                    let lhs = stack.pop().expect("bytecode stack underflow (lhs)");
                    stack.push(binary_pure(bin_op, lhs, rhs)?);
                }
                Op::Unary(un_op) => {
                    let v = stack.pop().expect("bytecode stack underflow (unary)");
                    stack.push(unary(un_op, v)?);
                }
            }
        }
        let top = stack
            .pop()
            .expect("compiled bytecode program must leave a result on the stack");
        predicate_value_holds(&top)
    }

    /// Evaluate the compiled predicate against `node`, returning `true` iff
    /// the three-valued result holds under [`predicate_value_holds`].
    pub(crate) fn admits(&mut self, ctx: ExecCtx<'_>, node: NodeId) -> Result<bool> {
        let keys = &self.code.keys;
        Self::eval_program(&self.code.ops, &self.consts, &mut self.stack, |idx| {
            let key = &keys[idx as usize];
            ctx.graph
                .node_prop_resolved(node, key)
                .unwrap_or(Value::Null)
        })
    }

    /// Evaluate the compiled predicate across candidate `ids` using `mask` to track active rows.
    ///
    /// Bit `i` in `mask` corresponds to `ids[i]`. Only rows with their bit set are evaluated.
    /// Any row that does not satisfy the predicate (or evaluates to null/false under Cypher 3VL)
    /// has its bit cleared in `mask`.
    ///
    /// If eligible, simple single-property comparisons are fast-pathed via
    /// `ctx.graph.node_filter_range` (`PropStore::filter_range`). Otherwise, referenced properties
    /// are fetched in batch via `ctx.graph.node_prop_batch` into reusable scratch buffers, and the
    /// bytecode is evaluated over surviving candidates.
    pub(crate) fn eval_batch(
        &mut self,
        ctx: ExecCtx<'_>,
        ids: &[NodeId],
        mask: &mut SelectionMask,
    ) -> Result<()> {
        let active = mask.count_ones(ids.len());
        if active == 0 || ids.is_empty() {
            return Ok(());
        }

        // Fast path: single-property comparison via filter_range
        if let [Op::LoadProp(k), Op::LoadConst(c), Op::Binary(bin_op)] = self.code.ops.as_slice() {
            if is_pred_op(*bin_op) {
                let key = &self.code.keys[*k as usize];
                let lit = &self.consts[*c as usize];
                if ctx
                    .graph
                    .node_filter_range(ids, key, *bin_op, lit, mask.as_mut_slice())
                    .is_some()
                {
                    return Ok(());
                }
            }
        }

        // Batch load referenced properties
        for (k_idx, key) in self.code.keys.iter().enumerate() {
            let buf = &mut self.prop_buffers[k_idx];
            buf.resize(ids.len(), None);
            ctx.graph.node_prop_batch(ids, key, buf);
        }

        // Evaluate bytecode program per candidate row
        let snapshot = *mask;
        for idx in snapshot.iter_set(ids.len()) {
            let passed =
                Self::eval_program(&self.code.ops, &self.consts, &mut self.stack, |k_idx| {
                    self.prop_buffers[k_idx as usize][idx]
                        .clone()
                        .unwrap_or(Value::Null)
                })?;
            if !passed {
                mask.clear(idx);
            }
        }
        Ok(())
    }
}

pub(crate) use crate::consumer::BATCH_ROWS;

/// Number of 64-bit words required to represent [`BATCH_ROWS`].
pub(crate) const MASK_WORDS: usize = BATCH_ROWS / 64;

/// Fixed-capacity selection bitmask for up to [`BATCH_ROWS`] rows.
///
/// Backed by a fixed stack array of `[u64; MASK_WORDS]`, paying zero heap allocation.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct SelectionMask {
    words: [u64; MASK_WORDS],
}

impl SelectionMask {
    /// Create a mask with all bits set up to `len` (where `len <= BATCH_ROWS`).
    /// Bits at indices `>= len` are 0.
    #[allow(dead_code)]
    pub(crate) fn all_set(len: usize) -> Self {
        assert!(
            len <= BATCH_ROWS,
            "len ({len}) exceeds BATCH_ROWS ({BATCH_ROWS})"
        );
        let mut words = [0u64; MASK_WORDS];
        let full_words = len / 64;
        for item in words.iter_mut().take(full_words) {
            *item = u64::MAX;
        }
        let rem = len % 64;
        if rem > 0 {
            words[full_words] = (1u64 << rem) - 1;
        }
        Self { words }
    }

    /// Create an empty mask with no bits set.
    pub(crate) fn empty() -> Self {
        Self {
            words: [0u64; MASK_WORDS],
        }
    }

    /// Whether bit `i` is set.
    #[inline]
    pub(crate) fn is_set(&self, i: usize) -> bool {
        assert!(
            i < BATCH_ROWS,
            "index {i} exceeds BATCH_ROWS ({BATCH_ROWS})"
        );
        (self.words[i / 64] & (1u64 << (i % 64))) != 0
    }

    /// Set bit `i`.
    #[inline]
    pub(crate) fn set(&mut self, i: usize) {
        assert!(
            i < BATCH_ROWS,
            "index {i} exceeds BATCH_ROWS ({BATCH_ROWS})"
        );
        self.words[i / 64] |= 1u64 << (i % 64);
    }

    /// Clear bit `i`.
    #[inline]
    pub(crate) fn clear(&mut self, i: usize) {
        assert!(
            i < BATCH_ROWS,
            "index {i} exceeds BATCH_ROWS ({BATCH_ROWS})"
        );
        self.words[i / 64] &= !(1u64 << (i % 64));
    }

    /// As mutable slice of words for passing to store primitives.
    #[inline]
    pub(crate) fn as_mut_slice(&mut self) -> &mut [u64] {
        &mut self.words
    }

    /// As slice of words.
    #[allow(dead_code)]
    #[inline]
    pub(crate) fn as_slice(&self) -> &[u64] {
        &self.words
    }

    /// Count set bits up to `len`.
    pub(crate) fn count_ones(&self, len: usize) -> usize {
        let bound = len.min(BATCH_ROWS);
        let full_words = bound / 64;
        let mut count = 0usize;
        for item in self.words.iter().take(full_words) {
            count += item.count_ones() as usize;
        }
        let rem = bound % 64;
        if rem > 0 {
            let rem_mask = (1u64 << rem) - 1;
            count += (self.words[full_words] & rem_mask).count_ones() as usize;
        }
        count
    }

    /// Iterate indices of all set bits up to `len`.
    pub(crate) fn iter_set(&self, len: usize) -> SelectionMaskIter {
        let bound = len.min(BATCH_ROWS);
        SelectionMaskIter {
            mask: *self,
            len: bound,
            word_idx: 0,
            current_word: if bound > 0 { self.words[0] } else { 0 },
        }
    }
}

/// Iterator over set bit indices in a [`SelectionMask`].
pub(crate) struct SelectionMaskIter {
    mask: SelectionMask,
    len: usize,
    word_idx: usize,
    current_word: u64,
}

impl Iterator for SelectionMaskIter {
    type Item = usize;

    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        while self.current_word == 0 {
            self.word_idx += 1;
            if self.word_idx >= MASK_WORDS || self.word_idx * 64 >= self.len {
                return None;
            }
            self.current_word = self.mask.words[self.word_idx];
        }
        let bit = self.current_word.trailing_zeros() as usize;
        let idx = self.word_idx * 64 + bit;
        if idx >= self.len {
            self.current_word = 0;
            return None;
        }
        self.current_word &= self.current_word - 1;
        Some(idx)
    }
}

#[cfg(test)]
mod tests;