use relate_core::Value;
use crate::graph::Graph;
use crate::pattern_engine::PatternEngine;
use super::test_support::{
assert_agrees_with_held, build, exec_cypher, profiled, record_for, same_rows, sort_rows,
written_and_held, Built,
};
fn hub(fan: usize) -> Built {
let total = 1 + fan + 2 * fan;
let labels = vec![&["N"][..]; total];
let mut rels = Vec::new();
for c in 0..fan {
let child = 1 + c;
rels.push((0, child, "E"));
for g in 0..2 {
rels.push((child, 1 + fan + 2 * c + g, "E"));
}
}
rels.push((1 + fan, 0, "E"));
build(&labels, &rels)
}
fn assert_agrees(matched: &str, rest: &str) {
let (written, held) = written_and_held(matched, rest);
assert_agrees_with_held(|| hub(6).graph, "folded", &written, &held);
}
#[test]
fn count_star_over_a_variable_length_match() {
assert_agrees("MATCH (h:N {id: 0})-[:E*1..2]->(e)", "RETURN count(*) AS c");
}
#[test]
fn count_distinct_end_over_a_variable_length_match() {
assert_agrees(
"MATCH (h:N {id: 0})-[:E*1..2]->(e)",
"RETURN count(DISTINCT e) AS c",
);
}
#[test]
fn sum_over_a_variable_length_match() {
assert_agrees(
"MATCH (h:N {id: 0})-[:E*1..2]->(e)",
"RETURN sum(e.id) AS s",
);
}
#[test]
fn group_key_over_a_variable_length_match() {
assert_agrees(
"MATCH (h:N {id: 0})-[:E*1..2]->(e)",
"RETURN e.id % 3 AS k, count(*) AS c",
);
}
#[test]
fn where_on_the_match() {
assert_agrees(
"MATCH (h:N {id: 0})-[:E*1..2]->(e) WHERE e.id > 3",
"RETURN count(*) AS c, sum(e.id) AS s",
);
}
#[test]
fn multi_pattern_match() {
assert_agrees(
"MATCH (h:N {id: 0})-[:E]->(a), (h)-[:E]->(b)",
"RETURN count(*) AS c, count(DISTINCT a) AS d",
);
}
#[test]
fn with_consumer_feeds_the_next_clause() {
assert_agrees(
"MATCH (h:N {id: 0})-[:E*1..2]->(e)",
"WITH count(*) AS c RETURN c + 1 AS next",
);
}
#[test]
fn an_empty_match_still_yields_the_keyless_group() {
let built = hub(3);
let r = exec_cypher(
&built.graph,
"MATCH (h:N {id: 99})-[:E*1..2]->(e) RETURN count(*) AS c",
);
assert_eq!(r.rows, vec![vec![Value::Int(0)]]);
}
#[test]
fn profile_counts_the_rows_the_stream_took() {
let built = hub(6);
let matched = "MATCH (h:N {id: 0})-[:E*1..2]->(e)";
let folded = profiled(&built.graph, &format!("{matched} RETURN count(*) AS c"));
let staged = profiled(
&built.graph,
&format!("{matched} WITH * RETURN count(*) AS c"),
);
let held = profiled(
&built.graph,
&format!("{matched} WITH h, e LIMIT 999999 RETURN count(*) AS c"),
);
let held_head = record_for(&held, 0);
assert!(
held_head.rows > 0 && held_head.memory_bytes > 0,
"the capped control holds its rows"
);
let folded_head = record_for(&folded, 0);
assert_eq!(
folded_head.rows, held_head.rows,
"the walk emits the same rows"
);
assert_eq!(folded_head.memory_bytes, 0, "the fold holds no rows");
let staged_head = record_for(&staged, 0);
let staged_with = record_for(&staged, 1);
assert_eq!(
staged_head.rows, folded_head.rows,
"the head clause's walk emits the same rows"
);
assert_eq!(
staged_head.memory_bytes, 0,
"the run leaves the head clause holding nothing"
);
assert_eq!(
staged_with.rows, staged_head.rows,
"the `WITH *` stage passes every row through"
);
assert_eq!(staged_with.memory_bytes, 0, "the stage holds no rows");
}
#[test]
fn optional_match_without_a_match_still_counts_the_null_row() {
let built = hub(3);
let r = exec_cypher(
&built.graph,
"MATCH (h:N {id: 99}) OPTIONAL MATCH (h)-[:E]->(b) RETURN count(*) AS c",
);
assert_eq!(r.rows, vec![vec![Value::Int(0)]], "no input row at all");
let r = exec_cypher(
&built.graph,
"MATCH (h:N {id: 0}) OPTIONAL MATCH (h)-[:NOPE]->(b) RETURN count(*) AS c",
);
assert_eq!(r.rows, vec![vec![Value::Int(1)]]);
let r = exec_cypher(
&built.graph,
"MATCH (h:N {id: 0}) OPTIONAL MATCH (h)-[:NOPE]->(b) WITH count(*) AS c RETURN c",
);
assert_eq!(r.rows, vec![vec![Value::Int(1)]]);
}
fn optional_graph() -> Built {
let mut labels = vec![&["P"][..]; 3];
labels.extend(vec![&["C"][..]; 13]);
labels.push(&["H"][..]);
labels.extend(vec![&["C"][..]; 10]);
let mut rels = vec![(0, 3, "R"), (1, 4, "R"), (1, 5, "R")];
rels.extend((17..27).map(|child| (16, child, "R")));
build(&labels, &rels)
}
fn on_every_engine(cypher: &str) -> Vec<Vec<Value>> {
let run = |engine: PatternEngine| {
let mut built = optional_graph();
built.graph.configure_pattern_engine(engine);
exec_cypher(&built.graph, cypher)
};
let reference = PatternEngine::default();
let baseline = run(reference);
for engine in PatternEngine::ALL
.into_iter()
.filter(|&engine| engine != reference)
{
assert!(
same_rows(&run(engine), &baseline),
"{cypher}: {engine:?} vs default"
);
}
let mut rows = baseline.rows;
sort_rows(&mut rows);
rows
}
fn ints_row(cells: &[i64]) -> Vec<Value> {
cells.iter().copied().map(Value::Int).collect()
}
#[test]
fn optional_match_of_one_two_and_ten_rows_aggregates_each() {
for (input, matched) in [(0, 1), (1, 2), (16, 10)] {
let rows = on_every_engine(&format!(
"MATCH (p {{id: {input}}}) OPTIONAL MATCH (p)-[:R]->(c) \
RETURN count(*) AS rows, count(c) AS matched"
));
assert_eq!(rows, vec![ints_row(&[matched, matched])], "input {input}");
}
}
#[test]
fn optional_match_adds_a_null_row_per_unmatched_input_only() {
let rows = on_every_engine(
"MATCH (p:P) OPTIONAL MATCH (p)-[:R]->(c) \
RETURN count(*) AS rows, count(c) AS matched",
);
assert_eq!(rows, vec![ints_row(&[4, 3])]);
}
#[test]
fn aggregates_over_the_null_row_follow_their_null_semantics() {
let rows = on_every_engine(
"MATCH (p:P) OPTIONAL MATCH (p)-[:R]->(c) \
RETURN count(*) AS rows, count(c) AS matched, sum(c.id) AS total, \
min(c.id) AS lo, max(c.id) AS hi, size(collect(c.id)) AS kept, \
count(DISTINCT c) AS distinct_matched",
);
assert_eq!(rows, vec![ints_row(&[4, 3, 12, 3, 5, 3, 3])]);
let rows = on_every_engine(
"MATCH (p {id: 2}) OPTIONAL MATCH (p)-[:R]->(c) \
RETURN count(*) AS rows, count(c) AS matched, sum(c.id) AS total, \
min(c.id) AS lo, max(c.id) AS hi, size(collect(c.id)) AS kept, \
count(DISTINCT c) AS distinct_matched",
);
assert_eq!(
rows,
vec![vec![
Value::Int(1),
Value::Int(0),
Value::Int(0),
Value::Null,
Value::Null,
Value::Int(0),
Value::Int(0),
]]
);
}
#[test]
fn group_by_an_input_variable_mixes_matched_and_unmatched_groups() {
let rows = on_every_engine(
"MATCH (p:P) OPTIONAL MATCH (p)-[:R]->(c) \
RETURN p.id AS p, count(*) AS rows, count(c) AS matched",
);
assert_eq!(
rows,
vec![
ints_row(&[0, 1, 1]),
ints_row(&[1, 2, 2]),
ints_row(&[2, 1, 0])
]
);
}
#[test]
fn matched_groups_equal_the_plain_match() {
let built = optional_graph();
let optional = exec_cypher(
&built.graph,
"MATCH (p:P) WHERE p.id IN [0, 1] OPTIONAL MATCH (p)-[:R]->(c) \
RETURN p.id AS p, count(*) AS rows, sum(c.id) AS total",
);
let plain = exec_cypher(
&built.graph,
"MATCH (p:P) WHERE p.id IN [0, 1] MATCH (p)-[:R]->(c) \
RETURN p.id AS p, count(*) AS rows, sum(c.id) AS total",
);
assert!(same_rows(&optional, &plain));
}
#[test]
fn optional_match_with_matches_counts_like_the_plain_match() {
let built = hub(3);
let plain = exec_cypher(
&built.graph,
"MATCH (h:N {id: 0}) MATCH (h)-[:E*1..2]->(e) RETURN count(*) AS c",
);
let optional = exec_cypher(
&built.graph,
"MATCH (h:N {id: 0}) OPTIONAL MATCH (h)-[:E*1..2]->(e) RETURN count(*) AS c",
);
assert!(same_rows(&optional, &plain));
}
#[test]
fn a_declining_frontier_rung_offers_the_fold_nothing() {
use std::cell::Cell;
use std::collections::BTreeMap;
use relate_front::parse_and_lower;
use relate_ir::Clause;
use super::frontier::frontier_run::try_frontier_rows;
use super::frontier::with_frontier_table_budget;
use super::pattern_policies::RowFold;
use crate::ctx::ExecCtx;
use crate::overlay::ExecGraph;
use crate::row::Row;
struct Counting(Cell<u64>);
impl RowFold for Counting {
fn offer(&self, _: &ExecGraph<'_>, _: Row) -> crate::exec::Result<()> {
self.0.set(self.0.get() + 1);
Ok(())
}
}
let total = 400;
let labels = vec![&["N"][..]; total];
let mut rels = vec![(0, 1, "T")];
rels.extend((2..total - 1).map(|i| (i, i + 1, "T")));
let built = build(&labels, &rels);
let query =
parse_and_lower("MATCH (x:N)-[:T*1..]->(y:N) RETURN count(DISTINCT y) AS c").unwrap();
let plan = relate_planner::plan(query, &mut |_| false).unwrap();
let clauses = &plan.parts[0];
let Clause::Match {
match_mode,
patterns,
where_clause,
..
} = &clauses[0]
else {
panic!("first clause is a MATCH");
};
let view = ExecGraph::read(&built.graph);
let params = BTreeMap::new();
let fold = Counting(Cell::new(0));
let answer = with_frontier_table_budget(2048, || {
try_frontier_rows(
ExecCtx::new(&view, ¶ms),
&[Row::new()],
false,
*match_mode,
patterns,
where_clause.as_ref(),
&clauses[1..],
None,
Some(&fold),
)
.unwrap()
.served()
});
assert!(answer.is_none(), "the later seed's run declines");
assert_eq!(fold.0.get(), 0, "a declined rung offered the fold rows");
}
#[test]
fn parked_fold_pairs_are_charged_against_the_expression_limit() {
use std::collections::BTreeMap;
use relate_front::parse_and_lower;
use relate_ir::Clause;
use super::frontier::frontier_run::try_frontier_rows;
use super::pattern_policies::RowFold;
use crate::ctx::ExecCtx;
use crate::overlay::ExecGraph;
use crate::row::Row;
struct Discard;
impl RowFold for Discard {
fn offer(&self, _: &ExecGraph<'_>, _: Row) -> crate::exec::Result<()> {
Ok(())
}
}
let fan = 500;
let mut built = hub(fan);
built.graph.configure_expression_memory_limit(Some(1024));
let query =
parse_and_lower("MATCH (x:N {id: 0})-[:E*1..]->(y:N) RETURN count(DISTINCT y) AS c")
.unwrap();
let plan = relate_planner::plan(query, &mut |_| false).unwrap();
let clauses = &plan.parts[0];
let Clause::Match {
match_mode,
patterns,
where_clause,
..
} = &clauses[0]
else {
panic!("first clause is a MATCH");
};
let view = ExecGraph::read(&built.graph);
let params = BTreeMap::new();
let err = try_frontier_rows(
ExecCtx::new(&view, ¶ms),
&[Row::new()],
false,
*match_mode,
patterns,
where_clause.as_ref(),
&clauses[1..],
None,
Some(&Discard),
)
.map(|_| ())
.unwrap_err();
assert!(
matches!(
err,
relate_core::Error::Capacity {
kind: relate_core::CapacityKind::Expression,
..
}
),
"{err}"
);
}
fn person_graph() -> Graph {
let g = Graph::default();
super::test_support::exec_autocommit(
&g,
"CREATE (a:Person {name: 'Alice'}),
(b1:Person {name: 'Bob', age: 25, score: 2, min_score: 5}),
(b2:Person {name: 'Charlie', age: 15, score: 3, min_score: 1}),
(b3:Person {name: 'Dave', age: 30, score: 10, min_score: 8}),
(b4:Person {name: 'Eve', age: 18, score: 8, min_score: 12}),
(a)-[:KNOWS]->(b1),
(a)-[:KNOWS]->(b2),
(a)-[:KNOWS]->(b3),
(a)-[:KNOWS]->(b4)",
)
.unwrap();
g
}
#[test]
fn single_node_boolean_bytecode_predicate_in_path_fold() {
let g = person_graph();
for (matched, rest, expected) in [
(
"MATCH (a:Person)-[:KNOWS]->(b:Person) WHERE b.age > 20 OR b.score < 5",
"RETURN count(b) AS c",
3,
),
(
"MATCH (a:Person)-[:KNOWS]->(b:Person) WHERE NOT (b.age <= 20)",
"RETURN count(b) AS c",
2,
),
(
"MATCH (a:Person)-[:KNOWS]->(b:Person) WHERE 20 < b.age",
"RETURN count(b) AS c",
2,
),
(
"MATCH (a:Person)-[:KNOWS]->(b:Person) WHERE b.score > b.min_score",
"RETURN count(b) AS c",
2,
),
] {
let (written, held) = written_and_held(matched, rest);
assert_agrees_with_held(person_graph, "folded", &written, &held);
let records = profiled(&g, &written);
assert_eq!(
records.len(),
1,
"path fold must consume the aggregating RETURN into clause 0 for {written}"
);
let head = record_for(&records, 0);
assert_eq!(
head.rows, 1,
"path fold emits the single aggregated group row directly for {written}"
);
assert_eq!(
head.kernel, None,
"path fold runs try_match_folds, not the walker"
);
let got = exec_cypher(&g, &written);
assert_eq!(
got.rows,
vec![vec![Value::Int(expected)]],
"count for {written}"
);
}
}