Skip to content

perf(#12149): openCypher starts a hop from an unlabelled source at the target a UNIQUE index pins - #12159

Merged
lvca merged 5 commits into
ArcadeData:mainfrom
shaunpatterson:fix/12149-cypher-unlabelled-source-reverse
Nov 23, 2026
Merged

lvca merged 5 commits into
ArcadeData:mainfrom
shaunpatterson:fix/12149-cypher-unlabelled-source-reverse

Conversation

@shaunpatterson

Copy link
Copy Markdown
Contributor

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.

…urce at the target a UNIQUE index pins

- step-based plan: a single fixed-length hop from an unlabelled, unconstrained node to a node pinned on every column of a UNIQUE index (inline map, values may read an UNWIND/WITH row, or WHERE equality/IN over literals and parameters) starts from that node and walks back
- unidirectional and untyped hops, OPTIONAL MATCH and path variables keep the written order
@coderabbitai

coderabbitai Bot commented Nov 16, 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 3 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: e36e8768-7125-45c3-bd9c-5d3692ab3d84
Commits

Reviewing files that changed from the base of the PR and between f691a70 and 155dcca.

Files selected for processing: 2

  • engine/src/main/java/com/arcadedb/query/opencypher/executor/MatchStepBuilder.java
  • engine/src/test/java/com/arcadedb/query/opencypher/CypherUnlabelledSourceReverseIssue12149Test.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

@codacy-production

codacy-production Bot commented Nov 16, 2026 •

Copy link
Copy Markdown

Up to standards ✅

🟢 Issues 0 issues

Results:
0 new issues

View in Codacy

🟢 Metrics 62 complexity

Metric Results
Complexity 62

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.

@mergify

mergify Bot commented Nov 16, 2026 •

Copy link
Copy Markdown
Contributor

This pull request is merged.

@github-actions github-actions Bot added engine Core engine: document/schema API has-issue The PR links an issue it resolves opencypher severity:minor Cosmetic, documentation, edge case, or a workaround exists triage:lgtm PR triage: nothing blocking, ready for a maintainer labels Nov 16, 2026
@github-actions

Copy link
Copy Markdown
Contributor

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

This looks good. I read the diff only and did not run anything.

What it does: In CypherExecutionPlan, a single fixed-length hop now starts from its target when the source is unlabelled and unconstrained, and the target is pinned on every column of a UNIQUE index. It reuses the existing reversed path, so no new execution machinery is added.

Strengths

  • The guards are conservative: OPTIONAL MATCH, a path variable, variable-length or quantified hops, untyped or unidirectional relationships, a NOTUNIQUE key and a labelled source all keep the written order.
  • The updated comment on the reversed entry points keeps the single-relationship invariant visible.
  • The new test class has a regression test for each shape. It checks the PROFILE plan, which node the plan starts from and how many rows it reads, and compares the answers against the same pattern written from the pinned end. It also includes controls that keep the written order.
  • The PR body gives benchmark numbers, and the cases it reports as failing on main also fail on unmodified main.

Minor suggestions (non-blocking)

  • The test asserts plan text such as MATCH NODE (d:Doc) and [index:. This is fragile if the PROFILE output format changes, though it is acceptable for a plan-shape regression.
  • Consider adding a case with a composite UNIQUE index that is only partly pinned, to show the planner keeps the written order. isUniquelyKeyedByWhere already handles this through containsAll, but it is untested.
  • Consider adding a case where the target variable is already bound or reused as the source. This guard is also untested.
  • CLAUDE.md asks for a unique database path per test. The fixed path ./target/databases/cypher-unlabelled-source-reverse-12149 is fine given the drop() in tearDown.

I found no security concerns.

@github-actions github-actions Bot added performance build triage:lgtm PR triage: nothing blocking, ready for a maintainer and removed triage:lgtm PR triage: nothing blocking, ready for a maintainer labels Nov 19, 2026
@github-actions

Copy link
Copy Markdown
Contributor

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

Thanks for the patch. I read the diff and found nothing that blocks a merge. I could not build or run anything, so this is a read-through only.

What it does. MatchStepBuilder.buildMatchStep now reverses a single-hop pattern to start from its target. This applies when the source is unlabelled and unconstrained, and a UNIQUE index pins the target.

Tests. CypherUnlabelledSourceReverseIssue12149Test covers each reversal shape and the written-order controls. It uses the assertThat(...) style, compares answers against the same pattern written from the pinned end, and asserts on the PROFILE plan rather than on wall-clock time.

Suggestions, none blocking:

  1. In setUp, delete any leftover ./target/databases/cypher-unlabelled-source-reverse-12149 before create(), the way other engine tests do. A crashed earlier run would otherwise fail every test in the class.
  2. Add a case where the target has an additional label, or the key is only partly pinned (a composite UNIQUE index with one column bound). Both should keep the written order.
  3. Reversal changes result order for queries with no ORDER BY. That is acceptable under Cypher semantics, but it is worth a line in the PR description.

shaunpatterson added a commit to shaunpatterson/arcadedb that referenced this pull request Nov 22, 2026
@lvca lvca self-assigned this Nov 23, 2026
@lvca lvca added this to the 26.12.1 milestone Nov 23, 2026
lvca added 2 commits November 23, 2026 04:52
…o reads WHERE values of an earlier clause, and keeps the written order when WHERE pins the first node

Builds on the contributor's reversal of a single hop from an unlabelled first node to a node a UNIQUE index pins. With main merged in (the cost-based optimizer now plans a plain MATCH of that shape from the labelled node, issue ArcadeData#11904), the step-based plan is the one left for a MATCH after an UNWIND or a WITH, so the tests follow a WITH 1 AS one to stay on it, as the ArcadeData#11904 tests do, and assert the rows read with an anchored pattern instead of a substring that '11 rows' also satisfies.

- A WHERE equality or IN-list whose values read a variable an earlier clause bound (UNWIND $keys AS k MATCH (x)-[:OF]->(d:Doc) WHERE d.key = k) reverses the hop too: the issue lists it with the inline map, and the node step seeks the index with the value of the row.

- A first node the WHERE clause pins by an equality or IN-list keeps the written order: the node step may seek an index of some type for it, where the walk back from a target with many relationships would read them all.

- Tests: a composite key pinned on one column of two, an extra label, a path variable, a variable-length hop, the first node written again as the last, an edge type whose subtype stores no incoming side, several patterns of one MATCH, a predicate on the first node, a CREATE and a DETACH DELETE after the reversed MATCH, keys that are null or of another kind answered as the written order answers them, and a user denied a vertex type, for whom the three plans (this one, the optimizer's, the pattern written from the pinned end) end the same way. The database of the test is dropped before it is created, so a killed run does not fail the class.
@github-actions github-actions Bot added performance-regression Automated: a nightly or release benchmark got worse triage:lgtm PR triage: nothing blocking, ready for a maintainer and removed triage:lgtm PR triage: nothing blocking, ready for a maintainer labels Nov 23, 2026
@github-actions

Copy link
Copy Markdown
Contributor

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

Summary: This is a planner-only optimization. In the step-based plan, a single fixed-length hop from an unlabelled, unconstrained source now starts from the target when a UNIQUE index pins every column of the target's label. It reuses the existing reversed path. I found no security hazards, no new dependencies and no unrelated changes. The linked issue is severity:minor and this is a performance change, so I kept that level.

What I checked (diff only, nothing was run):

  • The guards are conservative, so the change only fires where reversal is safe:
    • no OPTIONAL MATCH, path variable, variable-length or quantified hop;
    • only typed relationships, and only bidirectional edge types (EdgeType.isBidirectional());
    • no source label, properties, inline WHERE, id filter or WHERE-pinned property;
    • the target must be keyed on all columns of a UNIQUE index that is ready for queries (isReadyForQueries()).
  • The readsOnlyEarlierClauses refactor into valueReadsOnlyEarlierClauses preserves behaviour and is reused for the WHERE form.
  • The tests are thorough:
    • They assert the plan shape under PROFILE and compare answers against the pattern written from the pinned end.
    • They cover null and mixed-type keys, composite keys, a subtype without an incoming side, write-after-match, and a restricted user (ACL).
    • They use assertThat(...) style and have no wall-clock assertions.

Minor nits (non-blocking):

  • The PR body says "5 tests", but the class has about 14 @​Test methods plus a nested ACL class. Update the description.
  • In MatchStepBuilder, the new startsFromUniquelyKeyedTarget call is wrapped in a way that deviates slightly from the surrounding style. Consider adding final to targetNode and the other new locals where it is still possible, per CLAUDE.md.
  • The (" tgt" + nextAnonymousId()) anonymous-variable naming follows existing practice. Confirm it cannot leak into RETURN * projections. The existing bound-target reversal path presumably handles this the same way.

The PR body reports the same pre-existing failures on main (ParallelSafeExpressionsStateTest and CypherCallInTransactionsOnErrorIssue11595Test), which this diff did not cause.

… reversed plan starts from is not projected by RETURN *
@github-actions github-actions Bot removed the triage:lgtm PR triage: nothing blocking, ready for a maintainer label Nov 23, 2026
@lvca

lvca commented Nov 23, 2026

Copy link
Copy Markdown
Member

Follow-up pushed on top of the contributor's commits (main merged in, no force push):

  • Main moved on: the cost-based optimizer now plans a plain MATCH of this shape from the labelled node (openCypher: a pattern with an unlabelled node scans the whole label for a range predicate on the indexed anchor (traditional MATCH NODE seeks only equalities) #11904), so the plan-text assertions of the new test no longer saw the step plan. Every query of the test now follows a WITH 1 AS one, which keeps it on the step-based plan, and the rows read are matched with an anchored pattern. On main's MatchStepBuilder, 11 of the 15 tests fail; the other 4 are controls (written order kept, writes after the reversed MATCH, restricted user).
  • A WHERE equality or IN-list whose values read a variable an earlier clause bound (UNWIND $keys AS k MATCH (x)-[:OF]->(d:Doc) WHERE d.key = k) reverses the hop too. The issue's expected behaviour lists it next to the inline map, and the node step seeks the index with the value of the row.
  • A first node that the WHERE clause pins by an equality or IN-list keeps the written order: the node step may seek an index of some type for it, where the walk back from a target with many relationships would read them all.
  • More cases: composite key pinned on one of two columns, extra label, path variable, variable-length hop, the first node written again as the last, an edge type whose subtype stores no incoming side, several patterns of one MATCH, a CREATE and a DETACH DELETE after the reversed MATCH, null and other-kind keys answered as the written order answers them, and the internal name of the anonymous target not showing up in RETURN *.
  • Restricted user: with a denied vertex type, the reversed plan, the optimizer's plan of the plain MATCH and the pattern written from the pinned end end the same way (a SecurityException on a property read of a denied vertex, the same count for count(x)). Before this change the step plan refused the count(x) statement instead. The edge walk does not read the denied record, so this is the existing behaviour of the other two plans, not a new one.
  • The result order of a MATCH without ORDER BY can change, which Cypher allows.

Tests run on the merged tree: the new class (16), the whole openCypher engine test package without the slow, benchmark and vector lanes (9,722 run, 0 failed), the openCypher TCK suite (3,897 scenarios, 0 failed).

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

Copy link
Copy Markdown
Contributor

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

Thanks for the PR. I read the diff and found no blocking problems.

Security: Nothing hazardous. The change only affects query planning (MatchStepBuilder) and adds a test. There are no new dependencies, no I/O and no reflection. I also checked the diff and PR text for anything aimed at the reviewer and found nothing. The test class covers a restricted user, so a denied type is not read through the reversed walk.

Correctness

  • The new startsFromUniquelyKeyedTarget check is conservative:
    • It skips OPTIONAL MATCH, path variables, variable-length and quantified hops, and untyped or unidirectional relationship types.
    • It skips a source that is labelled, has properties, has an inline WHERE, or is bound already.
    • It skips a source pinned by an id filter or a WHERE equality or IN-list.
    • It requires every column of a UNIQUE, ready index to be pinned on the target.
  • It reuses the existing reversed path and EdgeIndexSeedPlanner.collectWherePredicates.
  • The refactor that extracts valueReadsOnlyEarlierClauses keeps the behaviour of readsOnlyEarlierClauses.
  • The anonymous target name (" tgt" + id) is checked not to leak into RETURN *.

Tests

  • The new test class covers each reversed shape: IN-list, equality, inline key, UNWIND and WITH keys, composite key, incoming arrow, subtype, and several patterns in one MATCH.
  • It also covers each case that keeps the written order: NOTUNIQUE key, unidirectional type, untyped hop, OPTIONAL, path variable, variable-length hop, labelled source.
  • It adds ACL cases and write-after-match cases.
  • It asserts on plan shape and row counts, with no wall-clock assertions, and follows the assertThat(...) style.

Nits (non-blocking)

  • The PR body says "5 tests", but the class has roughly 14. Please update the description.
  • isUniquelyKeyedByWhere and startsFromUniquelyKeyedTarget call database.getSchema() repeatedly. This only runs at plan time, so it is fine.
  • The author reports 4 failures that also occur on unmodified main. They are unrelated to this diff.

LGTM.

@lvca lvca added the pr_approved review-pr: CI LGTM + clean triage + green sandbox tests on the reviewed head label Nov 23, 2026
@lvca
lvca merged commit 998f922 into ArcadeData:main Nov 23, 2026
26 of 31 checks passed
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 performance build performance-regression Automated: a nightly or release benchmark got worse 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