use std::cell::RefCell;
use std::collections::BTreeMap;
use relate_core::Value;
use relate_planner::{plan_with_tokens, LogicalPlan, MatchStrategy};
use super::{take_hash_join_engagements, with_hash_join_disabled};
use crate::exec::graph_stats::GraphStats;
use crate::exec::test_support::{exec_autocommit, run_planned, same_rows, ClauseRecords};
use crate::exec::QueryResult;
use crate::graph::Graph;
use crate::metrics::ClauseMetricsRecord;
fn plan_with_graph_stats(g: &Graph, cypher: &str, params: &BTreeMap<String, Value>) -> LogicalPlan {
let query = relate_front::parse_and_lower(cypher).expect("valid cypher");
let stats = GraphStats::new(g, params);
plan_with_tokens(query, &mut |_| false, &stats, g).expect("valid plan")
}
fn exec_with_stats(
g: &Graph,
cypher: &str,
params: &BTreeMap<String, Value>,
) -> (LogicalPlan, QueryResult, Vec<ClauseMetricsRecord>) {
let plan = plan_with_graph_stats(g, cypher, params);
let recorder = ClauseRecords(RefCell::new(Vec::new()));
let res = run_planned(g, &plan, cypher, params, Some(&recorder)).expect("query succeeds");
(plan, res, recorder.0.take())
}
fn build_snw_q3_shape_a() -> Graph {
let g = Graph::default();
g.begin_write().unwrap();
let mut persons = Vec::with_capacity(500);
for i in 0..500 {
persons.push(
g.create_node(
vec!["Person".into()],
BTreeMap::from([
("id".into(), Value::Int(i as i64)),
("name".into(), Value::String(format!("p_{i}").into())),
]),
)
.unwrap(),
);
}
for i in 0..500 {
for offset in 1..=10 {
let target = (i + offset * 7) % 500;
g.create_rel(persons[i], persons[target], "KNOWS".into(), BTreeMap::new())
.unwrap();
}
}
let mut interests = Vec::with_capacity(50);
for i in 0..50 {
let name = if i == 0 {
"Rust".to_string()
} else {
format!("topic_{i}")
};
interests.push(
g.create_node(
vec!["Interest".into()],
BTreeMap::from([("name".into(), Value::String(name.into()))]),
)
.unwrap(),
);
}
for (idx, &p) in persons.iter().enumerate() {
let interest = if idx < 10 {
interests[0]
} else {
interests[1 + (idx % 49)]
};
g.create_rel(p, interest, "HAS_INTEREST".into(), BTreeMap::new())
.unwrap();
}
g.commit_write();
exec_autocommit(
&g,
"CREATE INDEX interest_name FOR (i:Interest) ON (i.name)",
)
.unwrap();
g
}
fn build_snw_q3_shape_b() -> Graph {
let g = Graph::default();
g.begin_write().unwrap();
let mut persons = Vec::with_capacity(500);
for i in 0..500 {
let name = if i == 0 {
"Alice".to_string()
} else {
format!("p_{i}")
};
persons.push(
g.create_node(
vec!["Person".into()],
BTreeMap::from([
("id".into(), Value::Int(i as i64)),
("name".into(), Value::String(name.into())),
]),
)
.unwrap(),
);
}
for i in 0..500 {
for offset in 1..=2 {
let target = (i + offset) % 500;
g.create_rel(persons[i], persons[target], "KNOWS".into(), BTreeMap::new())
.unwrap();
}
}
let mut interests = Vec::with_capacity(500);
for i in 0..500 {
interests.push(
g.create_node(
vec!["Interest".into()],
BTreeMap::from([("name".into(), Value::String(format!("topic_{i}").into()))]),
)
.unwrap(),
);
}
for (idx, &p) in persons.iter().enumerate() {
for k in 0..4 {
g.create_rel(
p,
interests[(idx + k) % 500],
"HAS_INTEREST".into(),
BTreeMap::new(),
)
.unwrap();
}
}
g.commit_write();
exec_autocommit(&g, "CREATE INDEX person_name FOR (p:Person) ON (p.name)").unwrap();
g
}
#[test]
fn junction_split_shape_a_engages_with_parity_and_fewer_db_hits() {
let g = build_snw_q3_shape_a();
let empty = BTreeMap::new();
let query = "MATCH (p:Person)-[:KNOWS*1..2]->(f:Person)-[:HAS_INTEREST]->(i:Interest) \
WHERE i.name = 'Rust' \
RETURN p.id AS pid, f.id AS fid, i.name AS topic \
ORDER BY pid, fid";
let _ = take_hash_join_engagements();
let (plan, joined, joined_records) = exec_with_stats(&g, query, &empty);
assert_eq!(
plan.match_strategy(0, 0),
Some(MatchStrategy::HashJoinJunctionSplit),
"Shape A must select HashJoinJunctionSplit"
);
assert!(
take_hash_join_engagements() >= 1,
"junction-split hash join must engage"
);
let (_, baseline, baseline_records) =
with_hash_join_disabled(|| exec_with_stats(&g, query, &empty));
assert!(
same_rows(&joined, &baseline),
"junction-split result must match FrontierNfa/walker"
);
assert!(!joined.rows.is_empty());
let joined_hits: u64 = joined_records.iter().map(|r| r.reads.total()).sum();
let baseline_hits: u64 = baseline_records.iter().map(|r| r.reads.total()).sum();
assert!(
joined_hits * 5 < baseline_hits,
"junction-split db_hits ({joined_hits}) must be dramatically lower than baseline ({baseline_hits})"
);
}
#[test]
fn junction_split_shape_b_selects_frontier_nfa_with_parity() {
let g = build_snw_q3_shape_b();
let empty = BTreeMap::new();
let query =
"MATCH (p:Person {name: 'Alice'})-[:KNOWS*1..2]->(f:Person)-[:HAS_INTEREST]->(i:Interest) \
RETURN p.name AS pname, f.id AS fid, i.name AS topic \
ORDER BY fid, topic";
let _ = take_hash_join_engagements();
let (plan, res, _) = exec_with_stats(&g, query, &empty);
assert_eq!(
plan.match_strategy(0, 0),
Some(MatchStrategy::FrontierNfa),
"Flipped Shape B must select FrontierNfa, not HashJoinJunctionSplit"
);
assert_eq!(
take_hash_join_engagements(),
0,
"hash join must not engage on Shape B"
);
let (_, baseline, _) = with_hash_join_disabled(|| exec_with_stats(&g, query, &empty));
assert!(same_rows(&res, &baseline));
assert!(!res.rows.is_empty());
}
#[test]
fn junction_split_syntactic_perturbations_land_on_same_strategy() {
let g = build_snw_q3_shape_a();
let empty = BTreeMap::new();
let params = BTreeMap::from([("topic".to_string(), Value::String("Rust".into()))]);
let clause_where = "MATCH (p:Person)-[:KNOWS*1..2]->(f:Person)-[:HAS_INTEREST]->(i:Interest) \
WHERE i.name = 'Rust' RETURN count(p) AS c";
let inline_where =
"MATCH (p:Person)-[:KNOWS*1..2]->(f:Person)-[:HAS_INTEREST]->(i:Interest {name: 'Rust'}) \
RETURN count(p) AS c";
let param_where = "MATCH (p:Person)-[:KNOWS*1..2]->(f:Person)-[:HAS_INTEREST]->(i:Interest) \
WHERE i.name = $topic RETURN count(p) AS c";
let (p1, r1, _) = exec_with_stats(&g, clause_where, &empty);
let (p2, r2, _) = exec_with_stats(&g, inline_where, &empty);
let (p3, r3, _) = exec_with_stats(&g, param_where, ¶ms);
assert_eq!(
p1.match_strategy(0, 0),
Some(MatchStrategy::HashJoinJunctionSplit)
);
assert_eq!(
p2.match_strategy(0, 0),
Some(MatchStrategy::HashJoinJunctionSplit)
);
assert_eq!(
p3.match_strategy(0, 0),
Some(MatchStrategy::HashJoinJunctionSplit)
);
assert!(same_rows(&r1, &r2));
assert!(same_rows(&r1, &r3));
}
#[test]
fn cross_clause_cost_crossover_flips_in_both_directions() {
let g_a = build_snw_q3_shape_a();
let empty = BTreeMap::new();
let q_a = "MATCH (p:Person) WITH p \
MATCH (p)-[:HAS_INTEREST]->(i:Interest) WHERE i.name = 'Rust' \
RETURN count(p) AS c";
let _ = take_hash_join_engagements();
let (plan_a, res_a, _) = exec_with_stats(&g_a, q_a, &empty);
assert_eq!(
plan_a.match_strategy(0, 2),
Some(MatchStrategy::HashJoinCrossClause),
"Shape A cross-clause MATCH must select HashJoinCrossClause"
);
assert!(
take_hash_join_engagements() >= 1,
"cross-clause hash join must engage on Shape A"
);
let (_, base_a, _) = with_hash_join_disabled(|| exec_with_stats(&g_a, q_a, &empty));
assert!(same_rows(&res_a, &base_a));
assert_eq!(res_a.rows, vec![vec![Value::Int(10)]]);
let g_b = build_snw_q3_shape_b();
let q_b = "MATCH (p:Person) WITH p LIMIT 2 \
MATCH (p)-[:HAS_INTEREST]->(i:Interest) \
RETURN count(i) AS c";
let _ = take_hash_join_engagements();
let (plan_b, res_b, _) = exec_with_stats(&g_b, q_b, &empty);
assert_eq!(
plan_b.match_strategy(0, 2),
Some(MatchStrategy::MorselPipeline),
"Flipped Shape B cross-clause MATCH must not select HashJoinCrossClause"
);
assert_eq!(
take_hash_join_engagements(),
0,
"cross-clause hash join must not engage on Shape B"
);
let (_, base_b, _) = with_hash_join_disabled(|| exec_with_stats(&g_b, q_b, &empty));
assert!(same_rows(&res_b, &base_b));
}
#[test]
fn cross_leg_inline_where_declines_junction_split_with_walker_parity() {
let g = build_snw_q3_shape_a();
let empty = BTreeMap::new();
let query = "MATCH (i:Interest {name: 'Rust'})<-[:HAS_INTEREST]-(f:Person)<-[:KNOWS*1..2]-(p:Person WHERE p.name <> i.name) \
RETURN p.id AS pid, f.id AS fid, i.name AS topic \
ORDER BY pid, fid";
let _ = take_hash_join_engagements();
let (plan, res, _) = exec_with_stats(&g, query, &empty);
assert_eq!(
plan.match_strategy(0, 0),
Some(MatchStrategy::FrontierNfa),
"cross-leg inline WHERE must decline HashJoinJunctionSplit"
);
assert_eq!(
take_hash_join_engagements(),
0,
"junction split hash join must not engage on cross-leg inline WHERE"
);
let (_, baseline, _) = with_hash_join_disabled(|| exec_with_stats(&g, query, &empty));
assert!(same_rows(&res, &baseline));
assert!(!res.rows.is_empty());
}