Skip to content

perf(#11904): a pattern with an unlabelled node is planned by the optimizer from an index on a labelled one - #11916

Merged
lvca merged 3 commits into
ArcadeData:mainfrom
shaunpatterson:perf/11904-unlabelled-node-optimizer
Nov 21, 2026
Merged

lvca merged 3 commits into
ArcadeData:mainfrom
shaunpatterson:perf/11904-unlabelled-node-optimizer

Conversation

@shaunpatterson

Copy link
Copy Markdown
Contributor

Fixes #11904.

Why the step plan, and what changed

A pattern with an unlabelled node was refused by CypherExecutionPlanner.shouldUseOptimizer ("optimizer requires labels for physical operators") and by LogicalPlan.hasRepresentableLabelSets, so it ran on the step-based plan, whose MATCH NODE seeks an index for an equality only. Looking at what actually needs the label: only the anchor operators do (a label scan of an unlabelled node would scan the type V, which does not exist). The expansions that reach a node (ExpandAll, VarLengthExpand, GAVExpandAll, the fused GAV chain) already skip their target-label filter when the target has no label. So the reason for the fallback holds for the anchor and not for a node a relationship reaches.

This PR plans such patterns with the optimizer, rather than patching MATCH NODE, because the issue's shapes also need the anchor choice (the pattern written from the unlabelled end, (q)-[:K]->(p:P), started from a scan of every vertex type):

  • shouldUseOptimizer admits an unlabelled node that a fixed-length relationship reaches (a lone unlabelled node is still refused), and hasRepresentableLabelSets admits an unlabelled node that is connected.
  • AnchorSelector.selectAnchor never picks an unlabelled node (it returns null when only unlabelled nodes are left), and neither does the unidirectional re-anchoring in validateAnchorForUnidirectionalEdges.
  • CypherOptimizer declines (falls back to the step plan, as before) a component that has no labelled node, and a component with an unlabelled node whose anchor is a whole-label scan.

Two shapes deliberately keep the step plan:

  • A whole-label scan anchor. The pattern then walks every vertex of the label on either plan, and on main the step plan walked that faster: MATCH (p:P)-[:K]->(q)-[:K]->(r) 382 ms on the step plan against 413 ms for the same chain labelled on the optimizer's plan. So the optimizer takes the pattern only for the index seek, IN seek or range scan a labelled node offers.
  • A variable-length hop into an unlabelled node. The step plan's ExpandPathStep counts count(DISTINCT end) while it walks (perf: count(DISTINCT b) over a variable-length hop is not fused on the step-based Cypher path (unlabeled end node) #10557), which the optimizer's plan does not do with a WHERE b <> a filter.

Not covered (unchanged): a pattern written from an unlabelled end with no index on the labelled node still scans every vertex type on the step plan.

Failing-first

On the parent commit's engine/src/main: CypherUnlabelledNodeOptimizerIssue11904Test 2 of 3 fail (anUnlabelledNodeNoLongerKeepsThePatternFromItsIndex, theSameAnswersAsTheTraditionalPlan: EXPLAIN shows the step plan), and the updated CypherMultiPatternSharedLabelIssue6322Test.anUnlabelledNodeIsPlannedByTheOptimizerOnlyFromAnIndex fails. With the change all pass. That 6322 test asserted the old gate; its comment said it was there so that a change admitting unlabelled nodes would trip over it, so it now asserts the new contract (step plan without an index, optimizer with one, step plan for a pattern with no label or a lone unlabelled node).

Differential test

theSameAnswersAsTheTraditionalPlan: a randomized graph (seeded) of 240 vertices of two types with missing properties on every indexed key, an INTEGER UNIQUE key, NOTUNIQUE INTEGER, STRING and DOUBLE keys, a composite (INTEGER, STRING) index, an undeclared property holding integers, longs, doubles, strings, booleans and nothing, and two edge types. 8 shapes (chain, reverse, two hops with an unlabelled middle, two MATCH clauses, an unlabelled node with an inline map, an untyped relationship returning labels(q), count(*), ORDER BY ... LIMIT) times 17 predicates (<, <=, >, both bounds, reversed operands, equality, IN with a parameter, ranges on each indexed type, STARTS WITH, composite prefix, unindexed mixed-type property) times 13 bound values (-1, 0, 5, 37, 150, 1000, 10.5, 7L, 'zzz', 'b', '10', true, null): 1,768 statements. Each is compared with the same statement after a leading WITH 1 AS one, which keeps it on the step plan. Each shape and predicate also asserts which plan runs: the optimizer for an indexed predicate, the step plan for the unindexed one.

End to end

Server with 60,000 :P nodes (UNIQUE id, NOTUNIQUE g) and 120,000 :K relationships. The baseline is the engine jar of main a7304ab2aa, one commit behind this branch's base (04efccfcd3, #11615, which touches no openCypher code); the other arm is this branch's engine jar, swapped in the same container. Each cell is the median of 3 alternating rounds of the per-round median of 5 runs after 6 warm-up runs. Answers are identical in every round.

statement anchor on this PR main this PR answer
MATCH (p:P)-[:K]->(q) WHERE p.id < 500 RETURN sum(1) AS c index range scan 38.2 ms 3.0 ms 974
MATCH (p:P)-[:K]->(q)-[:K]->(r) WHERE p.id < 500 RETURN sum(1) AS c index range scan 40.4 ms 5.0 ms 1961
MATCH (p:P)-[:K]->(q:P)-[:K]->(r:P) WHERE p.id < 500 RETURN sum(1) AS c index range scan (labelled, CBO on both) 6.0 ms 5.6 ms 1961
MATCH (p:P)-[:K]->(q)-[:K]->(r) WHERE p.id = 5 RETURN sum(1) AS c index seek (step plan seeks it on main too) 1.8 ms 1.4 ms 3
MATCH (q)-[:K]->(p:P) WHERE p.id < 500 RETURN sum(1) AS c index range scan; main starts from (q), every vertex type 189.6 ms 2.6 ms 967
MATCH (p:P) WHERE p.id < 500 MATCH (p)-[:K]->(q) RETURN sum(1) AS c index range scan 41.1 ms 2.5 ms 974
MATCH (p:P)-[:K]->(q) WHERE p.id >= 100 AND p.id < 200 RETURN sum(1) AS c index range scan 45.6 ms 2.1 ms 183
MATCH (p:P)-[:K]->(q) WHERE p.g IN [1,2,3] RETURN sum(1) AS c IN seek (step plan seeks it on main too) 2.1 ms 2.4 ms 377
MATCH (p:P)-[:K]->(q) WHERE p.id < 500 RETURN p.id AS a, q.id AS b ORDER BY a, b LIMIT 3 index range scan 42.5 ms 4.8 ms 3 rows
MATCH (p:P)-[:K]->(q) WHERE p.id < 30000 RETURN sum(1) AS c index range scan 67.4 ms 70.0 ms 59696
MATCH (p:P)-[:K]->(q) RETURN sum(1) AS c label scan: step plan on both 114.6 ms 107.1 ms 120000
MATCH (p:P)-[:K]->(q)-[:K]->(r) RETURN sum(1) AS c label scan: step plan on both 466.1 ms 460.0 ms 240547

On this server p.g IN [1,2,3] was already served by the step plan's IN-list seek (2 ms on main).

Tests

  • New CypherUnlabelledNodeOptimizerIssue11904Test (3 tests); CypherMultiPatternSharedLabelIssue6322Test updated as above.
  • Engine tests run: the whole openCypher package (-Dtest=com/arcadedb/query/opencypher/**/*Test -DexcludedGroups=slow, 8,619 tests) plus the 88 test classes outside it that run Cypher (graph, olap, index, sql, function, schema): 11,665 run, 11,652 passed, 11 skipped, 2 failed. Both failures also fail on the parent commit: ParallelSafeExpressionsStateTest.theWhitelistedExpressionsHoldNoUnsafeMutableState (InExpression.lastSeenIdentity) and SqlParserRobustnessTest.callsAtTheDeclaredBoundsAreNeverArityErrors (SQL function arity of cypherrid, fulltext.searchFieldsMore, fulltext.searchIndexMore; checked on the parent commit's sources).

…by the optimizer from an index on a labelled one

A pattern with a node that has no label was always run by the step-based plan,
whose MATCH NODE seeks an index for an equality only: a range on the labelled
node's indexed property scanned its whole label, and a pattern written from the
unlabelled end scanned every vertex type. The optimizer now admits an unlabelled
node a fixed-length relationship reaches: the anchor is chosen among the labelled
nodes and the unlabelled node is reached by an expansion that accepts any vertex.
It plans such a pattern when the anchor is an index seek or range scan; a pattern
it would start from a whole-label scan, one with no labelled node, a lone
unlabelled node, or a variable-length hop into one keeps the step-based plan.
@coderabbitai

coderabbitai Bot commented Nov 15, 2026 •

Copy link
Copy Markdown

Warning

Review limit reached

You've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository.

Next included review available in 35 minutes.

Check out review usage here.

View limit details

Limit details: You’ve used all 4 included reviews currently available.

Learn how review limits work.

Review configuration:

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: defaults
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 0df28d42-9fad-4bd3-8e79-c6997a49b15d
Commits

Reviewing files that changed from the base of the PR and between c6492b1 and 8936228.

Files selected for processing: 12

  • engine/src/main/java/com/arcadedb/query/opencypher/executor/operators/AbstractPhysicalOperator.java
  • engine/src/main/java/com/arcadedb/query/opencypher/executor/operators/EdgeIndexSeek.java
  • engine/src/main/java/com/arcadedb/query/opencypher/executor/operators/IndexNestedLoopJoin.java
  • engine/src/main/java/com/arcadedb/query/opencypher/executor/operators/NodeIndexRangeScan.java
  • engine/src/main/java/com/arcadedb/query/opencypher/executor/operators/NodeIndexSeek.java
  • engine/src/main/java/com/arcadedb/query/opencypher/optimizer/AnchorSelector.java
  • engine/src/main/java/com/arcadedb/query/opencypher/optimizer/CypherOptimizer.java
  • engine/src/main/java/com/arcadedb/query/opencypher/optimizer/plan/LogicalPlan.java
  • engine/src/main/java/com/arcadedb/query/opencypher/planner/CypherExecutionPlanner.java
  • engine/src/test/java/com/arcadedb/query/opencypher/CypherMultiPatternSharedLabelIssue6322Test.java
  • engine/src/test/java/com/arcadedb/query/opencypher/CypherUnlabelledNodeOptimizerAclIssue11904Test.java
  • engine/src/test/java/com/arcadedb/query/opencypher/CypherUnlabelledNodeOptimizerIssue11904Test.java
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

@mergify

mergify Bot commented Nov 15, 2026 •

Copy link
Copy Markdown
Contributor

This pull request is merged.

@codacy-production

codacy-production Bot commented Nov 15, 2026 •

Copy link
Copy Markdown

Up to standards ✅

🟢 Issues 0 issues

Results:
0 new issues

View in Codacy

🟢 Metrics 14 complexity

Metric Results
Complexity 14

View in Codacy

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.

@github-actions

Copy link
Copy Markdown
Contributor

Triage: triage:lgtm · severity:minor · areas: opencypher, engine · has-issue

Summary: This PR lets the OpenCypher optimizer plan patterns that contain an unlabelled node, but only when a labelled node gives it an index seek or range scan to start from. That avoids the step plan's whole-label scan, or its scan of every vertex type. It's a performance improvement, which makes it severity:minor, matching #11904.

Security: I found nothing hazardous. The diff touches only planner and optimizer logic and tests. It adds no dependencies, I/O or reflection, and nothing in it tries to steer the reviewer.

Correctness: The gating looks sound.

  • AnchorSelector skips unlabelled nodes and returns null when none are left.
  • CypherOptimizer handles the null by falling back to the step plan.
  • CypherOptimizer also falls back to the step plan when the anchor is a whole-label scan and the component has an unlabelled node.
  • validateAnchorForUnidirectionalEdges skips unlabelled nodes.
  • shouldUseOptimizer keeps the step plan for variable-length hops (perf: count(DISTINCT b) over a variable-length hop is not fused on the step-based Cypher path (unlabeled end node) #10557) and for lone unlabelled nodes.
  • LogicalPlan.hasRepresentableLabelSets now admits an unlabelled node only if it is connected.

I checked the other callers of selectAnchor in the diff only. It's worth confirming that none of them dereference the result without a null check.

Tests: Coverage is good.

Suggestions (non-blocking):

  • theSameAnswersAsTheTraditionalPlan runs about 1,768 statements, each executed twice plus EXPLAINs. If it takes more than a few seconds in CI, consider @​Tag("slow") per CLAUDE.md.
  • hasUnlabelledNode re-walks the component variables. This is fine at planning time and not a hot path.
  • The 11 openCypher/SQL failures in the PR body are said to be pre-existing on the parent commit, so I ignored them.

1 value(s) redacted.

@lvca lvca self-assigned this Nov 20, 2026
@lvca lvca added this to the 26.12.1 milestone Nov 20, 2026
…pe the user may not read, and the unlabelled-node tests cover unidirectional types, writes and edge seeds

More statements reach the optimizer's index anchors now that a pattern with an unlabelled node is planned from the index of a labelled one. A walk of the buckets of a type refuses a user who may not read it whatever the keys are, while an anchor loads a record only when the index holds a key in the bounds, so it refused only then and told the user whether the type holds one. The user's own planning counts the type and is refused, falling back to the traditional plan, but the cache of Cypher plans belongs to the database: a plan built for a user who may read the type is run as it is by one who may not. NodeIndexSeek, NodeIndexRangeScan, IndexNestedLoopJoin and EdgeIndexSeek now ask the read permission of the types they answer for, subtypes included, once per execution (AbstractPhysicalOperator.requireReadable), in the operator and not in the plan so that a cached plan is covered.

The single-node branch of the optimizer declines when no labelled node is left, instead of dereferencing a null anchor that hasRepresentableLabelSets keeps out today.

Tests: CypherUnlabelledNodeOptimizerAclIssue11904Test runs each of 8 statements as a user who may read every type first, then as one who may not, over keys the type holds and keys it does not; it fails on the previous head. CypherUnlabelledNodeOptimizerIssue11904Test gains a unidirectional edge type, an edge index seeded from an unlabelled endpoint, statements that write after the MATCH (compared on the graph they leave) and a set of everyday shapes around the unlabelled node, all against the traditional plan. The permission gaps of the traditional plan's own seeks are ArcadeData#12663, the range seek of MATCH NODE after UNWIND, WITH and OPTIONAL MATCH is ArcadeData#12664.
@github-actions github-actions Bot removed the triage:lgtm PR triage: nothing blocking, ready for a maintainer label Nov 20, 2026
@lvca

lvca commented Nov 20, 2026

Copy link
Copy Markdown
Member

Review pass on 8936228 (main merged in, no conflicts):

Run on this head: the whole openCypher package (585 classes, 9,546 tests) green, and 60 connected classes outside it (graph, GAV, index, query, schema, per-type ACL): 2,098 run, 1 failure in QueryHeapBudgetIssue8591Test.concurrentQueriesCannotHoldMoreThanTheBudget (SQL only, a JVM-wide heap budget race), which passes alone.

@github-actions github-actions Bot added the triage:lgtm PR triage: nothing blocking, ready for a maintainer label Nov 20, 2026
@github-actions

Copy link
Copy Markdown
Contributor

Triage: triage:lgtm · severity:minor · areas: opencypher, engine · has-issue

Overall this looks good. It is a performance improvement and the linked issue #11904 is severity:minor.

What I checked

  • The planner gates are consistent. shouldUseOptimizer and hasRepresentableLabelSets admit an unlabelled node that a fixed-length relationship reaches. AnchorSelector and validateAnchorForUnidirectionalEdges never anchor on an unlabelled node. CypherOptimizer returns null, so the step plan is used, when there is no labelled anchor or when the anchor is a whole-label scan. These changes agree with each other.
  • Security: the plan cache belongs to the database, so a plan built for one user can run for another. Each index anchor (NodeIndexSeek, NodeIndexRangeScan, IndexNestedLoopJoin, EdgeIndexSeek) now calls requireReadable once per execution, including the subtype buckets. This stops an index anchor from revealing whether a denied type holds a key. [redacted] covers this for cached plans, with bounds above and below the stored keys.
  • Tests: there is a failing-first regression test, a seeded differential test against the step plan, an ACL test, and an updated 6322 test. The tests use no wall-clock assertions and no hard-coded ports, and they use the assertThat(...) style.

Non-blocking suggestions

  • [redacted] runs about 1,768 statements, each twice. If it takes more than a few seconds in CI, add @​Tag("slow") at class level, as CLAUDE.md asks.
  • requireReadable makes a schema lookup and a bucket-permission check on every execution of each index anchor. That cost is small, but if an anchor is executed repeatedly inside a nested plan, consider caching the result for the execution.

2 value(s) redacted.

@lvca lvca added the pr_approved review-pr: CI LGTM + clean triage + green sandbox tests on the reviewed head label Nov 20, 2026
@lvca
lvca merged commit 9f2359e into ArcadeData:main Nov 21, 2026
28 of 31 checks passed
lvca added a commit that referenced this pull request Nov 23, 2026
…e target a UNIQUE index pins (#12159)

Fixes #12149.

### What changes

In the step-based plan (`CypherExecutionPlan`), a pattern of one
fixed-length hop now starts from its target when two things hold:

- **The source is unlabelled and unconstrained.** It has no label, no
property map, no inline `WHERE`, no id predicate, and is not bound
earlier. Starting from it scans every vertex of every type, once per row
after an `UNWIND` or `WITH`.
- **The target is pinned on every column of a UNIQUE index of its
label.** The pin comes either from its inline map, whose values may be
literals, parameters, or a variable an earlier clause bound (`UNWIND
$keys AS k MATCH (x)-[:OF]->(:Doc {key: k})`), or from the `WHERE`
clause, as equalities or `IN`-lists over literals and parameters.

The step that starts the pattern then finds the target through that
index (per row when the key comes from the row), and the hop walks its
relationships backwards. The existing reversal path does this; until now
it was reached only for a target already bound by an earlier clause. The
pattern keeps its written order for:

- a relationship with no type or a unidirectional type, because no
vertex stores its incoming side;
- an OPTIONAL MATCH;
- a path variable;
- a NOTUNIQUE key;
- a labelled source.

Relation to #11904 / #11916: that PR lets the cost-based optimizer take
patterns with an unlabelled node when a labelled node has an index seek,
which also fixes the two plain `MATCH` forms below. The two changes are
independent, and when both are merged the optimizer simply takes those
statements first. This change covers what reaches the step-based plan
regardless, the `UNWIND ... MATCH` / `WITH ... MATCH` forms in
particular. On the #11916 branch, `UNWIND $keys AS k MATCH
(x)-[:OF]->(:Doc {key: k})` still runs `MATCH NODE (x) (400,200 rows)`.

### End to end

Graph of the issue at 100k items (100 `Doc` with a UNIQUE `key`, 100,000
`Item -[:OF]-> Doc`, 100,000 unrelated `Other`; 200,100 vertices), `keys
= [7, 8]`. Standalone server built from main `2eb615cd26`. The only
difference between the two runs is the engine jar. Median of 5 over
HTTP:

| Form | main | this PR | answer |
|---|---|---|---|
| `MATCH (x)-[:OF]->(d:Doc) WHERE d.key IN $keys RETURN labels(x)[0],
count(x)` | 336.2 ms | 9.4 ms | Item, 2000 |
| `MATCH (x)-[:OF]->(d:Doc {key: 7}) RETURN ...` | 130.8 | 3.6 | Item,
1000 |
| `UNWIND $keys AS k MATCH (x)-[:OF]->(:Doc {key: k}) RETURN ...` |
291.1 | 4.1 | Item, 2000 |
| `MATCH (d:Doc)<-[:OF]-(x) WHERE d.key IN $keys RETURN ...` (written
from `d`, reference) | 3.9 | 3.2 | Item, 2000 |
| `MATCH (x:Item)-[:OF]->(d:Doc) WHERE d.key IN $keys RETURN ...`
(labelled source, reference) | 3.7 | 4.5 | Item, 2000 |

### Tests

- New `CypherUnlabelledSourceReverseIssue12149Test` (5 tests). Each test
asserts, under PROFILE, which node the plan starts from (the first
`MATCH NODE` step, its `[index: ...]` and the rows it read) and checks
the answer against the same pattern written from the pinned end. The
shapes covered: `IN $keys`, an inline literal key, a key from an
`UNWIND` row and from a `WITH` row, an incoming arrow, and the cases
that keep the written order (NOTUNIQUE key, unidirectional type, untyped
hop, OPTIONAL MATCH), with their answers. On main, 4 of the 5 fail. The
one that passes is the written-order control.
- Whole openCypher test package
(`-Dtest='com/arcadedb/query/opencypher/**/*Test'
-DexcludedGroups=slow,benchmark,vector`): 8,705 run. The only failures
are
`ParallelSafeExpressionsStateTest.theWhitelistedExpressionsHoldNoUnsafeMutableState`
and 3 errors in `CypherCallInTransactionsOnErrorIssue11595Test`, which
fail the same way on unmodified main `2eb615cd26`.

---------

Co-authored-by: lvca <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

engine Core engine: document/schema API has-issue The PR links an issue it resolves opencypher pr_approved review-pr: CI LGTM + clean triage + green sandbox tests on the reviewed head severity:minor Cosmetic, documentation, edge case, or a workaround exists triage:lgtm PR triage: nothing blocking, ready for a maintainer

Projects

None yet

2 participants