use relate_ir::{orient, pattern_prop_key, var_prop, BinaryOp, Expr, NodePattern};
use relate_names::{NamedToken, SmallName, Token};
use super::estimate::Basis;
use crate::literal::static_arg_value;
use crate::stats::{PatternStats, Provenance};
const EQUALITY: f64 = 0.1;
const RANGE_ONE_SIDED: f64 = 0.3;
const RANGE_PAIR: f64 = 0.1;
const NOT_EQUAL: f64 = 0.9;
const STRING_AFFIX: f64 = 0.3;
const STRING_LEN: f64 = 6.0;
const LIST_LEN: f64 = 25.0;
const MIN_SELECTIVITY: f64 = 1e-9;
const BACKOFF_TERMS: usize = 4;
const MAX_TERMS: usize = 16;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Side {
Lower,
Upper,
}
impl Side {
fn opposite(self) -> Side {
match self {
Side::Lower => Side::Upper,
Side::Upper => Side::Lower,
}
}
}
#[derive(Clone, Copy, Debug)]
enum Term<'a> {
Scalar(f64, Basis),
Bound(Property<'a>, Side, Option<f64>),
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) struct Priced {
pub selectivity: f64,
pub basis: Basis,
}
fn comparison<'a>(expr: &'a Expr, var: &SmallName) -> Option<(Property<'a>, BinaryOp, &'a Expr)> {
let Expr::Binary { op, left, right } = expr else {
return None;
};
let (property, constant, op) = orient(|e| targeted_property(e, var), left, right, *op)?;
is_constant(constant).then_some((property, op, constant))
}
#[derive(Clone, Copy, Debug)]
struct Property<'a> {
key: &'a SmallName,
token: Token,
wrapped: bool,
}
impl<'a> Property<'a> {
fn plain(key: &'a SmallName, token: Token) -> Self {
Property {
key,
token,
wrapped: false,
}
}
}
impl Property<'_> {
fn named(&self) -> NamedToken {
(self.key.clone(), self.token)
}
}
pub(crate) struct Context<'s> {
pub node: &'s NodePattern,
pub label_rows: u64,
pub stats: &'s dyn PatternStats,
}
impl Context<'_> {
fn equality(&self, property: &NamedToken, value: &Expr) -> Option<(f64, Basis)> {
let best = self
.node
.labels
.iter()
.filter_map(|label| self.stats.equality_estimate(label, property, value))
.min_by_key(|estimate| estimate.rows)?;
Some((self.fraction(best.rows), Basis::Statistic(best.provenance)))
}
fn wrapped_equality(&self, property: &NamedToken) -> Option<(f64, Basis)> {
let distinct = self
.node
.labels
.iter()
.filter_map(|label| self.stats.key_stats(label, property))
.map(|key| key.distinct)
.filter(|distinct| *distinct > 0)
.min()?;
Some((
1.0 / distinct as f64,
Basis::Statistic(Provenance::Sketched),
))
}
fn range(
&self,
property: &NamedToken,
lo: Option<f64>,
hi: Option<f64>,
) -> Option<(f64, Basis)> {
let fraction = self
.node
.labels
.iter()
.filter_map(|label| self.stats.key_stats(label, property))
.filter_map(|key| {
Some((
key.min.as_ref()?.as_number()?,
key.max.as_ref()?.as_number()?,
))
})
.filter(|(min, max)| min.is_finite() && max.is_finite() && max > min)
.map(|(min, max)| {
let lo = lo.unwrap_or(min).max(min);
let hi = hi.unwrap_or(max).min(max);
((hi - lo) / (max - min)).clamp(MIN_SELECTIVITY, 1.0)
})
.min_by(f64::total_cmp)?;
Some((fraction, Basis::Statistic(Provenance::Sketched)))
}
fn fraction(&self, rows: u64) -> f64 {
(rows as f64 / (self.label_rows.max(1) as f64)).clamp(MIN_SELECTIVITY, 1.0)
}
}
pub(crate) fn price<'a>(
ctx: &Context<'_>,
where_conjuncts: impl Iterator<Item = &'a Expr>,
) -> Option<Priced> {
let node = ctx.node;
let mut terms = [Term::Scalar(1.0, Basis::Default); MAX_TERMS];
let mut len = 0;
let mut push = |term| {
if len < MAX_TERMS {
terms[len] = term;
len += 1;
}
};
if let Some(Expr::Map(pairs)) = node.properties.as_ref() {
for (key, value) in pairs.iter().filter(|(_, value)| is_constant(value)) {
let (key, token) = pattern_prop_key(&node.prop_keys, key);
let property = Property::plain(&key, token);
push(equality_term(ctx, &property, value));
}
}
if let Some(var) = node.variable.as_ref() {
for expr in where_conjuncts {
if let Some(term) = conjunct_term(ctx, expr, var) {
push(term);
}
}
}
(len > 0).then(|| combine(ctx, &terms[..len]))
}
fn literal_bound(expr: &Expr) -> Option<f64> {
static_arg_value(expr)?.as_number()
}
fn equality_term<'a>(ctx: &Context<'_>, property: &Property<'_>, value: &Expr) -> Term<'a> {
let key = property.named();
let priced = if property.wrapped {
ctx.wrapped_equality(&key)
} else {
ctx.equality(&key, value)
};
match priced {
Some((selectivity, basis)) => Term::Scalar(selectivity, basis),
None => Term::Scalar(EQUALITY, Basis::Default),
}
}
pub(crate) fn scale_rows(rows: u128, selectivity: f64) -> u128 {
debug_assert!(
selectivity.is_finite() && (MIN_SELECTIVITY..=1.0).contains(&selectivity),
"selectivity {selectivity} outside [MIN_SELECTIVITY, 1]"
);
((rows as f64) * selectivity).ceil() as u128
}
fn combine(ctx: &Context<'_>, terms: &[Term<'_>]) -> Priced {
let mut selectivities = [1.0_f64; MAX_TERMS];
let mut n = 0;
let mut basis = Basis::Statistic(Provenance::Exact);
let mut consumed = [false; MAX_TERMS];
for (i, term) in terms.iter().enumerate() {
if consumed[i] {
continue;
}
let (selectivity, term_basis) = match *term {
Term::Scalar(s, term_basis) => (s, term_basis),
Term::Bound(property, side, bound) => {
price_window(ctx, terms, &mut consumed, i, (property, side, bound))
}
};
selectivities[n] = selectivity;
basis = basis.min(term_basis);
n += 1;
}
let selectivities = &mut selectivities[..n];
selectivities.sort_by(f64::total_cmp);
let selectivity = selectivities
.iter()
.take(BACKOFF_TERMS)
.zip(0..)
.map(|(s, k)| s.powf(0.5_f64.powi(k)))
.product::<f64>()
.clamp(MIN_SELECTIVITY, 1.0);
Priced { selectivity, basis }
}
fn price_window(
ctx: &Context<'_>,
terms: &[Term<'_>],
consumed: &mut [bool],
at: usize,
(property, side, bound): (Property<'_>, Side, Option<f64>),
) -> (f64, Basis) {
let partner = (at + 1..terms.len()).find_map(|j| match terms[j] {
Term::Bound(other, other_side, other_bound)
if !consumed[j] && other.key == property.key && other_side == side.opposite() =>
{
Some((j, other_bound))
}
_ => None,
});
if let Some((j, _)) = partner {
consumed[j] = true;
}
let paired = partner.map(|(_, other_bound)| other_bound);
let (lo, hi) = match (side, paired) {
(Side::Lower, Some(other)) => (bound, other),
(Side::Upper, Some(other)) => (other, bound),
(Side::Lower, None) => (bound, None),
(Side::Upper, None) => (None, bound),
};
let from_stats = (lo.is_some() || hi.is_some())
.then(|| ctx.range(&property.named(), lo, hi))
.flatten();
from_stats.unwrap_or(match paired {
Some(_) => (RANGE_PAIR, Basis::Default),
None => (RANGE_ONE_SIDED, Basis::Default),
})
}
fn conjunct_term<'a>(ctx: &Context<'_>, expr: &'a Expr, var: &SmallName) -> Option<Term<'a>> {
let (property, op, constant) = comparison(expr, var)?;
let scalar = |s| Term::Scalar(s, Basis::Default);
Some(match op {
BinaryOp::Eq => equality_term(ctx, &property, constant),
BinaryOp::Neq => scalar(NOT_EQUAL),
BinaryOp::Lt | BinaryOp::Lte | BinaryOp::Gt | BinaryOp::Gte if property.wrapped => {
scalar(RANGE_ONE_SIDED)
}
BinaryOp::Lt | BinaryOp::Lte => Term::Bound(property, Side::Upper, literal_bound(constant)),
BinaryOp::Gt | BinaryOp::Gte => Term::Bound(property, Side::Lower, literal_bound(constant)),
BinaryOp::In => {
let k = match constant {
Expr::List(items) => items.len() as f64,
_ => LIST_LEN,
};
scalar(1.0 - (1.0 - EQUALITY).powf(k))
}
BinaryOp::StartsWith | BinaryOp::EndsWith => {
let len = match constant {
Expr::String(text) => text.chars().count() as f64,
_ => STRING_LEN,
};
scalar(STRING_AFFIX / len.max(1.0))
}
_ => return None,
})
}
fn targeted_property<'a>(expr: &'a Expr, var: &SmallName) -> Option<Property<'a>> {
if let (Some((name, key)), Expr::Property { key_id, .. }) = (var_prop(expr), expr) {
return (name == var).then_some(Property::plain(key, *key_id));
}
let Expr::Function { args, .. } = expr else {
return None;
};
let (first, rest) = args.split_first()?;
rest.iter().all(is_constant).then(|| {
targeted_property(first, var).map(|property| Property {
wrapped: true,
..property
})
})?
}
const VOLATILE_FUNCTIONS: [&str; 3] = ["rand", "randomUUID", "timestamp"];
fn is_constant(expr: &Expr) -> bool {
match expr {
leaf if leaf.is_seek_const() || matches!(leaf, Expr::RuntimeValue(_)) => true,
Expr::List(items) => items.iter().all(is_constant),
Expr::Function { name, args, .. } => {
!name.with_str(|n| VOLATILE_FUNCTIONS.iter().any(|v| n.eq_ignore_ascii_case(v)))
&& args.iter().all(is_constant)
}
Expr::Unary { expr, .. } => is_constant(expr),
_ => false,
}
}