use std::collections::{BTreeMap, HashSet};
use relate_core::{NodeId, Result, Value};
use relate_ir::{BinaryOp, DisjunctionArms, Expr, NodePattern};
use relate_names::SmallName;
use crate::eval::expr_vars;
use crate::overlay::{intersect_ids, union_ids, ExecGraph};
use crate::pattern_walk::PatternMapRole;
use crate::pattern_walk::{binding, pattern_props, Binding, NodeBinding};
use crate::row::Row;
use crate::tiered_set::{TieredWordSet, WordHash};
mod seek;
#[cfg(test)]
mod tests;
pub(crate) use seek::{id_fn_conversion, leaf_seek, IdConversion, Seek, ServedIds};
pub(crate) fn label_index_seekable(node: &NodePattern) -> bool {
node.label_expr
.as_ref()
.is_none_or(|expr| expr.is_static_conjunction())
}
pub(crate) fn scan_answers_exactly(node: &NodePattern) -> bool {
label_index_seekable(node) || node.static_disjunction_arms().is_some()
}
fn seek_union(
graph: &ExecGraph<'_>,
seek: &Seek,
arms: &DisjunctionArms<'_>,
) -> Result<Option<Vec<NodeId>>> {
let mut per_arm: Vec<Vec<NodeId>> = Vec::with_capacity(arms.len());
for arm in arms.arms() {
let labels: Vec<String> = arm.map(|label| label.to_string()).collect();
let Some(ids) = served(seek, graph, &labels, true) else {
return Ok(None);
};
per_arm.push(ids.into_ids());
}
union_dedup(per_arm.into_iter()).map(Some)
}
fn union_dedup(served: impl Iterator<Item = Vec<NodeId>>) -> Result<Vec<NodeId>> {
let mut seen = TieredWordSet::new(WordHash::Id);
let mut ids = Vec::new();
for arm_ids in served {
for id in arm_ids {
if seen.insert(id as u64, "union")? {
ids.push(id);
}
}
}
ids.sort_unstable();
Ok(ids)
}
enum IndexArm {
Served(ServedIds),
Unserved,
Decline,
}
struct OrCtx<'a> {
graph: &'a ExecGraph<'a>,
row: &'a Row,
params: &'a BTreeMap<String, Value>,
labels: &'a [String],
label_seekable: bool,
}
fn or_union_candidates(var: &SmallName, conjuncts: &[Expr], ctx: &OrCtx<'_>) -> Option<ServedIds> {
conjuncts
.iter()
.filter(|c| {
matches!(
c,
Expr::Binary {
op: BinaryOp::Or,
..
}
)
})
.filter_map(|c| match index_arm(var, c, ctx) {
IndexArm::Served(served) => Some(served),
IndexArm::Unserved | IndexArm::Decline => None,
})
.reduce(|previous, served| previous.folded(served, intersect_ids))
}
fn index_arm(var: &SmallName, expr: &Expr, ctx: &OrCtx<'_>) -> IndexArm {
match expr {
Expr::Binary {
op: BinaryOp::Or,
left,
right,
} => match (index_arm(var, left, ctx), index_arm(var, right, ctx)) {
(IndexArm::Decline, _) | (_, IndexArm::Decline) => IndexArm::Decline,
(IndexArm::Served(a), IndexArm::Served(b)) => IndexArm::Served(a.folded(b, union_ids)),
_ => IndexArm::Unserved,
},
Expr::Binary {
op: BinaryOp::And,
left,
right,
} => match (index_arm(var, left, ctx), index_arm(var, right, ctx)) {
(IndexArm::Decline, _) | (_, IndexArm::Decline) => IndexArm::Decline,
(IndexArm::Served(a), IndexArm::Served(b)) => {
IndexArm::Served(a.folded(b, intersect_ids))
}
(IndexArm::Served(a), IndexArm::Unserved)
| (IndexArm::Unserved, IndexArm::Served(a)) => {
IndexArm::Served(ServedIds::Superset(a.into_ids()))
}
(IndexArm::Unserved, IndexArm::Unserved) => IndexArm::Unserved,
},
other => index_leaf(var, other, ctx),
}
}
fn served(
seek: &Seek,
graph: &ExecGraph<'_>,
labels: &[String],
label_seekable: bool,
) -> Option<ServedIds> {
if !seek.servable(graph, labels, label_seekable) {
return None;
}
seek.serve(graph, labels)
}
fn index_leaf(var: &SmallName, expr: &Expr, ctx: &OrCtx<'_>) -> IndexArm {
let mut vars = HashSet::new();
expr_vars(expr, &mut vars);
if vars.len() != 1 || !var.with_str(|text| vars.contains(text)) {
return IndexArm::Decline;
}
let Some(seek) = leaf_seek(var, expr, ctx.graph, ctx.row, ctx.params) else {
return IndexArm::Decline;
};
served(&seek, ctx.graph, ctx.labels, ctx.label_seekable)
.map_or(IndexArm::Unserved, IndexArm::Served)
}
fn ranked_seeks(
v: &SmallName,
conjuncts: &[Expr],
graph: &ExecGraph<'_>,
row: &Row,
params: &BTreeMap<String, Value>,
) -> Vec<Seek> {
let mut seeks: Vec<Seek> = conjuncts
.iter()
.filter_map(|c| leaf_seek(v, c, graph, row, params))
.collect();
seeks.sort_by_key(Seek::rank);
seeks
}
fn pattern_labels(np: &NodePattern) -> Vec<String> {
np.label_names().map(|label| label.to_string()).collect()
}
pub(crate) struct Prepared<'a> {
seeks: Vec<Seek>,
labels: Vec<String>,
label_seekable: bool,
arms: Option<DisjunctionArms<'a>>,
}
pub(crate) fn prepared<'a>(
v: &SmallName,
np: &'a NodePattern,
conjuncts: &[Expr],
graph: &ExecGraph<'_>,
row: &Row,
params: &BTreeMap<String, Value>,
) -> Option<Prepared<'a>> {
if np.force_scan {
return None;
}
Some(Prepared {
seeks: ranked_seeks(v, conjuncts, graph, row, params),
labels: pattern_labels(np),
label_seekable: label_index_seekable(np),
arms: np.static_disjunction_arms(),
})
}
enum Answered {
Union(Vec<NodeId>),
Serve(ServedIds),
}
impl Prepared<'_> {
fn union_step(&self, seek: &Seek) -> Option<&DisjunctionArms<'_>> {
self.arms.as_ref().filter(|_| seek.indexed())
}
fn first_answered(&self, graph: &ExecGraph<'_>) -> Result<Option<Answered>> {
for seek in &self.seeks {
if let Some(arms) = self.union_step(seek) {
if let Some(ids) = seek_union(graph, seek, arms)? {
return Ok(Some(Answered::Union(ids)));
}
continue;
}
if let Some(served) = served(seek, graph, &self.labels, self.label_seekable) {
return Ok(Some(Answered::Serve(served)));
}
}
Ok(None)
}
pub(crate) fn first_served_seek(&self, graph: &ExecGraph<'_>) -> Option<&Seek> {
self.seeks.iter().find(|seek| {
self.union_step(seek).is_none()
&& served(seek, graph, &self.labels, self.label_seekable).is_some()
})
}
}
pub(crate) fn node_candidates(
graph: &ExecGraph<'_>,
np: &NodePattern,
row: &Row,
params: &BTreeMap<String, Value>,
conjuncts: &[Expr],
) -> Result<Vec<NodeId>> {
funnel(
graph,
np,
row,
params,
Ask {
conjuncts,
cap: None,
},
)
}
#[derive(Clone, Copy)]
struct Ask<'a> {
conjuncts: &'a [Expr],
cap: Option<usize>,
}
pub(crate) enum Capped {
Within(Vec<NodeId>),
Over(u64),
}
pub(crate) fn node_candidates_capped(
graph: &ExecGraph<'_>,
np: &NodePattern,
row: &Row,
params: &BTreeMap<String, Value>,
conjuncts: &[Expr],
cap: usize,
) -> Result<Capped> {
let ask = Ask {
conjuncts,
cap: Some(cap),
};
let ids = funnel(graph, np, row, params, ask)?;
Ok(if ids.len() > cap {
Capped::Over(cap as u64 + 1)
} else {
Capped::Within(ids)
})
}
fn funnel(
graph: &ExecGraph<'_>,
np: &NodePattern,
row: &Row,
params: &BTreeMap<String, Value>,
ask: Ask<'_>,
) -> Result<Vec<NodeId>> {
let reads_before = crate::ctx::node_reads();
let candidates =
crate::ctx::phase_seek(|| binding_arm(binding(np, row), np, ask, graph, row, params))?;
if crate::ctx::node_reads() == reads_before {
crate::ctx::count_node_reads(candidates.len() as u64);
}
Ok(candidates)
}
fn binding_arm(
class: NodeBinding<'_>,
np: &NodePattern,
ask: Ask<'_>,
graph: &ExecGraph<'_>,
row: &Row,
params: &BTreeMap<String, Value>,
) -> Result<Vec<NodeId>> {
let Ask { conjuncts, cap } = ask;
let props = || {
pattern_props(
graph,
row,
np.properties.as_ref(),
PatternMapRole::Match,
params,
)
};
let v = match class {
Binding::Bound(id) => return Ok(vec![id]),
Binding::Mismatch => return Ok(Vec::new()),
Binding::Anonymous => return scan_ids(graph, np, props, cap),
Binding::Unbound(v) => v,
};
let Some(p) = prepared(v, np, conjuncts, graph, row, params) else {
return scan_ids(graph, np, || Ok(BTreeMap::new()), cap);
};
match p.first_answered(graph)? {
Some(Answered::Union(ids)) => return Ok(ids),
Some(Answered::Serve(served)) => return served.narrowed(graph, &p.labels, props),
None => {}
}
let ctx = OrCtx {
graph,
row,
params,
labels: &p.labels,
label_seekable: p.label_seekable,
};
if let Some(served) = or_union_candidates(v, conjuncts, &ctx) {
return served.narrowed(graph, &p.labels, props);
}
scan_ids(graph, np, props, cap)
}
fn scan_ids(
graph: &ExecGraph<'_>,
np: &NodePattern,
props: impl FnOnce() -> Result<BTreeMap<String, Value>>,
cap: Option<usize>,
) -> Result<Vec<NodeId>> {
if label_index_seekable(np) {
let labels = pattern_labels(np);
if let Some(ids) = graph.lookup_nodes_upto(&labels, &props()?, cap) {
return Ok(ids);
}
} else if let Some(arms) = np.static_disjunction_arms() {
if let Some(ids) = scan_disjunction_arms(graph, &arms, &props()?, cap)? {
return Ok(ids);
}
}
Ok(graph.all_node_ids())
}
fn scan_disjunction_arms(
graph: &ExecGraph<'_>,
arms: &DisjunctionArms<'_>,
props: &BTreeMap<String, Value>,
cap: Option<usize>,
) -> Result<Option<Vec<NodeId>>> {
if !props.is_empty() {
return union_dedup(arms.arms().map(|arm| {
let labels: Vec<String> = arm.map(|label| label.to_string()).collect();
graph
.lookup_nodes_upto(&labels, props, cap)
.expect("an arm's labels are non-empty: lookup_nodes always serves")
}))
.map(Some);
}
if !arms.base().is_empty() {
let labels: Vec<String> = arms.base().iter().map(|label| label.to_string()).collect();
return Ok(Some(graph.lookup_nodes_upto(&labels, props, cap).expect(
"the base labels are non-empty: lookup_nodes always serves",
)));
}
Ok(None)
}