use relate_ir::{Clause, Expr, PathPattern, Query};
use crate::clause_kind::clause_mutates_store;
use crate::names::{projected_scope, stage_output_names};
use crate::plan::{plan_any_clause, plan_any_expr, LogicalPlan};
pub fn plan_is_bounded_work(plan: &LogicalPlan) -> bool {
!plan_any_clause(plan, &mut clause_escalates)
&& !plan_any_expr(plan, &mut Expr::is_scope_bearing)
&& !cartesian_join_graph(plan)
}
const MAX_SHALLOW_EXPRESSION_DEPTH: usize = 16;
fn deeper_than(expr: &Expr, bound: usize) -> bool {
let mut stack = vec![(expr, 1)];
while let Some((expr, depth)) = stack.pop() {
if depth > bound {
return true;
}
expr.each_child(&mut |child| stack.push((child, depth + 1)));
}
false
}
pub(crate) fn plan_is_shallow(plan: &LogicalPlan) -> bool {
!plan_any_expr(plan, &mut |expr| {
deeper_than(expr, MAX_SHALLOW_EXPRESSION_DEPTH)
})
}
pub(crate) fn plan_is_shallow_bounded_work(plan: &LogicalPlan) -> bool {
plan_is_shallow(plan) && plan_is_bounded_work(plan)
}
pub(crate) fn query_is_shallow(query: &Query) -> bool {
if query.next.is_some() {
return false;
}
!crate::plan::query_any_expr(query, &mut |expr| {
deeper_than(expr, MAX_SHALLOW_EXPRESSION_DEPTH)
})
}
pub fn plan_references_auto_parameter(plan: &LogicalPlan) -> bool {
plan_any_expr(plan, &mut |expr| {
matches!(expr, Expr::Parameter(name)
if relate_parser::name_is_auto_parameter(name))
})
}
pub fn hit_is_inline_safe(plan: &LogicalPlan, query: &Query) -> bool {
plan_is_shallow_bounded_work(plan)
&& query_is_shallow(query)
&& !plan_references_auto_parameter(plan)
}
fn clause_escalates(clause: &Clause) -> bool {
if clause_mutates_store(clause) {
return true;
}
match clause {
Clause::Unwind { .. } => true,
Clause::Call { .. } => true,
Clause::CallSubquery { .. } => true,
Clause::Conditional { .. } => true,
Clause::Match {
patterns, search, ..
} => search.is_some() || patterns.iter().any(pattern_escalates),
Clause::LoadCsv { .. } => true,
Clause::With { .. }
| Clause::Return { .. }
| Clause::ShowIndexes
| Clause::Finish
| Clause::Use { .. } => false,
Clause::Foreach { .. }
| Clause::Create { .. }
| Clause::Merge { .. }
| Clause::Delete { .. }
| Clause::Set { .. }
| Clause::Remove { .. }
| Clause::CreateIndex { .. }
| Clause::DropIndex { .. }
| Clause::Catalog(_) => false,
}
}
fn cartesian_join_graph(plan: &LogicalPlan) -> bool {
let stages: Vec<&LogicalPlan> = plan.stages().collect();
let mut carried_hops: usize = 0;
let mut seed_names: Vec<String> = Vec::new();
for (index, stage) in stages.iter().enumerate() {
let seed_variables: Vec<&str> = seed_names.iter().map(String::as_str).collect();
let mut stage_hops: usize = 0;
for part in &stage.parts {
let (product, hops) = part_products(part, &seed_variables, carried_hops);
if product || hops >= MULTI_HOP_ESCALATION_HOPS {
return true;
}
stage_hops = stage_hops.max(hops);
}
carried_hops = stage_hops;
if index + 1 < stages.len() {
seed_names = stage_output_names(
stage.parts.iter().map(Vec::as_slice),
std::mem::take(&mut seed_names),
&std::collections::HashSet::new(),
)
.expect("a planned statement's stage columns agree");
}
}
false
}
fn part_products(part: &[Clause], seed_variables: &[&str], carried_hops: usize) -> (bool, usize) {
use std::collections::HashSet;
let mut live: HashSet<String> = seed_variables.iter().map(|n| n.to_string()).collect();
let mut rows_flow = !seed_variables.is_empty();
let mut hops = carried_hops;
for clause in part {
match clause {
Clause::Match { patterns, .. } => {
for pattern in patterns {
let variables = relate_ir::pattern_anchor_variables(pattern);
if rows_flow && !variables.iter().any(|v| v.with_str(|t| live.contains(t))) {
return (true, hops);
}
rows_flow = true;
for name in variables {
live.insert(name.to_string());
}
hops += pattern.rels.len();
}
}
Clause::With { items, .. } => {
let incoming: Vec<String> = live.iter().cloned().collect();
live = projected_scope(items, incoming).into_iter().collect();
rows_flow = true;
}
Clause::Return { .. }
| Clause::ShowIndexes
| Clause::Finish
| Clause::Use { .. }
| Clause::Catalog(_)
| Clause::Foreach { .. }
| Clause::LoadCsv { .. }
| Clause::Create { .. }
| Clause::Merge { .. }
| Clause::Delete { .. }
| Clause::Set { .. }
| Clause::Remove { .. }
| Clause::CreateIndex { .. }
| Clause::DropIndex { .. }
| Clause::Unwind { .. }
| Clause::Call { .. }
| Clause::CallSubquery { .. }
| Clause::Conditional { .. } => {}
}
}
(false, hops)
}
const MULTI_HOP_ESCALATION_HOPS: usize = 2;
fn pattern_escalates(pattern: &PathPattern) -> bool {
pattern.needs_gpm()
|| pattern
.rels
.iter()
.any(|rel| rel.var_length || rel.quantified)
}
#[cfg(test)]
mod tests {
use super::*;
fn bounded_work(cypher: &str) -> bool {
plan_is_bounded_work(&crate::plan_of(cypher))
}
#[test]
fn writes_never_run_inline() {
for cypher in [
"MATCH (a:User {id: $i}) CREATE (a)-[:T]->(:N)",
"MATCH (a:User {id: $i}) SET a.x = 1",
"MATCH (a:User {id: $i}) DELETE a",
"MERGE (a:User {id: $i})",
] {
assert!(!bounded_work(cypher), "{cypher}");
}
}
#[test]
fn bounded_reads_run_inline() {
for cypher in [
"MATCH (n:User) WHERE n.id = $i RETURN n.id",
"MATCH (n:User {id: $i}) RETURN n.id",
"RETURN $i AS i",
"RETURN 1 AS n",
"MATCH (n:User) RETURN n LIMIT 10",
"SHOW DATABASES",
"SHOW INDEXES",
"USE neo4j MATCH (n:User) RETURN n",
"MATCH (n:User) WHERE n.id = $i WITH n RETURN n.id",
"RETURN 1 AS x UNION RETURN 2 AS x",
"MATCH (n:User) WHERE n.id = $i RETURN n.id LIMIT 1",
"MATCH (a:User {id: $i})-[:T]->() RETURN a",
"MATCH (a:User {id: $i}) MATCH (a)-[:T]->(b) RETURN b",
"MATCH (a:User {id: $i}) WITH a MATCH (a)-[:T]->(b) RETURN b",
"MATCH (a:User {id: $i}) RETURN a AS n UNION MATCH (b:City {id: $i}) RETURN b AS n",
"MATCH (a:User {id: $i}) RETURN a NEXT MATCH (a)-[:T]->(b) RETURN b AS m",
] {
assert!(bounded_work(cypher), "must be bounded work: {cypher}");
}
}
#[test]
fn shallow_bounded_work_tracks_the_depth_bound() {
for cypher in [
"MATCH (n:User {id: $i}) RETURN n.id",
"MATCH (n:User {id: $i}) RETURN n.id + 1 AS next",
"MATCH (a:User {id: $i})-[:T]->(b) RETURN count(b.id)",
"RETURN 1 AS n",
] {
let plan = crate::plan_of(cypher);
assert!(
plan_is_shallow_bounded_work(&plan),
"must be shallow bounded work: {cypher}"
);
}
let deep = format!("RETURN {}$x{} AS n", "$x+(".repeat(20), ")".repeat(20));
let plan = crate::plan_of(&deep);
assert!(
plan_is_bounded_work(&plan),
"the fixture stays bounded work: {deep}"
);
assert!(
!plan_is_shallow_bounded_work(&plan),
"a deep expression must not run inline on an unasserted thread: {deep}"
);
for cypher in [
"MATCH (n)-[r:T*1..3]->(m) RETURN n",
"MATCH (a:User {id: $i})-[:T]->(b)-[:U]->(c) RETURN b",
"UNWIND range(1, 10) AS x RETURN x",
] {
let plan = crate::plan_of(cypher);
assert!(
!plan_is_shallow_bounded_work(&plan),
"must escalate: {cypher}"
);
}
}
#[test]
fn the_containment_rule_composes_its_conjuncts() {
let placeholder = crate::plan_of("MATCH (n:User {id: $__AUTO_INT_0__}) RETURN n.id");
assert!(
plan_is_shallow_bounded_work(&placeholder),
"the fixture is shallow bounded work"
);
assert!(
plan_references_auto_parameter(&placeholder),
"the placeholder reference is the conjunct's fact"
);
assert!(
!hit_is_inline_safe(
&placeholder,
&crate::query_of("MATCH (n:User {id: 1}) RETURN n.id")
),
"the auto-parameter conjunct declines the hit"
);
let plan = crate::plan_of("MATCH (n:User {id: $i}) RETURN n.id");
assert!(
hit_is_inline_safe(
&plan,
&crate::query_of("MATCH (n:User {id: $i}) RETURN n.id")
),
"the point-lookup family is inline-safe"
);
let chained = crate::query_of(
"MATCH (a:User {id: $i}) RETURN a AS n NEXT MATCH (b:City) RETURN b AS m",
);
assert!(
!query_is_shallow(&chained),
"a NEXT chain declines structurally"
);
}
#[test]
fn data_proportional_and_unbounded_shapes_escalate() {
for cypher in [
"UNWIND range(1, 10) AS x RETURN x",
"UNWIND [1, 2, 3] AS x CREATE (:N)",
"CREATE (:User {id: $i})",
"MERGE (n:User {id: $i}) ON CREATE SET n.fresh = true",
"MATCH (n:User) WHERE n.id = $i SET n.seen = true",
"MATCH (n:User) WHERE n.id = $i DELETE n",
"MATCH (n:User) WHERE n.id = $i REMOVE n.seen",
"CREATE RANGE INDEX user_id FOR (u:User) ON (u.id)",
"DROP INDEX user_id",
"ALTER DATABASE neo4j SET DEFAULT LANGUAGE CYPHER 5",
"CREATE GRAPH TYPE gt AS { (n:Person => {name :: STRING}) }",
"CREATE INDEX i FOR (n:User) ON (n.id)",
"MATCH (a:User), (b:City) RETURN a, b",
"MATCH (a:User), (b:User) RETURN count(a)",
"MATCH (a:User), (b:User) WHERE a.id = $i AND b.id = $i RETURN a",
"MATCH (a)-[:T]->(b), (c)-[:U]->(d) RETURN a",
"MATCH (a:User) MATCH (b:City) RETURN count(a)",
"MATCH (a:User), (b:City) RETURN a AS n UNION MATCH (c) RETURN c AS n",
"MATCH (a:User {id: $i}) RETURN a AS n NEXT MATCH (b:City) RETURN b AS m",
"MATCH (a:User {id: $i}) RETURN a AS n NEXT MATCH (a)-[:T]->(b) RETURN b AS m",
"MATCH (a:User {id: $i}) WITH 1 AS x MATCH (b:City) RETURN b",
"MATCH (a:User {id: $i}) WITH a AS x MATCH (b:City) RETURN b",
"MATCH (a:User {id: $i}) RETURN a AS n NEXT MATCH (a)-[:T]->(b), (c:City) RETURN b AS m",
"MATCH (a) MATCH (b) MATCH (a)-[:T]->(b) RETURN b",
"MATCH (a:User {id: $i})-[:T]->(b)-[:U]->(c) RETURN b",
"MATCH (a)-[:T]->(b)-[:T]->(c) RETURN a",
"MATCH (a)-[:T]->(b), (b)-[:T]->(c) RETURN c",
"MATCH (a)-[:T]->(b) MATCH (b)-[:T]->(c) RETURN c",
"MATCH (a:User {id: $i})-[:T]->(b) RETURN b NEXT MATCH (b)-[:T]->(c) RETURN c",
"MATCH (), (n) RETURN n",
"MATCH () MATCH (n) RETURN n",
"MATCH (n)-[r:T*1..3]->(m) RETURN n",
"MATCH (n)-[r:T*]->(m) RETURN n",
"MATCH (n)-[r:T]->{1,3}(m) RETURN n",
"MATCH (a)-->(b)((x)-[e]->(y)){1,3}(c) RETURN a",
"MATCH ANY SHORTEST (n)-[r:T]->(m) RETURN n",
"MATCH (n WHERE n.id = $i)-[r:T]->(m) RETURN n",
"MATCH p = (n)-[r:T WHERE r.w > 1]->(m) RETURN p",
"CALL { MATCH (n) RETURN n }",
"FOREACH (x IN [1, 2] | CREATE (:N))",
"WHEN true THEN { RETURN 1 AS x } ELSE { RETURN 2 AS x }",
"CALL db.labels()",
"LOAD CSV FROM 'file:///f.csv' AS row CREATE (n)",
"LOAD CSV FROM 'file:///f.csv' AS row RETURN row",
"MATCH (n:User) WHERE EXISTS { (n)-[:T]->(m) } RETURN n",
"MATCH (n:User) WHERE count { (n)-[:T]->() } > 1 RETURN n",
"MATCH (n:User) RETURN [(n)-[:T]->(m) | m.name] AS names",
"MATCH (a:User), (b:User) RETURN shortestPath((a)-[:T*]->(b))",
] {
assert!(!bounded_work(cypher), "must escalate: {cypher}");
}
}
#[test]
fn escalation_covers_every_nesting_position() {
for cypher in [
"MATCH (n:User) WITH n, EXISTS { (n)-[:T]->(m) } AS live RETURN live",
"MATCH (n:User) WHERE EXISTS { (n)-[:T]->(m) } RETURN n",
"MATCH (n:User) RETURN [(n)-[:T]->(m) | m.name] AS names",
] {
assert!(
!bounded_work(cypher),
"must escalate from its nest: {cypher}"
);
}
}
}