Skip to content

fix(#5490): apply the relationship inline WHERE on variable-length patterns - #5493

Merged
robfrank merged 3 commits into
mainfrom
fix/5490-varlen-rel-inline-where-ignored
Jul 28, 2026
Merged

robfrank merged 3 commits into
mainfrom
fix/5490-varlen-rel-inline-where-ignored

Conversation

@robfrank

Copy link
Copy Markdown
Collaborator

Closes #5490

A relationship inline WHERE on a variable-length pattern was parsed onto the AST but never handed to the traversal engine, so -[r:E*1..1 WHERE r.tag = 'ok']-> returned every row and WHERE false returned every row too. Two producers built a VariableLengthPathTraverser from the relationship pattern and passed only the types, the property map and the hop bounds: ExpandPathStep.createTraverser() (the MATCH executor) and PatternPredicateExpression.evaluateVLPPattern() (the EXISTS {} evaluator). GraphTraverser and its BFS/DFS subclasses had no notion of a per-relationship predicate, so there was nothing for the producers to pass it to. This threads an optional Predicate<Edge> through the traversal package, applied at the same per-edge choke point as the existing property filter and forwarded by VariableLengthPathTraverser to whichever strategy it delegates to.

Semantics: every relationship the path traverses must satisfy the predicate, matching the inline property map and the clause-level all(e IN r WHERE ...) spelling. A test asserts the inline and clause-level spellings agree.

Why prune rather than post-filter: filtering completed paths would be simpler, but under BFS shortest-path semantics it would discard a target whose shortest path fails the predicate instead of finding the longer path that satisfies it.

Performance: a null predicate means unconstrained, so patterns without an inline WHERE do no per-edge evaluation. Enclosing bindings are copied once per source row, not per edge, since a traversal evaluates this for every relationship it walks.

Scope

The issue reported the MATCH shape. I probed every surface that parses a variable-length relationship before fixing, which found a second broken one and two that were already correct:

Surface Before Verdict
MATCH, fixed length correct not affected
MATCH, variable length (*1..1, *1..2, *) predicate ignored broken
MATCH, variable length, property map correct not affected
EXISTS {}, variable length predicate ignored broken
EXISTS {}, variable length, property map correct not affected
Pattern comprehension, variable length correct not affected

Pattern comprehensions were already correct because PatternComprehensionExpression.traverseVariableLength enforces the predicate itself instead of delegating to the shared traverser. That is pinned by a control test so the two implementations cannot drift apart silently.

Test plan

  • Issue5490VarLengthRelInlineWhereTest, 13 methods: 7 fail before the fix, all 13 pass after
    • the reported shape, and WHERE false / WHERE true as conclusive evidence the predicate is reaching the traversal
    • multi-hop: every relationship of the path must satisfy the predicate
    • unbounded * pattern
    • predicate referencing an outer-scope binding (r.w < a.v + 10)
    • parity against the clause-level all(e IN r WHERE ...) spelling
    • both EXISTS {} shapes, inline WHERE and property map
    • controls: fixed length, variable-length property map, pattern comprehension, predicate-free
  • Full com.arcadedb.query.opencypher.** package: 7632 tests, 0 failures
  • All consumers of the traversal classes checked: ExpandPathStep, PatternPredicateExpression, ShortestPathStep are the only ones, all inside the OpenCypher engine and all covered by that run. ShortestPathStep uses only the static matchesPropertyFilter helper, which is untouched.
  • The 3 OpenCypherCustomFunctionTest GraalVM polyglot NoClassDefFoundErrors are pre-existing: reproduced identically on a clean tree at 4aaa90c with the change stashed

Known gaps, not addressed here

  • For a multi-hop variable-length pattern the relationship variable binds to a single edge rather than the list of traversed edges when a predicate reads it. That predates this change; the predicate is evaluated per traversed relationship, which is the semantics implemented here.

…tterns

A relationship inline WHERE on a variable-length pattern was parsed onto the AST
but never handed to the traversal engine, so WHERE false still returned every
row. Two producers built a VariableLengthPathTraverser from the pattern and
passed only the types, the property map and the hop bounds: ExpandPathStep (the
MATCH executor) and PatternPredicateExpression.evaluateVLPPattern (the EXISTS {}
evaluator). GraphTraverser had no notion of a per-relationship predicate, so
there was nothing to pass it to.

Threads an optional Predicate<Edge> through the traversal package, applied at the
same per-edge choke point as the existing property filter, and forwarded by
VariableLengthPathTraverser to the BFS or DFS strategy it delegates to. Both
producers now build it from the pattern's WHERE, copying the enclosing bindings
once per source row so the predicate can reference outer-scope variables.

Pruning during traversal rather than post-filtering completed paths is
deliberate: under BFS shortest-path semantics a post-filter would discard a
target whose shortest path fails the predicate instead of finding the longer
path that satisfies it.

Pattern comprehensions were already correct and are pinned by a control test.
@mergify

mergify Bot commented Jul 28, 2026

Copy link
Copy Markdown
Contributor

Tick the box to add this pull request to the merge queue (same as @mergifyio queue).

  • Queue this pull request

@codacy-production

codacy-production Bot commented Jul 28, 2026 •

Copy link
Copy Markdown

Up to standards ✅

🟢 Issues 0 issues

Results:
0 new issues

View in Codacy

🟢 Metrics 0 complexity

Metric Results
Complexity 0

View in Codacy

🟢 Coverage 91.18% diff coverage · -8.38% coverage variation

Metric Results
Coverage variation ✅ -8.38% coverage variation
Diff coverage ✅ 91.18% diff coverage

View coverage diff in Codacy

Coverage variation details
Coverable lines Covered lines Coverage
Common ancestor commit (4aaa90c) 138789 105147 75.76%
Head commit (f18d3c0) 177857 (+39068) 119847 (+14700) 67.38% (-8.38%)

Coverage variation is the difference between the coverage for the head and common ancestor commits of the pull request branch: <coverage of head commit> - <coverage of common ancestor commit>

Diff coverage details
Coverable lines Covered lines Diff coverage
Pull request (#5493) 34 31 91.18%

Diff coverage is the percentage of lines that are covered by tests out of the coverable lines that the pull request added or modified: <covered lines added or modified>/<coverable lines added or modified> * 100%

NEW Get contextual insights on your PRs based on Codacy's metrics, along with PR and Jira context, without leaving GitHub. Enable AI reviewer
TIP This summary will be updated as you push new changes.

@claude

claude Bot commented Jul 28, 2026

Copy link
Copy Markdown

Review: fix(#5490) apply relationship inline WHERE on variable-length patterns

Nice work. This is a high-quality, well-scoped fix. The diagnosis in the PR body and the docs/5490-*.md note (which follows the existing docs/ per-issue convention) are excellent, and the fix threads the predicate through the traversal package at the same choke point as the existing property filter, which is exactly the right place. I confirmed the behavior against the code:

  • Correctness of the choke point: matchesEdgePredicate is applied in both BreadthFirstTraverser and DepthFirstTraverser right after matchesPropertyFilter, and the BFS iterator here enumerates all in-bounds paths (no single-visit vertex marking), so pruning a bad edge doesn't preclude reaching a target via a longer all-ok path. The matchVariableLengthRequiresEveryRelationshipToSatisfyThePredicate test pins this.
  • Semantics: binding r to each individual traversed relationship for the inline WHERE matches Neo4j's relationship-pattern-predicate semantics, and the parity test against all(e IN r WHERE ...) is a good guardrail.
  • Performance: null-predicate short-circuit keeps predicate-free patterns free of per-edge cost; copying the enclosing scope once per source row (not per edge) is the right call. VariableLengthPathTraverser.delegate() unifying both entry points cleanly prevents the two paths from silently dropping the predicate.
  • Test coverage: strong - WHERE false/WHERE true as conclusive probes, unbounded *, outer-binding reference, both EXISTS {} shapes, and controls for the surfaces that were already correct.

Minor suggestions (non-blocking)

  1. Duplication between the two predicate builders. ExpandPathStep.buildEdgePredicate and PatternPredicateExpression.buildRelationshipPredicate are near-identical: copy row properties into a fresh ResultInternal, rebind the relationship variable per edge, evaluate the WHERE. Since both live in the OpenCypher engine and both feed GraphTraverser.withEdgePredicate, consider extracting a small static helper (e.g. on GraphTraverser or a shared util) so the two can't drift in how they build the scope. The parity is currently only enforced by tests, not by shared code.

  2. pattern.getWhereExpression() inside the lambda. In ExpandPathStep.buildEdgePredicate the getter is re-invoked on every edge; hoisting it into a local final BooleanExpression where = pattern.getWhereExpression(); before the lambda (as PatternPredicateExpression already does) is marginally cleaner and avoids the repeated call on the per-edge hot path.

  3. Thread-safety note (confirmation, not a defect). The captured ResultInternal scope is mutated per edge, which is safe because a fresh traverser + predicate is built per source row and traversal is single-threaded. Worth keeping in mind if var-length traversal is ever parallelized - the mutable shared scope would need revisiting. A one-line comment to that effect wouldn't hurt.

The documented known gap (relationship variable binding to a single edge rather than the list for multi-hop reads) is correctly called out as pre-existing and out of scope.

Overall: correct, well-tested, and consistent with the codebase's conventions. LGTM once you consider the DRY cleanup in (1).

robfrank added 2 commits July 28, 2026 13:27
claude[bot] review on d41bd16 raised three non-blocking points, all applied.

The two predicate builders in ExpandPathStep and PatternPredicateExpression were
near-identical, so the scope-construction rule could drift between the MATCH and
EXISTS spellings with only tests holding them together. Collapsed onto
RelationshipPattern.buildInlineWherePredicate, which already owns both the
relationship variable and the WHERE expression.

Placed there rather than on GraphTraverser as suggested: GraphTraverser is in the
traversal package and knows nothing about expression evaluation, so hosting the
scope construction there would make the traversal layer depend on the AST and the
evaluator.

This also hoists getWhereExpression() out of the per-edge lambda, and the javadoc
records that the returned predicate mutates a captured row and so needs a fresh
instance per worker if variable-length traversal is ever parallelized.
@claude

claude Bot commented Jul 28, 2026

Copy link
Copy Markdown

Code review: PR #5493 - apply relationship inline WHERE on variable-length patterns

Reviewed the diff and the touched traversal/AST classes. This is a tight, well-scoped fix and one of the more carefully argued PRs I have seen. Summary: looks correct, ship-worthy, with a couple of minor notes.

What is good

  • Root cause is right and the fix sits at the right layer. The predicate is threaded to the same per-edge choke point (matchesEdgePredicate right after matchesPropertyFilter) in both BreadthFirstTraverser and DepthFirstTraverser, and VariableLengthPathTraverser.delegate() forwards it to whichever strategy it builds. The null-predicate short-circuit means predicate-free patterns pay nothing per edge, which is good for the hot path.
  • Single builder eliminates drift. Collapsing both producers onto RelationshipPattern.buildInlineWherePredicate is the correct call, and keeping it on RelationshipPattern (which owns the variable and the WHERE) rather than pushing expression evaluation into the traversal package keeps the layering clean.
  • Prune-vs-post-filter reasoning is sound. Under the enumerate-all-in-bounds-paths BFS behavior, pruning a failing edge cannot wrongly exclude a longer satisfying path, since that longer path is separately enumerated. The all(e IN r WHERE ...) parity test is a nice pin on this.
  • Scope handling. Copying enclosing bindings once per source row and rebinding only the relationship variable per candidate edge is the right cost tradeoff, and the thread-safety caveat (fresh predicate per source row, single-threaded traversal) is documented on the builder, so a future parallelization will not silently inherit a shared mutable row.
  • Test coverage is excellent: always-false/always-true as conclusive evidence the predicate reaches the traversal, multi-hop all-edges-must-satisfy, unbounded *, outer-binding reference, clause-level parity, both EXISTS shapes, plus controls for fixed-length/property-map/comprehension/predicate-free. I verified the *1..2 tag predicate expected {7,10} result by hand against the fixture and it is correct.

Minor notes (non-blocking)

  1. docs/5490-varlen-rel-inline-where-ignored.md (146 lines) reads as an internal work/tracking log (Review cycles, claude[bot], gemini-code-assist, Final state: timeout). That is process metadata rather than project documentation, and committing it to docs/ mixes it with user-facing docs. Consider dropping it from the PR (the commit messages and PR description already capture the rationale) or moving it out of docs/.
  2. GraphTraverser.edgePredicate is the one non-final field among otherwise-final traverser state, mutated via the withEdgePredicate setter. Functionally fine given the per-traversal construction pattern, but it opens a mutability window the other fields do not have. Passing it through the constructor would keep the class fully immutable and consistent with the surrounding style, worth it only if it does not ripple too far into the constructor overloads.
  3. Known gap is correctly called out: for multi-hop the relationship variable binds to a single edge rather than the traversed list when a predicate reads it. Agreed this predates the change and the per-relationship semantics implemented here are the sensible interpretation, and it is good that it is documented rather than silently shipped.

Nice work - the probe-before-fix table that surfaced the second broken surface (EXISTS {}) and confirmed the two already-correct ones is exactly the right instinct.

@claude

claude Bot commented Jul 28, 2026

Copy link
Copy Markdown

Review: fix(#5490) apply the relationship inline WHERE on variable-length patterns

Thanks for the thorough writeup and the probing table, it made the review much easier to follow. Overall this is a clean, well-targeted fix: threading an optional Predicate<Edge> through the traversal layer and applying it at the same per-edge choke point as the existing property filter is the right shape, and the null-means-unconstrained design keeps the common path allocation-free and evaluation-free. Nicely done.

I verified the central correctness claim independently: BreadthFirstTraverser.performTraversal() has no global visited set (uniqueness is per-path, only for TRAIL/ACYCLIC), so it really does enqueue every in-bounds path. Pruning a failing edge therefore cannot preclude reaching a target by a longer satisfying path, which is exactly the argument the PR makes for pruning rather than post-filtering. Good.

A few points below, one of which I would like your take on before merge.

1. The PatternPredicateExpression.evaluateVLPPattern change looks untested (please confirm)

The two existsVariableLength* tests use the EXISTS brace form. That form is parsed into ExistsExpression, whose evaluate() (ExistsExpression.java:47-52) re-runs the body as a full subquery via context.getDatabase().query("opencypher", ...), i.e. it goes through the MATCH engine and ExpandPathStep, not through PatternPredicateExpression. So as far as I can tell:

  • existsVariableLengthAppliesTheRelationshipInlineWhere and existsVariableLengthAppliesTheRelationshipPropertyMap actually exercise the ExpandPathStep fix a second time (which is also why the property-map control passes: ExpandPathStep.createTraverser forwards props, whereas evaluateVLPPattern passes null).
  • The evaluateVLPPattern edge-predicate change is reached only by the bare pattern-predicate form, e.g. a WHERE (a)-[r:E*1..2 WHERE r.tag = ...]->(:A) conjunct with no EXISTS keyword, and no test uses that spelling.

The change itself looks correct (it mirrors the ExpandPathStep path), but it would be good to guard it directly with a bare-pattern-predicate test so a future refactor of evaluateVLPPattern cannot silently reintroduce the bug. If I have misread the routing, let me know.

2. buildInlineWherePredicate duplicates the existing matchesInlineWhere

The new RelationshipPattern.buildInlineWherePredicate is essentially identical to the pre-existing PatternPredicateExpression.matchesInlineWhere (PatternPredicateExpression.java:375-388): both build a ResultInternal, copy the outer row's properties, bind the relationship variable, and evaluate. The fixed-length path (matchesRelationship) still uses the private copy. The PR's stated goal is a single definition so the spellings cannot drift, and consolidating the two VLP producers is a real improvement, but the fixed-length path is a third copy of the same rule. Consider having matchesRelationship delegate to relPattern.buildInlineWherePredicate(row, context).test(edge) to finish the consolidation. Non-blocking.

3. Adjacent, pre-existing: evaluateVLPPattern ignores the relationship property map

Related to #1: because evaluateVLPPattern passes null for the edge property filter, a bare pattern-predicate variable-length relationship carrying an inline property map appears to drop the map entirely. This predates your change and is out of scope, but it is in the exact method you touched, so it may be worth a follow-up issue while the context is fresh. (I could not run the suite in this environment to confirm, so please sanity-check.)

Minor

  • The mutable scope reused and rebound per edge in buildInlineWherePredicate is safe under the current single-threaded VLP traversal, and I appreciate that you documented the constraint in the javadoc so a future parallelization will not silently inherit a shared row.
  • Test setup/teardown, AssertJ style, and @BeforeEach/@AfterEach all match the repo conventions.

Nice work overall; the traversal-layer plumbing is clean and the reasoning in the PR body is unusually careful. The main thing I would like resolved before merge is the coverage question in #1.

@robfrank
robfrank merged commit 2dfc3c7 into main Jul 28, 2026
22 of 26 checks passed
@robfrank
robfrank deleted the fix/5490-varlen-rel-inline-where-ignored branch July 28, 2026 11:39
@codecov

codecov Bot commented Jul 28, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 76.47059% with 8 lines in your changes missing coverage. Please review.
✅ Project coverage is 65.15%. Comparing base (4aaa90c) to head (f18d3c0).
⚠️ Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
...dedb/query/opencypher/ast/RelationshipPattern.java 75.00% 0 Missing and 3 partials ⚠️
...uery/opencypher/executor/steps/ExpandPathStep.java 75.00% 1 Missing and 1 partial ⚠️
...uery/opencypher/traversal/DepthFirstTraverser.java 0.00% 2 Missing ⚠️
...ncypher/traversal/VariableLengthPathTraverser.java 83.33% 0 Missing and 1 partial ⚠️
Additional details and impacted files
@@             Coverage Diff              @@
##               main    #5493      +/-   ##
============================================
- Coverage     66.60%   65.15%   -1.46%     
- Complexity        0     1113    +1113     
============================================
  Files          1696     1742      +46     
  Lines        138789   145858    +7069     
  Branches      30065    31226    +1161     
============================================
+ Hits          92447    95032    +2585     
- Misses        33680    37928    +4248     
- Partials      12662    12898     +236     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

robfrank added a commit that referenced this pull request Aug 14, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Cypher: relationship inline WHERE is ignored entirely on variable-length patterns

1 participant