use super::OptimizerCatalog;
use hawdb_core::RelationshipDirection;
pub(super) const START_COST_MARGIN: f64 = 2.0;
const MAX_ESTIMATED_HOPS: usize = 8;
#[derive(Debug, Clone)]
pub(super) struct PathNode<'a> {
pub(super) variable: &'a str,
pub(super) label: &'a str,
pub(super) equalities: Vec<&'a str>,
pub(super) values: std::collections::BTreeMap<&'a str, &'a hawdb_core::Value>,
pub(super) bound: bool,
}
#[derive(Debug, Clone)]
pub(super) struct PathEdge<'a> {
pub(super) rel_type: Option<&'a str>,
pub(super) equalities: Vec<&'a str>,
pub(super) values: std::collections::BTreeMap<&'a str, &'a hawdb_core::Value>,
pub(super) direction: RelationshipDirection,
pub(super) min_hops: usize,
pub(super) max_hops: usize,
pub(super) reversible: bool,
}
#[derive(Debug, Clone, PartialEq)]
pub(super) struct StartChoice {
pub(super) start: usize,
pub(super) property: String,
pub(super) work: f64,
pub(super) current_work: f64,
}
#[derive(Debug, Clone, PartialEq)]
pub(super) enum StartDecision {
Chosen(StartChoice),
Kept { detail: String },
}
pub(super) fn seekable_property<'a>(
catalog: &OptimizerCatalog,
node: &PathNode<'a>,
) -> Option<&'a str> {
if node.bound || !single_label(node.label) {
return None;
}
node.equalities
.iter()
.copied()
.filter(|property| catalog.has_property_index(node.label, property))
.min_by_key(|property| {
node.values.get(property).map_or_else(
|| catalog.estimate_property_index_eq_rows(node.label, property),
|value| catalog.estimate_property_index_value_rows(node.label, property, value),
)
})
}
pub(super) fn choose_start(
catalog: &OptimizerCatalog,
nodes: &[PathNode<'_>],
edges: &[PathEdge<'_>],
current: usize,
) -> Option<StartDecision> {
debug_assert_eq!(nodes.len(), edges.len() + 1);
let candidates = nodes
.iter()
.enumerate()
.filter(|(position, _)| *position != current)
.filter_map(|(position, node)| {
seekable_property(catalog, node).map(|property| (position, property))
})
.collect::<Vec<_>>();
if candidates.is_empty() {
return None;
}
let current_work = walk_work(catalog, nodes, edges, current)?;
let mut best: Option<StartChoice> = None;
let mut considered = Vec::new();
for (start, property) in candidates {
let Some(work) = walk_work(catalog, nodes, edges, start) else {
considered.push(format!("{}=unknown", nodes[start].variable));
continue;
};
considered.push(format!("{}={work:.1}", nodes[start].variable));
if best.as_ref().is_none_or(|best| work < best.work) {
best = Some(StartChoice {
start,
property: property.to_string(),
work,
current_work,
});
}
}
match best {
Some(choice) if choice.work * START_COST_MARGIN <= current_work => {
Some(StartDecision::Chosen(choice))
}
_ => Some(StartDecision::Kept {
detail: format!(
"current start {} estimated work {current_work:.1}; candidates [{}] are not {START_COST_MARGIN}x cheaper",
nodes[current].variable,
considered.join(", ")
),
}),
}
}
pub(super) fn walk_work(
catalog: &OptimizerCatalog,
nodes: &[PathNode<'_>],
edges: &[PathEdge<'_>],
start: usize,
) -> Option<f64> {
walk(catalog, nodes, edges, start).map(|estimate| estimate.work)
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub(super) struct WalkEstimate {
pub(super) work: f64,
pub(super) rows: f64,
}
pub(super) fn walk(
catalog: &OptimizerCatalog,
nodes: &[PathNode<'_>],
edges: &[PathEdge<'_>],
start: usize,
) -> Option<WalkEstimate> {
if catalog.path_counts.is_empty() && catalog.bounded_path_complete_through_hop.is_none() {
return None;
}
let labelled = nodes
.iter()
.map(|node| {
let label = nodes
.iter()
.find(|other| other.variable == node.variable && !other.label.is_empty())
.map_or(node.label, |other| other.label);
PathNode {
label,
..node.clone()
}
})
.collect::<Vec<_>>();
let nodes = labelled.as_slice();
if edges[..start].iter().any(|edge| !edge.reversible) {
return None;
}
let initial = node_work(catalog, &nodes[start])?;
let (mut rows, mut work) = (initial.rows, initial.work);
let mut visited = vec![false; nodes.len()];
visited[start] = true;
let steps = (start..edges.len())
.map(|index| (index, index + 1, edges[index].direction))
.chain(
(0..start)
.rev()
.map(|index| (index + 1, index, reverse(edges[index].direction))),
);
for (from, to, direction) in steps {
let edge = &edges[from.min(to)];
let expansion = expand_work(catalog, &nodes[from], &nodes[to], edge, direction)?;
work += rows * expansion.work;
let candidates = rows * expansion.rows;
let target = &nodes[to];
let repeated = nodes
.iter()
.enumerate()
.any(|(position, node)| visited[position] && node.variable == target.variable);
rows = if target.bound || repeated {
candidates / catalog.label_count(target.label) as f64
} else {
candidates * node_selectivity(catalog, target)
};
visited[to] = true;
}
Some(WalkEstimate { work, rows })
}
pub(super) fn node_work(catalog: &OptimizerCatalog, node: &PathNode<'_>) -> Option<WalkEstimate> {
let (rows, work) = if node.bound {
(1.0, 1.0)
} else if !single_label(node.label) {
return None;
} else if let Some(property) = seekable_property(catalog, node) {
let seek = node.values.get(property).map_or_else(
|| catalog.estimate_property_index_eq_rows(node.label, property),
|value| catalog.estimate_property_index_value_rows(node.label, property, value),
) as f64;
let rows = node
.equalities
.iter()
.filter(|other| **other != property)
.fold(seek, |rows, other| {
rows * equality_selectivity(
catalog,
node.label,
other,
node.values.get(other).copied(),
)
});
(rows, seek + 1.0)
} else {
let scanned = catalog.label_count(node.label) as f64;
(scanned * node_selectivity(catalog, node), scanned)
};
Some(WalkEstimate { work, rows })
}
#[derive(Debug, Clone, PartialEq)]
pub(super) struct MeetingEstimate {
pub(super) per_row: f64,
pub(super) build: f64,
pub(super) build_rows: f64,
pub(super) build_start: usize,
}
impl MeetingEstimate {
pub(super) fn hash_join_is_cheaper(&self, input_rows: f64) -> bool {
let hash_join = self.build + self.build_rows + input_rows;
hash_join * START_COST_MARGIN <= input_rows * self.per_row
}
}
pub(super) fn meeting(
catalog: &OptimizerCatalog,
nodes: &[PathNode<'_>],
edges: &[PathEdge<'_>],
key: usize,
per_row_start: usize,
) -> Option<MeetingEstimate> {
let key_variable = nodes[key].variable;
let with = |bound: bool| {
nodes
.iter()
.map(|node| PathNode {
bound: if node.variable == key_variable {
bound
} else {
node.bound
},
..node.clone()
})
.collect::<Vec<_>>()
};
let per_row_nodes = with(true);
let per_row = match choose_start(catalog, &per_row_nodes, edges, per_row_start) {
Some(StartDecision::Chosen(choice)) => choice.work,
_ => walk_work(catalog, &per_row_nodes, edges, per_row_start)?,
};
let build_nodes = with(false);
if build_nodes.iter().any(|node| node.bound) {
return None;
}
let build_start = match choose_start(catalog, &build_nodes, edges, 0) {
Some(StartDecision::Chosen(choice)) => choice.start,
_ => 0,
};
let build = walk(catalog, &build_nodes, edges, build_start)?;
Some(MeetingEstimate {
per_row,
build: build.work,
build_rows: build.rows,
build_start,
})
}
pub(super) fn expand_work(
catalog: &OptimizerCatalog,
from: &PathNode<'_>,
to: &PathNode<'_>,
edge: &PathEdge<'_>,
direction: RelationshipDirection,
) -> Option<WalkEstimate> {
let rel_type = edge.rel_type?;
let complete = catalog
.bounded_path_complete_through_hop
.is_some_and(|hop| edge.max_hops <= hop);
if !single_label(from.label)
|| !single_label(to.label)
|| (catalog.path_counts.is_empty()
&& (!complete || direction == RelationshipDirection::Undirected))
{
return None;
}
if edge.max_hops > MAX_ESTIMATED_HOPS {
return None;
}
let paths = |source: &str, target: &str| {
catalog
.path_counts
.get(&(source.to_string(), rel_type.to_string(), target.to_string()))
.copied()
.unwrap_or(0) as f64
};
let relationships = match direction {
RelationshipDirection::Outgoing => paths(from.label, to.label),
RelationshipDirection::Incoming => paths(to.label, from.label),
RelationshipDirection::Undirected => {
paths(from.label, to.label) + paths(to.label, from.label)
}
};
let selectivity = edge.equalities.iter().fold(1.0, |selectivity, property| {
let rows = catalog.relationship_count(rel_type).max(1);
let selected = edge.values.get(property).and_then(|value| {
catalog.rel_property_equality_estimate(rel_type, property, value, rows)
});
selectivity
* selected.map_or_else(
|| {
1.0 / catalog
.rel_property_distinct_count(rel_type, property)
.max(1) as f64
},
|estimate| estimate.rows.max(1) as f64 / rows as f64,
)
});
let population = catalog.label_count(from.label) as f64;
let one_hop = relationships / population;
let fallback = if one_hop > 0.0 {
one_hop
} else {
catalog.relationship_count(rel_type) as f64 / population
};
let hop_fanout = |hop: usize| {
if hop == 0 {
return (1.0, false);
}
let count = if hop == 1 {
Some(relationships)
} else {
match direction {
RelationshipDirection::Outgoing => catalog
.bounded_path_count(from.label, rel_type, to.label, hop)
.map(|count| count as f64),
RelationshipDirection::Incoming => catalog
.bounded_path_count(to.label, rel_type, from.label, hop)
.map(|count| count as f64),
RelationshipDirection::Undirected => None,
}
};
match count {
Some(count) if count > 0.0 => (count / population, false),
Some(_) => (1.0 / population, true),
None if one_hop > 0.0 => (one_hop.powi(hop as i32), false),
None => (fallback.powi(hop as i32).max(1.0 / population), false),
}
};
let mut rows = 0.0;
for hop in edge.min_hops..=edge.max_hops {
let (candidates, fallback) = hop_fanout(hop);
let matches = candidates * selectivity.powi(hop as i32);
rows += if fallback { 1.0 / population } else { matches };
}
let mut prefixes = [0.0; MAX_ESTIMATED_HOPS + 1];
let orientations = |source: &str, target: &str| match direction {
RelationshipDirection::Outgoing => u8::from(source == from.label),
RelationshipDirection::Incoming => u8::from(target == from.label),
RelationshipDirection::Undirected => {
u8::from(source == from.label) + u8::from(target == from.label)
}
};
for ((source, kind, target), count) in &catalog.path_counts {
if kind == rel_type {
prefixes[1] += *count as f64 * orientations(source, target) as f64 / population;
}
}
prefixes[1] = prefixes[1].max(catalog.relationship_count(rel_type) as f64 / population);
if direction != RelationshipDirection::Undirected {
for ((source, kind, target, hop), count) in &catalog.bounded_path_counts {
if kind == rel_type
&& (2..=edge.max_hops).contains(hop)
&& catalog
.bounded_path_complete_through_hop
.is_none_or(|horizon| *hop <= horizon)
{
prefixes[*hop] += *count as f64 * orientations(source, target) as f64 / population;
}
}
}
let mut work = 1.0;
for (hop, prefix) in prefixes.iter().enumerate().take(edge.max_hops + 1).skip(1) {
let known = direction != RelationshipDirection::Undirected
&& catalog
.bounded_path_complete_through_hop
.is_some_and(|horizon| hop <= horizon);
let candidates = if hop == 1 || *prefix > 0.0 || known {
*prefix
} else {
prefixes[1].powi(hop as i32)
};
work += candidates;
if hop < edge.max_hops {
work += candidates;
}
}
Some(WalkEstimate { work, rows })
}
pub(super) fn node_selectivity(catalog: &OptimizerCatalog, node: &PathNode<'_>) -> f64 {
if !single_label(node.label) {
return 1.0;
}
node.equalities.iter().fold(1.0, |selectivity, property| {
selectivity
* equality_selectivity(
catalog,
node.label,
property,
node.values.get(property).copied(),
)
})
}
fn equality_selectivity(
catalog: &OptimizerCatalog,
label: &str,
property: &str,
value: Option<&hawdb_core::Value>,
) -> f64 {
let rows = catalog.label_count(label);
value.map_or_else(
|| catalog.estimate_property_eq_rows(label, property, rows),
|value| catalog.estimate_property_value_rows(label, property, value, rows),
) as f64
/ rows as f64
}
fn single_label(label: &str) -> bool {
!label.is_empty() && !label.contains(':')
}
pub(super) fn reverse(direction: RelationshipDirection) -> RelationshipDirection {
match direction {
RelationshipDirection::Outgoing => RelationshipDirection::Incoming,
RelationshipDirection::Incoming => RelationshipDirection::Outgoing,
RelationshipDirection::Undirected => RelationshipDirection::Undirected,
}
}
#[cfg(test)]
pub(super) mod tests;