use std::time::Instant;
use relate_core::Value;
use crate::ctx::ClauseMetricsRecord;
use crate::exec::test_support::{
column, exec_cypher, int_cell, patterns, profiled, same_rows, string_cell, try_exec_cypher_on,
Builder,
};
use crate::graph::Graph;
use crate::overlay::ExecGraph;
use crate::QueryResult;
use super::super::{take_frontier_counters, take_frontier_decline};
use super::frontier_run::single_quantified;
use super::{
take_kernel_engagements, with_frontier_disabled, with_frontier_table_budget,
with_kernels_disabled,
};
use crate::ctx::FrontierRunDecline;
pub(super) fn ring_graph() -> Graph {
let b = Builder::new();
let n: Vec<_> = (0..6).map(|i| b.node(&format!("n{i}"), &["Geo"])).collect();
for i in 0..6 {
let j = (i + 1) % 6;
b.rel(n[i], n[j], "LINK", &[]);
b.rel(n[j], n[i], "LINK", &[]);
}
b.done()
}
fn web_graph() -> Graph {
let b = Builder::new();
let n: Vec<_> = (0..8).map(|i| b.node(&format!("w{i}"), &["Web"])).collect();
for i in 0..8 {
for step in 1..=2 {
let j = (i + step) % 8;
b.rel(n[i], n[j], "LINK", &[]);
b.rel(n[j], n[i], "LINK", &[]);
}
}
b.done()
}
fn ab(g: &Graph, cypher: &str) -> (QueryResult, QueryResult) {
let engaged = exec_cypher(g, cypher);
let dfs = with_frontier_disabled(|| exec_cypher(g, cypher));
assert!(
same_rows(&engaged, &dfs),
"rows diverge for {cypher}:\n frontier: {:?}\n dfs: {:?}",
engaged.rows,
dfs.rows
);
(engaged, dfs)
}
pub(super) fn differential(g: &Graph, cypher: &str) -> QueryResult {
let (engaged, _dfs) = ab(g, cypher);
assert_eq!(
take_kernel_engagements(),
1,
"the frontier engages for {cypher}"
);
assert!(
take_frontier_counters().levels > 0,
"the frontier ran for {cypher}"
);
engaged
}
pub(super) fn differential_declined(g: &Graph, cypher: &str) -> QueryResult {
let (enabled, _dfs) = ab(g, cypher);
assert_eq!(
take_kernel_engagements(),
0,
"no kernel takes the declined shape {cypher}"
);
assert_eq!(
take_frontier_counters().levels,
0,
"the frontier never runs for {cypher}"
);
enabled
}
#[test]
fn exists_over_an_unbounded_cyclic_pattern_answers_fast_and_identically() {
let g = web_graph();
let query = "RETURN EXISTS { MATCH (x:Web {id:'w0'})-[:LINK*]-(y:Web {id:'w5'}) } AS hit";
let t0 = Instant::now();
let engaged = exec_cypher(&g, query);
let elapsed = t0.elapsed();
assert_eq!(engaged.rows, vec![vec![Value::Bool(true)]]);
assert_eq!(take_kernel_engagements(), 1, "the frontier arm served it");
assert!(
take_frontier_counters().levels > 0,
"the frontier ran to fixpoint"
);
assert!(
elapsed.as_millis() < 500,
"the frontier answered in {elapsed:?}"
);
let dfs = with_frontier_disabled(|| exec_cypher(&g, query));
assert_eq!(
dfs.rows, engaged.rows,
"the DFS probe answers the same boolean"
);
}
#[test]
fn profile_counters_prove_the_frontier_engagement() {
let g = web_graph();
let query = "MATCH (x:Web {id:'w0'})-[:LINK*]-(y:Web) RETURN count(DISTINCT y.id) AS c";
let records = profiled(&g, query);
let ran: Vec<&ClauseMetricsRecord> = records
.iter()
.filter(|record| record.frontier.levels > 0)
.collect();
assert_eq!(
ran.len(),
1,
"exactly the MATCH clause's record carries the frontier (of {} records)",
records.len()
);
let record = ran[0];
assert!(record.frontier.edge_visits > 0, "the BFS visited edges");
assert!(record.frontier.endpoints > 0, "the BFS accepted endpoints");
assert!(
record.reads.neighbor_walks >= record.frontier.edge_visits,
"the edge visits ride the standard neighbor-walk read kind"
);
assert_eq!(record.rows, 8, "the distinct-endpoint answer: every node");
}
#[test]
fn capped_emission_over_an_unbounded_cyclic_pattern_returns_valid_rows() {
let g = web_graph();
let query = "MATCH p = (x:Web {id:'w0'})-[:LINK*]-(y:Web) RETURN p LIMIT 5";
let engaged = exec_cypher(&g, query);
assert_eq!(take_kernel_engagements(), 1, "the frontier engages");
assert!(
take_frontier_counters().levels > 0,
"the frontier ran for the capped emission"
);
assert_eq!(engaged.rows.len(), 5, "the cap fills with exactly n rows");
assert_eq!(engaged.columns, vec!["p".to_string()]);
for row in &engaged.rows {
let Value::Path(path) = &row[0] else {
panic!("the capped consumer binds the path variable: {row:?}");
};
assert!(
!path.rels.is_empty(),
"the quantifier's min is 1 hop: {row:?}"
);
let mut seen = std::collections::HashSet::new();
assert!(
path.rels.iter().all(|rel| seen.insert(rel.id)),
"the default pool answers TRAIL rows: {row:?}"
);
assert!(
path.nodes
.first()
.is_some_and(|node| node.id == seed_id(&g, "w0")),
"the witness chain anchors at the seed: {row:?}"
);
}
let dfs = with_frontier_disabled(|| exec_cypher(&g, query));
assert_eq!(dfs.rows.len(), 5, "the DFS cap rider also halts at n");
}
#[test]
fn distinct_endpoint_answers_match_the_dfs() {
let g = ring_graph();
let aggregate = differential(
&g,
"MATCH (x:Geo {id:'n0'})-[:LINK*1..3]-(y:Geo) RETURN count(DISTINCT y.id) AS c",
);
assert_eq!(aggregate.rows, vec![vec![Value::Int(6)]]);
differential(
&g,
"MATCH (x:Geo {id:'n0'})-[:LINK*1..3]-(y:Geo) RETURN DISTINCT y.id AS y",
);
differential(
&g,
"MATCH (x:Geo {id:'n0'})-[:LINK*1..3]-(y:Geo) RETURN min(y.id) AS m",
);
differential(
&g,
"MATCH (x:Geo {id:'n0'})-[:LINK*]-(y:Geo) RETURN count(DISTINCT y.id) AS c",
);
}
#[test]
fn declined_shapes_fall_through_to_the_unchanged_dfs() {
let g = ring_graph();
let full = differential_declined(
&g,
"MATCH (x:Geo {id:'n0'})-[:LINK*1..3]-(y:Geo) RETURN x.id AS x, y.id AS y",
);
assert!(full.rows.len() > 10, "the fixture enumerates many trails");
differential_declined(
&g,
"MATCH (x:Geo {id:'n0'})-[:LINK*1..3]-(y:Geo) \
RETURN y.id AS y ORDER BY y.id LIMIT 3",
);
differential_declined(
&g,
"MATCH (x:Geo {id:'n0'})-[:LINK*1..3]-(y:Geo) RETURN count(*) AS n",
);
differential_declined(
&g,
"MATCH (x:Geo {id:'n0'})-[:LINK*1..3]-(y:Geo), (z:Geo {id:'n3'}) \
RETURN count(DISTINCT y.id) AS c",
);
differential_declined(
&g,
"UNWIND [0] AS u MATCH (x:Geo {id:'n0'})-[:LINK*1..3]-(y:Geo) \
RETURN count(DISTINCT y.id) AS c",
);
differential_declined(
&g,
"MATCH (x:Geo {id:'n0'})-[:LINK*1..3]-(y:Geo) \
WHERE size(y.id) > 1 RETURN count(DISTINCT y.id) AS c",
);
differential_declined(
&g,
"MATCH p = TRAIL (x:Geo {id:'n0'})-[:LINK*1..3]-(y:Geo) \
RETURN count(DISTINCT y.id) AS c",
);
}
#[test]
fn frontier_served_exists_walk_ticks_the_budget_once() {
let g = ring_graph();
let view = ExecGraph::read(&g);
let query = "RETURN EXISTS { MATCH (x:Geo {id:'n0'})-[:LINK*]-(y:Geo {id:'n3'}) } AS hit";
let kernaled = try_exec_cypher_on(&view, query).unwrap();
assert_eq!(take_kernel_engagements(), 1, "the frontier arm served it");
assert_eq!(kernaled.rows, vec![vec![Value::Bool(true)]]);
assert_eq!(view.nested_evals().count(), 1, "one evaluation, one tick");
let probed = with_frontier_disabled(|| try_exec_cypher_on(&view, query).unwrap());
assert_eq!(take_kernel_engagements(), 0);
assert_eq!(probed.rows, vec![vec![Value::Bool(true)]]);
assert_eq!(view.nested_evals().count(), 1);
}
#[test]
fn multi_quantifier_exists_probe_declines_at_the_cheap_gate() {
let g = ring_graph();
let pattern = "(x:Geo {id:'n0'})((a)-[:LINK]-(b))+((c)-[:LINK]-(d))+(y:Geo {id:'n3'})";
assert!(
single_quantified(&g, &patterns(&format!("MATCH {pattern} RETURN y"))).is_none(),
"two top-level quantified groups fail the cheap gate"
);
differential_declined(&g, &format!("RETURN EXISTS {{ MATCH {pattern} }} AS hit"));
differential_declined(
&g,
&format!("MATCH {pattern} RETURN count(DISTINCT y) AS c"),
);
}
pub(super) fn seed_id(g: &Graph, name: &str) -> relate_core::NodeId {
let rows = exec_cypher(g, &format!("MATCH (n {{id:'{name}'}}) RETURN id(n) AS i")).rows;
match rows.first().and_then(|row| row.first()).and_then(int_cell) {
Some(id) => id as relate_core::NodeId,
None => panic!("the fixture's seed lookup: id(n) returned no integer"),
}
}
#[test]
fn a_tables_over_ceiling_clause_declines_to_the_dfs() {
let g = ring_graph();
let query = "MATCH (x:Geo {id:'n0'})-[:LINK*]-(y:Geo) RETURN count(DISTINCT y.id) AS c";
differential(&g, query);
assert_eq!(take_frontier_decline(), None, "no run declined");
with_frontier_table_budget(0, || {
let engaged = exec_cypher(&g, query);
assert!(take_frontier_counters().levels > 0, "the frontier ran");
assert_eq!(take_kernel_engagements(), 0, "no kernel served it");
assert_eq!(
take_frontier_decline(),
Some(FrontierRunDecline::TableBudget),
"the typed run-time decline"
);
let dfs = with_frontier_disabled(|| exec_cypher(&g, query));
assert_eq!(engaged.rows, dfs.rows, "the DFS's own rows");
});
}
fn clique_graph(n: usize) -> Graph {
let b = Builder::new();
let s = b.node("s", &["User"]);
let clique: Vec<_> = (0..n)
.map(|i| b.node(&format!("c{i}"), &["User"]))
.collect();
for &ci in &clique {
b.rel(s, ci, "R", &[]);
}
for (i, &ci) in clique.iter().enumerate() {
for (j, &cj) in clique.iter().enumerate() {
if i != j {
b.rel(ci, cj, "R", &[]);
}
}
}
let a = b.node("a", &["User"]);
let tail_b = b.node("b", &["User"]);
let u = b.node("u", &["User"]);
b.rel(s, a, "R", &[]);
b.rel(a, s, "R", &[]);
b.rel(s, tail_b, "R", &[]);
b.rel(tail_b, u, "R", &[]);
b.done()
}
#[test]
fn clique_exact_quantifier_falls_through_on_the_rearrival_budget() {
for n in [28usize, 32, 36] {
let mut g = clique_graph(n);
g.configure_expression_memory_limit(None);
let count = "MATCH (s:User {id:'s'})-[:R*4..4]->(n:User) RETURN count(DISTINCT n) AS c";
let engaged = exec_cypher(&g, count);
assert!(
take_frontier_counters().levels > 0,
"the frontier ran for N={n}"
);
assert_eq!(
take_kernel_engagements(),
0,
"the rung declined mid-clause for N={n}: no kernel served it"
);
assert_eq!(
take_frontier_decline(),
Some(FrontierRunDecline::RearrivalBudget),
"the typed run-time decline for N={n}"
);
assert_eq!(
engaged.rows,
vec![vec![Value::Int(n as i64 + 1)]],
"the exact endpoint count for N={n}"
);
let dfs = with_frontier_disabled(|| exec_cypher(&g, count));
assert_eq!(dfs.rows, engaged.rows, "the stood-down frontier for N={n}");
let walker = with_kernels_disabled(|| exec_cypher(&g, count));
assert_eq!(
walker.rows, engaged.rows,
"the all-kernels-off walker for N={n}"
);
let collect =
"MATCH (s:User {id:'s'})-[:R*4..4]->(n:User) RETURN collect(DISTINCT n.id) AS ids";
let ids = exec_cypher(&g, collect);
take_frontier_counters();
take_kernel_engagements();
assert_eq!(
take_frontier_decline(),
Some(FrontierRunDecline::RearrivalBudget),
"the collect shape declines too for N={n}"
);
let Value::List(list) = &ids.rows[0][0] else {
panic!("collect(DISTINCT n.id) binds a list: {:?}", ids.rows)
};
assert_eq!(list.len(), n + 1, "the distinct endpoint ids for N={n}");
let dfs_ids = with_frontier_disabled(|| exec_cypher(&g, collect));
assert_eq!(dfs_ids.rows, ids.rows, "the stood-down collect for N={n}");
let filtered =
"MATCH (s:User {id:'s'})-[:R*4..4]->(n:User) WHERE n.id = 'u' RETURN DISTINCT n.id AS id";
let hit = exec_cypher(&g, filtered);
take_frontier_counters();
take_kernel_engagements();
assert_eq!(
take_frontier_decline(),
Some(FrontierRunDecline::RearrivalBudget),
"the WHERE shape declines too for N={n}"
);
assert_eq!(
column(&hit, "id", string_cell),
vec!["u".to_string()],
"u is the one filtered endpoint for N={n}"
);
let dfs_hit = with_frontier_disabled(|| exec_cypher(&g, filtered));
assert_eq!(dfs_hit.rows, hit.rows, "the stood-down WHERE for N={n}");
}
}
#[test]
fn clique_inside_the_budget_still_frontier_serves() {
for n in [8usize, 16, 24] {
let g = clique_graph(n);
let query = "MATCH (s:User {id:'s'})-[:R*4..4]->(n:User) RETURN count(DISTINCT n) AS c";
let engaged = differential(&g, query);
assert_eq!(
engaged.rows,
vec![vec![Value::Int(n as i64 + 1)]],
"the frontier-served exact count for N={n}"
);
assert_eq!(
take_frontier_decline(),
None,
"no budget fall-through for N={n}"
);
}
}