use rand::rngs::StdRng;
use rand::{Rng, SeedableRng};
use relate_core::{CapacityKind, Error, Value};
use relate_ir::Direction;
use crate::exec::test_support::{
exec_autocommit, exec_write_uncommitted, try_exec_cypher, Builder,
};
use crate::graph::Graph;
use super::anchor::{with_list_limit, without_far_set, AnchorArm};
use super::fan_drivers::{take_batches, without_batched_fan};
use super::fixtures::{counting, gpm, run, sorted, DirectionExt, Selector, DIRS, SELECTORS};
const SEED: u64 = 0x0556_0001;
fn graph(rng: &mut StdRng, n: usize, groups: usize, rels: usize) -> Graph {
let b = Builder::new();
let nodes: Vec<_> = (0..n)
.map(|i| {
b.prop_node(
&i.to_string(),
&["N"],
&[("g", Value::Int((i % groups) as i64))],
)
})
.collect();
for _ in 0..rels {
let (a, z) = (rng.random_range(0..n), rng.random_range(0..n));
b.rel(nodes[a], nodes[z], "R", &[]);
}
b.done()
}
fn arm_label(arm: AnchorArm) -> &'static str {
match arm {
AnchorArm::Pair => "pair",
AnchorArm::FanForward => "fan forward",
AnchorArm::FanBackward => "fan backward",
AnchorArm::Loop => "loop",
}
}
struct Shape {
arm: AnchorArm,
name: &'static str,
far_listed: bool,
cols: &'static str,
start: &'static str,
end: &'static str,
n: usize,
groups: usize,
rels: usize,
}
impl Shape {
fn label(&self) -> String {
format!("{} {}", arm_label(self.arm), self.name)
}
}
#[rustfmt::skip]
const SHAPES: [Shape; 12] = [
Shape { arm: AnchorArm::Pair, name: "1x1", far_listed: false, cols: "a.id, b.id, length(p)", start: "(a {id: '0'})", end: "(b {id: '5'})", n: 12, groups: 3, rels: 26 },
Shape { arm: AnchorArm::Pair, name: "4x1", far_listed: false, cols: "a.id, b.id, length(p)", start: "(a {g: 0})", end: "(b {id: '5'})", n: 12, groups: 3, rels: 26 },
Shape { arm: AnchorArm::Pair, name: "4x4", far_listed: false, cols: "a.id, b.id, length(p)", start: "(a {g: 0})", end: "(b {g: 1})", n: 12, groups: 3, rels: 26 },
Shape { arm: AnchorArm::FanForward, name: "6x6", far_listed: true, cols: "a.id, b.id, length(p)", start: "(a {g: 0})", end: "(b {g: 1})", n: 12, groups: 2, rels: 26 },
Shape { arm: AnchorArm::FanBackward, name: "20x1", far_listed: false, cols: "a.id, b.id, length(p)", start: "(a {g: 0})", end: "(b {id: '5'})", n: 40, groups: 2, rels: 44 },
Shape { arm: AnchorArm::FanForward, name: "start scan", far_listed: false, cols: "a.id, b.id, length(p)", start: "(a)", end: "(b {g: 1})", n: 40, groups: 2, rels: 44 },
Shape { arm: AnchorArm::FanForward, name: "fan 1x20", far_listed: false, cols: "a.id, b.id, length(p)", start: "(a {id: '0'})", end: "(b {g: 1})", n: 40, groups: 2, rels: 44 },
Shape { arm: AnchorArm::FanBackward, name: "backward listed", far_listed: true, cols: "a.id, b.id, length(p)", start: "(a {g: 0})", end: "(b {g: 1})", n: 40, groups: 3, rels: 120 },
Shape { arm: AnchorArm::FanForward, name: "fan 20x20", far_listed: true, cols: "a.id, b.id, length(p)", start: "(a {g: 0})", end: "(b {g: 1})", n: 40, groups: 2, rels: 44 },
Shape { arm: AnchorArm::FanForward, name: "20 x scan", far_listed: false, cols: "a.id, b.id, length(p)", start: "(a {g: 0})", end: "(b)", n: 40, groups: 2, rels: 44 },
Shape { arm: AnchorArm::FanBackward, name: "scan x 1", far_listed: false, cols: "a.id, b.id, length(p)", start: "(a)", end: "(b {id: '5'})", n: 12, groups: 3, rels: 26 },
Shape { arm: AnchorArm::Loop, name: "same variable", far_listed: false, cols: "a.id, length(p)", start: "(a {g: 0})", end: "(a)", n: 12, groups: 3, rels: 24 },
];
fn query(shape: &Shape, sel: Selector, dir: Direction) -> String {
let Selector { open, close, .. } = sel;
let (l, r) = dir.arrows();
format!(
"MATCH p = {open}{}{l}[:R*..4]{r}{}{close} \
RETURN {}, [n IN nodes(p) | n.id]",
shape.start, shape.end, shape.cols
)
}
fn comparable(rows: Vec<Vec<Value>>, sel: Selector) -> Vec<Vec<Value>> {
let rows = rows.into_iter().map(|mut row| {
if !sel.all {
row.pop();
}
row
});
let mut rows = sorted(rows.collect());
if !sel.all {
rows.dedup();
}
rows
}
#[test]
fn property_endpoint_anchors_agree_with_the_gpm_walk() {
let mut rng = StdRng::seed_from_u64(SEED);
for shape in &SHAPES {
for index in 0..3 {
let g = graph(&mut rng, shape.n, shape.groups, shape.rels);
for sel in SELECTORS {
for dir in DIRS {
let q = query(shape, sel, dir);
let (rows, counts) = run(&g, &q);
assert!(
counts.route_runs > 0,
"{} graph {index}: the route must take {q}",
shape.label()
);
assert_eq!(
counts.arms,
vec![shape.arm],
"{} graph {index}: Route::anchor took the wrong arm for {q}",
shape.label()
);
assert_eq!(
comparable(rows, sel),
comparable(gpm(&g, &q), sel),
"{} graph {index}: route and GPM disagree on {q}",
shape.label()
);
}
}
}
}
}
#[test]
fn shortest_paths_see_the_write_views_uncommitted_graph() {
let g = Graph::default();
exec_autocommit(
&g,
"CREATE (:N {id: 'x'})-[:R]->(:N {id: 'm'})-[:R]->(:N {id: 'y'})",
)
.unwrap();
let write = |q: &str| counting(|| exec_write_uncommitted(&g, q).rows);
let bound = "CREATE (a:N {id: 's'})-[:R]->(:N {id: 't'})-[:R]->(b:N {id: 'u'}) \
WITH a, b MATCH p = shortestPath((a)-[:R*..4]->(b)) RETURN length(p)";
let (rows, counts) = write(bound);
assert!(counts.route_runs > 0, "the route must take the write form");
assert_eq!(sorted(rows), vec![vec![Value::Int(2)]]);
let seek = "CREATE (:N {id: 'p'})-[:R]->(:N {id: 'q'})-[:R]->(:N {id: 'r'}) \
WITH count(*) AS made \
MATCH p = ANY SHORTEST (a {id: 'p'})-[:R*..4]->(b {id: 'r'}) \
RETURN length(p)";
let (rows, counts) = write(seek);
assert!(counts.route_runs > 0, "the route must take the seek form");
assert_eq!(sorted(rows), vec![vec![Value::Int(2)]]);
let hidden = "MATCH (:N {id: 'x'})-[r:R]->(:N {id: 'm'}) DELETE r \
WITH count(*) AS gone \
MATCH p = ANY SHORTEST (a {id: 'x'})-[:R*..4]->(b {id: 'y'}) \
RETURN length(p)";
let (rows, counts) = write(hidden);
assert!(
counts.route_runs > 0,
"the route must take the hidden-rel form"
);
assert_eq!(sorted(rows), Vec::<Vec<Value>>::new());
}
#[test]
fn an_over_bound_seek_is_not_materialized() {
let g = Graph::default();
exec_autocommit(
&g,
"UNWIND range(0, 199) AS i CREATE (:N {id: toString(i), g: i % 2})",
)
.unwrap();
exec_autocommit(
&g,
"MATCH (a:N {id: '0'}), (b:N) WHERE b.g = 1 CREATE (a)-[:R]->(b)",
)
.unwrap();
let q = "MATCH p = ANY SHORTEST (a {id: '0'})-[:R*..2]->(b {g: 1}) RETURN b.id, length(p)";
let _ = crate::ctx::take_node_reads();
let (rows, counts) = run(&g, q);
let reads = crate::ctx::take_node_reads();
assert!(counts.route_runs > 0, "the route must take {q}");
assert_eq!(rows.len(), 100);
assert_eq!(sorted(rows), gpm(&g, q));
assert_eq!(reads, 200 + 34, "the end seek was materialized");
let none = "MATCH p = ANY SHORTEST (a {id: 'nope'})-[:R*..2]->(b {g: 1}) RETURN length(p)";
let (rows, counts) = run(&g, none);
assert!(counts.route_runs > 0, "the route must take {none}");
assert!(rows.is_empty());
let none = "MATCH p = ANY SHORTEST (a {g: 1})-[:R*..2]->(b {id: 'nope'}) RETURN length(p)";
assert!(run(&g, none).0.is_empty());
}
#[test]
fn a_capped_seek_over_a_write_view_counts_what_survives_the_scratch() {
let g = Graph::default();
exec_autocommit(
&g,
"CREATE (s:N {id: 's'}) \
WITH s UNWIND range(0, 19) AS i \
CREATE (s)-[:R]->(:N {id: toString(i), g: 0, k: i})",
)
.unwrap();
let q = "MATCH (n:N {g: 0}) WHERE n.k < 10 DETACH DELETE n \
WITH count(*) AS gone \
MATCH p = ANY SHORTEST (a {id: 's'})-[:R*..2]->(b {g: 0}) \
RETURN b.id, length(p)";
let (rows, counts) = counting(|| exec_write_uncommitted(&g, q).rows);
assert!(counts.route_runs > 0, "the route must take the write form");
assert_eq!(rows.len(), 10, "{rows:?}");
}
#[test]
fn pair_arms_follow_the_row_bound_forms_expansions() {
let mut rng = StdRng::seed_from_u64(SEED ^ 2);
let pairs: Vec<&Shape> = SHAPES.iter().filter(|s| s.arm == AnchorArm::Pair).collect();
assert!(
!pairs.is_empty(),
"the pair arm must have shapes to identify"
);
for shape in pairs {
let g = graph(&mut rng, shape.n, shape.groups, shape.rels);
let (start, end) = (shape.start, shape.end);
let seek = format!("MATCH p = ANY SHORTEST {start}-[:R*..4]->{end} RETURN length(p)");
let bound = format!(
"MATCH {start}, {end} \
MATCH p = ANY SHORTEST (a)-[:R*..4]->(b) RETURN length(p)"
);
let (seek_rows, seek_counts) = run(&g, &seek);
let (bound_rows, bound_counts) = run(&g, &bound);
assert!(
seek_counts.route_runs > 0 && bound_counts.route_runs > 0,
"both forms must ride the route: {seek}"
);
assert!(
!seek_counts.arms.is_empty() && seek_counts.arms.iter().all(|a| *a == AnchorArm::Pair),
"the property form must take the pair arm: {seek} (got {:?})",
seek_counts.arms
);
assert!(
!bound_counts.arms.is_empty()
&& bound_counts.arms.iter().all(|a| *a == AnchorArm::Pair),
"the bound form must take the pair arm: {seek} (got {:?})",
bound_counts.arms
);
assert_eq!(sorted(seek_rows), sorted(bound_rows), "{seek}");
assert_eq!(
seek_counts.expands,
bound_counts.expands,
"the {} property form must take the pair partitions the bound form takes: {seek}",
shape.label()
);
}
}
#[test]
fn an_over_limit_listing_is_a_typed_capacity_refusal() {
let g = Graph::default();
exec_autocommit(
&g,
"UNWIND range(0, 199) AS i CREATE (:N {id: toString(i), g: i % 2})",
)
.unwrap();
let q = "MATCH p = ANY SHORTEST (a {g: 0})-[:R*..2]->(b {g: 1}) RETURN length(p)";
let _ = crate::ctx::take_node_reads();
let err = with_list_limit(40, || try_exec_cypher(&g, q))
.err()
.expect("100 matches past a 40-node listing limit must refuse");
assert!(
matches!(
err,
Error::Capacity {
used: 41,
limit: 40,
kind: CapacityKind::SeekCandidates,
}
),
"{err}"
);
assert_eq!(crate::ctx::take_node_reads(), 148);
assert!(with_list_limit(200, || try_exec_cypher(&g, q)).is_ok());
}
#[test]
fn a_negated_label_endpoint_is_never_refused_by_the_listing_limit() {
let g = Graph::default();
exec_autocommit(
&g,
"UNWIND range(0, 99) AS i CREATE (:N {id: toString(i), g: i % 50}), (:M {id: 'm', g: 1})",
)
.unwrap();
exec_autocommit(
&g,
"MATCH (a:N {id: '0'}), (b:N {g: 1}) CREATE (a)-[:R]->(b)",
)
.unwrap();
let q =
"MATCH p = ANY SHORTEST (a:!M {g: 0})-[:R*..2]->(b:!M {g: 1}) RETURN a.id, b.id, length(p)";
let rows = with_list_limit(4, || try_exec_cypher(&g, q))
.expect("a superset list must not trip the listing refusal")
.rows;
assert_eq!(sorted(rows), gpm(&g, q));
}
#[test]
fn the_far_set_changes_cost_not_answers() {
let mut rng = StdRng::seed_from_u64(SEED ^ 0x1698);
let mut saved_any = false;
for shape in SHAPES.iter().filter(|s| s.far_listed) {
let mut saved = false;
for _ in 0..3 {
let g = graph(&mut rng, shape.n, shape.groups, shape.rels);
for sel in SELECTORS {
for dir in DIRS {
let q = query(shape, sel, dir);
let (on, on_counts) = without_batched_fan(|| run(&g, &q));
let (off, off_counts) = without_batched_fan(|| without_far_set(|| run(&g, &q)));
assert_eq!(
comparable(on, sel),
comparable(off, sel),
"far set changed the answer of {q}"
);
assert!(on_counts.expands <= off_counts.expands, "{q}");
saved |= on_counts.expands < off_counts.expands;
}
}
}
assert!(
saved || shape.arm != AnchorArm::FanBackward,
"{}: the early stop never saved an expansion",
shape.label()
);
saved_any |= saved;
}
assert!(saved_any, "the early stop never saved an expansion");
}
#[test]
fn the_batched_fan_changes_cost_not_answers() {
let mut rng = StdRng::seed_from_u64(SEED ^ 0x1698_0002);
let wide = [
("fan wide", "(a {g: 0})", "(b {g: 1})", 300, 2, 330),
("fan sparse", "(a {g: 0})", "(b {g: 1})", 300, 2, 140),
("fan 64", "(a {g: 0})", "(b {g: 1})", 128, 2, 150),
];
let mut batched = false;
for (name, start, end, n, groups, rels) in wide {
let shape = Shape {
arm: AnchorArm::FanForward,
name,
far_listed: true,
cols: "a.id, b.id, length(p)",
start,
end,
n,
groups,
rels,
};
let g = graph(&mut rng, n, groups, rels);
for sel in SELECTORS {
for dir in DIRS {
let q = query(&shape, sel, dir);
let _ = take_batches();
let (on, _) = run(&g, &q);
batched |= take_batches() > 0;
let (off, _) = without_batched_fan(|| run(&g, &q));
assert_eq!(
comparable(on, sel),
comparable(off, sel),
"{name}: the batch changed the answer of {q}"
);
}
}
}
assert!(batched, "no fan took the batched sweep");
}
#[test]
fn the_batched_fan_keeps_the_end_admission_and_pair_predicates() {
let mut rng = StdRng::seed_from_u64(SEED ^ 0x1698_0003);
let g = graph(&mut rng, 200, 2, 260);
let queries = [
"MATCH p = ANY SHORTEST (a {g: 0})-[:R*..4]-(b {g: 1}) \
WHERE a.id <> b.id RETURN a.id, b.id, length(p)",
"MATCH p = ALL SHORTEST (a {g: 0})-[:R*..3]->(b {g: 0}) \
RETURN a.id, b.id, length(p), [n IN nodes(p) | n.id]",
"MATCH p = SHORTEST 1 (a {g: 0})<-[:R*..4]-(b {g: 1}) \
RETURN a.id, b.id, length(p)",
];
for q in queries {
let _ = take_batches();
let (on, _) = run(&g, q);
assert!(take_batches() > 0, "the batched sweep must run for {q}");
let (off, _) = without_batched_fan(|| run(&g, q));
assert_eq!(sorted(on), sorted(off), "{q}");
}
}
#[test]
fn a_wide_id_span_keeps_the_per_origin_fan() {
let mut rng = StdRng::seed_from_u64(SEED ^ 0x1698_0004);
let g = graph(&mut rng, 100, 2, 140);
let q = "MATCH p = ANY SHORTEST (a {g: 0})-[:R*..4]-(b {g: 1}) RETURN a.id, b.id, length(p)";
let (rows, _) = run(&g, q);
let _ = take_batches();
let (capped, _) = crate::shortest::multi_source::with_span_cap(8, || run(&g, q));
assert_eq!(take_batches(), 0);
assert_eq!(sorted(rows), sorted(capped));
}
#[test]
fn the_sweep_does_not_scale_with_path_count() {
let b = Builder::new();
let head = b.prop_node("head", &["N"], &[("g", Value::Int(2))]);
let mut rels = 0u64;
for i in 0..5 {
let s = b.prop_node(&format!("s{i}"), &["N"], &[("g", Value::Int(0))]);
b.rel(s, head, "R", &[]);
rels += 1;
}
let mut prev = head;
for i in 0..40 {
let (l, r, next) = (
b.prop_node(&format!("l{i}"), &["N"], &[("g", Value::Int(2))]),
b.prop_node(&format!("r{i}"), &["N"], &[("g", Value::Int(2))]),
b.prop_node(&format!("j{i}"), &["N"], &[("g", Value::Int(2))]),
);
for (x, y) in [(prev, l), (prev, r), (l, next), (r, next)] {
b.rel(x, y, "R", &[]);
}
rels += 4;
prev = next;
}
for i in 0..5 {
let t = b.prop_node(&format!("t{i}"), &["N"], &[("g", Value::Int(1))]);
b.rel(prev, t, "R", &[]);
rels += 1;
}
let g = b.done();
let q = "MATCH p = ANY SHORTEST (a {g: 0})-[:R*..200]->(b {g: 1}) RETURN length(p)";
let _ = take_batches();
let (rows, counts) = run(&g, q);
assert!(take_batches() > 0, "the fan must take the batched sweep");
assert_eq!(rows.len(), 25, "one trail per (start, end) pair");
assert!(
counts.expands < 30 * rels,
"{} expansions over {rels} relationships",
counts.expands
);
}
#[test]
fn the_batched_fan_covers_scratch_created_nodes() {
let g = Graph::default();
let q = "UNWIND range(0, 19) AS i \
CREATE (:N {id: 's' + toString(i), g: 0})-[:R]->(m:N {id: 'm' + toString(i), g: 2})\
-[:R]->(:N {id: 't' + toString(i), g: 1}) \
WITH count(*) AS made \
MATCH p = ANY SHORTEST (a {g: 0})-[:R*..3]->(b {g: 1}) \
RETURN a.id, b.id, length(p)";
let _ = take_batches();
let rows = exec_write_uncommitted(&g, q).rows;
assert!(take_batches() > 0, "the fan must take the batched sweep");
let oracle = without_batched_fan(|| exec_write_uncommitted(&g, q).rows);
assert_eq!(rows.len(), 20);
assert_eq!(sorted(rows), sorted(oracle));
}
#[test]
fn a_lone_trailing_origin_keeps_the_layered_fan() {
let mut rng = StdRng::seed_from_u64(SEED ^ 0x1698_0005);
let g = graph(&mut rng, 130, 2, 200);
let q = "MATCH p = ANY SHORTEST (a {g: 0})-[:R*..4]-(b {g: 1}) RETURN a.id, b.id, length(p)";
let _ = take_batches();
let (rows, _) = run(&g, q);
assert_eq!(take_batches(), 1, "only the full batch of 64 sweeps");
let (off, _) = without_batched_fan(|| run(&g, q));
assert_eq!(
comparable(rows, SELECTORS[0]),
comparable(off, SELECTORS[0])
);
}
#[test]
fn label_only_endpoints_take_the_batched_sweep() {
let mut rng = StdRng::seed_from_u64(SEED ^ 0x0334);
let b = Builder::new();
let mut nodes = Vec::new();
for (label, count) in [("A", 90usize), ("H", 40), ("E", 20)] {
for i in 0..count {
nodes.push(b.prop_node(&format!("{label}{i}"), &[label], &[]));
}
}
for _ in 0..320 {
let (x, y) = (
rng.random_range(0..nodes.len()),
rng.random_range(0..nodes.len()),
);
let ty = ["R", "S", "T"][rng.random_range(0..3)];
b.rel(nodes[x], nodes[y], ty, &[]);
}
let g = b.done();
let mut batched = false;
for sel in SELECTORS {
for dir in DIRS {
let Selector { open, close, .. } = sel;
let (l, r) = dir.arrows();
let q = format!(
"MATCH p = {open}(a:A){l}[:R|S*..5]{r}(e:E){close} \
RETURN a.id, e.id, length(p), [n IN nodes(p) | n.id]"
);
let _ = take_batches();
let (on, counts) = run(&g, &q);
batched |= take_batches() > 0;
assert!(counts.route_runs > 0, "the route must take {q}");
let (off, _) = without_batched_fan(|| without_far_set(|| run(&g, &q)));
assert_eq!(comparable(on.clone(), sel), comparable(off, sel), "{q}");
assert_eq!(comparable(on, sel), comparable(gpm(&g, &q), sel), "{q}");
}
}
assert!(batched, "no label-only fan took the batched sweep");
}
#[test]
fn an_empty_label_only_far_side_is_the_empty_pair() {
let mut rng = StdRng::seed_from_u64(SEED ^ 0x0335);
let g = graph(&mut rng, 40, 2, 60);
for q in [
"MATCH p = ANY SHORTEST (a)-[:R*..4]->(b:Missing) RETURN length(p)",
"MATCH p = ANY SHORTEST (a:Missing)-[:R*..4]->(b) RETURN length(p)",
] {
let (rows, _) = run(&g, q);
assert!(rows.is_empty(), "{q}");
assert!(gpm(&g, q).is_empty(), "{q}");
}
}
#[test]
fn an_origin_that_is_the_only_far_node_keeps_its_closed_trails() {
let g = Graph::default();
exec_autocommit(
&g,
"CREATE (x:L:F {id: 'x'}), (y:L {id: 'y'}), (z:L {id: 'z'}), \
(x)-[:R]->(y), (y)-[:R]->(x), (x)-[:R]->(x), (z)-[:R]->(x)",
)
.unwrap();
for q in [
"MATCH p = ALL SHORTEST (a:L)-[:R*1..3]->(b:F) RETURN a.id, length(p)",
"MATCH p = ANY SHORTEST (a:L)-[:R*1..3]-(b:F) RETURN a.id, length(p)",
"MATCH p = SHORTEST 2 (a:L)-[:R*1..3]->(b:F) RETURN a.id, length(p)",
] {
let _ = take_batches();
let (rows, _) = run(&g, q);
let sweeps = !q.contains("SHORTEST 2");
assert_eq!(take_batches() > 0, sweeps, "the far set's sweep for {q}");
assert_eq!(sorted(rows.clone()), gpm(&g, q), "{q}");
assert!(
rows.iter().any(|r| r[0] == Value::String("x".into())),
"{q}"
);
}
}
#[test]
fn a_label_less_far_side_is_not_listed() {
let mut rng = StdRng::seed_from_u64(SEED ^ 0x0336);
let g = graph(&mut rng, 60, 2, 90);
let q = "MATCH p = ANY SHORTEST (a {g: 0})-[:R*..4]->(b) RETURN a.id, b.id, length(p)";
let _ = take_batches();
let (rows, _) = run(&g, q);
assert_eq!(
take_batches(),
0,
"a label-less far side must stay unlisted"
);
assert_eq!(
comparable(rows, SELECTORS[0]),
comparable(gpm(&g, q), SELECTORS[0])
);
}