use std::collections::HashSet;
use proptest::prelude::*;
use relate_core::{NodeId, Value};
use super::super::take_frontier_counters;
use crate::exec::test_support::{build, exec_cypher, patterns, same_rows, Builder, Built};
use crate::graph::Graph;
use crate::pattern_engine::PatternEngine;
use crate::test_support::config_with_floor;
use crate::QueryResult;
use super::frontier_rider_tests::{differential, differential_declined, ring_graph, seed_id};
use super::nfa::compile;
use super::rearival_tests::{multigraph, multigraph_case, pattern_body, VOCAB};
use super::{take_kernel_engagements, with_frontier_disabled};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Kind {
DistinctEndpoints,
Capped { uncapped: &'static str },
Exists,
Decline,
}
struct Statement {
template: &'static str,
kind: Kind,
}
const STATEMENTS: &[Statement] = &[
Statement {
template: "MATCH {mode}{body} RETURN DISTINCT y AS y",
kind: Kind::DistinctEndpoints,
},
Statement {
template: "MATCH {mode}{body} RETURN count(DISTINCT y) AS c",
kind: Kind::DistinctEndpoints,
},
Statement {
template: "MATCH {mode}{body} RETURN min(y.id) AS m",
kind: Kind::DistinctEndpoints,
},
Statement {
template: "MATCH {mode}{body} WHERE y.id > 1 RETURN count(DISTINCT y) AS c",
kind: Kind::DistinctEndpoints,
},
Statement {
template: "MATCH {mode}p = {body} RETURN p LIMIT 3",
kind: Kind::Capped {
uncapped: "MATCH {mode}p = {body} RETURN p",
},
},
Statement {
template: "MATCH {mode}p = {body} RETURN p, y.id AS y SKIP 1 LIMIT 3",
kind: Kind::Capped {
uncapped: "MATCH {mode}p = {body} RETURN p, y.id AS y",
},
},
Statement {
template: "RETURN EXISTS { MATCH {mode}{body} } AS hit",
kind: Kind::Exists,
},
Statement {
template: "MATCH {mode}{body} RETURN x.id AS x, y.id AS y",
kind: Kind::Decline,
},
Statement {
template: "MATCH {mode}p = {body} RETURN p, y.id AS y ORDER BY y.id LIMIT 3",
kind: Kind::Decline,
},
Statement {
template: "MATCH {mode}{body} RETURN count(*) AS n",
kind: Kind::Decline,
},
];
const MODES: &[&str] = &["", "REPEATABLE ELEMENTS "];
const DEFAULT_POOL: usize = 0;
const WALK: usize = 1;
const CAPPED_WANT: usize = 3;
fn statement_text(template: &str, body: &str, mode: usize) -> String {
template
.replace("{mode}", MODES[mode])
.replace("{body}", body)
}
struct StatementAb {
engaged: QueryResult,
dfs: QueryResult,
ran: bool,
engagements: u32,
}
fn statement_ab(g: &Graph, cypher: &str) -> StatementAb {
let engaged = exec_cypher(g, cypher);
let ran = take_frontier_counters().levels > 0;
let dfs = with_frontier_disabled(|| exec_cypher(g, cypher));
let stood_down = take_frontier_counters().levels > 0;
let engagements = take_kernel_engagements();
assert!(!stood_down, "the stand-down hook holds for {cypher}");
StatementAb {
engaged,
dfs,
ran,
engagements,
}
}
fn assert_capped_rows(
g: &Graph,
cypher: &str,
result: &QueryResult,
seed: NodeId,
walk_pool: bool,
oracle: &QueryResult,
) {
let nfa = compile(g, &patterns(cypher)[0], PatternEngine::Auto)
.unwrap_or_else(|| panic!("{cypher} should compile"));
let max = nfa.max_hops.unwrap_or_else(|| {
u32::try_from(g.next_rel_id()).expect("a test graph's rel count fits u32")
});
let p = result
.columns
.iter()
.position(|column| column == "p")
.unwrap_or_else(|| panic!("{cypher}: no `p` column"));
assert!(
result.rows.len() <= CAPPED_WANT,
"{cypher}: the cap bounds the rows: {}",
result.rows.len()
);
for row in &result.rows {
let Value::Path(path) = &row[p] else {
panic!("{cypher}: the path variable binds a path: {row:?}")
};
assert_eq!(
path.nodes.first().map(|node| node.id),
Some(seed),
"{cypher}: the witness anchors at the seed: {row:?}"
);
assert!(
u32::try_from(path.rels.len()).is_ok_and(|hops| nfa.min_hops <= hops && hops <= max),
"{cypher}: the witness is hop-bounded: {row:?}"
);
if !walk_pool {
let mut seen = HashSet::new();
assert!(
path.rels.iter().all(|rel| seen.insert(rel.id)),
"{cypher}: the default pool answers TRAIL rows: {row:?}"
);
}
assert!(
oracle.rows.contains(row),
"{cypher}: the row is one of the DFS's uncapped rows: {row:?}"
);
}
}
fn assert_statement(
g: &Graph,
statement: &Statement,
body: &str,
mode: usize,
seed: NodeId,
) -> bool {
let cypher = statement_text(statement.template, body, mode);
let ab = statement_ab(g, &cypher);
if ab.ran {
assert_eq!(ab.engagements, 1, "exactly the frontier took {cypher}");
} else {
assert_eq!(ab.engagements, 0, "no kernel takes the declined {cypher}");
}
match statement.kind {
Kind::Capped { uncapped } if ab.ran => {
assert_eq!(ab.engaged.columns, ab.dfs.columns, "{cypher}");
let oracle =
with_frontier_disabled(|| exec_cypher(g, &statement_text(uncapped, body, mode)));
assert_capped_rows(g, &cypher, &ab.engaged, seed, mode == WALK, &oracle);
}
Kind::Decline => {
assert!(!ab.ran, "the answer-shape gate declines {cypher}");
assert_eq!(
ab.engaged.rows, ab.dfs.rows,
"the decline is the DFS's own rows: {cypher}"
);
}
_ if ab.ran => {
assert!(
same_rows(&ab.engaged, &ab.dfs),
"rows diverge for {cypher}:\n frontier: {:?}\n dfs: {:?}",
ab.engaged.rows,
ab.dfs.rows
);
}
_ => {
assert_eq!(
ab.engaged.rows, ab.dfs.rows,
"the declined {cypher} is the DFS's own rows"
);
}
}
ab.ran
}
fn multigraph_fixture() -> Built {
build(
&[&["N"], &["N"], &["N"], &["N"], &["N"], &["N"]],
&[
(0, 1, "KNOWS"),
(1, 0, "KNOWS"),
(1, 1, "KNOWS"),
(3, 3, "KNOWS"),
(2, 2, "LIKES"),
(0, 2, "KNOWS"),
(2, 3, "KNOWS"),
(3, 4, "KNOWS"),
(4, 5, "KNOWS"),
(5, 0, "KNOWS"),
(1, 3, "KNOWS"),
(2, 4, "KNOWS"),
(3, 5, "KNOWS"),
(4, 0, "KNOWS"),
(1, 2, "KNOWS"),
(0, 3, "LIKES"),
(1, 4, "LIKES"),
(2, 5, "LIKES"),
(0, 1, "LIKES"),
],
)
}
#[test]
fn statement_vocabulary_matrix_matches_the_dfs_stand_down() {
let built = multigraph_fixture();
const SEED: usize = 2;
let anchor = built.nodes[SEED];
let mut engaged: HashSet<(usize, usize)> = HashSet::new();
for pattern in 0..VOCAB.len() {
let body = pattern_body(pattern, SEED);
for (index, statement) in STATEMENTS.iter().enumerate() {
for mode in 0..MODES.len() {
if assert_statement(&built.graph, statement, &body, mode, anchor) {
engaged.insert((index, mode));
}
}
}
}
for (index, statement) in STATEMENTS.iter().enumerate() {
for mode in 0..MODES.len() {
let engageable = matches!(
statement.kind,
Kind::DistinctEndpoints | Kind::Capped { .. }
) || (statement.kind == Kind::Exists && mode == DEFAULT_POOL);
if engageable {
assert!(
engaged.contains(&(index, mode)),
"statement {index} under pool {mode} never engaged"
);
}
}
}
}
proptest! {
#![proptest_config(config_with_floor(256))]
#[test]
fn differential_statements_match_the_dfs_stand_down(
(n, edges, seed, pattern) in multigraph_case(),
) {
let body = pattern_body(pattern, seed);
let built = multigraph(n, &edges);
let anchor = built.nodes[seed];
for statement in STATEMENTS {
for mode in 0..MODES.len() {
assert_statement(&built.graph, statement, &body, mode, anchor);
}
}
}
}
#[test]
fn walk_pool_row_statements_match_the_dfs_repeatable_spelling() {
let g = ring_graph();
differential(
&g,
"MATCH REPEATABLE ELEMENTS (x:Geo {id:'n0'})-[:LINK*1..3]-(y:Geo) \
RETURN count(DISTINCT y.id) AS c",
);
differential(
&g,
"MATCH REPEATABLE ELEMENTS (x:Geo {id:'n0'})-[:LINK*1..3]-(y:Geo) \
RETURN min(y.id) AS m",
);
differential(
&g,
"MATCH REPEATABLE ELEMENTS (x:Geo {id:'n0'})-[:LINK*1..3]-(y:Geo) \
WHERE y.id <> 'n2' RETURN DISTINCT y.id AS y",
);
let query =
"MATCH REPEATABLE ELEMENTS p = (x:Geo {id:'n0'})-[:LINK*1..3]-(y:Geo) RETURN p LIMIT 3";
let engaged = exec_cypher(&g, query);
assert_eq!(
take_kernel_engagements(),
1,
"the frontier engages for {query}"
);
assert!(
take_frontier_counters().levels > 0,
"the frontier ran for {query}"
);
let oracle = with_frontier_disabled(|| {
exec_cypher(
&g,
"MATCH REPEATABLE ELEMENTS p = (x:Geo {id:'n0'})-[:LINK*1..3]-(y:Geo) RETURN p",
)
});
assert_capped_rows(&g, query, &engaged, seed_id(&g, "n0"), true, &oracle);
}
#[test]
fn capped_skip_and_limit_stay_valid_under_the_frontier() {
let g = ring_graph();
let query = "MATCH p = (x:Geo {id:'n0'})-[:LINK*1..4]-(y:Geo) RETURN p SKIP 2 LIMIT 3";
let engaged = exec_cypher(&g, query);
assert_eq!(
take_kernel_engagements(),
1,
"the frontier engages for {query}"
);
assert!(
take_frontier_counters().levels > 0,
"the frontier ran for {query}"
);
let oracle = with_frontier_disabled(|| {
exec_cypher(
&g,
"MATCH p = (x:Geo {id:'n0'})-[:LINK*1..4]-(y:Geo) RETURN p",
)
});
assert_capped_rows(&g, query, &engaged, seed_id(&g, "n0"), false, &oracle);
let dfs = with_frontier_disabled(|| exec_cypher(&g, query));
assert!(
dfs.rows.len() <= 3,
"the DFS cap rider also halts at the cap"
);
}
#[test]
fn exists_false_arm_runs_to_fixpoint_identically() {
let g = ring_graph();
let query = "RETURN EXISTS { MATCH (x:Geo {id:'n0'})-[:LINK*]-(y:Geo {id:'zz'}) } AS hit";
let engaged = differential(&g, query);
assert_eq!(engaged.rows, vec![vec![Value::Bool(false)]]);
}
#[test]
fn walk_pool_exists_statements_decline_to_the_probe() {
let g = ring_graph();
let declined = differential_declined(
&g,
"RETURN EXISTS { MATCH REPEATABLE ELEMENTS \
(x:Geo {id:'n0'})-[:LINK*1..3]-(y:Geo {id:'n3'}) } AS hit",
);
assert_eq!(declined.rows, vec![vec![Value::Bool(true)]]);
}
#[test]
fn re_arrival_shapes_answer_identically_as_statements() {
let triangle = build(
&[&["N"], &["N"], &["N"]],
&[(0, 1, "KNOWS"), (1, 2, "KNOWS"), (0, 2, "KNOWS")],
);
differential(
&triangle.graph,
"MATCH (x:N {id: 0})-[:KNOWS*]-(y:N) RETURN DISTINCT y AS y",
);
let capped = "MATCH p = (x:N {id: 0})-[:KNOWS*]-(y:N) RETURN p LIMIT 2";
let engaged = exec_cypher(&triangle.graph, capped);
assert_eq!(
take_kernel_engagements(),
1,
"the frontier engages for {capped}"
);
let oracle = with_frontier_disabled(|| {
exec_cypher(
&triangle.graph,
"MATCH p = (x:N {id: 0})-[:KNOWS*]-(y:N) RETURN p",
)
});
assert_capped_rows(
&triangle.graph,
capped,
&engaged,
triangle.nodes[0],
false,
&oracle,
);
let parallel = build(&[&["N"], &["N"]], &[(0, 1, "KNOWS"), (0, 1, "KNOWS")]);
differential(
¶llel.graph,
"MATCH (x:N {id: 0})-[:KNOWS*]-(y:N) RETURN DISTINCT y AS y",
);
let self_loop = build(&[&["N"], &["N"]], &[(0, 1, "KNOWS"), (1, 1, "KNOWS")]);
differential(
&self_loop.graph,
"MATCH (x:N {id: 0})-[:KNOWS*]-(y:N) RETURN DISTINCT y AS y",
);
let type_blind = build(
&[&["N"], &["N"], &["N"]],
&[(0, 1, "KNOWS"), (1, 2, "KNOWS"), (1, 2, "LIKES")],
);
differential(
&type_blind.graph,
"MATCH (x:N {id: 0})-[:KNOWS*]-(y:N) RETURN DISTINCT y AS y",
);
differential(
&build(&[&["N"], &["N"]], &[(1, 0, "KNOWS"), (1, 1, "KNOWS")]).graph,
"MATCH (x:N {id: 1})-[:KNOWS*2..3]-(y:N) RETURN DISTINCT y AS y",
);
}
#[test]
fn boundary_inline_predicates_decline_through_the_walker() {
let g = ring_graph();
let target = differential_declined(
&g,
"MATCH (x:Geo {id:'n0'})-[:LINK*]-(y:Geo WHERE y.id <> 'n3') \
RETURN count(DISTINCT y.id) AS c",
);
assert_eq!(target.rows, vec![vec![Value::Int(5)]]);
let seed_side = differential_declined(
&g,
"MATCH (x:Geo WHERE x.id = 'n2')-[:LINK*]-(y:Geo) \
RETURN count(DISTINCT y.id) AS c",
);
assert_eq!(seed_side.rows, vec![vec![Value::Int(6)]]);
let mixed = mixed_label_ring();
let labeled = differential_declined(
&mixed,
"MATCH (x:Geo {id:'a'})-[:LINK*]-(y:Geo|Other) \
RETURN count(DISTINCT y.id) AS c",
);
assert_eq!(labeled.rows, vec![vec![Value::Int(3)]]);
}
fn mixed_label_ring() -> Graph {
let b = Builder::new();
let a = b.node("a", &["Geo"]);
let c = b.node("c", &["Other"]);
let d = b.node("d", &["Web"]);
let e = b.node("e", &["Geo", "Other"]);
b.rel(a, c, "LINK", &[]);
b.rel(c, d, "LINK", &[]);
b.rel(d, e, "LINK", &[]);
b.rel(e, a, "LINK", &[]);
b.done()
}