use crate::UsedSet;
use std::collections::BTreeMap;
use relate_core::{NodeId, RelId, Value};
use super::frontier::FrontierRun;
use super::frontier_emit::{capped_rows, CappedRun};
use super::frontier_match::{boundary, Consumer, FrontierContract};
use super::frontier_tables::fresh_tables;
use super::nfa::{compile, Pool};
use super::program::{NodeTarget, Prog};
use super::rearival::RuleBuffers;
use super::with_rearival_deferred_budget;
use crate::ctx::ExecCtx;
use crate::exec::test_support::{build, exec_cypher, patterns, Built};
use crate::frontier_decline::FrontierRunDecline;
use crate::graph::Graph;
use crate::overlay::ExecGraph;
use crate::pattern_engine::PatternEngine;
use crate::row::Row;
fn capped(
graph: &Graph,
cypher: &str,
seed: NodeId,
pool: Pool,
want: usize,
) -> (Vec<(Row, UsedSet)>, FrontierRun) {
match capped_answer(graph, cypher, seed, pool, want) {
CappedRun::Served { matched, run } => (matched, run),
CappedRun::Declined { facts, reason } => {
panic!("{cypher} should serve, not decline on {reason:?}: {facts:?}")
}
}
}
fn capped_answer(graph: &Graph, cypher: &str, seed: NodeId, pool: Pool, want: usize) -> CappedRun {
let pattern = &patterns(cypher)[0];
let nfa = compile(graph, pattern, PatternEngine::Auto)
.unwrap_or_else(|| panic!("{cypher} should compile"));
let (start, target) =
boundary(pattern).unwrap_or_else(|| panic!("{cypher}: the pattern's boundary is nodes"));
let bare = |node| NodeTarget {
pattern: node,
prog: Prog::Bare,
};
let contract = FrontierContract {
pattern,
nfa,
start: bare(start),
target: bare(target),
consumer: Consumer::Capped { want },
pool,
};
let view = ExecGraph::read(graph);
let mut tables = fresh_tables(&contract.nfa);
let params = BTreeMap::new();
let ctx = ExecCtx::new(&view, ¶ms);
capped_rows(
ctx,
seed,
&contract,
&Row::new(),
want,
&mut tables,
&mut RuleBuffers::new(),
)
.unwrap_or_else(|error| panic!("{cypher} should emit: {error}"))
}
fn engine(graph: &Graph, cypher: &str, names: &[&str]) -> Vec<Vec<Value>> {
let result = exec_cypher(graph, cypher);
let indexes: Vec<usize> = names
.iter()
.map(|name| {
result
.columns
.iter()
.position(|column| column == name)
.unwrap_or_else(|| panic!("{cypher}: no `{name}` column"))
})
.collect();
result
.rows
.iter()
.map(|row| indexes.iter().map(|&i| row[i].clone()).collect())
.collect()
}
fn emitted(rows: &[(Row, UsedSet)], names: &[&str]) -> Vec<Vec<Value>> {
rows.iter()
.map(|(row, _)| {
names
.iter()
.map(|name| {
row.get(name)
.cloned()
.unwrap_or_else(|| panic!("no `{name}` binding in the emitted row"))
})
.collect()
})
.collect()
}
fn chain_graph() -> Built {
let next: &[&str] = &["N"];
let labels = vec![next; 5];
let rels: Vec<(usize, usize, &str)> = (0..4).map(|i| (i, i + 1, "KNOWS")).collect();
build(&labels, &rels)
}
#[test]
fn rows_byte_match_the_dfs_emission_in_order() {
let built = chain_graph();
let seed = built.nodes[0];
let cases: &[(&str, &[&str])] = &[
(
"MATCH p = (x:N {id: 0})-[rs:KNOWS*1..3]-(y:N) RETURN p, rs, x, y",
&["p", "rs", "x", "y"],
),
(
"MATCH p = (x:N {id: 0})((a)-[r1:KNOWS]-(b)-[r2:KNOWS]-(c)){1,2}(y:N) \
RETURN p, a, r1, b, r2, c, x, y",
&["p", "a", "r1", "b", "r2", "c", "x", "y"],
),
(
"MATCH p = (x:N {id: 0})-[c1:KNOWS]->(m)-[rs:KNOWS*1..2]-(y:N) \
RETURN p, c1, m, rs, y",
&["p", "c1", "m", "rs", "y"],
),
(
"MATCH p = (x:N {id: 0})-[rs:KNOWS*1..2]-()-[t1:KNOWS]->(y:N) \
RETURN p, rs, t1, y",
&["p", "rs", "t1", "y"],
),
];
for (cypher, names) in cases {
let (rows, _) = capped(&built.graph, cypher, seed, Pool::Default, 10);
assert_eq!(
emitted(&rows, names),
engine(&built.graph, cypher, names),
"{cypher}"
);
}
}
#[test]
fn cyclic_rows_are_valid_dfs_rows() {
let built = build(
&[&["N"], &["N"], &["N"], &["N"]],
&[
(0, 1, "KNOWS"),
(1, 2, "KNOWS"),
(2, 0, "KNOWS"),
(2, 3, "LIKES"),
],
);
let cypher = "MATCH p = (x:N {id: 0})-[rs:KNOWS*1..3]-(y:N) RETURN p, rs, y";
let (rows, run) = capped(&built.graph, cypher, built.nodes[0], Pool::Default, 10);
assert_eq!(rows.len(), run.endpoints.len(), "one witness per endpoint");
let engine = engine(&built.graph, cypher, &["p", "rs", "y"]);
for row in emitted(&rows, &["p", "rs", "y"]) {
assert!(
engine.contains(&row),
"the emitted row is one of the DFS's: {row:?}"
);
}
}
#[test]
fn per_witness_mode_checks_per_pool() {
let built = build(&[&["N"], &["N"]], &[(0, 1, "KNOWS"), (0, 1, "KNOWS")]);
let seed = built.nodes[0];
let body = "(x:N {id: 0})-[rs:KNOWS*2..2]-(y)";
let cypher = format!("MATCH p = {body} RETURN p, rs, y");
let (rows, _) = capped(&built.graph, &cypher, seed, Pool::Default, 10);
assert_eq!(rows.len(), 1, "the re-reached seed is the one endpoint");
let engine_rows = engine(&built.graph, &cypher, &["p", "rs", "y"]);
assert_eq!(engine_rows.len(), 2, "the DFS emits both rel orders");
assert!(engine_rows.contains(&emitted(&rows, &["p", "rs", "y"])[0]));
let acyclic = format!("MATCH p = ACYCLIC {body} RETURN p, rs, y");
assert!(engine(&built.graph, &acyclic, &["p", "rs", "y"]).is_empty());
let (none, _) = capped(&built.graph, &acyclic, seed, Pool::Default, 10);
assert!(none.is_empty(), "no acyclic witness exists to emit");
let simple = format!("MATCH p = SIMPLE {body} RETURN p, rs, y");
let (rows, _) = capped(&built.graph, &simple, seed, Pool::Default, 10);
assert_eq!(rows.len(), 1, "the closed simple walk is emitted");
let simple_engine = engine(&built.graph, &simple, &["p", "rs", "y"]);
assert_eq!(simple_engine.len(), 2, "the DFS emits both rel orders");
assert!(simple_engine.contains(&emitted(&rows, &["p", "rs", "y"])[0]));
let repeatable = format!("MATCH REPEATABLE ELEMENTS p = {body} RETURN p, rs, y");
let (rows, _) = capped(&built.graph, &repeatable, seed, Pool::Walk, 10);
assert_eq!(rows.len(), 1);
let walk_engine = engine(&built.graph, &repeatable, &["p", "rs", "y"]);
assert_eq!(walk_engine.len(), 4, "every rel pair, both orders");
assert!(walk_engine.contains(&emitted(&rows, &["p", "rs", "y"])[0]));
}
#[test]
fn walk_pool_emits_the_rel_reusing_witness() {
let built = build(
&[&["N"], &["N"], &["N"]],
&[(0, 1, "KNOWS"), (1, 2, "KNOWS"), (2, 0, "KNOWS")],
);
let cypher =
"MATCH REPEATABLE ELEMENTS p = (x:N {id: 0})-[rs:KNOWS*1..3]-(y:N) RETURN p, rs, y";
let (rows, _) = capped(&built.graph, cypher, built.nodes[0], Pool::Walk, 10);
let values = emitted(&rows, &["p", "rs", "y"]);
let seed_row = values
.iter()
.find(|row| matches!(&row[2], Value::Node(node) if node.id == built.nodes[0]))
.expect("the re-reached seed is emitted");
match &seed_row[1] {
Value::List(rels) => {
let ids: Vec<RelId> = rels
.iter()
.map(|rel| match rel {
Value::Relationship(rel) => rel.id,
other => panic!("a rel list of rels, not {other:?}"),
})
.collect();
assert_eq!(ids.len(), 2);
assert_eq!(ids[0], ids[1], "the 2-walk reuses the seed's own rel");
}
other => panic!("the rel list binds a list, not {other:?}"),
}
let engine_rows = engine(&built.graph, cypher, &["p", "rs", "y"]);
assert!(engine_rows.contains(seed_row));
}
#[test]
fn cap_early_halt_stops_at_the_filling_level() {
let built = build(
&[&["N"], &["N"], &["N"], &["N"], &["N"]],
&[
(1, 1, "KNOWS"),
(1, 0, "KNOWS"),
(1, 3, "KNOWS"),
(3, 4, "KNOWS"),
],
);
let seed = built.nodes[1];
let cypher = "MATCH p = (x:N {id: 1})-[rs:KNOWS*2..3]-(y:N) RETURN p, rs, y";
let engine_rows = engine(&built.graph, cypher, &["p", "rs", "y"]);
assert_eq!(engine_rows.len(), 4, "the engine enumerates every trail");
let (rows, run) = capped(&built.graph, cypher, seed, Pool::Default, 1);
assert_eq!(emitted(&rows, &["p", "rs", "y"]).len(), 1);
assert!(engine_rows.contains(&emitted(&rows, &["p", "rs", "y"])[0]));
assert_eq!(run.per_level, vec![1, 2, 1], "halted after level 2");
assert_eq!(
run.endpoints.len(),
1,
"the candidates are dropped at the halt, the cap rider's own semantics"
);
let (rows, run) = capped(&built.graph, cypher, seed, Pool::Default, 10);
let values = emitted(&rows, &["p", "rs", "y"]);
assert_eq!(values.len(), 3, "nodes 4, 3, and 0, one row each");
assert_eq!(run.per_level, vec![1, 2, 1, 0], "the natural fixpoint");
assert_eq!(run.endpoints.len(), 3);
for row in &values {
assert!(
engine_rows.contains(row),
"every row is one of the engine's: {row:?}"
);
}
}
#[test]
fn output_sensitive_cap_times_depth_never_path_count() {
let next: &[&str] = &["N"];
let labels = vec![next; 10];
let rels: Vec<(usize, usize, &str)> = (0..10)
.flat_map(|i| (i + 1..10).map(move |j| (i, j, "KNOWS")))
.collect();
let built = build(&labels, &rels);
let cypher = "MATCH p = (x:N {id: 0})-[rs:KNOWS*2..]-(y:N) RETURN p, rs, y";
let (rows, run) = capped(&built.graph, cypher, built.nodes[0], Pool::Default, 5);
assert_eq!(rows.len(), 5, "the cap fills at level 2");
assert_eq!(run.per_level, vec![1, 9, 0], "halted after level 2");
assert_eq!(
run.edge_visits, 90,
"the undirected degree sum, pair-bounded"
);
for row in emitted(&rows, &["p", "rs", "y"]) {
match &row[1] {
Value::List(rels) if rels.len() == 2 => {}
other => panic!("a 2-hop witness, not {other:?}"),
}
}
}
#[test]
fn zero_length_endpoint_binds_the_empty_path() {
let built = build(&[&["N"], &["N"]], &[(0, 1, "KNOWS")]);
let cypher = "MATCH p = (x:N {id: 0})-[rs:KNOWS*0..1]-(y:N) RETURN p, rs, x, y";
let (rows, _) = capped(&built.graph, cypher, built.nodes[0], Pool::Default, 10);
assert_eq!(
emitted(&rows, &["p", "rs", "x", "y"]),
engine(&built.graph, cypher, &["p", "rs", "x", "y"]),
"both rows, in the DFS's order"
);
}
#[test]
fn target_admission_filters_endpoints() {
let b = crate::exec::test_support::Builder::new();
let nodes: Vec<NodeId> = (0..3)
.map(|i| b.node(&format!("n{i}"), if i == 2 { &["Other"] } else { &["N"] }))
.collect();
b.rel(nodes[0], nodes[1], "KNOWS", &[]);
b.rel(nodes[1], nodes[2], "KNOWS", &[]);
let graph = b.done();
let cypher = "MATCH p = (x:N {id: \"n0\"})-[rs:KNOWS*1..2]-(y:Other) RETURN p, rs, y";
let (rows, _) = capped(&graph, cypher, nodes[0], Pool::Default, 10);
let values = emitted(&rows, &["p", "rs", "y"]);
assert_eq!(values.len(), 1, "only the Other-labeled endpoint emits");
assert!(matches!(&values[0][2], Value::Node(node) if node.id == nodes[2]));
assert_eq!(values, engine(&graph, cypher, &["p", "rs", "y"]));
}
#[test]
fn a_deferred_cut_carries_the_cutting_rules_tally() {
let built = build(&[&["N"], &["N"]], &[(1, 0, "KNOWS"), (1, 1, "KNOWS")]);
let cypher = "MATCH (x:N {id: 1})-[:KNOWS*2..3]-(y) RETURN y";
let declined = with_rearival_deferred_budget(1, || {
capped_answer(&built.graph, cypher, built.nodes[1], Pool::Walk, 10)
});
match declined {
CappedRun::Declined {
facts,
reason: FrontierRunDecline::RearrivalBudget,
} => {
assert!(
facts.declined_exhausted >= 1,
"the cutting rule's tally must ride the decline: {facts:?}"
);
}
other => panic!("the drained deferred pass must decline: {other:?}"),
}
}
#[test]
fn a_served_capped_run_counts_its_deferred_pass_works() {
let built = build(
&[&["N"], &["N"]],
&[(0, 0, "LIKES"), (0, 1, "KNOWS"), (1, 1, "KNOWS")],
);
let cypher = "MATCH (x:N {id: 1})-[:KNOWS*2..3]-(y) RETURN y";
let (_, run) = capped(&built.graph, cypher, built.nodes[1], Pool::Default, 10);
assert_eq!(
run.rule.search_proven, 2,
"the runner's admission ask and the deferred pass's ask both count: {:?}",
run.rule
);
}