use std::collections::HashSet;
use relate_ir::{
orient, pattern_prop_key, var_prop_named, BinaryOp, Expr, NodePattern, PathPattern,
PatternElement, RelPattern,
};
use relate_names::{NamedToken, SmallName};
use crate::stats::{ContainsCount, NoPatternStats, PatternStats};
const RANK_EQ: u128 = 1 << 20;
const RANK_LABEL: u128 = 1 << 48;
const RANK_BARE: u128 = 1 << 62;
const RANGE_SEEK_WIN_FLOOR: u64 = 256;
pub(crate) fn range_seek_wins(window: u64, label_rows: u64) -> bool {
window <= RANGE_SEEK_WIN_FLOOR || window * 4 < label_rows
}
pub fn crossover_scan_rows<L>(
labels: impl IntoIterator<Item = L>,
rows_of: impl Fn(&L) -> Option<u64>,
) -> Option<u64> {
let mut scan_rows: Option<u64> = None;
for label in labels {
let rows = rows_of(&label)?;
scan_rows = Some(scan_rows.map_or(rows, |min| min.min(rows)));
}
scan_rows
}
pub fn range_seek_gated(window: u64, scan_rows: Option<u64>) -> bool {
scan_rows.is_some_and(|scan| !range_seek_wins(window, scan))
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Estimate {
Measured(u128),
SampleScan {
rows: u128,
scan: u128,
},
Rank(u128),
}
pub fn where_conjuncts_of(where_clause: Option<&Expr>) -> Vec<&Expr> {
let mut conjuncts = Vec::new();
if let Some(expr) = where_clause {
each_conjunct(expr, &mut |expr| conjuncts.push(expr));
}
conjuncts
}
fn unmeasured_rows(node: &NodePattern) -> u128 {
let equality = matches!(&node.properties, Some(Expr::Map(pairs)) if !pairs.is_empty());
if equality {
RANK_EQ
} else if !node.labels.is_empty() {
RANK_LABEL
} else {
RANK_BARE
}
}
pub type Bound<'a> = &'a dyn Fn(&str) -> bool;
pub fn endpoint_estimate<'a>(
node: &'a NodePattern,
bound: Bound<'_>,
where_conjuncts: impl Iterator<Item = &'a Expr> + Clone,
stats: &dyn PatternStats,
) -> Estimate {
if endpoint_bound(node, bound) {
return Estimate::Measured(1);
}
let measured = |hits: Option<u64>| hits.map(u128::from).map(Estimate::Measured);
measured(best_seek(node, where_conjuncts.clone(), stats).map(|pick| pick.rows()))
.or_else(|| contains_hits(node, where_conjuncts, stats))
.or_else(|| measured(label_hits(node, stats)))
.unwrap_or_else(|| Estimate::Rank(unmeasured_rows(node)))
}
fn best_equality<'a>(node: &'a NodePattern, stats: &dyn PatternStats) -> Option<SeekPick<'a>> {
let Expr::Map(pairs) = node.properties.as_ref()? else {
return None;
};
let mut best: Option<(&SmallName, NamedToken, &Expr, u64)> = None;
for (key, value) in pairs {
let key = pattern_prop_key(&node.prop_keys, key);
for named in &node.labels {
let Some(rows) = stats.equality_rows(named, &key, value) else {
continue;
};
if best
.as_ref()
.is_none_or(|(_, _, _, best_rows)| rows < *best_rows)
{
best = Some((&named.0, key.clone(), value, rows));
}
}
}
best.map(|(label, prop, bound, rows)| SeekPick {
label,
prop: prop.0,
op: BinaryOp::Eq,
bound,
rows,
})
}
fn best_range<'a>(
node: &'a NodePattern,
where_conjuncts: impl IntoIterator<Item = &'a Expr>,
stats: &dyn PatternStats,
) -> Option<SeekPick<'a>> {
let var = node.variable.as_ref()?;
let scan_rows = crossover_scan_rows(node.labels.iter(), |label| stats.label_rows(label));
let mut best: Option<(&SmallName, NamedToken, BinaryOp, &Expr, u64)> = None;
for expr in where_conjuncts {
let Some((prop, op, bound)) = range_prop(expr, var) else {
continue;
};
for named in &node.labels {
let Some(rows) = stats.range_rows(named, &prop, op, bound) else {
continue;
};
if !range_seek_gated(rows, scan_rows)
&& best
.as_ref()
.is_none_or(|(_, _, _, _, best_rows)| rows < *best_rows)
{
best = Some((&named.0, prop.clone(), op, bound, rows));
}
}
}
best.map(|(label, prop, op, bound, rows)| SeekPick {
label,
prop: prop.0,
op,
bound,
rows,
})
}
fn range_prop<'a>(expr: &'a Expr, var: &SmallName) -> Option<(NamedToken, BinaryOp, &'a Expr)> {
let Expr::Binary { op, left, right } = expr else {
return None;
};
if !matches!(
op,
BinaryOp::Lt | BinaryOp::Lte | BinaryOp::Gt | BinaryOp::Gte
) {
return None;
}
orient(|e| key_named(e, var), left, right, *op).map(|(prop, bound, op)| (prop, op, bound))
}
pub struct SeekPick<'a> {
pub label: &'a SmallName,
pub prop: SmallName,
pub op: BinaryOp,
pub bound: &'a Expr,
pub rows: u64,
}
impl SeekPick<'_> {
fn rows(&self) -> u64 {
self.rows
}
}
pub fn best_seek<'a>(
node: &'a NodePattern,
where_conjuncts: impl IntoIterator<Item = &'a Expr>,
stats: &dyn PatternStats,
) -> Option<SeekPick<'a>> {
best_equality(node, stats).or_else(|| best_range(node, where_conjuncts, stats))
}
fn contains_hits<'a>(
node: &NodePattern,
where_conjuncts: impl IntoIterator<Item = &'a Expr>,
stats: &dyn PatternStats,
) -> Option<Estimate> {
let var = node.variable.as_ref()?;
where_conjuncts
.into_iter()
.filter_map(|expr| contains_prop(expr, var))
.flat_map(|(prop, needle)| {
node.labels
.iter()
.map(move |label| (label, prop.clone(), needle))
})
.filter_map(|(label, prop, needle)| stats.contains_rows(label, &prop, needle))
.min_by_key(|count| count.rows())
.map(|count| match count {
ContainsCount::TextIndex(rows) => Estimate::Measured(u128::from(rows)),
ContainsCount::SampleScan { rows, scan } => Estimate::SampleScan {
rows: u128::from(rows),
scan: u128::from(scan),
},
})
}
fn label_hits(node: &NodePattern, stats: &dyn PatternStats) -> Option<u64> {
node.labels
.iter()
.filter_map(|label| stats.label_rows(label))
.min()
}
fn each_conjunct<'a>(expr: &'a Expr, visit: &mut impl FnMut(&'a Expr)) {
if let Expr::Binary {
op: BinaryOp::And,
left,
right,
} = expr
{
each_conjunct(left, visit);
each_conjunct(right, visit);
} else {
visit(expr);
}
}
fn key_named(expr: &Expr, var: &SmallName) -> Option<NamedToken> {
var_prop_named(expr)
.filter(|(name, _)| *name == var)
.map(|(_, key)| key)
}
fn contains_prop<'a>(expr: &'a Expr, var: &SmallName) -> Option<(NamedToken, &'a Expr)> {
let Expr::Binary {
op: BinaryOp::Contains,
left,
right,
} = expr
else {
return None;
};
key_named(left, var).map(|key| (key, right.as_ref()))
}
fn orientation_locked(path: &PathPattern) -> bool {
path.has_path_name()
|| path.needs_gpm()
|| path.nodes.len() < 2
|| path
.rels
.iter()
.any(|rel| rel.var_length && rel.variable.is_some())
}
fn reversal_safe(path: &PathPattern, bound: Bound<'_>) -> bool {
let own = |var: &str| {
path.nodes
.iter()
.any(|n| n.variable.as_ref().is_some_and(|v| v == var))
|| path
.rels
.iter()
.any(|r| r.variable.as_ref().is_some_and(|v| v == var))
};
let mut refs = HashSet::new();
for node in &path.nodes {
if let Some(e) = &node.properties {
relate_ir::expr_vars(e, &mut refs);
}
if let Some(e) = &node.where_clause {
relate_ir::expr_vars(e, &mut refs);
}
if let Some(le) = &node.label_expr {
relate_ir::label_expr_vars(le, &mut refs);
}
}
for rel in &path.rels {
if let Some(e) = &rel.properties {
relate_ir::expr_vars(e, &mut refs);
}
if let Some(e) = &rel.where_clause {
relate_ir::expr_vars(e, &mut refs);
}
}
!refs.iter().any(|var| own(var) && !bound(var.as_str()))
}
fn direction_cost(
path: &PathPattern,
reversed: bool,
bound: Bound<'_>,
where_conjuncts: &[&Expr],
stats: &dyn PatternStats,
) -> (u128, u128) {
if path.nodes.is_empty() {
return (RANK_BARE, RANK_BARE);
}
let seed = if reversed {
path.nodes.last().expect("nodes is non-empty")
} else {
path.nodes.first().expect("nodes is non-empty")
};
let estimate = endpoint_estimate(seed, bound, where_conjuncts.iter().copied(), stats);
let walked = if reversed {
walk_cost(
estimate,
path.nodes
.iter()
.rev()
.zip(path.rels.iter().rev())
.map(|(node, rel)| (node, rel, seed_on_rel_start(rel, true))),
stats,
)
} else {
walk_cost(
estimate,
path.nodes
.iter()
.zip(path.rels.iter())
.map(|(node, rel)| (node, rel, seed_on_rel_start(rel, false))),
stats,
)
};
(walked, seed_rows(estimate))
}
pub fn seed_on_rel_start(rel: &RelPattern, reversed: bool) -> bool {
match rel.direction {
relate_ir::Direction::Outgoing => !reversed,
relate_ir::Direction::Incoming => reversed,
relate_ir::Direction::Both => false,
}
}
#[derive(Clone, Copy, PartialEq, Eq)]
enum HopRows {
Seeds,
Paths,
}
pub fn apply_degree(
rows: u128,
start: &NodePattern,
rel: &RelPattern,
seed_is_start: bool,
stats: &dyn PatternStats,
) -> u128 {
scale_degree(rows, start, rel, seed_is_start, stats, HopRows::Seeds)
}
pub fn apply_path_degree(
rows: u128,
start: &NodePattern,
rel: &RelPattern,
seed_is_start: bool,
stats: &dyn PatternStats,
) -> u128 {
scale_degree(rows, start, rel, seed_is_start, stats, HopRows::Paths)
}
fn scale_degree(
rows: u128,
start: &NodePattern,
rel: &RelPattern,
seed_is_start: bool,
stats: &dyn PatternStats,
hop_rows: HopRows,
) -> u128 {
priced_degree(rows, start, rel, seed_is_start, stats, hop_rows).unwrap_or(rows)
}
enum RelTypes<'a> {
None,
One(&'a NamedToken),
Many,
}
impl<'a> RelTypes<'a> {
fn of(rel: &'a RelPattern) -> Self {
match rel.types.as_slice() {
[] => Self::None,
[one] => Self::One(one),
_ => Self::Many,
}
}
}
pub fn apply_hop_bound(
rows: u128,
start: &NodePattern,
rel: &RelPattern,
seed_is_start: bool,
stats: &dyn PatternStats,
) -> u128 {
if let Some(priced) = priced_degree(rows, start, rel, seed_is_start, stats, HopRows::Seeds) {
return priced;
}
if !seed_is_start {
return rows;
}
let rel_type = match RelTypes::of(rel) {
RelTypes::One((rel_type, _)) => Some(rel_type),
RelTypes::None | RelTypes::Many => None,
};
stats
.any_degree_tail(rel_type)
.map_or(rows, |tail| rows.saturating_mul(u128::from(tail)))
}
fn priced_degree(
rows: u128,
start: &NodePattern,
rel: &RelPattern,
seed_is_start: bool,
stats: &dyn PatternStats,
hop_rows: HopRows,
) -> Option<u128> {
let RelTypes::One(rel_type) = RelTypes::of(rel) else {
return None;
};
if seed_is_start {
if let Some(tail) = start
.labels
.iter()
.filter_map(|label| stats.degree_tail(label, rel_type))
.min()
{
let scaled = rows.saturating_mul(u128::from(tail));
return Some(match (hop_rows, stats.rel_type_rows(rel_type)) {
(HopRows::Seeds, Some(total)) => scaled.min(u128::from(total)),
_ => scaled,
});
}
}
let rel_rows = stats.rel_type_rows(rel_type)?;
let label_rows = label_hits(start, stats)?;
if label_rows == 0 {
return None;
}
let scaled = rows.saturating_mul(u128::from(rel_rows)) / u128::from(label_rows);
Some(if rows > 0 && rel_rows > 0 && scaled == 0 {
1
} else {
scaled
})
}
fn endpoint_bound(node: &NodePattern, bound: Bound<'_>) -> bool {
node.variable
.as_ref()
.is_some_and(|var| var.with_str(|text| bound(text)))
}
pub fn seed_rows(estimate: Estimate) -> u128 {
walk_cost(estimate, std::iter::empty::<Hop<'_>>(), &NoPatternStats)
}
pub type Hop<'a> = (&'a NodePattern, &'a RelPattern, bool);
fn degree_walk<'a>(
rows: u128,
hops: impl Iterator<Item = Hop<'a>>,
stats: &dyn PatternStats,
) -> u128 {
let mut output = rows;
for (node, rel, seed_is_start) in hops {
output = apply_degree(output, node, rel, seed_is_start, stats);
}
output
}
pub fn walk_cost<'a>(
estimate: Estimate,
hops: impl Iterator<Item = Hop<'a>>,
stats: &dyn PatternStats,
) -> u128 {
match estimate {
Estimate::Measured(rows) => degree_walk(rows, hops, stats),
Estimate::SampleScan { rows, scan } => degree_walk(rows, hops, stats).max(scan),
Estimate::Rank(rows) => rows,
}
}
fn choose_orientation(
path: &PathPattern,
bound: Bound<'_>,
where_conjuncts: &[&Expr],
stats: &dyn PatternStats,
) -> (bool, u128) {
let forced = match (path.nodes.first(), path.nodes.last()) {
(Some(first), Some(last)) if !orientation_locked(path) => {
let first_bound = endpoint_bound(first, bound);
let last_bound = endpoint_bound(last, bound);
if !reversal_safe(path, bound) || (first_bound && !last_bound) {
Some(false)
} else if last_bound && !first_bound {
Some(true)
} else {
None
}
}
_ => Some(false),
};
if let Some(reversed) = forced {
return (
reversed,
direction_cost(path, reversed, bound, where_conjuncts, stats).0,
);
}
let (written, written_seed) = direction_cost(path, false, bound, where_conjuncts, stats);
let (flipped, flipped_seed) = direction_cost(path, true, bound, where_conjuncts, stats);
if flipped < written {
return (true, flipped);
}
if written < flipped {
return (false, written);
}
if flipped_seed < written_seed {
(true, flipped)
} else {
(false, written)
}
}
fn pattern_touches(path: &PathPattern, bound: Bound<'_>) -> bool {
relate_ir::path_pattern_vars(path).any(|var| var.with_str(|text| bound(text)))
}
fn reverse_path(path: &mut PathPattern) {
path.nodes.reverse();
path.rels.reverse();
for rel in &mut path.rels {
rel.direction = rel.direction.flip();
}
if path.elements.len() == path.nodes.len() + path.rels.len() {
path.elements.reverse();
for element in &mut path.elements {
if let PatternElement::Relationship(rel) = element {
rel.direction = rel.direction.flip();
}
}
}
}
pub(crate) fn order_patterns(
patterns: &mut Vec<PathPattern>,
prebound: &HashSet<String>,
where_clause: Option<&Expr>,
stats: &dyn PatternStats,
) {
let mut bound = prebound.clone();
let where_conjuncts = where_conjuncts_of(where_clause);
let mut pending: Vec<(usize, PathPattern)> =
std::mem::take(patterns).into_iter().enumerate().collect();
let mut chosen = Vec::with_capacity(pending.len());
while !pending.is_empty() {
let bound_view = |name: &str| bound.contains(name);
let connected_exists = !chosen.is_empty()
&& pending
.iter()
.any(|(_, path)| pattern_touches(path, &bound_view));
let (index, (reversed, _)) = pending
.iter()
.enumerate()
.filter(|(_, (_, path))| !connected_exists || pattern_touches(path, &bound_view))
.map(|(index, (_, path))| {
(
index,
choose_orientation(path, &bound_view, &where_conjuncts, stats),
)
})
.min_by_key(|&(index, (_, cost))| (cost, pending[index].0))
.expect("candidate set is non-empty");
let (_, mut path) = pending.remove(index);
if reversed {
reverse_path(&mut path);
}
add_pattern_vars(&mut bound, &path);
chosen.push(path);
}
*patterns = chosen;
}
fn add_pattern_vars(bound: &mut HashSet<String>, p: &PathPattern) {
bound.extend(
relate_ir::pattern_anchor_variables(p)
.into_iter()
.map(|name| name.to_string()),
);
}
#[cfg(test)]
mod tests;