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
//! The contracted-operator layer (ADR-0473): plan-time structural
//! matching over a small family table ([`matcher`]), cost-gated
//! engagement over the planner's own estimate machinery (ADR-0218), and
//! the two traversal kernels — the unrolled fixed-k chain ([`chain`]) and
//! the hub-star candidate intersection ([`hub_star`]) — over the batch
//! substrate's typed column buffers, per-hop predicate programs
//! monomorphized ([`program`]).
//!
//! Engagement is fail-through, never fail-silent: every condition is a
//! proof (the matcher's structural and predicate proofs, the cost gate's
//! estimate), and an unproved clause runs today's per-row walker
//! unchanged — same rows, same errors, so the openCypher TCK is the net
//! either way. The kernels complement the proven machinery, they do not
//! replace it: the aggregate folds (`agg_fold`), the exists probe's
//! depth-first seek, and the scan-filter chain (`exec/batch.rs`) keep
//! every shape the kernels decline; the LABS-348 hub join keeps the
//! multi-row driving tables and the predicate shapes outside the kernels'
//! closed vocabulary (its measured 128-row floor is its own join's
//! grouping cost, which the flat per-hub combination does not pay).
//!
//! The two entry points: [`try_match_kernel`] (the row-returning `MATCH`
//! path, engaged ahead of the per-row walker) and [`try_exists_kernel`]
//! (the existence path, engaged ahead of the exists probe's seek).

pub(crate) mod matcher;
#[cfg(test)]
mod matcher_tests;
pub(crate) mod program;

// The sparse node-keyed map under the frontier family's tables and the
// re-arrival rule's buffers: open-addressed, generation-stamped (O(1)
// reset), sized by the keys inserted — never by the store's span.
pub(crate) mod node_map;

// Input-keyed memoisation of pure per-node checks (LABS-1478): the
// stage-local table and the `Memoized` predicate wrapper the chain kernel
// puts in front of its admission.
pub(crate) mod construct_memo;
pub(crate) mod memo;
pub(crate) mod value_hash;

// The diagnostic engine switch's routing pins (ADR-0519): the forced
// rung, the stood-down kernels, and the auto twin — the switch's own
// suite, beside the rider wiring's.
#[cfg(test)]
mod engine_switch_tests;

// The PROFILE rung record's own pins (LABS-1117): two distinct shapes
// (a fixed chain and a var-length pattern) so a constant rung fails, plus
// the walker's positive record.
#[cfg(test)]
mod rung_tests;

// The kernel ratio guard (REL8-1969): every traversal kernel must beat
// the stood-down walker by 1.5x or more on its own engaging shape — the
// A/B timing lane whose failure retires or widens a kernel.
#[cfg(test)]
mod ratio_guard_tests;

#[cfg(test)]
mod cancel_tests;
mod chain_tally;
pub(crate) mod count_entry;
#[cfg(test)]
mod memo_differential_tests;
#[cfg(test)]
mod memo_profile_tests;
#[cfg(test)]
mod memo_wiring_tests;

pub(crate) use chain_tally::try_fold_two_hop_tally;

use relate_core::{NodeId, Result, Value};
use relate_ir::{
    classify_aggregate, AggregateKind, Clause, Expr, MatchMode, PathPattern, Projection,
};
use relate_planner::{endpoint_estimate, seed_rows};

use crate::ctx::ExecCtx;
use crate::graph::Graph;
use crate::metrics::WalkStart;
use crate::overlay::ExecGraph;
use crate::pattern_engine::PatternEngine;
use crate::pattern_walk::node_candidates;
use crate::row::Row;

use super::agg_fold::FoldedReturn;
use super::graph_stats::GraphStats;
use super::pushdown::{flatten_and_owned, match_scope, Residual};
use super::record_walk_start;

use crate::exec::frontier::frontier_match::{boundary, boundary_vars};
use matcher::Contract;
use program::{NodePred, NodeTarget};

/// The one projection item when the suffix is exactly `RETURN count(*)`
/// / `RETURN count(<boundary var>)` — non-DISTINCT, one item, no
/// grouping, ordering, or paging: the answer is the walk count. The
/// RETURN-shape gate both count folds consult (the frontier walk count
/// and the chain count), so it lives beside them in the shared parent.
pub(crate) fn counted_return<'c>(
    clause: Option<&'c Clause>,
    pattern: &PathPattern,
) -> Option<&'c Projection> {
    let Some(Clause::Return {
        distinct: false,
        group_by: None,
        items,
        order,
        skip: None,
        limit: None,
    }) = clause
    else {
        return None;
    };
    let ([item], true) = (items.as_slice(), order.is_empty()) else {
        return None;
    };
    match &item.expr {
        Expr::CountStar => Some(item),
        Expr::Function {
            name,
            distinct: false,
            args,
        } if name.with_str(classify_aggregate) == Some(AggregateKind::Count) => {
            let [Expr::Variable(var)] = args.as_slice() else {
                return None;
            };
            let (start, target) = boundary(pattern)?;
            boundary_vars(start, target)
                .into_iter()
                .flatten()
                .any(|name| name == var)
                .then_some(item)
        }
        _ => None,
    }
}

/// The count folds' one-row answer tail: the `i64` conversion decline,
/// the item's output name, and the single `(name → count)` cell spelled
/// once for both the row and the result's data, so the two cannot drift.
pub(crate) fn count_fold_tail(
    graph: &ExecGraph<'_>,
    count: u128,
    item: &Projection,
) -> Option<FoldedReturn> {
    let Ok(count) = i64::try_from(count) else {
        return None;
    };
    let name = item.output_name(0);
    let cell = Value::Int(count);
    let mut out = Row::new();
    out.insert(name.clone(), cell.clone());
    Some(FoldedReturn {
        result: super::QueryResult::intermediate(vec![name], vec![vec![cell]], graph.stats()),
        rows: vec![out],
        consumed_after: 1,
    })
}

/// What a caller wants from a contracted kernel.
pub(crate) enum KernelMode<'a> {
    /// Every complete binding, as rows — the clause's output. `want` is
    /// the plain cap's `SKIP+LIMIT` count riding the kernel (LABS-990,
    /// ADR-0524): the kernel's **final collection** — the chain's last
    /// hop, the hub-star's pairing loop — halts after `want` complete
    /// bindings; `None` collects every binding. Only complete bindings
    /// are counted, so the answer is exactly `min(want, total)` —
    /// count-exact by construction, never starved: no intermediate stage
    /// is capped, because the first `want` partials can all die
    /// downstream. Which `want` rows arrive is the kernel's enumeration
    /// order, a contract-free prefix the way ADR-0478 §4 states it for
    /// the frontier's capped emission: LIMIT without ORDER BY promises a
    /// count, not a selection. The count's WHERE-exactness rests on the
    /// kernels' own admissions — a conjunct outside the closed vocabulary
    /// declines the kernel ([`matcher::compile`]), so only kept rows
    /// land and no sink filter runs on this path.
    Rows { want: Option<usize> },
    /// Existence: stop at the first complete binding whose counted
    /// expression is non-null. `None` counts every complete binding (an
    /// `EXISTS { MATCH … }`).
    Exists { counted: Option<&'a Expr> },
}

/// A kernel's answer.
pub(crate) enum KernelOutput {
    Rows(Vec<Row>),
    Exists(bool),
}

/// The row-returning entry: one `MATCH` clause's patterns as the batch
/// chain's traversal twin. `Ok(None)` is the decline — the caller runs
/// its per-row path unchanged; `Ok(Some((rows, rung)))` is the clause's
/// output together with the rung that served it (LABS-1117), so the
/// ladder's return value names the kernel without a second lookup.
///
/// The engagement proofs beyond the matcher's: the clause is the
/// statement's first (a single unbound seed row — bindings carried into a
/// mid-statement clause keep the walker's per-row semantics), not
/// `OPTIONAL` (the null-binding arm is the walker's), and no sink
/// projection rides it (its semantics live in the per-row walker's sink,
/// the batch chain's own gate). A **plain** limit cap rides as the rows
/// mode's `want` — it halts the kernel's final collection (LABS-990;
/// ADR-0524), replacing the earlier policy of dropping the cap and
/// letting the trailing projection truncate a fully enumerated space; the
/// ordered and distinct caps still decline (their semantics are the
/// walker's own, the ladder's gate keeps them there).
#[allow(clippy::too_many_arguments)]
pub(crate) fn try_match_kernel(
    ctx: ExecCtx<'_>,
    rows: &[Row],
    optional: bool,
    match_mode: MatchMode,
    patterns: &[PathPattern],
    where_clause: Option<&Expr>,
    cap_want: Option<usize>,
) -> Result<Option<(Vec<Row>, KernelRung)>> {
    if kernels_stood_down(ctx.graph.base()) {
        return Ok(None);
    }
    if optional || rows.len() != 1 {
        return Ok(None);
    }
    let conjuncts = where_clause.map(flatten_and_owned).unwrap_or_default();
    let Some(contract) = matcher::compile(patterns, match_mode, &rows[0], &conjuncts) else {
        return Ok(None);
    };
    let stats = GraphStats::new(ctx.graph.base(), ctx.params);
    if !engages(&stats, &conjuncts, &contract, false) {
        return Ok(None);
    }
    let rung = contract.rung();
    #[cfg(test)]
    kernel_engaged();
    let residual = Residual {
        conjuncts: &conjuncts,
        scope: &match_scope(ctx.graph, &rows[0], patterns),
    };
    let output = run(
        ctx,
        &contract,
        &residual,
        KernelMode::Rows { want: cap_want },
    )?;
    Ok(Some(match output {
        KernelOutput::Rows(rows) => (rows, rung),
        // `run` answers Rows for the rows mode — the two halves of the
        // enum pair up at the two entry points, never across them.
        KernelOutput::Exists(_) => {
            unreachable!("the row entry never asks for existence")
        }
    }))
}

/// The existence entry: the patterns of a plain `MATCH` span (the
/// boolean-count fold's, or an `EXISTS { MATCH … }` subquery's) with the
/// counted expression of the fold, over the one unbound seed row.
/// `Ok(None)` is the decline — the caller keeps the exists probe.
pub(crate) fn try_exists_kernel(
    ctx: ExecCtx<'_>,
    patterns: &[PathPattern],
    wheres: &[Expr],
    row: &Row,
    match_mode: MatchMode,
    counted: Option<&Expr>,
) -> Result<Option<bool>> {
    if kernels_stood_down(ctx.graph.base()) {
        return Ok(None);
    }
    if match_mode != MatchMode::DifferentRelationships || !row.is_empty() {
        return Ok(None);
    }
    // The counted expression must be a single property read of a node
    // variable (the fold's `count(DISTINCT var.key)` family) — anything
    // richer, or a rel variable's property (the probe's row-shaped eval
    // serves it), keeps the probe.
    if let Some(counted) = counted {
        let Some((var, _)) = relate_ir::var_prop(counted) else {
            return Ok(None);
        };
        let is_node_var = patterns
            .iter()
            .flat_map(|path| path.nodes.iter())
            .any(|node| node.variable.as_ref() == Some(var));
        if !is_node_var {
            return Ok(None);
        }
    }
    let conjuncts: Vec<Expr> = wheres.iter().flat_map(flatten_and_owned).collect();
    let stats = GraphStats::new(ctx.graph.base(), ctx.params);
    if let Some(contract) = matcher::compile(patterns, match_mode, row, &conjuncts) {
        if engages(&stats, &conjuncts, &contract, true) {
            #[cfg(test)]
            kernel_engaged();
            let residual = Residual {
                conjuncts: &conjuncts,
                scope: &match_scope(ctx.graph, row, patterns),
            };
            let output = run(ctx, &contract, &residual, KernelMode::Exists { counted })?;
            return Ok(Some(match output {
                KernelOutput::Exists(hit) => hit,
                KernelOutput::Rows(_) => {
                    unreachable!("the existence entry never asks for rows")
                }
            }));
        }
    }
    // The frontier family's arm (ADR-0478 Decision 2's first shape): the
    // quantified patterns the structural matcher above declines, as a
    // witness existence answer over the BFS. The nested-evaluation
    // budget tick stays the caller's (`patterns_exist`), after this
    // entry answers — one tick per engaged evaluation on either arm,
    // never on decline.
    if let Some(hit) = crate::exec::frontier::frontier_run::try_frontier_exists(
        ctx, patterns, row, match_mode, &conjuncts, counted, &stats,
    )? {
        #[cfg(test)]
        kernel_engaged();
        return Ok(Some(hit));
    }
    Ok(None)
}

/// Run an engaged contract: the scan segment(s), the walk-start fact, and
/// the family's kernel.
fn run(
    ctx: ExecCtx<'_>,
    contract: &Contract<'_>,
    residual: &Residual<'_>,
    mode: KernelMode<'_>,
) -> Result<KernelOutput> {
    let Contract::Chain(chain_contract) = contract;
    // The walk starts at the pattern's first element, forward —
    // the recorded default (the kernel ignores the start ladder;
    // the cost gate is what decided the plan).
    record_walk_start(WalkStart::seed_side_forward());
    let starts = scan_segment(ctx, &chain_contract.start, residual)?;
    super::morsel_pipeline::try_morsel_match(ctx, chain_contract, starts, mode)
}

/// The scan segment: candidates from the one funnel — index seeks, the
/// PROFILE node-read counter, and the seek-phase stamp all keep working —
/// admitted by the target's monomorphic program.
pub(crate) fn scan_segment(
    ctx: ExecCtx<'_>,
    target: &NodeTarget<'_>,
    residual: &Residual<'_>,
) -> Result<Vec<NodeId>> {
    let candidates = node_candidates(
        ctx.graph,
        target.pattern,
        &Row::new(),
        ctx.params,
        residual.conjuncts,
    )?;
    if candidates.is_empty() {
        return Ok(Vec::new());
    }
    scan_admit(ctx, target, candidates)
}

/// Admit a non-empty candidate list through one target's program.
pub(crate) fn scan_admit(
    ctx: ExecCtx<'_>,
    target: &NodeTarget<'_>,
    candidates: Vec<NodeId>,
) -> Result<Vec<NodeId>> {
    admit_each(ctx, target, candidates)
}

/// The monomorphic admission loop over a candidate list — the scan
/// segment's filter half.
fn admit_each<P: NodePred>(
    ctx: ExecCtx<'_>,
    pred: P,
    candidates: Vec<NodeId>,
) -> Result<Vec<NodeId>> {
    let mut prepared: Option<P::Prepared> = None;
    let mut out = Vec::with_capacity(candidates.len());
    for id in candidates {
        ctx.graph.cancel_tick()?;
        if pred.admits(&mut prepared, ctx, id)? {
            out.push(id);
        }
    }
    Ok(out)
}

/// The chain kernel's stage ceiling: the frontier a stage may be
/// estimated to reach before the clause keeps the streaming walker (the
/// walker materializes full rows per pattern, so the ceiling guards the
/// kernel's buffers, not a behavior the walker lacks).
const MAX_ESTIMATED_STAGE_ROWS: u128 = 1 << 20;

/// The existence-mode early-exit allowance: hub-driven existence stops at
pub(crate) fn chain_stages_fit(
    stats: &GraphStats<'_>,
    conjuncts: &[Expr],
    chain: &matcher::Chain<'_>,
    priced: &[matcher::Hop<'_>],
) -> bool {
    let unbound = |_: &str| false;
    let mut rows = seed_rows(endpoint_estimate(
        chain.start.pattern,
        &unbound,
        conjuncts.iter(),
        stats,
    ));
    for hop in priced {
        rows = hop.scaled_from_seed(rows, stats);
        if rows > MAX_ESTIMATED_STAGE_ROWS {
            return false;
        }
    }
    true
}

/// The cost gate (ADR-0473): engage only when the kernel's plan is
/// estimated to pay. All estimates come from the planner's own machinery
/// (ADR-0218's endpoint ladder and degree tails over the live
/// [`GraphStats`]) — the same numbers the compound start selector reads,
/// never a second statistics implementation.
///
/// - The **chain** engages when every stage's estimated width stays under
///   the ceiling — the affordability guard; below it the kernel is the
///   same walk as the planner-oriented one with strictly less per-row
///   machinery, so there is no crossover to gate (the walker's cost is
///   the kernel's plus the row overhead).
/// - The **hub-star** engages when the hub-driven plan's estimated work
///   is no worse than the terminal-driven alternative's — the plan the
///   per-row walker runs (its cheapest-start ladder starts at whichever
///   end estimates cheaper, so a shape whose terminals are the cheaper
///   plan keeps the walker). Existence mode gets the early-exit slop.
/// - The **frontier family** (the quantified-path shapes, ADR-0478) is
///   cost-gated by its own arm — `frontier_cost::frontier_engages`
///   inside `frontier_match::compile_frontier`, over the planner's
///   degree statistics —
///   because its contract is not run by the chain/hub-star kernels: it
///   engages on an unbounded quantifier or when the DFS's estimated
///   trails cost more than the frontier's pairs and probes, and declines
///   keep the GPM DFS.
fn engages(
    stats: &GraphStats<'_>,
    conjuncts: &[Expr],
    contract: &Contract<'_>,
    _exists: bool,
) -> bool {
    let Contract::Chain(chain) = contract;
    chain_stages_fit(stats, conjuncts, chain, &chain.hops)
}

#[cfg(test)]
use std::cell::Cell;

use crate::metrics::KernelRung;

#[cfg(test)]
thread_local! {
    /// Test hook: force the decline, so a differential test can pin the
    /// per-row path's answer on a shape the kernel would take.
    static KERNELS_DISABLED: Cell<bool> = const { Cell::new(false) };
    /// Test counter: how many clauses the kernels took since the last take.
    static KERNEL_ENGAGED: Cell<u32> = const { Cell::new(0) };
}

/// Whether the test hook forced the per-row path.
#[cfg(test)]
fn kernels_disabled() -> bool {
    KERNELS_DISABLED.with(Cell::get)
}

/// Whether the chain/hub-star kernels stand down for clauses of this
/// store: the diagnostic switch's `walk` value (ADR-0519 — the
/// env-reachable form of the `KERNELS_DISABLED` differential hook, read
/// from the store's service bundle) or, in test builds, the hook itself.
pub(crate) fn kernels_stood_down(graph: &Graph) -> bool {
    #[cfg(test)]
    let hooked = kernels_disabled();
    #[cfg(not(test))]
    let hooked = false;
    graph.pattern_engine() == PatternEngine::Walk || hooked
}

/// Count one engaged kernel — the differential suites' test-only counter.
/// The production rung is the ladder's own return value (LABS-1117), so
/// this counter never feeds PROFILE: a nested evaluation's engagement
/// cannot be attributed to the enclosing clause.
#[cfg(test)]
pub(crate) fn kernel_engaged() {
    KERNEL_ENGAGED.with(|c| c.set(c.get() + 1));
}

/// Test helper: run `f` with the kernels forced off (the per-row path),
/// restoring the flag afterwards — including on unwind, so a panicking
/// assertion inside the closure cannot leave the kernels disabled for
/// every later test on the thread (the shared guard).
#[cfg(test)]
pub(crate) fn with_kernels_disabled<R>(f: impl FnOnce() -> R) -> R {
    super::test_support::with_flag_disabled(&KERNELS_DISABLED, f)
}

/// Test helper: drain the engagement counter (0 = the per-row path took
/// every clause since the last take).
#[cfg(test)]
pub(crate) fn take_kernel_engagements() -> u32 {
    KERNEL_ENGAGED.with(|c| c.replace(0))
}