use crate::UsedSet;
use std::collections::{BTreeMap, HashSet};
use relate_core::{NodeId, Result};
use relate_ir::{path_pattern_vars, MatchMode, PathPattern};
use relate_names::SmallName;
use crate::ctx::ExecCtx;
use crate::row::{Row, RowRung};
use super::feed::RowStream;
use super::one_path::{match_one_path, PathFilters};
use super::pattern_policies::{reduce_row, MatchReduce, MatchTail, Matched};
use super::pushdown::{residual_ok, Residual};
const HUB_JOIN_MIN_SIDE_ROWS: usize = 128;
#[cfg(test)]
thread_local! {
static HUB_JOIN_DISABLED: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
static HUB_JOIN_ENGAGED: std::cell::Cell<u32> = const { std::cell::Cell::new(0) };
}
#[cfg(test)]
pub(crate) fn with_hub_join_disabled<R>(f: impl FnOnce() -> R) -> R {
super::test_support::with_flag_disabled(&HUB_JOIN_DISABLED, f)
}
#[cfg(test)]
pub(crate) fn take_hub_join_engagements() -> u32 {
HUB_JOIN_ENGAGED.with(|c| c.replace(0))
}
fn hub_join_applies<'p>(
patterns: &'p [PathPattern],
match_mode: MatchMode,
row: &Row,
plain_rows_only: bool,
) -> Option<&'p SmallName> {
if patterns.len() != 2 || !plain_rows_only {
return None;
}
if match_mode == MatchMode::RepeatableElements {
return None;
}
for p in patterns {
if p.nodes.len() != 2
|| p.rels.len() != 1
|| p.rels[0].var_length
|| p.rels[0].quantified
|| p.is_shortest_path_function
|| p.needs_gpm()
{
return None;
}
for v in path_pattern_vars(p) {
if row.get_name(v).is_some() {
return None;
}
}
}
let a: HashSet<&SmallName> = path_pattern_vars(&patterns[0]).collect();
let b: HashSet<&SmallName> = path_pattern_vars(&patterns[1]).collect();
let shared: Vec<&SmallName> = a.intersection(&b).copied().collect();
if shared.len() == 1 && is_shared_node_var(patterns, shared[0]) {
Some(shared[0])
} else {
None
}
}
fn is_shared_node_var(patterns: &[PathPattern], name: &SmallName) -> bool {
patterns
.iter()
.all(|p| p.nodes.iter().any(|n| n.variable.as_ref() == Some(name)))
}
pub(super) fn try_hub_join<'a: 'r, 'r>(
ctx: ExecCtx<'a>,
patterns: &'r [PathPattern],
match_mode: MatchMode,
row: &'r Row,
a_rows: &'r Matched,
residual: &'r Residual<'r>,
plain_rows_only: bool,
) -> Result<Option<RowStream<'r>>> {
#[cfg(test)]
if HUB_JOIN_DISABLED.with(std::cell::Cell::get) {
return Ok(None);
}
let Some(hub_var) = hub_join_applies(patterns, match_mode, row, plain_rows_only) else {
return Ok(None);
};
if a_rows.len() < HUB_JOIN_MIN_SIDE_ROWS {
return Ok(None);
}
let a_index = HubIndex::build(a_rows.iter(), hub_var)?;
let b_filters = PathFilters::resolve(ctx.graph, &patterns[1], match_mode);
let b_rows = plain_side_rows(
ctx,
&patterns[1],
&b_filters,
row.clone(),
match_mode,
residual,
)?;
#[cfg(test)]
HUB_JOIN_ENGAGED.with(|c| c.set(c.get() + 1));
let Some((first, _)) = b_rows.first() else {
return Ok(Some(RowStream::emitting(std::iter::empty())));
};
let a_names: Vec<String> = a_index
.by_hub
.values()
.flatten()
.next()
.map(|(row, _)| row.keys().cloned().collect())
.expect("the join gate kept at least one side-A row");
let b_names: Vec<String> = first.keys().cloned().collect();
let merge = merged_schema(&a_names, &b_names);
Ok(Some(RowStream::emitting(HubFanOut {
ctx,
index: a_index,
b_rows: b_rows.into_iter(),
hub: hub_var,
b_names,
merge,
residual,
current: None,
})))
}
pub(super) fn hub_join_answer<'a: 'r, 'r>(
ctx: ExecCtx<'a>,
patterns: &'r [PathPattern],
match_mode: MatchMode,
base: &'r Row,
current: &'r Matched,
residual: &'r Residual<'r>,
reduce: Option<&MatchReduce<'_>>,
) -> Result<Option<Vec<Row>>> {
let plain_rows_only = reduce.is_none_or(|r| r.sink.irrevocable());
let Some(mut stream) = try_hub_join(
ctx,
patterns,
match_mode,
base,
current,
residual,
plain_rows_only,
)?
else {
return Ok(None);
};
let mut out = Vec::new();
while let Some(batch) = stream.next_batch()? {
for row in batch {
out.extend(reduce_row(ctx.graph, row, reduce)?);
}
}
Ok(Some(out))
}
struct HubFanOut<'a, 'r> {
ctx: ExecCtx<'a>,
index: HubIndex<'r>,
b_rows: std::vec::IntoIter<(Row, UsedSet)>,
hub: &'r SmallName,
b_names: Vec<String>,
merge: HubMerge,
residual: &'r Residual<'r>,
current: Option<(Row, UsedSet, NodeId, usize)>,
}
impl Iterator for HubFanOut<'_, '_> {
type Item = Result<Row>;
fn next(&mut self) -> Option<Result<Row>> {
loop {
let Some((hub, slot)) = self.current.as_ref().map(|(_, _, hub, slot)| (*hub, *slot))
else {
let (b_row, b_used) = self.b_rows.next()?;
let hub = row_node_id(&b_row, self.hub);
if self.index.by_hub.contains_key(&hub) {
self.current = Some((b_row, b_used, hub, 0));
}
continue;
};
let Some((a_row, a_used)) = self
.index
.by_hub
.get(&hub)
.and_then(|side| side.get(slot))
.copied()
else {
self.current = None;
continue;
};
let (b_row, b_used) = {
let (b_row, b_used, _, slot) = self.current.as_mut().expect("checked above");
*slot += 1;
(b_row, b_used)
};
if let Err(error) = self.ctx.graph.cancel_tick() {
return Some(Err(error));
}
if !a_used.is_disjoint(b_used) {
continue;
}
let mut merged = a_row.clone();
merged.stamp(
&self.merge.rung,
self.merge
.fresh_slots
.iter()
.map(|&s| b_row.values()[s].clone()),
);
for &s in &self.merge.bound_slots {
merged.insert(self.b_names[s].clone(), b_row.values()[s].clone());
}
match residual_ok(self.ctx.graph, &merged, self.ctx.params, self.residual) {
Ok(true) => return Some(Ok(merged)),
Ok(false) => continue,
Err(error) => return Some(Err(error)),
}
}
}
}
struct HubIndex<'a> {
by_hub: BTreeMap<NodeId, Vec<&'a (Row, UsedSet)>>,
charge: relate_core::tokens::WorkspaceCharge,
slots: usize,
}
impl<'a> HubIndex<'a> {
fn build(rows: impl Iterator<Item = &'a (Row, UsedSet)>, hub_var: &SmallName) -> Result<Self> {
const SLOT: u64 = size_of::<&(Row, UsedSet)>() as u64;
let mut index = Self {
by_hub: BTreeMap::new(),
charge: relate_core::tokens::WorkspaceCharge::empty(),
slots: 0,
};
for pair in rows {
let hub = row_node_id(&pair.0, hub_var);
let fresh = usize::from(!index.by_hub.contains_key(&hub));
let (hubs, slots) = (index.by_hub.len() + fresh, index.slots + 1);
index.charge.resize_with(|| {
crate::workspace::map_entries_bytes(hubs)
+ crate::workspace::buffer_bytes(slots, SLOT)
})?;
index.by_hub.entry(hub).or_default().push(pair);
index.slots += 1;
}
Ok(index)
}
}
struct HubMerge {
rung: RowRung,
fresh_slots: Vec<usize>,
bound_slots: Vec<usize>,
}
fn merged_schema(a_names: &[String], b_names: &[String]) -> HubMerge {
let mut merged_names = a_names.to_vec();
let mut fresh_slots = Vec::new();
let mut bound_slots = Vec::new();
for (slot, name) in b_names.iter().enumerate() {
if a_names.iter().any(|bound| bound == name) {
bound_slots.push(slot);
} else {
fresh_slots.push(slot);
merged_names.push(name.clone());
}
}
HubMerge {
rung: RowRung::from_names(&merged_names),
fresh_slots,
bound_slots,
}
}
fn plain_side_rows(
ctx: ExecCtx<'_>,
pattern: &PathPattern,
filters: &PathFilters,
row: Row,
match_mode: MatchMode,
residual: &Residual<'_>,
) -> Result<Matched> {
match_one_path(
ctx,
pattern,
filters,
row,
UsedSet::default(),
match_mode,
residual,
None,
MatchTail::Carry,
)
}
fn row_node_id(row: &Row, var: &SmallName) -> NodeId {
crate::pattern_walk::classify(Some(var), row, crate::pattern_walk::node_id)
.bound_id()
.expect("a bound hub variable always holds a node")
}
#[cfg(test)]
mod tests {
use std::collections::BTreeMap;
use relate_core::tokens::{workspace_meter, LedgerGuard};
use relate_ir::Clause;
use crate::overlay::ExecGraph;
use crate::row::RowNames;
use super::super::batch_tail::BATCH_ROWS;
use super::super::test_support::{build, clauses_of};
use super::*;
const SIDE_A_ROWS: usize = 128;
const SIDE_B_ROWS: usize = 32;
fn pair_patterns() -> Vec<PathPattern> {
let clauses = clauses_of("MATCH (a:A)-[:RA]->(h:H), (b:B)-[:RB]->(h) RETURN count(*) AS c");
match clauses.into_iter().next() {
Some(Clause::Match { patterns, .. }) => patterns,
_ => panic!("the fixture opens with the comma-pair MATCH"),
}
}
fn measure(hubs: usize) -> (usize, u64) {
assert_eq!(SIDE_A_ROWS % hubs, 0);
let mut labels: Vec<&[&str]> = vec![&["H"][..]; hubs];
labels.resize(hubs + SIDE_B_ROWS, &["B"][..]);
let rels: Vec<(usize, usize, &str)> = (0..SIDE_B_ROWS)
.map(|b| (hubs + b, b % hubs, "RB"))
.collect();
let built = build(&labels, &rels);
let view = ExecGraph::read(&built.graph);
let params = BTreeMap::new();
let ctx = ExecCtx::new(&view, ¶ms);
let patterns = pair_patterns();
let names = RowNames::new(&["h".to_string()]);
let a_rows: Matched = (0..SIDE_A_ROWS)
.map(|i| {
let hub = built.nodes[i % hubs];
(
Row::from_names(&names, vec![view.node_value(hub)]),
UsedSet::default(),
)
})
.collect();
let base = Row::new();
let residual = Residual::empty();
let mut ledger = crate::test_support::roomy_ledger();
let guard = LedgerGuard::install(&mut ledger);
let _ = take_hub_join_engagements();
let mut stream = try_hub_join(
ctx,
&patterns,
MatchMode::DifferentRelationships,
&base,
&a_rows,
&residual,
true,
)
.expect("the join runs infallibly")
.expect("the join takes the pair");
assert_eq!(take_hub_join_engagements(), 1, "the join engaged");
assert!(!stream.is_held(), "the join hands back a produced stream");
assert!(stream.probe().is_empty(), "no merged row is in hand");
let mut rows = 0usize;
while let Some(batch) = stream.next_batch().expect("the join is infallible") {
let count = batch.into_iter().count();
assert!(count <= BATCH_ROWS, "a batch is bounded");
rows += count;
}
let (_, peak, _) = workspace_meter().expect("a ledger is installed");
drop(guard);
(rows, peak)
}
#[test]
fn the_join_streams_a_fan_out_independent_of_the_hub_index() {
let (four_hubs, at_four_hubs) = measure(4);
let (one_hub, at_one_hub) = measure(1);
assert_eq!(four_hubs, SIDE_A_ROWS * SIDE_B_ROWS / 4);
assert_eq!(one_hub, SIDE_A_ROWS * SIDE_B_ROWS);
assert!(at_four_hubs > 0, "the side-A index is charged");
assert!(
at_one_hub <= at_four_hubs,
"the fan-out per hub grew 4x ({four_hubs} -> {one_hub} rows) \
but the retained total rose: {at_one_hub} vs {at_four_hubs}"
);
}
}