Skip to content

fix(#6338, #6334, #6328, #6336, #6335): a label disjunction means the same thing wherever the node sits, and the star is what the parser wrote rather than what it is called - #6348

Merged
lvca merged 4 commits into
mainfrom
fix/issues-6338-6336-6335-6334-6328
Aug 18, 2026
Merged

lvca merged 4 commits into
mainfrom
fix/issues-6338-6336-6335-6334-6328

Conversation

@lvca

@lvca lvca commented Aug 18, 2026 •

Copy link
Copy Markdown
Member

Fixes #6338, #6334, #6328, #6336, and settles #6335.

Five small openCypher issues that came out of the reviews of #6322 and #6326. Two of them are the same shape - a fact about a query that two places decided separately and disagreed about - so both are fixed by giving that fact one home rather than by patching the disagreeing site.

#6338 - a label disjunction on an expanded node matched nothing

(y:A|B) written on a node a relationship expands into rejected every row, silently, while the same disjunction on the pattern anchor matched. An empty result reads as "no such data" rather than as a bug, so this is the kind of defect that does not get reported.

Three things in MatchRelationshipStep were wrong, not one:

where what it did what it should do
matchesTargetLabel(Vertex) ANDed the alternatives OR them for a disjunction
the GAV bucket-id fast path tested getLabels().get(0) only test the whole list
targetLabelsExistInSchema required every alternative to name an existing type a disjunction needs only one

The third is its own silent-empty: (y:NoSuchLabel|Topic) short-circuited the step to nothing before the scan started. An alternative that matches nothing is not a filter that matches nothing.

Rather than fix three call sites, the meaning of a disjunction now lives in one place - Labels.matches(vertex|type, labels, disjunction) and Labels.canMatchInSchema(...) - and the five copies that existed (MatchNodeStep x2, ExpandPathStep, MatchRelationshipStep, and the WHERE-side LabelCheckExpression) all route through it. The type-level overload keeps the bucket-id path free of a record load.

The optimizer is not implicated: shouldUseOptimizer declines a disjunction on a node with incident relationships, because ExpandAll/ExpandInto carry a single targetLabel. Verified, not assumed.

A second root cause, found while acting on review round 2. The review pointed at four more copies of the AND-only check; tracing them found one cause underneath rather than four bugs. CypherExpressionBuilder.parseNodePattern built every node pattern in expression position with the disjunction flag hardcoded to false, so a pattern comprehension or a pattern predicate received (y:A|B) already indistinguishable from (y:A:B), and no executor-side fix could recover what the parser had discarded. It now reads the flag off the grammar through ParserUtils.isLabelDisjunction, as the MATCH-side builder does. Two shapes were observably wrong:

query was expected
[(a)-->(y:Author|Topic) | y.k] [] ["t1"]
exists((a)-->(:Author|Topic)) no row the row

the second while the block form EXISTS { (a)-->(:Author\|Topic) } answered correctly all along, because it takes the subquery path - two spellings of one predicate disagreeing about what a disjunction means.

MERGE was worse than an under-count. MERGE (n:A|B {k:'x'}) ANDed its match, missed an existing :B node, and then created a second one under an invented A~B composite type: a silent duplicate, from the one clause whose purpose is not to make one. CREATE (n:A|B) invented the same composite. Neo4j refuses a label expression in both, for the reason that settles it - a disjunction says which labels a node may have, and no node a write produces satisfies "A or B" without picking one. Both are now refused, with a message naming the spelling that does mean something.

The refusal keys on the disjunction flag, not on the label count: collectStaticLabels leaves a dynamic $(expression) alternative out of the static list, so CREATE (n:Author|$('Topic')) carries a single static label and slipped past a count-based guard - the shape where a write acting on "A or B" is least defensible, the second label not being known until the query runs.

Filed as #6352 rather than widened into this PR, being a different defect in a path none of these five issues reach: PatternComprehensionExpression.traverseUncorrelatedStart picks getLabels().get(0) as its scan root, so an unbound comprehension start node with a disjunction under-scans ([(y:Author|Topic)-->() | y.k] gives ["a1"] where the equivalent MATCH gives ["a1","t1"]), and a missing first alternative empties the result outright.

#6334 - WITH n AS \*`was mistaken forWITH *` (regression from #6326)

applyProjectionToScope decided an item was the star by comparing its resolved name to "*". A user can write a variable called `*`, so WITH n AS \*`` was read as a star: the incoming scope was forwarded instead of being reset to the one name projected, and the alias itself was never projected at all.

The issue suggested keying on the expression type. That leaves the bare WITH `*` ambiguous, so this goes one step further: being the star is now a property of the item. ReturnClause.ReturnItem.star() is the only thing that builds one - the parser has exactly three sites - and isStar() is the only thing that asks. Every name-based test moved over: the scope application, WithStep's projection, the variable-projection strip, isReturnAll(), the referenced-variable walk, and five sites in the semantic validator. No spelling of a user variable can now be confused for the star.

#6328 - REMOVE did not update the other aliases of the same node

SET points every alias in the row that binds the same record at the updated document; REMOVE replaced only the alias it was given, so REMOVE n.p left m.p reporting the removed value while SET n.p = null - the same write, spelled differently - answered null for both. Cypher has one binding per node per row.

The helper moved out of SetStep into RowAliases, shared by both steps the way #6326 gave them one shared LabelReplacements. It deliberately does not descend into paths/lists/maps, and says why: there the record is alive and merely older, not deleted, so the walk would be charged to every row of every SET to fix a stale read in an unusual shape.

#6336 - EagerDistinctCollectOptionalMatchStep deleted

296 lines nothing constructs. git log --follow answers the question the issue asked: it was dead from birth. It landed in the same commit as the fix for #3218, which took a different route entirely (CypherFunctionFactory + AggregationStep), and nothing has referenced it since. docs/5789-...md, which had flagged it as dead code to keep in step with a DISTINCT fix, is updated to say it is gone.

#6335 - a label write is O(degree) and changes RIDs; now it says so

Not a defect - the cost of the model, and it deserved a decision rather than being inherited. A label is a type, a type is a bucket, and a record's type comes from the bucket it lives in, so SET n:Label cannot edit metadata: it rewrites the vertex under the new type, re-creates every incident edge in both directions (mutating each neighbour's edge list), and hands the vertex and all of its edges new RIDs. On a supernode that is the difference between a millisecond and a stall, and it undoes the locality the striping/append-merge work builds.

The two real fixes are both out of scope for this PR and are recorded as such in docs/6335-cypher-label-write-cost.md: modelling extra labels as a property is the right answer and its own epic, and a bulk edge move would cut the constant but neither the complexity nor the RID churn. What was actually broken is that the cost was silent, so:

  • LabelReplacements.replace() counts the edges it migrates - free, it walks them anyway - and logs a WARNING naming the node, both types and the count above arcadedb.opencypher.labelWriteDegreeWarning (default 10000, 0 disables). A stall that has already happened now has a line in the log that explains it.
  • arcadedb.opencypher.labelWriteDegreeLimit refuses the write above a degree, checked before any record moves. Off by default (0): the rewrite is slow rather than wrong, and a query that merely takes too long should not start failing on upgrade. Enabling it costs one extra edge-list walk per label write.
  • The cost and the RID change are now in the javadoc of the method that pays them.

Tests

Four new classes, each verified to fail without its fix (temporarily reverted, run, restored):

  • CypherLabelDisjunctionOnExpandedNodeIssue6338Test - the disjunction in each position of a chain (anchor, intermediate, final), since only the anchor was covered before; plus a variable-length target, an alternative absent from the schema, and a conjunction that must still require every label. 3 of 7 failed before the fix.
  • CypherBacktickedStarAliasIssue6334Test - the alias case, the alias being projected, the alias forwarded onwards, the real star still forwarding (alone and combined with a projection), and RETURN *. 3 of 7 failed before.
  • CypherRemovePropertyAliasIssue6328Test - two aliases in one row, the same node reached again on a later row via UNWIND, SET n.p = null answering identically, persistence, and a no-op removal leaving the other alias alone. 2 of 5 failed before.
  • CypherLabelWriteDegreeGuardIssue6335Test - limit off by default, refusal above it with nothing moved, REMOVE guarded the same way, a write at the limit allowed, and crossing the warning threshold reporting without refusing.

Green: the full engine unit suite (12487 tests), the openCypher package (4665 after the tests added across review rounds), and the openCypher TCK suite (3897) - the TCK is what pins the CREATE/MERGE refusal as spec behaviour rather than a preference.

One unrelated failure appeared in a single run and is not from this change: Issue6301AlgoSteinerTreeWeightAlignmentTest.anActiveOverlayDoesNotLendItsWeightsToTheWrongEdges. It calls AlgoBellmanFord.execute() directly with a BasicCommandContext - no Cypher parsing, no MATCH, no projection - and depends on JVM-global GraphAnalyticalView overlay state shared across test classes. It passes in isolation, at algo-package scope, and in the re-run of the same wide selection.

Review rounds

Three rounds, every point acted on:

  1. checkDuplicateAliases still decided the star by name - the one site the isStar() sweep missed, and now a real collision since a column can legitimately be named `*`. The degree guard measured with countEdges(BOTH), which counts a self-loop twice while the migration re-creates it once, so the limit refused on a number the warning would never print; countEdgesToMigrate() mirrors the migration's own traversal. The WARNING was never asserted, so deleting the log call kept every test green.
  2. Four more copies of the AND-only label check - which led to the parser root cause and the MERGE duplicate above.
  3. The size() > 1 guard on the CREATE/MERGE refusal, which turned out to be a hole rather than dead defensiveness (the dynamic-label shape above). Plus two readability notes now in the code: the sequential-execution assumption behind the CapturingLogger swap, and why RowAliases does not need to consult LabelReplacements' map.

Every fix in every round is pinned by a test verified to fail without it, by temporarily reverting the fix and re-running.

@lvca lvca self-assigned this Aug 18, 2026
@mergify

mergify Bot commented Aug 18, 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 Aug 18, 2026 •

Copy link
Copy Markdown

Up to standards ✅

🟢 Issues 0 issues

Results:
0 new issues

View in Codacy

🟢 Metrics -42 complexity

Metric Results
Complexity -42

View in Codacy

🟢 Coverage 93.55% diff coverage · -6.54% coverage variation

Metric Results
Coverage variation ✅ -6.54% coverage variation
Diff coverage ✅ 93.55% diff coverage

View coverage diff in Codacy

Coverage variation details
Coverable lines Covered lines Coverage
Common ancestor commit (2304fba) 160517 127366 79.35%
Head commit (adc7e15) 192752 (+32235) 140330 (+12964) 72.80% (-6.54%)

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 (#6348) 124 116 93.55%

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 Aug 18, 2026

Copy link
Copy Markdown

Review

Overall this is a clean, well-scoped set of fixes. Consolidating label-disjunction semantics into Labels.matches/canMatchInSchema and moving the alias-propagation helper into RowAliases are good calls - they replace several copies of subtly-different logic with one, which is exactly what let #6338 and #6328 happen in the first place. The regression tests are thorough (each documented as verified to fail pre-fix), and the #6335 doc/warning/limit design (opt-in refusal, always-on but cheap counting) is a sensible way to make an inherent cost visible without breaking existing queries on upgrade.

A few things worth a look:

1. CypherSemanticValidator.checkDuplicateAliases still special-cases the literal "*" (medium)

In engine/src/main/java/com/arcadedb/query/opencypher/parser/CypherSemanticValidator.java (~line 1976-1987):

String name = item.getAlias();
if (name == null && item.getExpression() instanceof VariableExpression)
  name = ((VariableExpression) item.getExpression()).getVariableName();
if (name != null && !"*".equals(name)) {
  if (!seen.add(name))
    throw new CommandParsingException("ColumnNameConflict: ...");
}

This is exactly the class of bug #6334 fixes elsewhere in this same file (deciding whether an item is the star by comparing a name to "" instead of asking item.isStar()), but this call site wasn't converted. Since a projection can now legitimately be aliased to the literal string * via a backticked alias, two return items each aliased to backtick-star (different expressions, same alias) silently skip the duplicate-column check instead of throwing ColumnNameConflict, because the guard excludes any item whose alias happens to be "" - real star or not. Worth switching this to item.isStar() the same way the rest of the file was, for consistency with the PR's stated goal ("no spelling of a user variable can now be confused for the star").

2. Degree guard's pre-check double-counts self-loops relative to what's actually migrated (minor)

In LabelReplacements.replace() (engine/.../executor/LabelReplacements.java):

final long degree = vertex.countEdges(Vertex.DIRECTION.BOTH);
if (degree > limit) throw ...

GraphEngine.countEdges(BOTH) sums the OUT edge-list count and the IN edge-list count independently, so a self-loop is counted twice. But the migration loop right below explicitly migrates a self-loop only once (per its own comment: "Outgoing first, so a self-loop is migrated exactly once"). For a vertex with self-loops, the pre-check degree (used for the labelWriteDegreeLimit refusal) will be higher than migratedEdges (the number actually logged for the warning). Not unsafe - it just makes the limit slightly more conservative than the real cost - but it's an inconsistency in a feature whose whole point is to report the true cost accurately, and it isn't exercised by any test (the Hub/Leaf fixture in CypherLabelWriteDegreeGuardIssue6335Test has no self-loops).

3. Test coverage gap: the WARNING log itself is never asserted (minor)

crossingTheWarningThresholdReportsWithoutRefusing in CypherLabelWriteDegreeGuardIssue6335Test only checks that the write still succeeds when the warning threshold is crossed; it doesn't assert that LogManager actually received a WARNING record. As written, deleting the LogManager.instance().log(...) call entirely would not fail any test. Might be worth capturing/asserting the log call if there's an easy way to hook LogManager in a test here, since "silent" is the exact failure mode this whole issue is about.

None of these block the PR - #1 is a legitimate small bug worth a follow-up (or a one-line fix here), and #2/#3 are minor precision/coverage notes.

@lvca lvca added this to the 26.9.1 milestone Aug 18, 2026
@claude

claude Bot commented Aug 18, 2026

Copy link
Copy Markdown

Review

Nice, well-documented PR overall — the Labels.matches()/canMatchInSchema() consolidation is a good move (one source of truth beats five copies that can silently diverge), the RowAliases extraction mirrors the existing LabelReplacements pattern, the degree-guard docs (docs/6335-cypher-label-write-cost.md) are thorough, and each fix ships with a regression test that's described as verified-to-fail-before-fix. Dead code removal (EagerDistinctCollectOptionalMatchStep) is a clean, well-justified deletion backed by git log --follow.

Correctness: the #6338 disjunction bug still exists in at least 4 other call sites

The PR's stated goal for #6338 is that "the meaning of a disjunction now lives in one place... and the five copies that existed... all route through it." That's true for MatchNodeStep, ExpandPathStep, MatchRelationshipStep, and LabelCheckExpression — but there are more copies of the exact same AND-only label check that weren't touched and still have the identical defect:

  • PatternPredicateExpression.matchesTargetLabels (engine/src/main/java/com/arcadedb/query/opencypher/ast/PatternPredicateExpression.java:335-345) — used for both the start and end node of EXISTS { ... } pattern predicates. It doesn't even reference isLabelDisjunction() at all; the loop unconditionally requires every label. The comment right above the start-node call (line 98) literally says "Enforce any label conjunction", suggesting disjunction was never considered here. MATCH (a:Post) WHERE EXISTS { (a)-->(y:Author|Topic) } will therefore reject rows it should match.
  • PatternComprehensionExpression.matchesStartPattern (…/ast/PatternComprehensionExpression.java:220-229) and matchesEndPattern (…/ast/PatternComprehensionExpression.java:318-327) — same AND-only loop, reachable from list comprehensions like [(a)-->(y:Author|Topic) | y.name].
  • MergeStep.matchesNodePattern (…/executor/steps/MergeStep.java:921-930) — same pattern; nothing in CypherSemanticValidator.validateMergePathPattern rejects a disjunctive label on a MERGE node pattern, so MERGE (y:Author|Topic {k:'x'}) reaches this AND-only check too.

All of these go through the same shared visitNodePattern/ParserUtils.isLabelDisjunction parsing path as the sites that were fixed (confirmed via CypherASTBuilder.visitPatternElement), so a disjunctive label expression reaches each of them with isLabelDisjunction() == true and gets silently ANDed instead of ORed — the same "empty result reads as no such data" failure mode the PR spends most of its description explaining. Given Labels.matches(Vertex, List<String>, boolean) already exists and is public, routing these four sites through it looks like a small, mechanical follow-up rather than new design work. Worth doing in this PR (or a fast follow) so the "one home for what a disjunction means" claim is actually true project-wide.

Everything else looks solid

  • LabelReplacements.countEdgesToMigrate mirroring the migration's own OUT-then-IN-skip-self-loop traversal (rather than countEdges(BOTH)) is a good catch from the review round — nice that it's pinned by aSelfLoopIsCountedOnceBecauseItIsMigratedOnce.
  • The degree-limit check happens before any record is created/moved, which is correctly asserted in aLabelWriteAboveTheLimitIsRefusedBeforeAnythingMoves.
  • RowAliases.propagateUpdate's choice not to descend into paths/lists/maps is explained and reasonable given the cost/benefit tradeoff spelled out in the javadoc.
  • ReturnItem.star() as the single construction site for the sentinel, with isStar() replacing every name-based "*".equals(...) check, is a clean fix for the WITH n AS \*`collision — andcheckDuplicateAliasespicking upisStar()` too closes the gap the first round of review flagged.
  • CypherLabelWriteDegreeGuardIssue6335Test's CapturingLogger swaps the JVM-wide LogManager logger — it's restored in finally and engine tests run sequentially by default in this repo (no junit-platform.properties parallel config), so this should be safe, but flagging it since global-logger swaps are the kind of thing that becomes flaky the moment parallel execution is turned on for this module.

No security or performance concerns beyond what's already called out in the PR description (the degree-limit walk is opt-in and documented).

lvca added 3 commits August 17, 2026 21:32
… same thing wherever the node sits, and the star is what the parser wrote rather than what it is called

#6338 - A disjunction (y:A|B) written on a node a relationship expands INTO matched nothing,
while the same disjunction on the pattern anchor matched. The anchor is served by MatchNodeStep,
which has always had a disjunction branch; the expanded endpoint was filtered by
MatchRelationshipStep, which ANDed the alternatives - so an ordinary Cypher pattern returned an
empty result, with no error and no warning, which reads as "no such data" rather than as a bug.

Three places in that step were wrong, not one: the loaded-vertex filter ANDed the labels, the
bucket-id fast path tested only getLabels().get(0), and the schema pre-check required EVERY
alternative to name an existing type, so a disjunction mentioning a label nobody had created
rejected every row before the scan even started - an alternative that matches nothing is not a
filter that matches nothing.

All of them, plus MatchNodeStep, ExpandPathStep and the WHERE-side LabelCheckExpression, now go
through Labels.matches(vertex|type, labels, disjunction) and Labels.canMatchInSchema(...): five
copies of "what does a disjunction mean" became one, which is what let them disagree. The
optimizer is not implicated - shouldUseOptimizer declines a disjunction on a node with incident
relationships, because ExpandAll/ExpandInto carry a single targetLabel.

#6334 - CypherExecutionPlan.applyProjectionToScope decided a projection item was the WITH * star
by comparing its resolved NAME to "*", so WITH n AS `*` - alias "*", expression VariableExpression
("n") - was read as a star and forwarded the incoming scope instead of resetting it to the one
name it projects, while the alias itself was never projected at all. A regression from #6326,
which gave the same sentinel the stronger meaning.

The star is now a property of the item rather than of its name: ReturnClause.ReturnItem.star()
is the only thing that builds it, isStar() is the only thing that asks, and every name-based test
- the scope application, the WITH projection step, the variable-projection strip, isReturnAll(),
the referenced-variable walk and five sites in the semantic validator - now asks that instead of
the name. That also settles the bare backticked WITH `*`, which the name-based predicate could
never take apart from a real star.

#6328 - SET calls propagateUpdateToSameNodeAliases after writing a property, so every alias in
the row binding the same record observes the write; REMOVE replaced only the alias it was given,
so a removed property stayed visible through a second alias of the same node while
SET n.p = null - the same write spelled differently - answered null for both. Cypher has one
binding per node per row. The helper moved out of SetStep into RowAliases, shared by both steps
the way #6326 gave them one shared LabelReplacements.

#6336 - EagerDistinctCollectOptionalMatchStep deleted. git log --follow shows it dead from birth:
it landed in the same commit as the fix for #3218, which took a different route entirely
(CypherFunctionFactory + AggregationStep), and nothing has constructed it since. It carried a
whole alternative buffering strategy for OPTIONAL MATCH, so a reader tracing that plan had to
work out it was not in the plan before they could trust what was.

#6335 - A Cypher label write is O(degree) and changes RIDs, and nothing said so. A label is a
type, a type is a bucket, and a record's type comes from the bucket it lives in, so SET n:Label
cannot edit metadata: it rewrites the vertex under the new type and re-creates every incident
edge in both directions, touching every neighbour's edge list, and hands the vertex and all of
its edges new RIDs. On a supernode that is the difference between a millisecond and a stall.

That is not fixable while a label is a type - modelling extra labels as a property is the real
fix and its own epic, and a bulk edge move would cut the constant but neither the complexity nor
the RID churn - so it is made visible instead. LabelReplacements.replace() counts the edges it
migrates, which costs nothing because it walks them anyway, and logs a WARNING naming the node,
both types and the count above arcadedb.opencypher.labelWriteDegreeWarning (10000, 0 disables).
arcadedb.opencypher.labelWriteDegreeLimit refuses the write above a degree, checked before any
record moves; it is off by default, because the rewrite is slow rather than wrong and a query
that merely takes too long should not start failing on upgrade. The cost and the RID change are
now in the javadoc of the method that pays them, and in docs/6335-cypher-label-write-cost.md.
…the degree guard refuses on the number it would report

Three points from the code review, all valid.

checkDuplicateAliases was the one site the #6334 sweep missed, and it is the same
bug one call further on: it decided an item was the star by comparing its name to
"*", so it exempted any projection whose alias happened to be that - and now that
a user can legitimately alias to the backticked `*`, two such columns collided
without being reported. It asks item.isStar() like the rest of the file.

The degree guard measured with countEdges(BOTH), which sums the two edge lists
independently and so counts a self-loop twice, while the migration right below it
re-creates a self-loop exactly once. The limit therefore refused on a number the
warning would never print, in a feature whose whole point is to report the true
cost. countEdgesToMigrate() mirrors the migration's own traversal instead - the
OUT list in full, the IN list skipping the self-loops the OUT pass already took -
and walks the connected RIDs rather than the edges, so the skip costs a list walk
and not a record load per edge.

The WARNING itself was never asserted: deleting the log call left every assertion
in crossingTheWarningThresholdReportsWithoutRefusing green, which is the exact
failure mode #6335 is about. The test now installs a capturing Logger through
LogManager.setLogger - documented as this hook, previous logger restored in a
finally - and checks the record's message and arguments.

Each of the three is pinned by a test verified to fail without its fix: removing
the log call fails the warning assertion, countEdges(BOTH) fails the new
self-loop test with "the vertex has 7 edges and ... limit is 6", and restoring the
"*" name guard fails the collision test.
…ion from the grammar, and the clauses that write refuse a label expression

The code review found four more copies of the AND-only label check, and it was
right, but tracing them turned up one cause underneath rather than four bugs:
CypherExpressionBuilder.parseNodePattern built every node pattern in EXPRESSION
position with the disjunction flag hardcoded to false. A pattern comprehension or
a pattern predicate therefore received (y:A|B) already indistinguishable from
(y:A:B), and no amount of fixing the executor could recover what the parser had
thrown away. It now reads the flag off the grammar through
ParserUtils.isLabelDisjunction, exactly as the MATCH-side builder does.

Two of these were observable:

  [(a)-->(y:Author|Topic) | y.k]        returned []       expected ["t1"]
  exists((a)-->(:Author|Topic))         returned no row   expected the row

the second while the block form EXISTS { (a)-->(:Author|Topic) } answered
correctly all along, because it takes the subquery path - two spellings of one
predicate disagreeing about what a disjunction means.

MERGE was worse than an under-count. MERGE (n:A|B {k:'x'}) ANDed its match, so it
missed an existing :B node, and then created a second one under an invented A~B
composite type: a duplicate, silently, from a clause whose entire purpose is not
to make one. CREATE (n:A|B) invented the same composite. Neo4j refuses a label
expression in both clauses, for the reason that settles it - a disjunction says
which labels a node MAY have, and there is no node a write can produce that
satisfies "A or B" without picking one. Both are now refused, with a message that
names the spelling that does mean something (:A:B).

PatternPredicateExpression, PatternComprehensionExpression (start and end) and
MergeStep.matchesNodePattern route through Labels.matches like the rest, so the
one-home claim holds for every site the review listed. MergeStep can no longer
see a disjunction at all, but it does not get to be the odd one out.

Left for its own issue, being a different defect: PatternComprehensionExpression
.traverseUncorrelatedStart picks getLabels().get(0) as its scan root, so an
UNBOUND comprehension start node with a disjunction still under-scans.

openCypher package 4664 tests green, openCypher TCK 3897 green - the TCK is what
pins the CREATE/MERGE refusal as the spec behaviour and not just a preference.
@lvca
lvca force-pushed the fix/issues-6338-6336-6335-6334-6328 branch from 8d4a32c to c205c83 Compare August 18, 2026 01:32
@claude

claude Bot commented Aug 18, 2026

Copy link
Copy Markdown

Review

Read through the full diff (5 commits, ~1080 additions) plus the linked issues. This is a well-scoped, well-documented fix set - the "one home for a disjunction" consolidation (Labels.matches/Labels.canMatchInSchema) is the right call given five call sites had drifted independently, and each fix ships with a test that was verified to fail pre-fix. A few notes below, nothing blocking.

Correctness - verified, no issues found

  • Labels.matches/canMatchInSchema (Labels.java:153-197): logic is correct for both the vertex- and type-level overloads, and the type-level overload is genuinely needed to keep the GAV bucket-id fast path in MatchRelationshipStep free of a record load - good call.
  • LabelReplacements.countEdgesToMigrate (LabelReplacements.java:525-531): I double-checked this doesn't undercount vs. the actual migration loop. getConnectedVertexRIDs(IN) walks the edge linked list and yields one RID per edge (not a deduplicated neighbor set - confirmed in GraphEngine.getConnectedVertexRIDs), so it mirrors vertex.getEdges(IN) exactly, self-loop skip included. The limit really does refuse on the number the warning would report, as the docstring claims.
  • The self-loop counted-once test (aSelfLoopIsCountedOnceBecauseItIsMigratedOnce) is a nice catch of a real discrepancy between countEdges(BOTH) and the actual migration.
  • RowAliases.propagateUpdate is a straight, faithful extraction of the pre-existing SetStep helper; REMOVE now calls it too, closing the actual Cypher: REMOVE of a property does not update the other aliases of the same node in the row, while SET does #6328 gap. Confirmed no leftover references to the old propagateUpdateToSameNodeAliases.
  • ReturnItem.isStar() sweep looks complete for the ReturnClause.ReturnItem call sites (CypherReferencedVariables, CypherExecutionPlan, WithStep, CypherSemanticValidator x5). Traced every remaining "*".equals(...) in the validator that wasn't converted, and they're all on unrelated node types (CALL (*) { } scope-variable strings, containsVariableReference's raw VariableExpression check in SKIP/LIMIT, isValidVariableName's synthetic-name filter) rather than ReturnItem, so they're out of this PR's scope, not missed instances of the same bug.
  • checkNoLabelDisjunction correctly walks path.getNodes(), so it covers a disjunction on any node in a CREATE/MERGE pattern, not just the anchor - matches the stated intent even though the test only exercises the anchor case.
  • Confirmed test isolation for the LogManager.setLogger swap in CypherLabelWriteDegreeGuardIssue6335Test: forkCount=1/reuseForks=true and no JUnit5 parallel-execution config in this module, so the global logger swap is safe (sequential execution) despite being global mutable state - worth keeping in mind if this module's test config ever changes to run classes in parallel.

Minor / non-blocking

  1. checkNoLabelDisjunction's size() > 1 guard (CypherSemanticValidator.java:1728) - if (node.isLabelDisjunction() && node.getLabels().size() > 1). Given the grammar, can isLabelDisjunction() ever be true with fewer than 2 labels? If not, the size() > 1 is dead defensiveness; if it can (some edge case in ParserUtils.isLabelDisjunction/extractLabels), it's worth a one-line comment on why a single-label "disjunction" is deliberately let through here rather than refused.

  2. Doc/PR-description nit: the PR description says "openCypher package 4664 tests green" in one commit and "4658" as the overall total in another paragraph - probably just reflects the incremental test count added between commits, not a discrepancy in the code, but worth a glance before merge in case it signals a test that didn't get counted.

  3. RowAliases and LabelReplacements now both "redirect row state after a write" but via different mechanisms (row-alias walk by RID vs. a replacement map keyed by RID persisted across rows) - the class docs cross-reference each other well, but it might be worth a one-line note in RowAliases itself (not just the javadoc) that it does not need to consult LabelReplacements' map, since a caller skimming SetStep.applyLabels could otherwise wonder if the two need to be composed for the label-write case. Not a bug - SetStep.applyLabels already calls RowAliases.propagateUpdate directly with prior/vertex before delegating to LabelReplacements, which is correct - just a readability note.

Test coverage

Good: each of the four new test classes pins a specific pre-fix failure with a comment noting what failed and why, and cross-cutting shapes are covered (disjunction at each position of a chain, self-loop counting, backticked-star alias forwarding vs. being projected, REMOVE-then-UNWIND re-observation). Nothing further to ask for.

Nice work overall, especially the "route five copies through one helper" approach rather than patching each site independently - that's exactly the kind of fix that prevents the next regression in the same shape.

@claude

claude Bot commented Aug 18, 2026

Copy link
Copy Markdown

Review

This is a well-scoped, carefully reasoned PR. Five related openCypher defects, each traced to a single root cause rather than patched at each call site, with regression tests written to fail without the fix (per repo convention) and thorough javadoc explaining why, not just what. I read the full diff; here's my assessment.

Correctness

I traced the trickiest parts by hand and didn't find a bug:

  • Self-loop counting (LabelReplacements.countEdgesToMigrate): verified that getConnectedVertexRIDs/EdgeLinkedList.ridIterator produce one RID per edge (no dedup), so the OUT-count-plus-non-self-IN-walk genuinely mirrors what replace() migrates, including for parallel edges. The countEdges(BOTH) double-counting bug this replaces was real and the fix is correct.
  • Labels.matches/canMatchInSchema consolidation: the five previously-divergent call sites (MatchNodeStep x2, ExpandPathStep, MatchRelationshipStep incl. the GAV bucket-id fast path, LabelCheckExpression, MergeStep, PatternComprehensionExpression x2, PatternPredicateExpression) now agree, and each is a faithful behavior-preserving extraction plus the OR-fix.
  • ReturnItem.isStar(): confirmed the star is now built in exactly one place (ReturnItem.star(), three call sites: ClauseDispatcher, and two in CypherASTBuilder) and every previous name-based "*".equals(...) check was converted. I didn't find a remaining name-based check that should have been converted.
  • CREATE/MERGE label-disjunction refusal: checkNoLabelDisjunction's labels.size() > 1 guard is a bit unusual — worth a one-line comment on why it's needed (defensive against a disjunction flag with a single label, which the current grammar shouldn't produce) since it reads like it could silently under-refuse a same-label disjunction edge case. Not a bug I could actually trigger, just a spot where the reasoning isn't as visible as the rest of this PR's comments.

Minor / non-blocking observations

  • CypherLabelWriteDegreeGuardIssue6335Test swaps the process-wide LogManager logger and global GlobalConfiguration values for the duration of a test, restoring both in finally. That's fine under the current sequential JUnit5 config (no junit-platform.properties parallelism enabled), but it's a footgun if parallel test execution is ever turned on for this module — might be worth a short comment noting the sequential-execution assumption, since nothing else currently documents it.
  • docs/6335-cypher-label-write-cost.md and the two new GlobalConfiguration entries are a nice touch — making a perf cliff observable instead of silent is the right call given it can't be fixed cheaply.

Test coverage

Strong. Each of the four new test classes targets the exact regression (anchor vs. expanded-node position, each position in a chain, variable-length target, missing-schema-label alternative, pattern comprehensions, both exists() spellings, CREATE/MERGE refusal; backticked-star alias in each place it can appear; multi-alias REMOVE including the UNWIND re-encounter case; degree-guard limit/warning/self-loop). The PR description states these were verified to fail before the fix and that the full engine + openCypher + TCK suites are green, which is the right bar for a change touching this many shared code paths.

Performance

No concerns — the degree-guard walk is opt-in (off by default, limit > 0 gates it), the warning count is free (piggybacks on the migration walk), and the Labels consolidation doesn't add allocations to the hot paths beyond what already existed.

Security

None relevant — no new I/O, deserialization, or external input handling.

Nice work tracing five separate-looking bugs back to two shared root causes rather than patching each site independently.

…ls came back with it

Both reviewers asked why checkNoLabelDisjunction guarded on getLabels().size() > 1,
and the answer turned out to be that it should not: the guard was a hole rather
than dead defensiveness. collectStaticLabels leaves a Cypher 25 dynamic
$(expression) alternative out of the static list, so CREATE (n:Author|$('Topic'))
arrives carrying one static label and a disjunction flag, and the count-based
guard let it straight through - in the shape where a write acting on "A or B" is
least defensible of all, the second label not being known until the query runs.

It now refuses on the flag alone, which is what actually means "a | was written",
and names the conjunction spelling only when there are two labels to name.
Pinned by a test that fails with the count restored.

Two readability notes from the same reviews, neither a behaviour change: the
CapturingLogger javadoc records the sequential-execution assumption it and the
GlobalConfiguration writes rest on, so turning on class parallelism for engine
does not quietly invalidate them; and RowAliases says why it does not consult
LabelReplacements' map - it answers "the row holds an older copy of a record
that is still there", a different question from "the row holds a record that was
deleted and replaced", and SetStep.applyLabels is the caller that needs both.

openCypher package 4665 green, openCypher TCK 3897 green.
@claude

claude Bot commented Aug 18, 2026

Copy link
Copy Markdown

Review

Went through the full diff (base vs head, not the per-commit patches) plus the four new test classes. This is a well-scoped, well-tested PR — five related openCypher defects consolidated into one shared abstraction (Labels.matches/canMatchInSchema) instead of patched at each disagreeing call site. Notes below are minor; nothing blocking.

Correctness — looks solid

  • Labels.matches(Vertex/DocumentType, List<String>, boolean) is now the single source of truth for disjunction vs. conjunction semantics, and all five previous call sites (MatchNodeStep x2, ExpandPathStep, MatchRelationshipStep x3 including the GAV bucket-id fast path, LabelCheckExpression, PatternComprehensionExpression x2, PatternPredicateExpression, MergeStep) now route through it. I checked each for behavioral equivalence with the described intent and didn't find a spot still doing the old AND-only check.
  • Nice side effect: the old GAV fast-path code did db.getSchema().getTypeByBucketId(...).getName() unconditionally, which would NPE if the bucket has no mapped type. The new Labels.matches(DocumentType, ...) null-checks type before calling instanceOf, so this is a (probably unintentional but welcome) NPE hardening as well.
  • ReturnItem.isStar() as a constructed property rather than a name comparison is the right fix for the WITH n AS \` regression — confirmed all name-based call sites were converted (CypherExecutionPlan, WithStep, CypherSemanticValidatorx5,CypherReferencedVariables, ReturnClause.isReturnAll), and the three parser sites that build (ClauseDispatcher, CypherASTBuilderx2) all now go throughReturnItem.star()`.
  • RowAliases.propagateUpdate cleanly extracted from SetStep and reused in RemoveStep; the identity comparison (other != updated && originalRid.equals(...)) correctly avoids redundant self-writes.
  • LabelReplacements.countEdgesToMigrate vs. the migration loop's own counting (migratedEdges): I traced through both and they agree on self-loop counting (OUT pass counts self-loops once, IN pass skips them) — matches what the round-2 review fix claims and what the aSelfLoopIsCountedOnceBecauseItIsMigratedOnce test exercises.
  • checkNoLabelDisjunction correctly keys off isLabelDisjunction() rather than label count, closing the CREATE (n:Author|$('Topic')) hole described in the PR body — confirmed collectStaticLabels leaves dynamic alternatives out of the static list, so a count-based guard really would have missed it.
  • Verified EagerDistinctCollectOptionalMatchStep's deletion is clean: its private SingleRowInputStep/IdentifiableWrapper were local inner classes, not shared with OptionalMatchStep's or CollectDistinctFunction's own same-named classes, so nothing is orphaned.

Minor observations (non-blocking)

  • LabelReplacements.replace() now does a limit-check pass (countEdgesToMigrate, walking getConnectedVertexRIDs(IN)) in addition to the actual migration loop when labelWriteDegreeLimit > 0. That's an intentional extra edge-list walk per the docs/javadoc ("costs one extra edge-list walk per label write"), so this is a known, documented, opt-in tradeoff rather than an oversight.
  • The new config docs (OPENCYPHER_LABEL_WRITE_DEGREE_WARNING/_LIMIT) are SCOPE.DATABASE — worth double-checking that's intentional vs. SCOPE.JVM, since a supernode write is a per-operation concern that might reasonably be tuned per-database (seems right, just flagging since most of the neighboring perf-tuning knobs in that file are a mix of both scopes).
  • CypherLabelWriteDegreeGuardIssue6335Test.CapturingLogger swaps the process-wide LogManager logger; the javadoc on it already flags the sequential-execution assumption (forkCount=1), which is exactly right given this repo's CLAUDE.md guidance on JVM-shared test state — good that it's called out explicitly rather than left implicit.

Test coverage

Strong — each of the four new test classes maps directly to a described defect, includes the "must not regress" neighboring cases (conjunction still AND-only, real * still forwards, self-loop counted once), and the PR body states each was verified to fail without its fix. That's the right discipline for this kind of change.

Docs

docs/6335-cypher-label-write-cost.md and the updated docs/5789-...md are clear and the javadoc on LabelReplacements.replace() mirrors them — good that the cost/RID-churn caveat lives at the point future readers will actually be.

Nothing here changes my assessment: this looks correct, consistent, and well-tested. Nice work consolidating five independent-looking bugs into one root-cause fix rather than four executor patches.

@codecov

codecov Bot commented Aug 18, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 79.83871% with 25 lines in your changes missing coverage. Please review.
✅ Project coverage is 70.67%. Comparing base (2304fba) to head (adc7e15).
⚠️ Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
...ain/java/com/arcadedb/query/opencypher/Labels.java 76.00% 2 Missing and 4 partials ⚠️
...ery/opencypher/parser/CypherSemanticValidator.java 77.27% 1 Missing and 4 partials ⚠️
...encypher/executor/steps/MatchRelationshipStep.java 42.85% 0 Missing and 4 partials ⚠️
...b/query/opencypher/executor/LabelReplacements.java 84.21% 1 Missing and 2 partials ⚠️
...opencypher/ast/PatternComprehensionExpression.java 50.00% 1 Missing and 1 partial ⚠️
...arcadedb/query/opencypher/executor/RowAliases.java 77.77% 1 Missing and 1 partial ⚠️
...edb/query/opencypher/executor/steps/MergeStep.java 0.00% 1 Missing and 1 partial ⚠️
...adedb/query/opencypher/executor/steps/SetStep.java 75.00% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #6348      +/-   ##
==========================================
+ Coverage   70.62%   70.67%   +0.05%     
==========================================
  Files        1850     1850              
  Lines      160517   160387     -130     
  Branches    33762    33713      -49     
==========================================
- Hits       113361   113353       -8     
+ Misses      33192    33085     -107     
+ Partials    13964    13949      -15     

☔ 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.

lvca added a commit that referenced this pull request Aug 18, 2026
One conflict: #6348 deleted EagerDistinctCollectOptionalMatchStep, which this branch had touched
for the unbalanced profiling parenthesis. The deletion wins - nothing on main references the
class any more, and the fix dies with the file. The eight remaining paren fixes are unaffected,
and no step added by #6348 carries the pattern.
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.

openCypher: a label disjunction (y:A|B) on a node bound by expansion matches nothing, while the same disjunction on the anchor works

1 participant