pub(crate) mod matcher;
#[cfg(test)]
mod matcher_tests;
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 construct_memo;
mod guard_memo;
pub(crate) mod memo;
pub(crate) mod value_hash;
pub(crate) mod rearival;
#[cfg(test)]
mod rearival_tests;
pub(crate) mod frontier_cost;
#[cfg(test)]
mod frontier_cost_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 frontier_pair_tests;
#[cfg(test)]
mod frontier_short_cap_tests;
#[cfg(test)]
mod frontier_decline_tests;
#[cfg(test)]
mod engine_switch_tests;
#[cfg(test)]
mod rung_tests;
#[cfg(test)]
mod ratio_guard_tests;
#[cfg(test)]
mod cancel_tests;
mod chain;
mod chain_count;
mod chain_tally;
mod count_entry;
mod hub_star;
#[cfg(test)]
mod memo_differential_tests;
#[cfg(test)]
mod memo_profile_tests;
#[cfg(test)]
mod memo_wiring_tests;
pub(crate) use chain_count::try_fold_chain_count;
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::seed_on_rel_start;
use relate_planner::{endpoint_estimate, seed_rows};
use crate::ctx::ExecCtx;
use crate::graph::Graph;
use crate::metrics::{StartReason, 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 frontier_match::{boundary, boundary_vars};
use matcher::Contract;
use program::{Admission, NodePred, NodeTarget};
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,
}
}
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> },
}
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(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) = 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,
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 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 unbound = |_: &str| false;
match contract {
Contract::Chain(chain) => chain_stages_fit(stats, conjuncts, chain, &chain.hops),
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::metrics::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 {
super::test_support::with_override(&FRONTIER_TABLE_BUDGET_OVERRIDE, bytes, 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 {
super::test_support::with_override(&REARRIVAL_DEFERRED_BUDGET_OVERRIDE, work, 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))
}