diff --git a/crates/lance-csr/src/datafusion_planner/builder/mod.rs b/crates/lance-csr/src/datafusion_planner/builder/mod.rs index 5d9a0be..7e9fa59 100644 --- a/crates/lance-csr/src/datafusion_planner/builder/mod.rs +++ b/crates/lance-csr/src/datafusion_planner/builder/mod.rs @@ -172,7 +172,14 @@ impl DataFusionPlanner { input, path, node_values, - } => self.build_path_match(ctx, input, path, *node_values), + relationship_condition, + } => self.build_path_match( + ctx, + input, + path, + *node_values, + relationship_condition.as_ref(), + ), LogicalOperator::ShortestPath { input, source_variable, diff --git a/crates/lance-csr/src/datafusion_planner/builder/path_ops.rs b/crates/lance-csr/src/datafusion_planner/builder/path_ops.rs index f7cd101..49422a3 100644 --- a/crates/lance-csr/src/datafusion_planner/builder/path_ops.rs +++ b/crates/lance-csr/src/datafusion_planner/builder/path_ops.rs @@ -1,8 +1,8 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright The lance-csr Authors -use crate::ast::PathPattern; use crate::ast::RelationshipDirection; +use crate::ast::{BooleanExpression, PathPattern}; use crate::case_insensitive::qualify_column; use crate::csr_expand::{AdjacencyCatalog, Neighbors}; use crate::datafusion_planner::{analysis::PlanningContext, DataFusionPlanner}; @@ -20,6 +20,7 @@ impl DataFusionPlanner { input: &LogicalOperator, path: &PathPattern, node_values: bool, + relationship_condition: Option<&BooleanExpression>, ) -> Result { let error = |message: String| GraphError::UnsupportedFeature { feature: message, @@ -239,6 +240,7 @@ impl DataFusionPlanner { .iter() .map(|segment| &segment.relationship.properties), ), + relationship_condition.map(crate::datafusion_planner::expression::to_df_boolean_expr), ) .map_err(|e| self.plan_error("Failed to plan path value", e))?; Ok(LogicalPlan::Extension(Extension { diff --git a/crates/lance-csr/src/logical_plan.rs b/crates/lance-csr/src/logical_plan.rs index 24e8d89..a1391eb 100644 --- a/crates/lance-csr/src/logical_plan.rs +++ b/crates/lance-csr/src/logical_plan.rs @@ -151,6 +151,9 @@ pub enum LogicalOperator { path: PathPattern, /// Preserve typed node identities for untyped relationship queries. node_values: bool, + /// A condition each relationship of the path must meet, over its properties + /// named as variables (`r.day > 5` is `day > 5`); see `all_relationships_condition`. + relationship_condition: Option, }, /// `shortestPath` / `allShortestPaths` between two variables bound in `input`; adds @@ -986,8 +989,8 @@ impl<'a> LogicalPlanner<'a> { } } GraphPattern::Path(path) if path.variable.is_some() || inventory_alternation => { - let pruned = filter.and_then(|f| with_all_relationship_equalities(path, f)); - plan = Some(self.plan_inventory_path(plan, pruned.as_ref().unwrap_or(path))?) + let condition = filter.and_then(|f| all_relationships_condition(path, f)); + plan = Some(self.plan_inventory_path(plan, path, condition)?) } GraphPattern::Path(path) if path.shortest.is_some() => { plan = Some(self.plan_shortest_path(plan, path)?) @@ -1002,7 +1005,7 @@ impl<'a> LogicalPlanner<'a> { { let mut path = path.clone(); path.variable = Some(format!("_path_value_{}", self.variables.len())); - plan = Some(self.plan_inventory_path(plan, &path)?); + plan = Some(self.plan_inventory_path(plan, &path, None)?); } GraphPattern::Path(path) => plan = Some(self.plan_path(plan, path)?), } @@ -1720,6 +1723,7 @@ impl<'a> LogicalPlanner<'a> { input: Box::new(plan.ok_or_else(|| GraphError::internal("both ends planned"))?), path: path.clone(), node_values: self.wildcard_relationships, + relationship_condition: None, }); } Ok(LogicalOperator::ShortestPath { @@ -2046,6 +2050,7 @@ impl<'a> LogicalPlanner<'a> { &mut self, base: Option, path: &PathPattern, + relationship_condition: Option, ) -> Result { let mut path = path.clone(); let start = path @@ -2091,6 +2096,7 @@ impl<'a> LogicalPlanner<'a> { input: Box::new(base), path, node_values: self.wildcard_relationships, + relationship_condition, }) } @@ -2390,20 +2396,22 @@ impl<'a> LogicalPlanner<'a> { } } -/// Copies `r.key = value` terms of `all(r IN relationships(p) WHERE ...)` conjuncts in -/// `filter` into the property map of every relationship of the named path `p`, so the -/// trail enumeration drops a failing edge as it reaches it instead of after building -/// the whole path. The WHERE still runs, so a term left out here only costs time. -/// Shortest paths are left alone: pruning edges would change which path is shortest. -fn with_all_relationship_equalities( +/// The condition every relationship of the named path `p` must meet for `filter` to +/// hold, from its `all(r IN relationships(p) WHERE x)` and `none(... WHERE x)` conjuncts, +/// with `r.key` written as the variable `key`. The path operator checks it on each edge +/// it reaches, so a failing edge ends its branch instead of being found after the whole +/// path is built. The WHERE still runs, so a predicate left out here only costs time. +/// Only predicates on `r`'s properties, parameters and literals qualify. Shortest paths +/// are left alone: pruning edges would change which path is shortest. +fn all_relationships_condition( path: &PathPattern, filter: &BooleanExpression, -) -> Option { +) -> Option { let variable = path .variable .as_deref() .filter(|_| path.shortest.is_none())?; - let mut equalities = HashMap::new(); + let mut condition = None; for conjunct in conjuncts(filter) { let BooleanExpression::Comparison { left, @@ -2431,67 +2439,48 @@ fn with_all_relationship_equalities( let over_path = matches!(list.as_ref(), ValueExpression::ScalarFunction { name, args } if name.eq_ignore_ascii_case("relationships") && matches!(args.as_slice(), [ValueExpression::Variable(p)] if p.eq_ignore_ascii_case(variable))); - let ValueExpression::Boolean(predicate) = predicate.as_ref() else { + if !over_path || !matches!(kind.as_str(), "all" | "none") { continue; + } + let mut predicate = match predicate.as_ref() { + ValueExpression::Boolean(predicate) => predicate.as_ref().clone(), + // A bare value is a condition that it is true, as in WHERE. + value => BooleanExpression::Comparison { + left: value.clone(), + operator: ComparisonOperator::Equal, + right: ValueExpression::Literal(PropertyValue::Boolean(true)), + }, }; - if kind != "all" || !over_path { + // Nothing from outside the predicate: no pattern, node, row or path variables. + let mut outer = HashSet::new(); + crate::pattern_order::boolean_variables(&predicate, &mut outer); + if !outer.is_empty() { continue; } - for term in conjuncts(predicate) { - let BooleanExpression::Comparison { - left, - operator: ComparisonOperator::Equal, - right, - } = term - else { - continue; - }; - let field = |value: &ValueExpression| match value { - ValueExpression::Field { base, field } if matches!(base.as_ref(), ValueExpression::LocalVariable(v) if v == element) => { - Some(field.clone()) + crate::ast::transform_boolean_values(&mut predicate, &mut |value| { + if let ValueExpression::Field { base, field } = value { + if matches!(base.as_ref(), ValueExpression::LocalVariable(v) if v == element) { + *value = ValueExpression::Variable(field.clone()); } - _ => None, - }; - let constant = |value: &ValueExpression| match value { - ValueExpression::Literal( - v @ (PropertyValue::String(_) - | PropertyValue::Integer(_) - | PropertyValue::Float(_) - | PropertyValue::Boolean(_) - | PropertyValue::Parameter(_)), - ) => Some(v.clone()), - ValueExpression::Parameter(name) => Some(PropertyValue::Parameter(name.clone())), - _ => None, - }; - if let Some((key, value)) = field(left) - .zip(constant(right)) - .or_else(|| field(right).zip(constant(left))) - { - equalities.entry(key).or_insert(value); } + }); + // Any local left is `r` itself, or a nested comprehension's element. + let mut local = false; + crate::ast::transform_boolean_values(&mut predicate, &mut |value| { + local |= matches!(value, ValueExpression::LocalVariable(_)); + }); + if local { + continue; } - } - if equalities.is_empty() { - return None; - } - let mut path = path.clone(); - for segment in &mut path.segments { - for (key, value) in &equalities { - // An existing map entry already filters this key; the WHERE checks the rest. - if !segment - .relationship - .properties - .keys() - .any(|k| k.eq_ignore_ascii_case(key)) - { - segment - .relationship - .properties - .insert(key.clone(), value.clone()); - } + if kind == "none" { + predicate = BooleanExpression::Not(Box::new(predicate)); } + condition = Some(match condition { + Some(c) => BooleanExpression::And(Box::new(c), Box::new(predicate)), + None => predicate, + }); } - Some(path) + condition } fn conjuncts(expr: &BooleanExpression) -> Vec<&BooleanExpression> { @@ -3469,11 +3458,14 @@ mod tests { ); } - /// The relationship property maps of the first PathMatch in a plan. - fn path_relationship_properties(query: &str) -> Vec> { - fn find(plan: &LogicalOperator) -> Option<&PathPattern> { + /// The relationship condition of the first PathMatch in a plan, as DataFusion shows it. + fn path_relationship_condition(query: &str) -> Option { + fn find(plan: &LogicalOperator) -> Option<&Option> { match plan { - LogicalOperator::PathMatch { path, .. } => Some(path), + LogicalOperator::PathMatch { + relationship_condition, + .. + } => Some(relationship_condition), LogicalOperator::Project { input, .. } | LogicalOperator::Filter { input, .. } => { find(input) } @@ -3490,45 +3482,42 @@ mod tests { .unwrap(); find(&plan) .expect("a path match") - .segments - .iter() - .map(|s| s.relationship.properties.clone()) - .collect() + .as_ref() + .map(|c| crate::datafusion_planner::expression::to_df_boolean_expr(c).to_string()) } #[test] - fn all_relationship_equalities_filter_each_path_edge() { - let maps = path_relationship_properties( - "MATCH p = (a:N {id: 0})-[:R*1..3]->(b:N)-[:R {day: 7}]->(c:N) \ - WHERE a.id = 0 AND all(r IN relationships(p) WHERE 5 = r.day AND r.kind = $k AND r.w > 1) \ + fn all_and_none_relationship_conditions_filter_each_path_edge() { + let condition = path_relationship_condition( + "MATCH p = (a:N {id: 0})-[:R*1..3]->(b:N) \ + WHERE a.id = 0 AND all(r IN relationships(p) WHERE r.day >= 5 AND (r.kind IN ['x', $k] OR r.ok)) \ + AND none(r IN relationships(p) WHERE r.w > 1) \ RETURN count(*)", ); - assert_eq!(maps[0].get("day"), Some(&PropertyValue::Integer(5))); assert_eq!( - maps[0].get("kind"), - Some(&PropertyValue::Parameter("k".into())) - ); - assert!(!maps[0].contains_key("w"), "only equalities are lowered"); - // An existing map entry stays; the WHERE still rejects the contradiction. - assert_eq!(maps[1].get("day"), Some(&PropertyValue::Integer(7))); - assert_eq!( - maps[1].get("kind"), - Some(&PropertyValue::Parameter("k".into())) + condition.as_deref(), + Some( + "day >= Int64(5) AND (kind IN ([Utf8(\"x\"), $k]) OR ok = Boolean(true)) \ + AND NOT w > Int64(1)" + ) ); } #[test] - fn other_path_predicates_leave_the_relationship_maps_alone() { + fn other_path_predicates_leave_the_relationships_unfiltered() { for predicate in [ "any(r IN relationships(p) WHERE r.day = 5)", + "single(r IN relationships(p) WHERE r.day = 5)", "all(r IN relationships(p) WHERE r.day = 5) OR a.id = 1", "NOT all(r IN relationships(p) WHERE r.day = 5)", - "all(r IN relationships(p) WHERE r.day = 5 OR r.day = 6)", + "all(r IN relationships(p) WHERE r.day = a.id)", + "all(r IN relationships(p) WHERE r IS NOT NULL)", + "all(r IN nodes(p) WHERE r.day = 5)", ] { - let maps = path_relationship_properties(&format!( + let condition = path_relationship_condition(&format!( "MATCH p = (a:N)-[:R*1..3]->(b:N) WHERE {predicate} RETURN count(*)" )); - assert!(maps[0].is_empty(), "{predicate}"); + assert_eq!(condition, None, "{predicate}"); } } diff --git a/crates/lance-csr/src/path_match.rs b/crates/lance-csr/src/path_match.rs index de83135..1f42318 100644 --- a/crates/lance-csr/src/path_match.rs +++ b/crates/lance-csr/src/path_match.rs @@ -17,7 +17,7 @@ use arrow::array::{ }; use arrow::compute::take; use arrow_schema::{Field, Schema, SchemaRef}; -use datafusion::common::tree_node::{Transformed, TransformedResult, TreeNodeRecursion}; +use datafusion::common::tree_node::{Transformed, TransformedResult, TreeNode, TreeNodeRecursion}; use datafusion::common::{DFSchema, DFSchemaRef, Result}; use datafusion::execution::session_state::SessionState; use datafusion::execution::{SendableRecordBatchStream, TaskContext}; @@ -113,6 +113,8 @@ pub(crate) struct PathMatchNode { sources: SourceBatches, // Node bindings first, then relationship steps, in traversal order. filters: Vec>, + /// A condition every relationship of the path meets, over its property columns. + relationship_condition: Option, schema: DFSchemaRef, outputs: Vec, } @@ -141,6 +143,7 @@ impl PathMatchNode { spec: PathSpec, sources: SourceBatches, properties: impl IntoIterator>, + relationship_condition: Option, ) -> Result { let filters = properties .into_iter() @@ -235,6 +238,7 @@ impl PathMatchNode { spec: Arc::new(spec), sources, filters, + relationship_condition, schema, outputs, }) @@ -273,6 +277,7 @@ impl PartialEq for PathMatchNode { self.inputs == other.inputs && Arc::ptr_eq(&self.spec, &other.spec) && self.filters == other.filters + && self.relationship_condition == other.relationship_condition } } impl Eq for PathMatchNode {} @@ -281,6 +286,7 @@ impl Hash for PathMatchNode { self.inputs.hash(state); Arc::as_ptr(&self.spec).hash(state); self.filters.hash(state); + self.relationship_condition.hash(state); } } impl PartialOrd for PathMatchNode { @@ -302,11 +308,13 @@ impl UserDefinedLogicalNodeCore for PathMatchNode { &self.schema } fn expressions(&self) -> Vec { - // The property columns belong to the inventory, so only expose the values. + // The property columns belong to the inventory, so only expose the values and + // the condition's parameters, which DataFusion binds per execution. self.filters .iter() .flatten() .map(|(_, value)| value.clone()) + .chain(placeholders(self.relationship_condition.as_ref())) .collect() } fn prevent_predicate_push_down_columns(&self) -> HashSet { @@ -343,19 +351,69 @@ impl UserDefinedLogicalNodeCore for PathMatchNode { } fn with_exprs_and_inputs(&self, exprs: Vec, inputs: Vec) -> Result { let mut node = self.clone(); - if exprs.len() != node.filters.iter().map(Vec::len).sum::() { + let values = node.filters.iter().map(Vec::len).sum::(); + if exprs.len() != values + placeholders(node.relationship_condition.as_ref()).len() { return datafusion::common::internal_err!( - "PathMatch expected one expression per property" + "PathMatch expected one expression per property and parameter" ); } - for ((_, value), expr) in node.filters.iter_mut().flatten().zip(exprs) { + let mut exprs = exprs.into_iter(); + for ((_, value), expr) in node.filters.iter_mut().flatten().zip(exprs.by_ref()) { *value = expr; } + if let Some(condition) = node.relationship_condition.take() { + // Placeholders are leaves, so post-order meets them in `placeholders`' order. + node.relationship_condition = Some( + condition + .transform_up(|e| match e { + Expr::Placeholder(_) => { + Ok(Transformed::yes(exprs.next().expect("counted above"))) + } + e => Ok(Transformed::no(e)), + }) + .data()?, + ); + } node.inputs = inputs; Ok(node) } } +/// The parameters in `condition`, in tree order. +fn placeholders(condition: Option<&Expr>) -> Vec { + let mut found = Vec::new(); + if let Some(condition) = condition { + condition + .apply(|e| { + if matches!(e, Expr::Placeholder(_)) { + found.push(e.clone()); + } + Ok(TreeNodeRecursion::Continue) + }) + .expect("visiting does not fail"); + } + found +} + +/// `condition` with its columns named as in `fields`; a property they lack is null. +fn on_fields(condition: &Expr, fields: &arrow_schema::Fields) -> Result { + condition + .clone() + .transform(|e| match &e { + Expr::Column(c) => Ok(Transformed::yes( + match fields + .iter() + .find(|f| f.name().eq_ignore_ascii_case(&c.name)) + { + Some(f) => Expr::Column(datafusion::common::Column::from_name(f.name())), + None => datafusion::logical_expr::lit(datafusion::common::ScalarValue::Null), + }, + )), + _ => Ok(Transformed::no(e)), + }) + .data() +} + pub(crate) fn has_path_match(plan: &LogicalPlan) -> Result { Ok(plan.apply_with_subqueries(|plan| { Ok(match plan { @@ -450,14 +508,21 @@ pub(crate) fn plan_path_match( .iter() .enumerate() .map(|(index, properties)| { - let schema = if index < node.spec.bindings.len() { - &nodes + let (schema, condition) = if index < node.spec.bindings.len() { + (&nodes, None) } else { - &edges + let condition = node.relationship_condition.as_ref(); + ( + &edges, + condition + .map(|c| on_fields(c, edges.fields())) + .transpose()?, + ) }; properties .iter() .map(|(key, value)| col(key.clone()).eq(value.clone())) + .chain(condition) .reduce(Expr::and) .map(|expr| state.create_physical_expr(expr, schema)) .transpose() @@ -472,7 +537,7 @@ pub(crate) fn plan_path_match( let filters = &node.filters[node.spec.bindings.len() + step]; hops.iter() .map(|hop| { - if filters.is_empty() { + if filters.is_empty() && node.relationship_condition.is_none() { return Ok(HopFilter::All); } let table = node.spec.rows(hop.kind).schema(); @@ -490,7 +555,31 @@ pub(crate) fn plan_path_match( .eq(value.clone()), ); } + if let Some(condition) = &node.relationship_condition { + terms.push(on_fields(condition, table.fields())?); + } let filter = terms.into_iter().reduce(Expr::and).expect("filtered"); + if filter.column_refs().is_empty() { + // The table lacks every property the condition reads, so the + // condition is the same for all its edges. + let one = RecordBatch::try_new_with_options( + Arc::new(Schema::empty()), + vec![], + &arrow::array::RecordBatchOptions::new().with_row_count(Some(1)), + )?; + let value = state + .create_physical_expr(filter, &DFSchema::empty())? + .evaluate(&one)? + .into_array(1)?; + let pass = value + .as_boolean_opt() + .is_some_and(|v| v.is_valid(0) && v.value(0)); + return Ok(if pass { + HopFilter::All + } else { + HopFilter::None + }); + } Ok(HopFilter::Where(CompiledFilter::new( &filter, &HashMap::new(), diff --git a/docs/csr.md b/docs/csr.md index aef4939..3956ff6 100644 --- a/docs/csr.md +++ b/docs/csr.md @@ -156,8 +156,8 @@ CSR is built at all: with `use_csr=False` every hop is a join. Named path values and `relationships(path)` need each relationship's identity and properties, which a CSR neighbor list doesn't hold on its own. When every relationship type and direction a named path follows has a CSR, the path walks it from its start node, as an explicit hop does. Each step reads the neighbors of only the -nodes the walk reaches and checks the step's relationship equalities, from an inline `{since: 2020}` or a -`WHERE all(r IN relationships(p) WHERE r.since = 2020)`, on just those edges. Properties are read only for the +nodes the walk reaches and checks the step's relationship conditions, from an inline `{since: 2020}` or a +`WHERE all(r IN relationships(p) WHERE r.since >= 2020)`, on just those edges. Properties are read only for the relationships of the paths returned. An edge's identity is its row in the relationship table, so parallel edges stay distinct, even when a path passes through `collect()` and `UNWIND`. The cost therefore follows the part of the graph the walk reaches rather than the size of the relationship table. diff --git a/docs/cypher.md b/docs/cypher.md index d00186f..6c6d1e6 100644 --- a/docs/cypher.md +++ b/docs/cypher.md @@ -371,9 +371,12 @@ RETURN length(p), nodes(p) expansion for the whole range; the join fallback uses one branch per length. A property map on a variable-length relationship, such as `[:KNOWS*1..3 {since: 2020}]`, must hold for every relationship on the path; a zero-hop match has none to check. Such a path uses the join fallback. - On a named path, `WHERE all(r IN relationships(p) WHERE r.since = 2020)` filters the same way: - equalities on `r` drop a failing relationship during the walk, and other conditions are checked - once each path is complete. + On a named path, `WHERE all(r IN relationships(p) WHERE r.since >= 2020)` filters the same way: + a relationship that fails the condition ends its branch during the walk, so the cost follows the + relationships that pass. This holds for any condition on `r`'s properties, parameters and literals + (comparisons, `IN`, `OR`, `IS NULL`), and for `none(r IN relationships(p) WHERE ...)`. Other + conditions, and `any()`, `single()` or an `all()` under `OR` or `NOT`, are checked once each path + is complete. - **Variable-length alternation** follows each relationship type's configured endpoint labels. With suitable CSR and node indexes, a mixed path such as `[:hasType|isSubclassOf*1..3]` stays in one operator. Named paths also support typed variable-length alternation. diff --git a/docs/internals/operators.md b/docs/internals/operators.md index 4da6fa5..2fa1cc1 100644 --- a/docs/internals/operators.md +++ b/docs/internals/operators.md @@ -286,7 +286,7 @@ and direction the steps follow. The plan scans only the participating node table labels and properties. The walk enumerates trails depth first from each start node, resuming between output batches. A frame reads its node's neighbors and their edge rows from the CSR the first time the walk needs them. An undirected step reads the outgoing and incoming CSR separately, so each edge keeps its stored direction. The step's relationship -equalities are compiled against each relationship table and checked by `EdgeFilterState`, the same rule +conditions are compiled against each relationship table and checked by `EdgeFilterState`, the same rule `CsrExpandExec` uses: fetch the filter columns of just the edges reached and, on a Lance table, switch to one read of the whole column once the edges checked pass 1/256 of the relationship's edges. Both halves of an undirected step share one state, so they count their checks together and read the column once. An edge's identity is its CSR row, @@ -321,8 +321,12 @@ the path, such as `length(p)`, `nodes(p)` or `WITH p AS q`, keeps the value. Path property values are logical expressions, so cached plans bind them before physical planning. The physical operator then builds node predicates against the inventory's node schema, and relationship predicates against the inventory's relationship schema or, on the CSR walk, each relationship table. -The planner adds the equalities of a `WHERE all(r IN relationships(p) WHERE ...)` term to every -relationship's property map, so the walk skips failing edges; the `WHERE` itself still runs. +The planner turns the conjuncts `all(r IN relationships(p) WHERE x)` and `none(... WHERE x)` of the `WHERE` +into one condition every relationship must meet, with `r.key` read as the column `key`. Only conditions on `r`'s +properties, parameters and literals qualify. `PathMatch` ANDs it into each step's relationship predicate, so the +walk skips failing edges; the `WHERE` itself still runs. A property a table lacks reads as null, and a condition +that reads no column of a table is evaluated once for all its edges. Only the condition's parameters are logical +expressions of the node, since DataFusion can't type its columns against the node's inputs. Each execution starts with fresh table scans that can share source batches within that execution. ## `Apply`: correlated CALL subqueries diff --git a/python/python/tests/test_engine_paths.py b/python/python/tests/test_engine_paths.py index 7b93782..d41dcb5 100644 --- a/python/python/tests/test_engine_paths.py +++ b/python/python/tests/test_engine_paths.py @@ -202,8 +202,13 @@ def test_variable_length_property_map_filters_every_hop(use_csr, pattern, expect ("all(r IN relationships(p) WHERE r.day = 5)", [2]), ("all(r IN relationships(p) WHERE r.day = $day AND r.ok)", [2]), ("all(r IN relationships(p) WHERE r.day = 6)", []), - # Not an equality, so it is checked after the walk. ("all(r IN relationships(p) WHERE r.day >= 5)", [2, 3, 4]), + ("all(r IN relationships(p) WHERE r.day < $day + 1)", [2]), + ("all(r IN relationships(p) WHERE r.day <> 6 AND r.ok)", [2]), + ("all(r IN relationships(p) WHERE r.day IN [5, 7])", [2]), + ("all(r IN relationships(p) WHERE r.day = 5 OR r.day = 6)", [2, 3, 4]), + ("none(r IN relationships(p) WHERE r.day = 6)", [2]), + # Not a condition on every relationship, so it is checked after the walk. ("any(r IN relationships(p) WHERE r.day = 6)", [3, 4]), ], ) diff --git a/python/python/tests/test_path_csr_walk.py b/python/python/tests/test_path_csr_walk.py index 3754410..293c556 100644 --- a/python/python/tests/test_path_csr_walk.py +++ b/python/python/tests/test_path_csr_walk.py @@ -55,6 +55,11 @@ f"MATCH p = (a:P)-[:R|S*1..3]->(b:P) " f"WHERE all(e IN relationships(p) WHERE e.day = 0) {PATH}", f"MATCH p = (a:P)-[:R|S*1..2 {{w: 3.0}}]-(b:P) {PATH}", + # S has no `w`, so its edges fail the first and pass the second. + f"MATCH p = (a:P)-[:R|S*1..3]-(b:P) " + f"WHERE all(e IN relationships(p) WHERE e.w < 20 AND e.day IN [0, 2]) {PATH}", + f"MATCH p = (a:P)-[:R|S*1..2]->(b:P) " + f"WHERE none(e IN relationships(p) WHERE e.w > 5 OR e.day = 1) {PATH}", f"MATCH p = (a:P)-[:R {{day: 2}}]->(b:P)-[:R {{day: 2}}]->(c:P) {PATH}", f"MATCH p = (c:C)<-[:L]-(a:P)-[:R*1..2]-(b:P) {PATH}", f"MATCH p = (a:P)-[:R*2..2]->(a) {PATH}", @@ -180,3 +185,29 @@ def test_path_values_are_built_only_when_read(use_csr): assert rows(engine, f"{path} RETURN b.id AS b") == sorted( repr([("b", row["b"])]) for row in engine.execute(ids).to_pylist() ) + + +@pytest.mark.parametrize("use_csr", [False, True]) +@pytest.mark.parametrize( + "condition", + [ + "e.day >= 1", + "e.day <> 1 AND e.w < 15", + "e.w > $w OR e.day IN [0]", + "e.w IS NULL", + "NOT e.day = 2", + ], +) +def test_relationship_conditions_prune_only_failing_paths(use_csr, condition): + # Under OR, all() and none() are checked only after the walk. + engine = CypherEngine(CONFIG, DATA, use_csr=use_csr) + match = "MATCH p = (a:P)-[:R|S*1..3]-(b:P) " + for w in [5.0, 10.0]: # a second binding reuses the cached plan + for kind in ["all", "none"]: + pruned = f"{kind}(e IN relationships(p) WHERE {condition})" + got = engine.execute(f"{match} WHERE {pruned} {PATH}", {"w": w}) + kept = f"{match} WHERE {pruned} OR a.id IS NULL {PATH}" + want = engine.execute(kept, {"w": w}) + assert sorted(map(repr, got.to_pylist())) == sorted( + map(repr, want.to_pylist()) + ), (pruned, w)