Repository navigation
perf(#11904): a pattern with an unlabelled node is planned by the optimizer from an index on a labelled one - #11916
Conversation
…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.
|
Warning Review limit reachedYou'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. View limit details
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. |
|
This pull request is merged. |
Up to standards ✅🟢 Issues
|
| Metric | Results |
|---|---|
| Complexity | 14 |
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.
|
Triage: 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 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.
I checked the other callers of Tests: Coverage is good.
Suggestions (non-blocking):
1 value(s) redacted. |
…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.
|
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 |
|
Triage: Overall this looks good. It is a performance improvement and the linked issue #11904 is What I checked
Non-blocking suggestions
2 value(s) redacted. |
…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]>
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 byLogicalPlan.hasRepresentableLabelSets, so it ran on the step-based plan, whoseMATCH NODEseeks 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 typeV, 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):shouldUseOptimizeradmits an unlabelled node that a fixed-length relationship reaches (a lone unlabelled node is still refused), andhasRepresentableLabelSetsadmits an unlabelled node that is connected.AnchorSelector.selectAnchornever picks an unlabelled node (it returns null when only unlabelled nodes are left), and neither does the unidirectional re-anchoring invalidateAnchorForUnidirectionalEdges.CypherOptimizerdeclines (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:
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.ExpandPathStepcountscount(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 aWHERE b <> afilter.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:CypherUnlabelledNodeOptimizerIssue11904Test2 of 3 fail (anUnlabelledNodeNoLongerKeepsThePatternFromItsIndex,theSameAnswersAsTheTraditionalPlan: EXPLAIN shows the step plan), and the updatedCypherMultiPatternSharedLabelIssue6322Test.anUnlabelledNodeIsPlannedByTheOptimizerOnlyFromAnIndexfails. 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 returninglabels(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 leadingWITH 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
:Pnodes (UNIQUEid, NOTUNIQUEg) and 120,000:Krelationships. The baseline is the engine jar of maina7304ab2aa, 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.MATCH (p:P)-[:K]->(q) WHERE p.id < 500 RETURN sum(1) AS cMATCH (p:P)-[:K]->(q)-[:K]->(r) WHERE p.id < 500 RETURN sum(1) AS cMATCH (p:P)-[:K]->(q:P)-[:K]->(r:P) WHERE p.id < 500 RETURN sum(1) AS cMATCH (p:P)-[:K]->(q)-[:K]->(r) WHERE p.id = 5 RETURN sum(1) AS cMATCH (q)-[:K]->(p:P) WHERE p.id < 500 RETURN sum(1) AS c(q), every vertex typeMATCH (p:P) WHERE p.id < 500 MATCH (p)-[:K]->(q) RETURN sum(1) AS cMATCH (p:P)-[:K]->(q) WHERE p.id >= 100 AND p.id < 200 RETURN sum(1) AS cMATCH (p:P)-[:K]->(q) WHERE p.g IN [1,2,3] RETURN sum(1) AS cMATCH (p:P)-[:K]->(q) WHERE p.id < 500 RETURN p.id AS a, q.id AS b ORDER BY a, b LIMIT 3MATCH (p:P)-[:K]->(q) WHERE p.id < 30000 RETURN sum(1) AS cMATCH (p:P)-[:K]->(q) RETURN sum(1) AS cMATCH (p:P)-[:K]->(q)-[:K]->(r) RETURN sum(1) AS cOn this server
p.g IN [1,2,3]was already served by the step plan's IN-list seek (2 ms on main).Tests
CypherUnlabelledNodeOptimizerIssue11904Test(3 tests);CypherMultiPatternSharedLabelIssue6322Testupdated as above.-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) andSqlParserRobustnessTest.callsAtTheDeclaredBoundsAreNeverArityErrors(SQL function arity ofcypherrid,fulltext.searchFieldsMore,fulltext.searchIndexMore; checked on the parent commit's sources).