pub(crate) mod matcher;
pub(crate) mod program;
pub(crate) mod nfa;
#[cfg(test)]
mod nfa_tests;
pub(crate) mod frontier;
#[cfg(test)]
mod frontier_tests;
pub(crate) mod frontier_tables;
#[cfg(test)]
mod frontier_tables_tests;
pub(crate) mod node_map;
pub(crate) mod rearival;
#[cfg(test)]
mod rearival_tests;
pub(crate) mod frontier_match;
#[cfg(test)]
mod frontier_match_tests;
pub(crate) mod frontier_emit;
#[cfg(test)]
mod frontier_emit_tests;
#[cfg(test)]
mod frontier_charge_tests;
#[cfg(test)]
mod frontier_rider_tests;
pub(crate) mod frontier_run;
pub(crate) mod frontier_count;
#[cfg(test)]
mod frontier_count_tests;
#[cfg(test)]
mod frontier_differential_tests;
#[cfg(test)]
mod engine_switch_tests;
#[cfg(test)]
mod chain_gate_tests;
#[cfg(test)]
mod rung_tests;
mod chain;
mod hub_star;
use relate_core::{NodeId, Result};
use relate_ir::{Expr, MatchMode, PathPattern};
use relate_planner::seed_on_rel_start;
use relate_planner::{endpoint_estimate, seed_rows};
use crate::ctx::{ExecCtx, StartReason, WalkStart};
use crate::graph::Graph;
use crate::pattern_engine::PatternEngine;
use crate::pattern_walk::node_candidates;
use crate::row::Row;
use super::graph_stats::GraphStats;
use super::pushdown::{flatten_and_owned, match_scope, Residual};
use super::record_walk_start;
use matcher::Contract;
use program::{Admission, NodePred, NodeTarget};
pub(crate) enum KernelMode<'a> {
Rows { want: Option<usize> },
Exists { counted: Option<&'a Expr> },
}
impl KernelMode<'_> {
pub(crate) fn halt(&self) -> Option<usize> {
match self {
Self::Rows { want } => *want,
Self::Exists { .. } => None,
}
}
}
pub(crate) enum KernelOutput {
Rows(Vec<Row>),
Exists(bool),
}
#[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(&rows[0], patterns),
};
let output = run(
ctx,
&contract,
&residual,
KernelMode::Rows { want: cap_want },
)?;
Ok(Some(match output {
KernelOutput::Rows(rows) => (rows, rung),
KernelOutput::Exists(_) => {
unreachable!("the row entry never asks for existence")
}
}))
}
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);
}
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(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")
}
}));
}
}
if let Some(hit) = frontier_run::try_frontier_exists(
ctx, patterns, row, match_mode, &conjuncts, counted, &stats,
)? {
#[cfg(test)]
kernel_engaged();
return Ok(Some(hit));
}
Ok(None)
}
fn run(
ctx: ExecCtx<'_>,
contract: &Contract<'_>,
residual: &Residual<'_>,
mode: KernelMode<'_>,
) -> Result<KernelOutput> {
match contract {
Contract::Chain(chain_contract) => {
record_walk_start(WalkStart::seed_side_forward());
let starts = scan_segment(ctx, &chain_contract.start, residual)?;
chain::run(ctx, chain_contract, starts, mode)
}
Contract::HubStar(star) => {
record_walk_start(WalkStart {
element: if star.hub_at_start[0] {
0
} else {
star.sides[0].len()
},
backward: !star.hub_at_start[0],
reason: StartReason::IndexZero,
});
let hubs = scan_segment(ctx, &star.hub[0], residual)?;
let hubs = if hubs.is_empty() {
hubs
} else {
scan_admit(ctx, &star.hub[1], hubs)?
};
hub_star::run(ctx, star, hubs, mode)
}
}
}
fn scan_segment(
ctx: ExecCtx<'_>,
target: &NodeTarget<'_>,
residual: &Residual<'_>,
) -> Result<Vec<NodeId>> {
let candidates = node_candidates(
ctx.graph,
target.pattern,
&Row::new(),
ctx.params,
ctx.cypher_version,
residual.conjuncts,
)?;
if candidates.is_empty() {
return Ok(Vec::new());
}
scan_admit(ctx, target, candidates)
}
fn scan_admit(
ctx: ExecCtx<'_>,
target: &NodeTarget<'_>,
candidates: Vec<NodeId>,
) -> Result<Vec<NodeId>> {
admit_each(ctx, Admission::of(target), candidates)
}
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)
}
const MAX_ESTIMATED_STAGE_ROWS: u128 = 1 << 20;
const EXISTS_EARLY_EXIT_SLOP: u128 = 2;
fn engages(
stats: &GraphStats<'_>,
conjuncts: &[Expr],
contract: &Contract<'_>,
exists: bool,
) -> bool {
let unbound = |_: &str| false;
match contract {
Contract::Chain(chain) => {
let start = seed_rows(endpoint_estimate(
chain.start.pattern,
&unbound,
conjuncts.iter(),
stats,
));
let mut rows = start;
for hop in &chain.hops {
rows = hop.scaled_from_seed(rows, stats);
if rows > MAX_ESTIMATED_STAGE_ROWS {
return false;
}
}
true
}
Contract::HubStar(star) => {
let hub_rows = seed_rows(endpoint_estimate(
star.hub[0].pattern,
&unbound,
conjuncts.iter(),
stats,
));
let mut hub_work = hub_rows;
for side in &star.sides {
let mut rows = hub_rows;
for hop in side {
rows = hop.scaled_from_seed(rows, stats);
hub_work = hub_work.saturating_add(rows);
}
}
let mut term_work = 0u128;
for (pi, side) in star.sides.iter().enumerate() {
let terminal = side
.last()
.expect("every side has at least one hop")
.target
.pattern;
let terminal_rows = seed_rows(endpoint_estimate(
terminal,
&unbound,
conjuncts.iter(),
stats,
));
term_work = term_work.saturating_add(terminal_rows);
let mut rows = terminal_rows;
for hop in side.iter().rev() {
let on_start = seed_on_rel_start(hop.rel, star.hub_at_start[pi]);
rows = relate_planner::apply_degree(
rows,
hop.target.pattern,
hop.rel,
on_start,
stats,
);
term_work = term_work.saturating_add(rows);
}
}
let allowance = if exists { EXISTS_EARLY_EXIT_SLOP } else { 1 };
hub_work <= allowance.saturating_mul(term_work)
}
}
}
#[cfg(test)]
use std::cell::Cell;
use crate::ctx::KernelRung;
#[cfg(test)]
thread_local! {
static KERNELS_DISABLED: Cell<bool> = const { Cell::new(false) };
static KERNEL_ENGAGED: Cell<u32> = const { Cell::new(0) };
static FRONTIER_DISABLED: Cell<bool> = const { Cell::new(false) };
static FRONTIER_TABLE_BUDGET_OVERRIDE: Cell<Option<u64>> = const { Cell::new(None) };
static REARRIVAL_DEFERRED_BUDGET_OVERRIDE: Cell<Option<u64>> = const { Cell::new(None) };
}
#[cfg(test)]
fn kernels_disabled() -> bool {
KERNELS_DISABLED.with(Cell::get)
}
#[cfg(test)]
fn frontier_disabled() -> bool {
FRONTIER_DISABLED.with(Cell::get)
}
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
}
pub(crate) fn frontier_stood_down(graph: &Graph) -> bool {
#[cfg(test)]
return kernels_stood_down(graph) || frontier_disabled();
#[cfg(not(test))]
kernels_stood_down(graph)
}
#[cfg(test)]
fn frontier_table_budget_override() -> Option<u64> {
FRONTIER_TABLE_BUDGET_OVERRIDE.with(Cell::get)
}
#[cfg(test)]
pub(crate) fn with_frontier_table_budget<R>(bytes: u64, f: impl FnOnce() -> R) -> R {
FRONTIER_TABLE_BUDGET_OVERRIDE.with(|cell| cell.set(Some(bytes)));
struct Restore;
impl Drop for Restore {
fn drop(&mut self) {
FRONTIER_TABLE_BUDGET_OVERRIDE.with(|cell| cell.set(None));
}
}
let _restore = Restore;
f()
}
#[cfg(test)]
fn rearival_deferred_budget_override() -> Option<u64> {
REARRIVAL_DEFERRED_BUDGET_OVERRIDE.with(Cell::get)
}
#[cfg(test)]
pub(crate) fn with_rearival_deferred_budget<R>(work: u64, f: impl FnOnce() -> R) -> R {
REARRIVAL_DEFERRED_BUDGET_OVERRIDE.with(|cell| cell.set(Some(work)));
struct Restore;
impl Drop for Restore {
fn drop(&mut self) {
REARRIVAL_DEFERRED_BUDGET_OVERRIDE.with(|cell| cell.set(None));
}
}
let _restore = Restore;
f()
}
#[cfg(test)]
fn kernel_engaged() {
KERNEL_ENGAGED.with(|c| c.set(c.get() + 1));
}
#[cfg(test)]
pub(crate) fn with_kernels_disabled<R>(f: impl FnOnce() -> R) -> R {
super::test_support::with_flag_disabled(&KERNELS_DISABLED, f)
}
#[cfg(test)]
pub(crate) fn with_frontier_disabled<R>(f: impl FnOnce() -> R) -> R {
super::test_support::with_flag_disabled(&FRONTIER_DISABLED, f)
}
#[cfg(test)]
pub(crate) fn take_kernel_engagements() -> u32 {
KERNEL_ENGAGED.with(|c| c.replace(0))
}