use std::collections::BTreeMap;
use relate_core::Value;
use super::{take_hash_join_engagements, with_hash_join_disabled};
use crate::exec::test_support::{exec_cypher, profiled, try_exec_cypher_params};
use crate::graph::Graph;
fn build_multi_hop_graph(hubs: usize, branches_per_hub: usize) -> Graph {
let g = Graph::default();
g.begin_write().unwrap();
let node = |label: &str, id: i64| {
g.create_node(
vec![label.into()],
BTreeMap::from([("id".into(), Value::Int(id))]),
)
.unwrap()
};
let mut hub_nodes = Vec::new();
for i in 0..hubs {
hub_nodes.push(node("H", i as i64));
}
let mut counter = 0i64;
for &h in &hub_nodes {
for _ in 0..branches_per_hub {
counter += 1;
let a = node("A", counter);
let b = node("B", counter);
g.create_rel(a, b, "RA".into(), BTreeMap::new()).unwrap();
g.create_rel(b, h, "RAB".into(), BTreeMap::new()).unwrap();
let c = node("C", counter);
let d = node("D", counter);
g.create_rel(c, d, "RC".into(), BTreeMap::new()).unwrap();
g.create_rel(d, h, "RCD".into(), BTreeMap::new()).unwrap();
}
}
g.commit_write();
g
}
#[test]
fn multi_hop_two_pattern_join_parity() {
let g = build_multi_hop_graph(20, 8);
let query = "MATCH (a:A)-[:RA]->(b:B)-[:RAB]->(h:H), (c:C)-[:RC]->(d:D)-[:RCD]->(h) \
RETURN h.id AS hub, a.id AS aid, c.id AS cid ORDER BY hub, aid, cid";
let _ = take_hash_join_engagements();
let joined = exec_cypher(&g, query);
assert_eq!(
take_hash_join_engagements(),
1,
"multi-hop hash join engaged"
);
let nested = with_hash_join_disabled(|| {
let _ = take_hash_join_engagements();
let r = exec_cypher(&g, query);
assert_eq!(take_hash_join_engagements(), 0, "hash join disabled");
r
});
assert_eq!(
joined.rows, nested.rows,
"exact parity between hash join and nested loop"
);
assert!(!joined.rows.is_empty());
}
#[test]
fn multi_key_join_parity_and_rel_uniqueness() {
let g = Graph::default();
g.begin_write().unwrap();
let node = |label: &str, id: i64| {
g.create_node(
vec![label.into()],
BTreeMap::from([("id".into(), Value::Int(id))]),
)
.unwrap()
};
let hubs = 20;
let mut h1_nodes = Vec::new();
let mut h2_nodes = Vec::new();
for i in 0..hubs {
h1_nodes.push(node("H1", i as i64));
h2_nodes.push(node("H2", i as i64));
}
let mut counter = 0i64;
for i in 0..hubs {
let h1 = h1_nodes[i];
let h2 = h2_nodes[i];
for _ in 0..10 {
counter += 1;
let a = node("A", counter);
g.create_rel(a, h1, "R1".into(), BTreeMap::new()).unwrap();
g.create_rel(a, h2, "R2".into(), BTreeMap::new()).unwrap();
let b = node("B", counter);
g.create_rel(b, h1, "R3".into(), BTreeMap::new()).unwrap();
g.create_rel(b, h2, "R4".into(), BTreeMap::new()).unwrap();
}
}
g.commit_write();
let query = "MATCH (h1:H1)<-[:R1]-(a:A)-[:R2]->(h2:H2), \
(h1:H1)<-[:R3]-(b:B)-[:R4]->(h2:H2) \
RETURN h1.id AS h1_id, h2.id AS h2_id, a.id AS aid, b.id AS bid \
ORDER BY h1_id, h2_id, aid, bid";
let _ = take_hash_join_engagements();
let joined = exec_cypher(&g, query);
assert_eq!(
take_hash_join_engagements(),
1,
"multi-key hash join engaged"
);
let nested = with_hash_join_disabled(|| exec_cypher(&g, query));
assert_eq!(joined.rows, nested.rows, "exact parity on multi-key join");
assert!(!joined.rows.is_empty());
}
#[test]
fn semi_mask_sip_effectiveness_and_profile_metrics() {
let g = Graph::default();
g.begin_write().unwrap();
let node = |label: &str, id: i64| {
g.create_node(
vec![label.into()],
BTreeMap::from([("id".into(), Value::Int(id))]),
)
.unwrap()
};
let hubs = 200;
let mut hub_nodes = Vec::new();
let mut counter = 0i64;
for i in 0..hubs {
let h = node("Hub", i as i64);
hub_nodes.push(h);
for _ in 0..10 {
counter += 1;
let a = node("A", counter);
g.create_rel(a, h, "TO_HUB".into(), BTreeMap::new())
.unwrap();
}
}
for &h in &hub_nodes {
for _ in 0..10 {
counter += 1;
let b = node("B", counter);
g.create_rel(b, h, "FROM_B".into(), BTreeMap::new())
.unwrap();
}
}
for i in 0..1000 {
counter += 1;
let non_hub = node("Hub", (100_000 + i) as i64);
let b = node("B", counter);
g.create_rel(b, non_hub, "FROM_B".into(), BTreeMap::new())
.unwrap();
}
g.commit_write();
let query = "MATCH (a:A)-[:TO_HUB]->(h:Hub), (b:B)-[:FROM_B]->(h:Hub) \
RETURN h.id AS hid, a.id AS aid, b.id AS bid ORDER BY hid, aid, bid";
let _ = take_hash_join_engagements();
let records = profiled(&g, query);
assert_eq!(take_hash_join_engagements(), 1, "hash join engaged");
let hj_rec = records.iter().find(|r| r.hash_join.build_rows > 0);
assert!(
hj_rec.is_some(),
"PROFILE record contains hash_join metrics"
);
let hj = hj_rec.unwrap().hash_join;
assert!(
hj.build_rows >= 1000,
"build_rows >= 1000, got {}",
hj.build_rows
);
assert!(hj.probe_rows > 0, "probe_rows > 0, got {}", hj.probe_rows);
assert!(
hj.semi_mask_rejected > 0,
"semi_mask_rejected > 0, got {}",
hj.semi_mask_rejected
);
let res = exec_cypher(&g, query);
let nested_res = with_hash_join_disabled(|| exec_cypher(&g, query));
assert_eq!(res.rows, nested_res.rows, "results match nested loop");
assert_eq!(res.rows.len(), 20_000);
}
#[test]
fn syntactic_perturbations_stay_engaged() {
let g = build_multi_hop_graph(20, 10);
let query_base = "MATCH (a:A)-[:RA]->(b:B)-[:RAB]->(h:H), (c:C)-[:RC]->(d:D)-[:RCD]->(h) \
RETURN h.id AS hid, a.id AS aid, c.id AS cid ORDER BY hid, aid, cid";
let query_where = "MATCH (a:A)-[:RA]->(b:B)-[:RAB]->(h:H), (c:C)-[:RC]->(d:D)-[:RCD]->(h) \
WHERE h.id >= 0 OR NOT (h.id < 0) \
RETURN h.id AS hid, a.id AS aid, c.id AS cid ORDER BY hid, aid, cid";
let query_param = "MATCH (a:A)-[:RA]->(b:B)-[:RAB]->(h:H), (c:C)-[:RC]->(d:D)-[:RCD]->(h) \
WHERE h.id >= $min_id \
RETURN h.id AS hid, a.id AS aid, c.id AS cid ORDER BY hid, aid, cid";
for (desc, q) in [
("base query", query_base),
("WHERE with OR / NOT", query_where),
] {
let _ = take_hash_join_engagements();
let res = exec_cypher(&g, q);
assert_eq!(
take_hash_join_engagements(),
1,
"query '{desc}' engaged hash join"
);
let disabled_res = with_hash_join_disabled(|| exec_cypher(&g, q));
assert_eq!(res.rows, disabled_res.rows, "parity on '{desc}'");
}
let params = BTreeMap::from([("min_id".to_string(), Value::Int(0))]);
let _ = take_hash_join_engagements();
let res = try_exec_cypher_params(&g, query_param, ¶ms).unwrap();
assert_eq!(
take_hash_join_engagements(),
1,
"parameterized query engaged hash join"
);
let disabled_res =
with_hash_join_disabled(|| try_exec_cypher_params(&g, query_param, ¶ms).unwrap());
assert_eq!(res.rows, disabled_res.rows, "parity on parameterized query");
}
#[test]
fn multiplicity_semi_join_subsumes_adr_0713() {
let g = Graph::default();
g.begin_write().unwrap();
let node = |label: &str, id: i64| {
g.create_node(
vec![label.into()],
BTreeMap::from([("id".into(), Value::Int(id))]),
)
.unwrap()
};
let persons: Vec<_> = (0..200).map(|i| node("Person", i as i64)).collect();
let int1 = node("Interest", 1);
let int2 = node("Interest", 2);
for &p in &persons {
g.create_rel(p, int1, "HAS".into(), BTreeMap::new())
.unwrap();
g.create_rel(p, int2, "HAS".into(), BTreeMap::new())
.unwrap();
}
for (i, &p) in persons.iter().enumerate() {
let city = node("City", (100 + i) as i64);
g.create_rel(p, city, "LIVES".into(), BTreeMap::new())
.unwrap();
}
g.commit_write();
let query = "MATCH (p:Person)-[:HAS]->(i:Interest), (p)-[:LIVES]->(c:City) \
RETURN p.id AS pid, c.id AS cid ORDER BY pid, cid";
let _ = take_hash_join_engagements();
let res = exec_cypher(&g, query);
assert_eq!(
take_hash_join_engagements(),
1,
"multiplicity hash join engaged"
);
let nested_res = with_hash_join_disabled(|| exec_cypher(&g, query));
assert_eq!(res.rows, nested_res.rows, "exact parity with nested loop");
assert_eq!(res.rows.len(), 400);
}
#[test]
fn multiplicity_declines_when_rel_types_overlap() {
let g = Graph::default();
g.begin_write().unwrap();
let node = |label: &str, id: i64| {
g.create_node(
vec![label.into()],
BTreeMap::from([("id".into(), Value::Int(id))]),
)
.unwrap()
};
let persons: Vec<_> = (0..200).map(|i| node("Person", i as i64)).collect();
for &p in &persons {
let o1 = node("Other", 1);
let o2 = node("Other", 2);
g.create_rel(p, o1, "CONNECTED".into(), BTreeMap::new())
.unwrap();
g.create_rel(p, o2, "CONNECTED".into(), BTreeMap::new())
.unwrap();
}
g.commit_write();
let query = "MATCH (p:Person)-[:CONNECTED]->(o1:Other), (p)-[:CONNECTED]->(o2:Other) \
RETURN p.id AS pid, o2.id AS o2id ORDER BY pid, o2id";
let res = exec_cypher(&g, query);
let nested_res = with_hash_join_disabled(|| exec_cypher(&g, query));
assert_eq!(res.rows, nested_res.rows, "parity when rel types overlap");
}
#[test]
fn multiplicity_declines_when_rel_is_untyped() {
let g = Graph::default();
g.begin_write().unwrap();
let node = |label: &str, id: i64| {
g.create_node(
vec![label.into()],
BTreeMap::from([("id".into(), Value::Int(id))]),
)
.unwrap()
};
let persons: Vec<_> = (0..200).map(|i| node("Person", i as i64)).collect();
for &p in &persons {
let i1 = node("Interest", 1);
let c1 = node("City", 1);
g.create_rel(p, i1, "HAS".into(), BTreeMap::new()).unwrap();
g.create_rel(p, c1, "LIVES".into(), BTreeMap::new())
.unwrap();
}
g.commit_write();
let query = "MATCH (p:Person)-[]->(i:Interest), (p)-[:LIVES]->(c:City) \
RETURN p.id AS pid, c.id AS cid ORDER BY pid, cid";
let res = exec_cypher(&g, query);
let nested_res = with_hash_join_disabled(|| exec_cypher(&g, query));
assert_eq!(res.rows, nested_res.rows, "parity when rel is untyped");
}
#[test]
fn multiplicity_declines_when_residual_references_side_a_non_join_var() {
let g = Graph::default();
g.begin_write().unwrap();
let node = |label: &str, id: i64| {
g.create_node(
vec![label.into()],
BTreeMap::from([("id".into(), Value::Int(id))]),
)
.unwrap()
};
let persons: Vec<_> = (0..200).map(|i| node("Person", i as i64)).collect();
for &p in &persons {
let i1 = node("Interest", 1);
let i2 = node("Interest", 2);
g.create_rel(p, i1, "HAS".into(), BTreeMap::new()).unwrap();
g.create_rel(p, i2, "HAS".into(), BTreeMap::new()).unwrap();
let c1 = node("City", 1);
g.create_rel(p, c1, "LIVES".into(), BTreeMap::new())
.unwrap();
}
g.commit_write();
let query = "MATCH (p:Person)-[:HAS]->(i:Interest), (p)-[:LIVES]->(c:City) \
WHERE i.id = 1 \
RETURN p.id AS pid, c.id AS cid ORDER BY pid, cid";
let res = exec_cypher(&g, query);
let nested_res = with_hash_join_disabled(|| exec_cypher(&g, query));
assert_eq!(
res.rows, nested_res.rows,
"parity when residual references non-join var"
);
}
#[test]
fn multiplicity_declines_when_downstream_is_fold_or_filter() {
let g = Graph::default();
g.begin_write().unwrap();
let node = |label: &str, id: i64| {
g.create_node(
vec![label.into()],
BTreeMap::from([("id".into(), Value::Int(id))]),
)
.unwrap()
};
let persons: Vec<_> = (0..200).map(|i| node("Person", i as i64)).collect();
for &p in &persons {
let i1 = node("Interest", 1);
let c1 = node("City", 1);
g.create_rel(p, i1, "HAS".into(), BTreeMap::new()).unwrap();
g.create_rel(p, c1, "LIVES".into(), BTreeMap::new())
.unwrap();
}
g.commit_write();
let query = "MATCH (p:Person)-[:HAS]->(i:Interest), (p)-[:LIVES]->(c:City) \
RETURN p.id AS pid, count(i) AS cnt ORDER BY pid";
let res = exec_cypher(&g, query);
let nested_res = with_hash_join_disabled(|| exec_cypher(&g, query));
assert_eq!(
res.rows, nested_res.rows,
"parity when downstream folds non-join var"
);
}
#[test]
fn profile_limit_reports_hash_join_metrics() {
let g = build_multi_hop_graph(20, 8);
let query = "MATCH (a:A)-[:RA]->(b:B)-[:RAB]->(h:H), (c:C)-[:RC]->(d:D)-[:RCD]->(h) \
RETURN h.id AS hub, a.id AS aid, c.id AS cid ORDER BY hub, aid, cid";
let _ = take_hash_join_engagements();
let records = profiled(&g, query);
assert_eq!(take_hash_join_engagements(), 1, "hash join engaged");
let hj_rec = records.iter().find(|r| r.hash_join.build_rows > 0);
assert!(
hj_rec.is_some(),
"PROFILE records contain hash_join metrics"
);
let hj = hj_rec.unwrap().hash_join;
assert_eq!(hj.build_rows, 160);
}
#[test]
fn the_join_streams_a_fan_out_independent_of_the_hub_index() {
use crate::ctx::ExecCtx;
use crate::exec::batch_tail::BATCH_ROWS;
use crate::exec::hash_join::try_hash_join;
use crate::exec::pattern_policies::Matched;
use crate::exec::pushdown::Residual;
use crate::exec::test_support::{build, clauses_of};
use crate::overlay::ExecGraph;
use crate::row::{Row, RowNames};
use crate::UsedSet;
use relate_core::tokens::{workspace_meter, LedgerGuard};
use relate_ir::{Clause, MatchMode, PathPattern};
const SIDE_A_ROWS: usize = 128;
const SIDE_B_ROWS: usize = 32;
let 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 clauses = clauses_of("MATCH (a:A)-[:RA]->(h:H), (b:B)-[:RB]->(h) RETURN count(*) AS c");
let patterns: Vec<PathPattern> = match clauses.into_iter().next() {
Some(Clause::Match { patterns, .. }) => patterns,
_ => panic!("the fixture opens with the comma-pair MATCH"),
};
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_hash_join_engagements();
let mut stream = try_hash_join(
ctx,
&patterns,
MatchMode::DifferentRelationships,
&base,
&a_rows,
&residual,
)
.expect("the join runs infallibly")
.expect("the join takes the pair");
assert_eq!(take_hash_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)
};
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}"
);
}