use std::collections::BTreeMap;
use proptest::prelude::*;
use relate_core::Value;
use crate::ctx::ExecCtx;
use crate::exec::test_support::{
build, complete_graph, count_of, decide, declines_with, exec_cypher, file_triangle,
leading_match, line_graph, planned_clauses, reset_frontier_facts, same_rows, Built,
LeadingMatch,
};
use crate::frontier_decline::FrontierDecline;
use crate::graph::Graph;
use crate::overlay::ExecGraph;
use crate::pattern_engine::PatternEngine;
use crate::row::Row;
use crate::test_support::config_with_floor;
use crate::QueryResult;
use super::super::take_frontier_counters;
use super::frontier_match::{BoundaryPair, Consumer};
use super::frontier_run::try_frontier_rows;
use super::take_kernel_engagements;
fn run_under(graph: &mut Graph, engine: PatternEngine, cypher: &str) -> (QueryResult, u32, u64) {
graph.configure_pattern_engine(engine);
reset_frontier_facts();
let answer = exec_cypher(graph, cypher);
let engagements = take_kernel_engagements();
let levels = take_frontier_counters().levels;
graph.configure_pattern_engine(PatternEngine::Auto);
(answer, engagements, levels)
}
struct Routed {
answer: QueryResult,
forced: RungFacts,
auto: RungFacts,
}
struct RungFacts {
engaged: u32,
levels: u64,
}
fn agree(graph: &mut Graph, cypher: &str) -> Routed {
let (walker, walk_engaged, walk_levels) = run_under(graph, PatternEngine::Walk, cypher);
assert_eq!(
(walk_engaged, walk_levels),
(0, 0),
"the walker oracle never rides a kernel: {cypher}"
);
let (auto, auto_engaged, auto_levels) = run_under(graph, PatternEngine::Auto, cypher);
assert!(same_rows(&auto, &walker), "auto vs walker: {cypher}");
let (forced, engaged, levels) = run_under(graph, PatternEngine::Nfa, cypher);
assert!(same_rows(&forced, &walker), "nfa vs walker: {cypher}");
Routed {
answer: walker,
forced: RungFacts { engaged, levels },
auto: RungFacts {
engaged: auto_engaged,
levels: auto_levels,
},
}
}
fn rides(graph: &mut Graph, cypher: &str, case: &str) -> Routed {
let routed = agree(graph, cypher);
assert_eq!(
(routed.forced.engaged, routed.forced.levels > 0),
(1, true),
"{case} rides the forced rung"
);
routed
}
#[test]
fn the_distinct_endpoint_consumer_admits_the_boundary_pair_comparison() {
for cypher in [
"MATCH (x:Person)-[:KNOWS*1..3]-(y:Person) WHERE x <> y RETURN DISTINCT x, y",
"MATCH (x:Person)-[:KNOWS*1..3]-(y:Person) WHERE y <> x RETURN DISTINCT x, y",
"MATCH (x:Person)-[:KNOWS*1..3]-(y:Person) WHERE x <> y AND y.id > 1 \
RETURN DISTINCT x, y",
"MATCH (x:Person)-[:KNOWS*1..3]-(y:Person) WHERE x <> y \
WITH DISTINCT x, y RETURN count(*) AS pairs",
] {
decide(cypher, &complete_graph(), false, &Row::new(), |decision| {
let contract = decision.unwrap_or_else(|e| panic!("{cypher} engages: {e:?}"));
assert_eq!(
contract.consumer,
Consumer::DistinctEndpoints {
pair: BoundaryPair::Distinct
},
"{cypher}"
);
});
}
decide(
"MATCH (x:Person)-[:KNOWS*1..3]-(y:Person) RETURN DISTINCT x, y",
&complete_graph(),
false,
&Row::new(),
|decision| {
let contract = decision.unwrap_or_else(|e| panic!("engages: {e:?}"));
assert_eq!(contract.consumer.pair(), BoundaryPair::Unconstrained);
},
);
}
#[test]
fn every_other_shape_keeps_the_conjunct_decline() {
let graph = complete_graph();
let declines = |cypher: &str| declines_with(cypher, &graph, FrontierDecline::Conjunct);
declines("MATCH (x:Person)-[:KNOWS*1..3]-(y:Person) WHERE x <> y RETURN x, y LIMIT 3");
decide(
"MATCH (x:Person)-[:KNOWS*1..3]-(y:Person) WHERE x <> y RETURN y",
&graph,
true,
&Row::new(),
|decision| assert_eq!(decision.err(), Some(FrontierDecline::Conjunct)),
);
declines("MATCH (x:Person)-[:KNOWS*1..3]-(y:Person) WHERE x = y RETURN DISTINCT x, y");
declines("MATCH (x:Person)-[:KNOWS*1..3]-(y:Person) WHERE x <> x RETURN DISTINCT x, y");
declines("MATCH (x:Person)((a)-[:KNOWS]-(b)){1,2}(y:Person) WHERE a <> y RETURN DISTINCT x, y");
declines(
"MATCH (x:Person)-[:KNOWS*1..3]-(y:Person) WHERE x <> y OR y.id > 1 \
RETURN DISTINCT x, y",
);
declines("MATCH (x:Person)-[:KNOWS*1..3]-(y:Person) WHERE x.id <> y.id RETURN DISTINCT x, y");
}
#[test]
fn the_cost_gate_still_decides_a_comparison_clause() {
decide(
"MATCH (x:Person)-[:KNOWS*1..2]-(y:Person) WHERE x <> y RETURN DISTINCT x, y",
&line_graph(),
false,
&Row::new(),
|decision| assert_eq!(decision.err(), Some(FrontierDecline::Cost)),
);
}
#[test]
fn the_seed_reached_again_is_excluded_per_pair_not_per_graph() {
let mut triangle = file_triangle();
let with = "MATCH (a:File)-[:T*1..3]-(b:File) WHERE a <> b \
WITH DISTINCT a, b RETURN count(*) AS pairs";
let without = "MATCH (a:File)-[:T*1..3]-(b:File) \
WITH DISTINCT a, b RETURN count(*) AS pairs";
let with_routed = rides(&mut triangle.graph, with, "the comparison");
assert_eq!(
count_of(&with_routed.answer),
6,
"the self pair of every seed drops"
);
let without_routed = rides(&mut triangle.graph, without, "the bare spelling");
assert_eq!(
count_of(&without_routed.answer),
9,
"without the comparison the seed stays"
);
let mut loops = build(
&[&["File"], &["File"]],
&[(0, 0, "T"), (0, 1, "T"), (0, 1, "T")],
);
let Routed {
answer: walker,
forced: RungFacts { engaged, .. },
..
} = agree(&mut loops.graph, with);
assert_eq!(engaged, 1);
assert_eq!(count_of(&walker), 2, "(0,1) and (1,0), the loops dropped");
let zero = "MATCH (a:File)-[:T*0..2]-(b:File) WHERE a <> b \
WITH DISTINCT a, b RETURN count(*) AS pairs";
let Routed {
answer: walker,
forced: RungFacts { engaged, .. },
..
} = agree(&mut loops.graph, zero);
assert_eq!(engaged, 1);
assert_eq!(count_of(&walker), 2);
}
#[test]
fn a_far_endpoint_equal_to_another_seed_still_answers() {
let mut line = build(
&[&["File"], &["File"], &["File"]],
&[(0, 1, "T"), (1, 2, "T")],
);
let query = "MATCH (a:File)-[:T*1..2]-(b:File) WHERE a <> b RETURN DISTINCT b.id AS b";
let Routed {
answer: walker,
forced: RungFacts { engaged, .. },
..
} = agree(&mut line.graph, query);
assert_eq!(engaged, 1);
assert_eq!(
walker.rows.len(),
3,
"every node is another seed's endpoint"
);
}
#[test]
fn an_anchored_seed_drops_itself() {
let mut tri = build(
&[&["File"], &["File", "Hot"], &["File"], &["File"]],
&[
(0, 1, "T"),
(1, 2, "T"),
(2, 0, "T"),
(2, 2, "T"),
(2, 3, "U"),
],
);
for cypher in [
"MATCH (a:File {id: 0})-[:T*0..3]-(b) WHERE b <> a RETURN count(DISTINCT b) AS c",
"MATCH (a:File {id: 0})-[:T|U*0..3]->(b) WHERE a <> b RETURN count(DISTINCT b) AS c",
"MATCH (a:File {id: 2})-[:T*1..3]-(b:Hot) WHERE a <> b RETURN count(DISTINCT b) AS c",
] {
let Routed {
forced: RungFacts { engaged, .. },
..
} = agree(&mut tri.graph, cypher);
assert_eq!(engaged, 1, "{cypher}");
}
}
#[test]
fn the_rung_drops_the_self_pair_without_a_reduce_tail() {
let mut built = file_triangle();
built.graph.configure_pattern_engine(PatternEngine::Nfa);
let cypher = "MATCH (a:File)-[:T*1..3]-(b:File) WHERE a <> b \
WITH DISTINCT a, b RETURN count(*) AS pairs";
let clauses = planned_clauses(cypher);
let LeadingMatch {
match_mode,
patterns,
where_clause,
suffix,
} = leading_match(&clauses, cypher);
let view = ExecGraph::read(&built.graph);
let params = BTreeMap::new();
let ctx = ExecCtx::new(&view, ¶ms);
let rows = try_frontier_rows(
ctx,
&[Row::new()],
false,
match_mode,
patterns,
where_clause,
suffix,
None,
None,
)
.unwrap()
.served()
.expect("the rung serves the clause");
assert_eq!(rows.len(), 6, "two endpoints per seed, the seed never one");
for row in &rows {
let (Some(Value::Node(a)), Some(Value::Node(b))) = (row.get("a"), row.get("b")) else {
panic!("both boundary variables are bound: {row:?}");
};
assert_ne!(a.id, b.id, "no row pairs a seed with itself");
}
}
#[test]
fn consumers_outside_the_pair_set_answer_as_the_walker() {
let mut tri = file_triangle();
for cypher in [
"MATCH (a:File)-[:T*1..3]-(b:File) WHERE a <> b RETURN count(*) AS paths",
"MATCH REPEATABLE ELEMENTS (a:File)-[:T*1..3]-(b:File) WHERE a <> b \
RETURN count(*) AS walks",
"MATCH (a:File)-[:T*1..3]-(b:File) WHERE a <> b RETURN a.id AS a, b.id AS b",
] {
let Routed {
forced: RungFacts { engaged, levels },
..
} = agree(&mut tri.graph, cypher);
assert_eq!((engaged, levels), (0, 0), "{cypher}");
}
}
const LABEL_SETS: [&[&str]; 4] = [
&["File"],
&["File", "Hot"],
&["Prompt"],
&["File", "Prompt"],
];
type PairCase = (Vec<usize>, Vec<(usize, usize, usize)>, u32);
fn pair_case() -> BoxedStrategy<PairCase> {
(
proptest::collection::vec(0usize..LABEL_SETS.len(), 3..=7),
proptest::collection::vec((0usize..7, 0usize..7, 0usize..3), 2..=12),
1u32..=4,
)
.prop_filter(
"two File nodes, both rel types interned",
|(labels, edges, _)| {
labels
.iter()
.filter(|slot| LABEL_SETS[**slot].contains(&"File"))
.count()
>= 2
&& ["T", "U"]
.iter()
.all(|name| edges.iter().any(|&(_, _, kind)| rel_type(kind) == *name))
},
)
.boxed()
}
fn rel_type(kind: usize) -> &'static str {
if kind < 2 {
"T"
} else {
"U"
}
}
fn pair_graph(labels: &[usize], edges: &[(usize, usize, usize)]) -> Built {
let sets: Vec<&[&str]> = labels.iter().map(|slot| LABEL_SETS[*slot]).collect();
let rels: Vec<(usize, usize, &str)> = edges
.iter()
.map(|&(a, b, kind)| (a % labels.len(), b % labels.len(), rel_type(kind)))
.collect();
build(&sets, &rels)
}
const ENGAGING: &[&str] = &[
"MATCH (a:File)-[:T*1..{k}]-(b:File) WHERE a <> b \
WITH DISTINCT a, b RETURN count(*) AS pairs",
"MATCH (a:File)-[:T*1..{k}]-(b:File) WHERE a <> b RETURN DISTINCT a.id AS a, b.id AS b",
"MATCH (a:File)-[:T|U*1..{k}]->(b:File) WHERE a <> b \
WITH DISTINCT a, b RETURN count(*) AS pairs",
"MATCH (a:File)<-[:T*1..{k}]-(b) WHERE b <> a RETURN DISTINCT a.id AS a, b.id AS b",
"MATCH (a:File)-[:T*1..{k}]-(b:File) WHERE a <> b AND b.id > 1 \
WITH DISTINCT a, b RETURN count(*) AS pairs",
"MATCH (a:File)-[:T*0..{k}]-(b:File) WHERE a <> b \
WITH DISTINCT a, b RETURN count(*) AS pairs",
"MATCH (a:File)-[:T*2..{k1}]-(b:File) WHERE a <> b \
WITH DISTINCT a, b RETURN count(*) AS pairs",
"MATCH (a:File)((u)-[:T]-(v)){1,{k}}(b:File) WHERE a <> b \
WITH DISTINCT a, b RETURN count(*) AS pairs",
"MATCH REPEATABLE ELEMENTS (a:File)-[:T*1..{k}]-(b:File) WHERE a <> b \
WITH DISTINCT a, b RETURN count(*) AS pairs",
"MATCH (a:File)-[:T*1..{k}]-(b:File) WHERE a <> b WITH DISTINCT a, b \
MATCH (b)-[:U]->(c) RETURN count(*) AS n",
"MATCH (a:File)-[:T*1..{k}]-(b:File) WHERE a <> b WITH DISTINCT a, b \
RETURN a.id AS a, b.id AS b ORDER BY a, b",
"MATCH (a:File)-[:T*1..{k}]-(b:File) WHERE a <> b RETURN DISTINCT b \
ORDER BY b.id SKIP 1",
"MATCH (a {id: 0})-[:T*0..{k}]-(b) WHERE b <> a RETURN count(DISTINCT b) AS c",
"MATCH (a:File)-[*1..{k}]-(b) WHERE a <> b \
WITH DISTINCT a, b RETURN count(*) AS pairs",
];
const DECLINING: &[&str] =
&["MATCH (a:File)-[:T*1..{k}]-(b:File) WHERE a <> b RETURN count(*) AS paths"];
proptest! {
#![proptest_config(config_with_floor(192))]
#[test]
fn generated_multigraphs_answer_as_the_walker(
(labels, edges, k) in pair_case(),
) {
let mut built = pair_graph(&labels, &edges);
for template in ENGAGING {
let cypher = template
.replace("{k}", &k.to_string())
.replace("{k1}", &(k + 1).to_string());
let Routed { forced: RungFacts { engaged, levels }, .. } = agree(&mut built.graph, &cypher);
prop_assert_eq!(engaged, 1, "the forced rung takes {}", cypher);
prop_assert!(levels > 0, "the frontier ran for {}", cypher);
}
for template in DECLINING {
let cypher = template
.replace("{k}", &k.to_string())
.replace("{k1}", &(k + 1).to_string());
let Routed { forced: RungFacts { engaged, levels }, .. } = agree(&mut built.graph, &cypher);
prop_assert_eq!((engaged, levels), (0, 0), "no rung takes {}", cypher);
}
}
}
fn gate_graph(nodes: usize) -> Built {
let mut state = 0x9E37_79B9_7F4A_7C15_u64;
let mut next = move |bound: usize| {
state ^= state << 13;
state ^= state >> 7;
state ^= state << 17;
(state % bound as u64) as usize
};
let labels: Vec<&[&str]> = (0..nodes)
.map(|i| {
if i % 3 == 0 {
&["File", "Prompt"][..]
} else {
&["File"][..]
}
})
.collect();
let rels: Vec<(usize, usize, &str)> = (0..nodes * 3 / 2)
.map(|_| (next(nodes), next(nodes), "TOUCHES"))
.collect();
build(&labels, &rels)
}
#[test]
fn unbounded_untyped_hops_answer_as_the_walker() {
let mut graph = line_graph();
for (cypher, auto_engages) in [
(
"MATCH (a:Person)-[*1..]-(b:Person) WHERE a <> b \
WITH DISTINCT a, b RETURN count(*) AS pairs",
true,
),
(
"MATCH (a:Person)-[*2..]-(b:Person) WHERE a <> b \
WITH DISTINCT a, b RETURN count(*) AS pairs",
true,
),
(
"MATCH (a:Person)-[*1..2]-(b:Person) WHERE a <> b \
WITH DISTINCT a, b RETURN count(*) AS pairs",
false,
),
] {
let Routed { forced, auto, .. } = agree(&mut graph, cypher);
assert_eq!(
(forced.engaged, forced.levels > 0),
(1, true),
"{cypher} rides the forced rung"
);
let want = u32::from(auto_engages);
assert_eq!(
(auto.engaged, auto.levels > 0),
(want, auto_engages),
"the `auto` routing of {cypher}"
);
}
}
#[test]
fn the_gate_statements_answer_as_the_walker() {
let mut built = gate_graph(36);
for d in 1..=4u32 {
let cypher = format!(
"MATCH (a:File)-[:TOUCHES*1..{}]-(b:File) WHERE a <> b \
WITH DISTINCT a, b RETURN count(*) AS pairs",
2 * d
);
rides(&mut built.graph, &cypher, &format!("d={d}"));
}
for k in 3..=5u32 {
let cypher = format!(
"MATCH (p:Prompt)-[*1..{k}]-(n) WHERE n <> p \
WITH DISTINCT p, n RETURN count(*) AS pairs"
);
rides(
&mut built.graph,
&cypher,
&format!("k={k}: the untyped hop"),
);
}
}