use std::collections::HashSet;
use std::rc::Rc;
use relate_core::{NodeId, Result};
use relate_ir::{path_pattern_vars, Expr, MatchMode, PathPattern};
use relate_names::SmallName;
use relate_planner::{
can_reverse_varlen_leg, detect_junction_split, junction_legs_have_cross_inline_refs,
reverse_varlen_leg, split_junction_legs, MatchStrategy,
};
use crate::ctx::ExecCtx;
use crate::exec::expand::match_resolved_path;
use crate::exec::graph_stats::{element_estimate, GraphStats};
use crate::exec::match_clause::MatchClauseInputs;
use crate::exec::one_path::{match_one_path, PathFilters};
use crate::exec::pattern_policies::{MatchReduce, MatchTail};
use crate::exec::profiling::count_hash_join;
use crate::exec::pushdown::{flatten_and_owned, match_scope, MatchCap, Residual};
use crate::exec::rider::{BindingSink, Rider};
use crate::exec::sink::SinkProjection;
use crate::hash_seed::IdMap;
use crate::overlay::{ExecGraph, RetainedTotal};
use crate::pattern_walk::UsedRels;
use crate::row::Row;
use crate::UsedSet;
use super::semi_mask::SemiMask;
use super::{downstream_projection, internal_vars_unused_downstream, min_side_rows, row_node_id};
fn legs_rel_types_disjoint(fixed: &PathPattern, var: &PathPattern) -> bool {
let mut fixed_types = HashSet::new();
for r in &fixed.rels {
if r.types.is_empty() || r.type_expr.is_some() {
return false;
}
for name in r.type_names() {
fixed_types.insert(name);
}
}
let mut var_types = HashSet::new();
for r in &var.rels {
if r.types.is_empty() || r.type_expr.is_some() {
return false;
}
for name in r.type_names() {
var_types.insert(name);
}
}
fixed_types.is_disjoint(&var_types)
}
fn expr_references_any(expr: &Expr, vars: &HashSet<String>) -> bool {
let mut used = HashSet::new();
crate::eval::expr_vars(expr, &mut used);
used.iter().any(|v| vars.contains(v))
}
fn is_multiplicity_downstream(
build_leg: &PathPattern,
junction_var: &SmallName,
conjuncts: &[Expr],
projection: Option<&SinkProjection<'_>>,
reduce: Option<&MatchReduce<'_>>,
) -> bool {
if build_leg.has_path_name() {
return false;
}
let internal: HashSet<String> = path_pattern_vars(build_leg)
.filter(|v| *v != junction_var)
.map(|v| v.to_string())
.collect();
internal_vars_unused_downstream(
&internal,
conjuncts,
downstream_projection(projection, reduce),
)
}
struct JunctionBuildTable {
multiplicity_only: bool,
disjoint_rels: bool,
counts: IdMap<NodeId, u64>,
by_key: IdMap<NodeId, Vec<(Row, UsedSet)>>,
charge: RetainedTotal,
build_rows: u64,
}
impl JunctionBuildTable {
fn new(graph: &ExecGraph<'_>, multiplicity_only: bool, disjoint_rels: bool) -> Result<Self> {
Ok(Self {
multiplicity_only,
disjoint_rels,
counts: IdMap::default(),
by_key: IdMap::default(),
charge: graph.retain_bytes(0)?,
build_rows: 0,
})
}
fn insert(
&mut self,
graph: &ExecGraph<'_>,
key: NodeId,
row: Row,
used: UsedSet,
) -> Result<()> {
self.build_rows += 1;
if self.multiplicity_only {
let existed = self.counts.contains_key(&key);
*self.counts.entry(key).or_default() += 1;
if !existed {
self.charge
.add_bytes(graph, crate::workspace::map_entries_bytes(1))?;
}
} else {
self.charge.add_row(graph, row.values())?;
let existed = self.by_key.contains_key(&key);
self.by_key.entry(key).or_default().push((row, used));
if !existed {
self.charge
.add_bytes(graph, crate::workspace::map_entries_bytes(1))?;
}
}
Ok(())
}
fn is_empty(&self) -> bool {
self.build_rows == 0
}
fn distinct_keys(&self) -> Vec<NodeId> {
if self.multiplicity_only {
self.counts.keys().copied().collect()
} else {
self.by_key.keys().copied().collect()
}
}
fn distinct_len(&self) -> u64 {
if self.multiplicity_only {
self.counts.len() as u64
} else {
self.by_key.len() as u64
}
}
fn emit_matches(
&self,
graph: &ExecGraph<'_>,
key: NodeId,
probe_row: &Row,
rel_disjoint: impl Fn(&UsedSet) -> bool,
emit: &mut EmitState<'_, '_, '_>,
) -> Result<bool> {
if self.multiplicity_only {
if let Some(&count) = self.counts.get(&key) {
for _ in 0..count {
if emit.push(graph, probe_row.clone())? {
return Ok(true);
}
}
}
} else if let Some(matching_rows) = self.by_key.get(&key) {
for (b_row, b_used) in matching_rows {
if !self.disjoint_rels && !rel_disjoint(b_used) {
continue;
}
let mut merged = probe_row.clone();
for (k, v) in b_row.iter() {
if !merged.contains_key(k) {
merged.insert(k.to_string(), v.clone());
}
}
if emit.push(graph, merged)? {
return Ok(true);
}
}
}
Ok(false)
}
}
struct EmitState<'out, 'cap, 'tail> {
tail: MatchTail<'tail>,
cap: Option<&'out mut MatchCap<'cap>>,
out: &'out mut Vec<Row>,
out_charge: RetainedTotal,
}
impl EmitState<'_, '_, '_> {
fn push(&mut self, graph: &ExecGraph<'_>, row: Row) -> Result<bool> {
if let Some(finished) = self.tail.finish_row(graph, row, self.cap.as_deref_mut())? {
self.out_charge.add_row(graph, finished.values())?;
self.out.push(finished);
if self.halted() {
return Ok(true);
}
}
Ok(false)
}
fn halted(&self) -> bool {
self.cap.as_ref().is_some_and(|c| c.full())
}
}
struct VarlenProbeSink<'a, 'out, 'cap, 'tail> {
junction_var: &'a SmallName,
semi_mask: &'a SemiMask,
table: &'a JunctionBuildTable,
emit: EmitState<'out, 'cap, 'tail>,
}
impl BindingSink for VarlenProbeSink<'_, '_, '_, '_> {
fn offer(&mut self, graph: &ExecGraph<'_>, fixed_row: Row, used: &UsedRels) -> Result<()> {
let c_id = row_node_id(&fixed_row, self.junction_var);
if !self.semi_mask.contains(c_id) {
return Ok(());
}
let _ = self.table.emit_matches(
graph,
c_id,
&fixed_row,
|b_used| used.is_disjoint(b_used),
&mut self.emit,
)?;
Ok(())
}
fn halted(&self) -> bool {
self.emit.halted()
}
}
struct JunctionSplitJob<'a, 'cap, 'cap_data, 'proj, 'red> {
ctx: ExecCtx<'a>,
fixed_leg: PathPattern,
var_leg: PathPattern,
fixed_on_left: bool,
junction_var: &'a SmallName,
match_mode: MatchMode,
disjoint_rels: bool,
conjuncts: Vec<Expr>,
fixed_conjuncts: Vec<Expr>,
var_conjuncts: Vec<Expr>,
cap: Option<&'cap mut MatchCap<'cap_data>>,
projection: Option<&'proj SinkProjection<'proj>>,
reduce: Option<&'red MatchReduce<'red>>,
}
impl JunctionSplitJob<'_, '_, '_, '_, '_> {
fn exec_build_fixed(mut self, seed_input: &Row, out: &mut Vec<Row>) -> Result<bool> {
let unbound = |_: &str| false;
if !self.fixed_on_left {
if !can_reverse_varlen_leg(&self.var_leg, &unbound) {
return Ok(false);
}
reverse_varlen_leg(&mut self.var_leg);
}
let stats = GraphStats::new(self.ctx.graph.base(), self.ctx.params);
let last_fixed = self.fixed_leg.nodes.len() - 1;
let est0 = element_estimate(
&stats,
&self.fixed_leg,
&unbound,
self.fixed_conjuncts.iter(),
0,
);
let est1 = element_estimate(
&stats,
&self.fixed_leg,
&unbound,
self.fixed_conjuncts.iter(),
last_fixed,
);
if est1.rows < est0.rows && relate_planner::can_reverse_path(&self.fixed_leg, &unbound) {
relate_planner::reverse_path(&mut self.fixed_leg);
}
let multiplicity_only = self.disjoint_rels
&& is_multiplicity_downstream(
&self.fixed_leg,
self.junction_var,
&self.conjuncts,
self.projection,
self.reduce,
);
let mut table =
JunctionBuildTable::new(self.ctx.graph, multiplicity_only, self.disjoint_rels)?;
let fixed_filters = PathFilters::resolve(self.ctx.graph, &self.fixed_leg, self.match_mode);
let fixed_patterns = [self.fixed_leg.clone()];
let fixed_scope = match_scope(self.ctx.graph, seed_input, &fixed_patterns);
let fixed_residual = Residual {
conjuncts: &self.fixed_conjuncts,
scope: &fixed_scope,
};
let junction_var = self.junction_var;
let graph = self.ctx.graph;
let mut build_sink = |row: Row, used: UsedSet| -> Result<bool> {
let key = row_node_id(&row, junction_var);
table.insert(graph, key, row, used)?;
Ok(false)
};
let mut build_rider = Rider::Stream(&mut build_sink);
let _ = match_one_path(
self.ctx,
&self.fixed_leg,
&fixed_filters,
seed_input.clone(),
UsedSet::default(),
self.match_mode,
&fixed_residual,
Some(&mut build_rider),
MatchTail::Carry,
)?;
#[cfg(test)]
super::HASH_JOIN_ENGAGED.with(|c| c.set(c.get() + 1));
if table.is_empty() {
count_hash_join(crate::metrics::HashJoinCounters {
build_rows: 0,
probe_rows: 0,
semi_mask_rejected: 0,
});
return Ok(true);
}
let junction_ids = table.distinct_keys();
let var_filters = PathFilters::resolve(self.ctx.graph, &self.var_leg, self.match_mode);
let var_patterns = [self.var_leg.clone()];
let mut emit = EmitState {
tail: MatchTail::Finish {
reduce: self.reduce,
},
cap: self.cap,
out,
out_charge: self.ctx.graph.retain_bytes(0)?,
};
let mut probe_rows: u64 = 0;
for junction_id in junction_ids {
self.ctx.graph.cancel_tick()?;
if emit.halted() {
break;
}
let mut seed_row = seed_input.clone();
seed_row.insert(
self.junction_var.to_string(),
self.ctx.graph.node_value(junction_id),
);
let var_scope = match_scope(self.ctx.graph, &seed_row, &var_patterns);
let var_residual = Residual {
conjuncts: &self.var_conjuncts,
scope: &var_scope,
};
let mut probe_sink = |v_row: Row, v_used: UsedSet| -> Result<bool> {
probe_rows += 1;
table.emit_matches(
graph,
junction_id,
&v_row,
|f_used| v_used.is_disjoint(f_used),
&mut emit,
)
};
let mut probe_rider = Rider::Stream(&mut probe_sink);
let _ = match_one_path(
self.ctx,
&self.var_leg,
&var_filters,
seed_row,
UsedSet::default(),
self.match_mode,
&var_residual,
Some(&mut probe_rider),
MatchTail::Carry,
)?;
}
count_hash_join(crate::metrics::HashJoinCounters {
build_rows: table.build_rows,
probe_rows,
semi_mask_rejected: 0,
});
Ok(true)
}
fn exec_build_varlen(self, rows: &[Row], out: &mut Vec<Row>) -> Result<bool> {
let fixed_filters = PathFilters::resolve(self.ctx.graph, &self.fixed_leg, self.match_mode);
let PathFilters::Classic { rels, plans } = &fixed_filters else {
return Ok(false);
};
let multiplicity_only = self.disjoint_rels
&& is_multiplicity_downstream(
&self.var_leg,
self.junction_var,
&self.conjuncts,
self.projection,
self.reduce,
);
let mut table =
JunctionBuildTable::new(self.ctx.graph, multiplicity_only, self.disjoint_rels)?;
let var_filters = PathFilters::resolve(self.ctx.graph, &self.var_leg, self.match_mode);
let var_patterns = [self.var_leg.clone()];
let var_scope = match_scope(self.ctx.graph, &Row::new(), &var_patterns);
let var_residual = Residual {
conjuncts: &self.var_conjuncts,
scope: &var_scope,
};
let junction_var = self.junction_var;
let graph = self.ctx.graph;
let mut build_sink = |row: Row, used: UsedSet| -> Result<bool> {
let key = row_node_id(&row, junction_var);
table.insert(graph, key, row, used)?;
Ok(false)
};
let mut build_rider = Rider::Stream(&mut build_sink);
let _ = match_one_path(
self.ctx,
&self.var_leg,
&var_filters,
Row::new(),
UsedSet::default(),
self.match_mode,
&var_residual,
Some(&mut build_rider),
MatchTail::Carry,
)?;
if table.is_empty() {
count_hash_join(crate::metrics::HashJoinCounters {
build_rows: 0,
probe_rows: rows.len() as u64,
semi_mask_rejected: 0,
});
return Ok(true);
}
#[cfg(test)]
super::HASH_JOIN_ENGAGED.with(|c| c.set(c.get() + 1));
let ids = table.distinct_keys();
let semi_mask = Rc::new(SemiMask::from_rows(&ids, |id| **id)?);
let fixed_patterns = [self.fixed_leg.clone()];
let fixed_scope = match_scope(self.ctx.graph, &Row::new(), &fixed_patterns);
let fixed_residual = Residual {
conjuncts: &self.fixed_conjuncts,
scope: &fixed_scope,
};
let mut sink = VarlenProbeSink {
junction_var: self.junction_var,
semi_mask: &semi_mask,
table: &table,
emit: EmitState {
tail: MatchTail::Finish {
reduce: self.reduce,
},
cap: self.cap,
out,
out_charge: self.ctx.graph.retain_bytes(0)?,
},
};
for row in rows {
self.ctx.graph.cancel_tick()?;
if sink.halted() {
break;
}
match_resolved_path(
self.ctx,
&self.fixed_leg,
rels,
plans,
&fixed_residual,
row.clone(),
UsedSet::default(),
&mut sink,
)?;
}
count_hash_join(crate::metrics::HashJoinCounters {
build_rows: table.distinct_len(),
probe_rows: rows.len() as u64,
semi_mask_rejected: semi_mask.rejected(),
});
Ok(true)
}
}
pub(crate) fn try_junction_split_hash_join(
ctx: ExecCtx<'_>,
rows: &[Row],
clause: MatchClauseInputs<'_>,
cap: Option<&mut MatchCap<'_>>,
projection: Option<&SinkProjection<'_>>,
reduce: Option<&MatchReduce<'_>>,
planned_strategy: Option<MatchStrategy>,
) -> Result<Option<Vec<Row>>> {
let MatchClauseInputs {
optional,
match_mode,
patterns,
where_clause,
} = clause;
if optional || patterns.len() != 1 || rows.is_empty() {
return Ok(None);
}
if match_mode == MatchMode::RepeatableElements {
return Ok(None);
}
#[cfg(test)]
if super::HASH_JOIN_DISABLED.with(std::cell::Cell::get) {
return Ok(None);
}
let pattern = &patterns[0];
if let Some(w) = where_clause {
let pat_vars: HashSet<String> = path_pattern_vars(pattern).map(|v| v.to_string()).collect();
if !relate_ir::all_vars_satisfy(w, |v| pat_vars.contains(v)) {
return Ok(None);
}
}
let Some(split) = detect_junction_split(pattern) else {
return Ok(None);
};
let junction_var = pattern.nodes[split.index]
.variable
.as_ref()
.expect("detect_junction_split guarantees a named junction node");
let (fixed_leg, var_leg) = split_junction_legs(pattern, split);
let fixed_vars: HashSet<String> = path_pattern_vars(&fixed_leg)
.filter(|v| *v != junction_var)
.map(|v| v.to_string())
.collect();
let var_vars: HashSet<String> = path_pattern_vars(&var_leg)
.filter(|v| *v != junction_var)
.map(|v| v.to_string())
.collect();
if junction_legs_have_cross_inline_refs(&fixed_leg, &var_leg, &fixed_vars, &var_vars) {
return Ok(None);
}
let conjuncts = where_clause.map(flatten_and_owned).unwrap_or_default();
for c in &conjuncts {
if expr_references_any(c, &var_vars) && expr_references_any(c, &fixed_vars) {
return Ok(None);
}
}
for r in rows {
for v in &var_vars {
if r.get_name(&SmallName::from(v.as_str())).is_some() {
return Ok(None);
}
}
}
let var_conjuncts: Vec<Expr> = conjuncts
.iter()
.filter(|c| !expr_references_any(c, &fixed_vars))
.cloned()
.collect();
let fixed_conjuncts: Vec<Expr> = conjuncts
.iter()
.filter(|c| !expr_references_any(c, &var_vars))
.cloned()
.collect();
let disjoint_rels = legs_rel_types_disjoint(&fixed_leg, &var_leg);
let job = JunctionSplitJob {
ctx,
fixed_leg,
var_leg,
fixed_on_left: split.fixed_on_left,
junction_var,
match_mode,
disjoint_rels,
conjuncts,
fixed_conjuncts,
var_conjuncts,
cap,
projection,
reduce,
};
let planner_selected = planned_strategy == Some(MatchStrategy::HashJoinJunctionSplit);
if planner_selected
&& rows.len() == 1
&& rows[0].get_name(junction_var).is_none()
&& !fixed_vars
.iter()
.any(|v| rows[0].get_name(&SmallName::from(v.as_str())).is_some())
{
let mut out = Vec::new();
return Ok(job.exec_build_fixed(&rows[0], &mut out)?.then_some(out));
}
#[cfg(test)]
let forced = super::HASH_JOIN_FORCED.with(std::cell::Cell::get);
#[cfg(not(test))]
let forced = false;
if !forced && rows.len() < min_side_rows() {
return Ok(None);
}
let mut out = Vec::new();
Ok(job.exec_build_varlen(rows, &mut out)?.then_some(out))
}