pub(crate) mod matcher;
#[cfg(test)]
mod matcher_tests;
pub(crate) mod program;
pub(crate) mod node_map;
pub(crate) mod construct_memo;
pub(crate) mod memo;
pub(crate) mod value_hash;
#[cfg(test)]
mod engine_switch_tests;
#[cfg(test)]
mod rung_tests;
#[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};
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,
}
}
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,
})
}
pub(crate) enum KernelMode<'a> {
Rows { want: Option<usize> },
Exists { counted: Option<&'a Expr> },
}
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(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),
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(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")
}
}));
}
}
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)
}
fn run(
ctx: ExecCtx<'_>,
contract: &Contract<'_>,
residual: &Residual<'_>,
mode: KernelMode<'_>,
) -> Result<KernelOutput> {
let Contract::Chain(chain_contract) = contract;
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)
}
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)
}
pub(crate) fn scan_admit(
ctx: ExecCtx<'_>,
target: &NodeTarget<'_>,
candidates: Vec<NodeId>,
) -> Result<Vec<NodeId>> {
admit_each(ctx, 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;
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
}
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! {
static KERNELS_DISABLED: Cell<bool> = const { Cell::new(false) };
static KERNEL_ENGAGED: Cell<u32> = const { Cell::new(0) };
}
#[cfg(test)]
fn kernels_disabled() -> bool {
KERNELS_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
}
#[cfg(test)]
pub(crate) 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 take_kernel_engagements() -> u32 {
KERNEL_ENGAGED.with(|c| c.replace(0))
}