Skip to content

fix(#6311, #6312, #6313): a hop checks its target against what the row holds when it runs, and a relabelled vertex takes its aliases with it - #6326

Merged
lvca merged 6 commits into
mainfrom
issue-6311-6312-6313
Aug 17, 2026
Merged

lvca merged 6 commits into
mainfrom
issue-6311-6312-6313

Conversation

@lvca

@lvca lvca commented Aug 17, 2026

Copy link
Copy Markdown
Member

Fixes #6311, fixes #6312, fixes #6313.

#6311 - WITH * changed the cardinality of a multi-pattern MATCH

WITH * is an identity projection, so nothing downstream of it should be able to tell it is there. It could:

MATCH (n0 {k2:true})<-[:rt0]-()<-[]-(n1), (n2)<-[:rt8]-()-[]->(n1)
RETURN n0.tag, n1.tag, n2.tag        -- 2 rows, joined on n1
MATCH (n0 {k2:true})<-[:rt0]-()<-[]-(n1), (n2)<-[:rt8]-()-[]->(n1)
WITH *
RETURN n0.tag, n1.tag, n2.tag        -- 4 rows, the full Cartesian product

The issue reports it on OPTIONAL MATCH, but OPTIONAL is incidental: plain MATCH breaks the same way, and so does any following clause, not just RETURN count(*).

The join between two comma-separated patterns of one MATCH is the identity check each hop runs on its target against the names the row already carries. Those names were handed to MatchRelationshipStep as the planner's live, mutable boundVariables set. That set is filled with the clause's own variables only after the clause is planned (boundVariables.addAll(matchVariables)), which is what made the check work at all - retroactively, through the shared reference. A following WITH clears the same set, and WITH * refilled it with the literal name *, so by the time the hop executed the shared variable was gone from it and every target was accepted.

Two changes:

  • the hop is given a snapshot of what is bound at the point it will run - everything bound before this MATCH plus everything this MATCH has bound so far (earlier comma-separated patterns, earlier hops). A variable can only be in a row if it was bound earlier, so this is exactly the set the check needs, and it no longer depends on a set someone else may edit later;
  • WITH * forwards the incoming scope instead of replacing it with "*". An explicit projection list still resets it, and WITH *, expr AS alias does both.

#6312 / #6313 - a label write left every other reference to the node dangling

ArcadeDB reads a record's type from the bucket it lives in, and in the Cypher mapping a label set is a type, so REMOVE n:L cannot retype in place: it writes a new record and deletes the old one. Every other reference to that node was left pointing at the deleted original - a second alias in the same row, or the same node reached again by a later row of the same clause (UNWIND fan-out, or simply two matches sharing the node). The next REMOVE then either failed to load the record:

com.arcadedb.exception.RecordNotFoundException: Record #7:0 not found
  at com.arcadedb.database.immutable.ImmutableDocument.checkForLazyLoading

or, on the way to deleting it a second time, followed its dangling edge-list chunk and reported the vertex as concurrently modified:

Edge list OUT of vertex #4:0 is not fully visible yet (concurrent commit in flight): Record #5:0 not found

SetStep already tracked its own replacements for SET n:L; RemoveStep tracked nothing. Both now share one LabelReplacements, which performs the rewrite and points every alias of the node - in this row and in every later one - at the live record, so a repeated label removal becomes an idempotent no-op instead of a fatal one.

Two defects of the rewrite itself, shared by SET and REMOVE, are fixed in the same place:

  • edge properties were silently dropped. The old code re-linked edges with newVertex.newEdge(edge.getTypeName(), other), i.e. by type alone, so -[:R {klist:[...]}]-> came back as -[:R]->. They are now carried over (and a LIGHTWEIGHT type, which has none, still gets none).
  • a self-loop was duplicated, migrated once by the OUT pass and again by the IN pass. It is now migrated once.

On the expected values in the reports

Tests

CypherWithStarScopeIssue6311Test (5) and CypherLabelWriteRowFanoutIssue6312Test (5), both new. Reverting the fix fails 7 of the 10; the remaining 3 are controls that must keep passing (explicit WITH n0, n1, n2, WITH * before a MATCH, WITH *, expr AS alias).

Verification run: the whole engine unit lane, 15,730 tests, green; the openCypher TCK suite, 3,897 scenarios, green.

…w holds when it runs, and a relabelled vertex takes its aliases with it

WITH * is an identity projection, so nothing downstream of it should be able to
tell it is there. It could: two comma-separated patterns of one MATCH that share
a variable were joined on it without the projection and multiplied out into a
Cartesian product with it. The join is the identity check each hop runs against
the names the row already carries, and those names were handed to the step as the
planner's own live, mutable set. The set is filled with this clause's variables
only after the clause is planned - which is what made the check work at all - and
a following WITH clears it, so the shared variable stopped being seen. The step
now gets a snapshot of what is bound at the point it will run: everything bound
before this MATCH plus everything this MATCH has bound so far. A WITH * also
stops replacing the scope with the literal name "*" and forwards it instead.

A Cypher label write has to rewrite the vertex - ArcadeDB reads a record's type
from the bucket it lives in, and a label set is a type - so the record moves and
the old one is deleted. Every other reference to that node was left pointing at
the deleted original: a second alias in the same row, or the same node reached
again by a later row of the same clause. The next REMOVE then either failed to
load the record or, on the way to deleting it a second time, followed its
dangling edge-list chunk and reported the vertex as concurrently modified. SET
already tracked its replacements; REMOVE tracked nothing. Both now share one
LabelReplacements, which performs the rewrite and points every alias of the node
at the live record, on this row and on all later ones. The shared rewrite also
carries the edges' own properties over - re-linking by type alone silently
dropped them - and migrates a self-loop once rather than once per direction.

- #6311 `WITH *` changes `OPTIONAL MATCH` cardinality
- #6312 `REMOVE` after `OPTIONAL MATCH` and `UNWIND` raises `RecordNotFoundException`
- #6313 `REMOVE` label after `OPTIONAL MATCH` raises an edge-list `RecordNotFoundException`
@lvca lvca self-assigned this Aug 17, 2026
@mergify

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

Copy link
Copy Markdown

Not up to standards ⛔

🔴 Issues 2 high

Alerts:
⚠ 2 issues (≤ 0 issues of at least minor severity)

Results:
2 new issues

Category Results
ErrorProne 2 high

View in Codacy

🟢 Metrics 37 complexity

Metric Results
Complexity 37

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.

@claude

claude Bot commented Aug 17, 2026

Copy link
Copy Markdown

Review: WITH * scope + label-write row fanout (#6311, #6312, #6313)

Overall this is a careful, well-scoped fix with a good root-cause writeup and a solid new-test suite (CypherWithStarScopeIssue6311Test, CypherLabelWriteRowFanoutIssue6312Test), including the control cases (explicit WITH n0,n1,n2, WITH * before a MATCH, WITH *, expr AS alias). A few notes below, none of which I'd call blocking, but worth a look before merge.

1. buildExecutionStepsLegacy still has the pre-fix bug pattern (low severity - looks unreachable today)

CypherExecutionPlan.buildExecutionStepsLegacy (around line 2612-2613) builds MatchRelationshipStep with the raw legacyBoundVariables set, not a snapshot merged with the current MATCH clause's own matchVariables (which is only folded into legacyBoundVariables at the very end of the clause, line 2676 - the same shape the optimizer path had before this PR's fix at line 2015-2023). So a comma-separated multi-pattern MATCH that shares a variable between two patterns (the exact #6311 repro, minus the WITH *) would still silently degrade the identity check into a Cartesian product if it ever executed through this method.

In practice buildExecutionStepsLegacy only runs when statement.getClausesInOrder() is null/empty (buildExecutionSteps, line 1125-1133), and StatementBuilder (the only production path constructing SimpleCypherStatement) always populates clausesInOrder, so this looks like dead code for actual parsed queries today. Given both CLAUDE.md files flag "optimizer and legacy execution paths - changes to clause handling may need updates in multiple paths" as a known landmine here, it's worth either applying the same snapshot fix to the legacy method for consistency, or leaving a comment noting it intentionally wasn't touched because it's unreachable (and maybe worth deleting eventually if it's truly dead).

2. LabelReplacements.redirect() only patches top-level Vertex/Edge-valued row properties

redirect() walks row.getPropertyNames() and swaps in the live vertex/edge only when the property value is directly a Vertex/Edge. A row property that's a composite - a bound path variable (p = (a)-[r]->(b)), or a List/Map produced by collect(n) or similar - can still hold a reference to the deleted original after a SET/REMOVE label write touches one of its members.

CypherLabelWriteRowFanoutIssue6312Test.removeSurvivesUnwindFanoutOverTheSameNodes actually binds a path variable (p0 = (n2)-[...]->(n1)...) in the repro query, but no assertion ever dereferences p0 afterward, so this path isn't exercised either way. Worth either confirming this is genuinely out of scope for #6312/#6313 (they were about direct vertex aliases), or adding a quick test that returns/uses the path variable after a label write on one of its nodes, since it's the kind of thing that resurfaces as a new issue report otherwise.

3. Minor: SetStep.applyLabels's manual resolve looks redundant with the new redirect() calls

applyLabels (SetStep.java, ~line 451-457) still does its own labelReplacements.resolve(vertex) + propagateUpdateToSameNodeAliases before recomputing labels, on top of the labelReplacements.redirect(result) that already runs once per row at the top of applySetOperations and once after every replace() call. I couldn't construct a case where the manual resolve fires with a different outcome than what the surrounding redirect() calls already establish - if it really is redundant now, dropping it would simplify the method (it's also harmless as belt-and-suspenders defensive code, so not a big deal either way).

Everything else checked out

  • LabelReplacements.replace()'s self-loop handling (migrate once via the OUT pass, continue on the IN pass when edge.getOut() == originalRid) is correct and matches the new removeLabelKeepsEdgeProperties test.
  • Edge property carryover via propertiesOf() correctly special-cases LIGHTWEIGHT edges (empty array, since that type rejects properties).
  • redirect() iterating row.getPropertyNames() while calling setProperty is safe: getPropertyNames() returns a fresh LinkedHashSet copy each call (ResultInternal.getPropertyNames()), not a live view, so there's no ConcurrentModificationException risk.
  • The applyProjectionToScope refactor correctly handles all three shapes - explicit list (clears + sets), WITH * (forwards, no-op), WITH *, expr AS alias (forwards + adds) - and is applied consistently across all three call sites that used to inline the old clear-and-rebuild logic (the two chained-optimization fast paths and the general WITH case).
  • Performance: redirect()/LabelReplacements add only an isEmpty() check per row in the common case (no label writes needing replacement), consistent with the project's performance guidance.

No security concerns spotted - this is query-planning/execution logic operating on already-authenticated database sessions, no new external input handling.

…ollows the node that moved under it

Three points from the review, all taken.

The legacy plan builder had the identical live-set hand-off, so the same
snapshot rule now applies there. It is unreachable for parsed queries today -
`clausesInOrder` is always populated - but this is precisely the "changes to
clause handling may need updates in multiple paths" landmine CLAUDE.md warns
about, and leaving one of the two paths holding the old shape is how it comes
back.

A row does not hold records only under their own name. A path variable, a
collect() list and a map hold them too, and those were left pointing at the
record the label write deleted - answering with the labels the node no longer
has, and one re-read away from failing outright. redirect() now rebuilds them
around the live records, and only when something inside actually moved, so a row
with no replacement to apply still costs one isEmpty() check. Two tests cover it;
both fail without this.

The resolve() in SET's label path is kept and REMOVE's now matches it: it reads
the write target directly, which does not depend on the row listing that
variable as a column - the one thing redirect() cannot reach. Both say so.
@lvca

lvca commented Aug 17, 2026

Copy link
Copy Markdown
Member Author

Thanks - all three taken.

1. buildExecutionStepsLegacy - fixed rather than annotated. You're right that it's unreachable for parsed queries today (clausesInOrder is always populated by StatementBuilder), but this is exactly the "optimizer and legacy execution paths - changes to clause handling may need updates in multiple paths" landmine CLAUDE.md warns about, and leaving one of the two paths holding the pre-fix shape is how it comes back. It now takes the same boundVariables ∪ matchVariables snapshot.

2. redirect() and composite values - real, and worse than a crash risk: it answers stale rather than failing. MATCH p = (a:Keep:Drop)-[:E]->(b) REMOVE a:Drop RETURN [n IN nodes(p) | labels(n)] returned [[Drop, Keep], []] - the label set the node no longer has - because the path still held the deleted record. redirect() now also walks TraversalPath, List and Map values and rebuilds them around the live records, allocating only when something inside actually moved (a row with nothing to redirect still costs the one isEmpty() check). Two new tests, aBoundPathFollowsItsRelabelledMembers and aCollectedListFollowsItsRelabelledMembers; both fail without the change.

3. SetStep.applyLabels's manual resolve - kept, and RemoveStep.removeLabels now matches it, because it is not quite redundant: redirect() can only reach aliases the row lists in getPropertyNames(), while resolving the write target reads it directly and does not depend on that. Both sites now carry a comment saying so, so the next reader doesn't have to re-derive it.

Re-verified: engine unit lane green, openCypher TCK 3,897 scenarios green.

@claude

claude Bot commented Aug 17, 2026

Copy link
Copy Markdown

Review

I read the diff plus the full current state of the touched files (CypherExecutionPlan.java, the new LabelReplacements.java, SetStep.java, RemoveStep.java, and both new test classes), and cross-checked the LabelReplacements/TraversalPath/Edge/Vertex APIs it relies on. Overall this is a careful, well-explained fix with strong regression coverage. A few notes below; nothing here looks blocking.

Correctness — looks solid

  • applyProjectionToScope correctly distinguishes WITH * (forward scope, don't clear) from an explicit projection list (clear + repopulate), and handles WITH *, expr AS alias (forward + add) without ever leaking the literal "*" into the scope set. Matches the described semantics and the new tests.
  • The targetIdentityVars snapshot (new HashSet<>(boundVariables); targetIdentityVars.addAll(matchVariables)) is built fresh per hop, so it's immune to the planner mutating/clearing the live boundVariables set afterward — this is the actual fix for ArcadeDB 26.8.1: WITH * changes OPTIONAL MATCH cardinality #6311 and looks correct.
  • LabelReplacements.replace()'s self-loop handling (migrate on the OUT pass, skip on the IN pass when originalRid.equals(edge.getOut())) is correct and matches the new removeLabelKeepsEdgeProperties test's "migrated once" assertion.
  • resolve()'s chain-following loop correctly handles a vertex relabelled more than once in the same clause.
  • redirect()/redirectValue()'s recursive handling of List/Map/TraversalPath correctly rebuilds only when something inside actually moved (identity comparison live != value), avoiding needless row mutation.

Minor: possibly redundant defensive code

In both SetStep.applyLabels and RemoveStep.removeLabels, there's a resolve()/backstop call justified by the comment "resolving the write target itself does not depend on the row listing that variable as a column, which is the one case redirect() cannot reach." But the write target is always read via result.getProperty(item.getVariable()) / result.getProperty(variable), i.e., always as a row column — and redirect(result) is unconditionally called immediately before the items loop (and again after every replace() inside the loop), so by the time either method runs, the row should already be up to date. I couldn't construct a case where this backstop actually fires today. Not a bug — just double-checking whether the comment describes a real remaining gap or is leftover reasoning from an earlier draft; if it's the latter, simplifying the comment (or the check) would reduce confusion for the next reader.

Worth double-checking: variable-length paths

The fix is applied to the fixed-length hop branch in both the ordered builder (buildMatchStep) and the legacy builder. The legacy builder's variable-length-path branch (computePrevVarsForVlp(pathPattern, i, legacyBoundVariables), still passing the live set directly) wasn't touched — which is fine since the PR notes the legacy builder is unreachable for parsed queries today. But is there an equivalent VLP branch in the ordered (reachable) builder, and if so, does it have the same live-set exposure as the fixed-length hop did? If computePrevVarsForVlp is purely about cycle-avoidance within the variable-length expansion (not an identity check against the row), this is a non-issue — but given how subtle #6311 turned out to be, it seemed worth flagging so it can be confirmed either way rather than assumed.

Performance note (not a regression, but worth being aware of)

LabelReplacements.redirect()'s top-level guard (vertices.isEmpty()) is step-wide, not per-row — once a single row anywhere in the step triggers a relabel, every subsequent row pays a full getPropertyNames() walk plus recursive descent into any List/Map/TraversalPath property, even rows that never touch the relabelled node. The old code had the same step-wide granularity but only checked top-level Vertex properties, not collections/paths, so this PR does add per-row work in the "at least one relabel already happened" case. This is presumably an intentional/necessary tradeoff for correctness (issue 3 in the PR, the bound-path/collect() fix), and is unlikely to matter for typical label-write workloads, but for a REMOVE/SET over very large fanout with big collected lists per row it could show up. Worth a one-line comment noting the tradeoff was deliberate, if it was.

Test coverage

The two new test classes are thorough and clearly tied to the reported issues, including a good "control" test (explicitProjectionOfTheSharedVariableBehavesTheSame) and an idempotency/stats-counting regression test for REMOVE (removeLabelIsIdempotentAcrossRowsAndCountsOnce). One small gap: there's no equivalent stats-idempotency test for SET n:Label across row fanout (only REMOVE has one) even though it shares the exact same LabelReplacements code path and addLabelsAdded counter — might be worth mirroring that test for symmetry, low priority given the shared implementation is already exercised elsewhere.

Nit

LabelReplacements is a new public final class with no dedicated unit test of its own (only exercised indirectly through the Cypher integration tests). Given it now owns fairly intricate logic (chain resolution, self-loop dedup, edge-property carry-over, recursive redirect), a few focused unit tests against the class directly (e.g., double-replacement chaining, lightweight-edge tracking) could make future regressions cheaper to localize — optional, since the integration tests already cover the observable behavior well.

Nice write-up in the PR description, by the way — the "why" behind both bugs (live mutable set hand-off; bucket-derived typing forcing a record move) is explained clearly enough that the fix is easy to verify against the stated root cause.

… own tests, and two comments say what is actually true

The variable-length branch was worth the question and turns out to be immune by
construction: ExpandPathStep reads its already-bound target from the incoming
row, not from a plan-time set, so there was never a live set to be emptied under
it. computePrevVarsForVlp only builds the relationship-uniqueness exclusion set,
which is the pre-clause scope by definition. A test now pins the shared-variable
join across a variable-length pattern, with and without the WITH *, because that
is the branch a reader would expect to share the defect.

The comment on the resolve() in both label paths claimed a gap it could not
demonstrate: the write target is always read as a row column, so the per-row
redirect() does reach it. The call stays - it makes each method correct on its
own terms rather than on its caller's - but it now says that instead.

redirect()'s descent into collections is charged to every row of the step once
any row has replaced something, because the map that knows a node moved is
step-wide. That trade is now written down where it is made.

LabelReplacements gets direct tests: the chain a twice-relabelled node builds,
the edges and edge properties carried over, the self-loop counted once, and rows
of every shape redirected - including the one where nothing moved and the list
must come back as the same instance. SET's label counter gets the idempotency
test REMOVE already had.
@lvca

lvca commented Aug 17, 2026

Copy link
Copy Markdown
Member Author

Second pass addressed - thanks, the variable-length question was the right one to ask.

Variable-length paths - immune by construction, and now pinned. ExpandPathStep resolves an already-bound target from the incoming row at runtime (lastResult.getProperty(targetVariable)), not from a plan-time variable set, so there was never a live set to be emptied under it. computePrevVarsForVlp builds only the relationship-uniqueness exclusion set, which is the pre-clause scope by definition (the analogue of previousStepVariables, which must stay pre-clause). Added withStarKeepsTheJoinOnAVariableLengthPattern: same shared-variable join over [:rt8*1..2], with and without the WITH *, both correct.

The resolve() comment - you're right, and I couldn't demonstrate the gap either: the write target is always read as a row column, so redirect() does reach it. Kept the call but rewrote both comments to say what is actually true - it makes each method correct on its own terms rather than on its caller's, at one map lookup that is skipped entirely until a label write happens.

Performance trade - correct reading, and deliberate: the map that knows a node moved is step-wide, so once any row replaces something every later row pays the walk. Now written down at redirect(), along with the other half - a clause with no label write pays one isEmpty() check per row and never walks anything.

Tests - both suggestions taken. addLabelIsIdempotentAcrossRowsAndCountsOnce mirrors the REMOVE stats test for SET n:Label. New LabelReplacementsTest covers the class directly: double-replacement chaining, edge and edge-property carry-over, lightweight-edge handling, the self-loop counted once, every row shape redirected, and the negative case where nothing moved and the collection must come back as the same instance rather than a rebuilt copy.

Re-verified: Cypher lane 7,037 green, openCypher TCK 3,897 green.

@claude

claude Bot commented Aug 17, 2026

Copy link
Copy Markdown

Review

Went through the full diff (CypherExecutionPlan, the new LabelReplacements, SetStep/RemoveStep, and the three new test classes). This is a careful, well-reasoned fix for three related correctness bugs, and the test coverage is unusually thorough (chain replacements, self-loops, edge properties, paths, collect() lists, idempotency, a pinned variable-length-pattern control). A few notes below; nothing here blocks the fix itself.

#6311 (WITH * scope)

applyProjectionToScope and the targetIdentityVars snapshot in CypherExecutionPlan look correct. One thing worth double-checking: at the point the snapshot is taken (CypherExecutionPlan.java ~L2022 and ~L2616), matchVariables already contains the current hop's own relVar/effectiveTargetVar (added a few lines earlier at L1996-1999/L2599-2601), so targetIdentityVars isn't strictly "what's bound before this hop runs" - it also includes the hop's own not-yet-bound target. That's harmless today because MatchRelationshipStep only acts on boundVariableNames when the row also already carries a non-null Vertex for that name (processStandardPath/processFastPath), so a fresh target name in the set is a no-op. Just flagging it since the surrounding comment describes the snapshot as "everything bound before this MATCH plus everything this MATCH has bound so far," which slightly undersells that it also includes this hop's own targets - worth a one-line comment tweak if you want the code to match the description exactly, but not a correctness issue.

#6312/#6313 (label rewrite + row fanout)

LabelReplacements is solid: the chain-resolution in resolve(), the self-loop dedup in replace() (OUT pass creates it, IN pass skips originalRid.equals(edge.getOut())), and the identity-based "did anything move" check in redirect()/redirectValue() (so a collect() list with nothing to redirect stays the same instance) are all correct and directly exercised by LabelReplacementsTest.

One gap, possibly intentional: track() skips lightweight edges (rid.getPosition() > -1 check), so edges never contains an entry for them, and redirectValue() therefore never rewrites a lightweight edge held directly as a row value. If a query binds a lightweight edge to a variable (e.g. MATCH (a:Drop)-[r:LightType]->(b) REMOVE a:Drop RETURN r) and something later dereferences r's stale endpoint, that would reproduce a milder version of the same class of bug this PR fixes for vertices/heavy edges. Given LightEdgeRID bakes its endpoints in at construction and has no independent identity, there may be no clean way to redirect it (the doc comment on LightEdgeRID explains why), so this might just be an accepted limitation - worth a short note in LabelReplacements' class doc confirming that's deliberate, and maybe a regression test showing what currently happens (no crash today, since nothing in the new tests exercises returning/using a lightweight edge across a label rewrite of its endpoint).

Minor

  • RemoveStep.removeProperty() (untouched by this PR) still doesn't call anything like propagateUpdateToSameNodeAliases for other row aliases pointing at the same doc, unlike SetStep.applyPropertySet. Pre-existing asymmetry, not introduced here, but since this PR is already unifying SET/REMOVE label-handling it might be worth a follow-up issue.
  • LabelReplacements.redirect() gets called twice per row when a clause removes/adds labels (once at the top of applyRemoveOperations/applySetOperations, once again inside removeLabels/applyLabels after replace()). Harmless (second call is a no-op once state is live) and the code comments already call out that it's a deliberate re-confirmation, just noting the double walk for anyone tuning later.

Test coverage

Very good - CypherWithStarScopeIssue6311Test pins the Cartesian-product regression with and without OPTIONAL, control cases for explicit projection lists and WITH *, expr AS alias, and a dedicated test confirming the variable-length-pattern branch was never exposed to begin with. CypherLabelWriteRowFanoutIssue6312Test/LabelReplacementsTest cover UNWIND fanout, multi-row same-node matches, edge property preservation, self-loop counting, bound-path redirection, and idempotent statistics. The PR description's honesty about the #6313 expected-value discrepancy (2 rows, not the reported 1) is a good sign this was actually verified against the fixture rather than rubber-stamped.

I wasn't able to run mvn compile/test myself in this environment (build commands were gated), so this is a static read-through rather than a verified green run - the PR description says the full engine lane (15,730 tests) and the openCypher TCK (3,897 scenarios) were run green, which I'd lean on rather than re-verifying here.

…d like any other

A lightweight edge has no record to address, but LightEdgeRID carries the
(type, out vertex, in vertex) triple and hashes on it, so it keys the
replacement map exactly like a heavy edge's address does - and the copy
re-attached to the replacement vertex is a different key rather than the same
one. The position guard that skipped them is gone: a row holding one now
follows the endpoint that moved instead of answering with a vertex that no
longer exists. Two tests, one at the class and one through Cypher.

The snapshot comment now admits that the set also carries the hop's own target
and relationship names, and says why that is free: the identity check reads a
name only when the row ALSO already holds a vertex under it, and a name the hop
is about to bind for the first time is not in the row.
@lvca

lvca commented Aug 17, 2026

Copy link
Copy Markdown
Member Author

Third pass done.

Lightweight edges - turned out to be fixable rather than an accepted limitation, so they're fixed. The premise that a lightweight edge has no independent identity is half right: it has no address, but LightEdgeRID carries the (type, out vertex, in vertex) triple and RID.hashCode() folds the endpoints in for any record-less RID, so it keys the replacement map exactly like a heavy edge's address does - and the copy re-attached to the replacement vertex is a different key rather than the same one. Dropped the getPosition() > -1 guard; a row holding a lightweight edge now follows the endpoint that moved instead of answering with a vertex that no longer exists. Covered at both levels: LabelReplacementsTest.redirectRewritesALightweightEdgeOntoTheReplacement (fails without the change) and aBoundLightweightEdgeFollowsTheEndpointThatMoved through Cypher.

targetIdentityVars includes the hop's own names - correct, and the comment now says so plus why it's free: the check reads a name only when the row also already holds a vertex under it, and a name the hop is about to bind for the first time is absent from the row. Excluding them would need the set rebuilt per hop in the opposite order for no gain.

RemoveStep.removeProperty() alias asymmetry - agreed it's real and agreed it's not this PR's: it changes REMOVE's observable semantics rather than fixing a crash, and it's unrelated to the three issues here. Filed as #6328 with a repro and the suggested shared-helper fix.

Double redirect() per row - noted, no change: the second call is the one that runs right after replace(), and it's what makes the remaining items of the same clause see the new record. Skipping it would mean the first call has to know a replacement is coming.

Re-verified after the change: Cypher lane 7,039 green, openCypher TCK 3,897 green.

@claude

claude Bot commented Aug 17, 2026

Copy link
Copy Markdown

test

@claude

claude Bot commented Aug 17, 2026

Copy link
Copy Markdown

Review

I read through the full diff (CypherExecutionPlan.java, the new LabelReplacements.java, SetStep.java/RemoveStep.java, and all three new test classes) plus the surrounding code these changes interact with.

Overall

The two fixes are well targeted and the reasoning in the PR description checks out against the code:

  • The WITH * scope fix (applyProjectionToScope) correctly distinguishes "forward the incoming scope" from "reset to an explicit projection list," and WITH *, expr AS alias does both, matching the test withStarPlusAliasKeepsBothTheScopeAndTheAlias.
  • Snapshotting targetIdentityVars = new HashSet<>(boundVariables); targetIdentityVars.addAll(matchVariables) per hop, instead of handing MatchRelationshipStep the planner's live, mutable boundVariables set, is the right fix - MatchRelationshipStep only stores the reference in a field and never mutates it, so a fresh per-hop copy is safe and cheap (this only runs at plan-build time, not per row).
  • LabelReplacements is a solid piece of design: resolve() correctly walks a multi-hop replacement chain, redirect()'s identity-based short-circuit (live != value) avoids rebuilding untouched collections, and the self-loop de-duplication in replace() (OUT pass rewrites the loop onto the new vertex, IN pass explicitly skips originalRid.equals(edge.getOut())) is correct. I checked LightEdgeRID.getBucketId() against the track() guard (rid.getBucketId() > -1) - a lightweight edge's bucket id is the real edge-type bucket (only the offset is -1), so lightweight edges are tracked as the comment intends; that had me worried for a moment but it checks out.
  • Test coverage for the two fixed paths is thorough, including the deliberately-tricky cases (variable-length pattern immunity, lightweight edge endpoints, bound paths/collect() lists following a relabelled node, idempotency-with-correct-counting across UNWIND fanout).

Finding: the same label-rewrite bug is still live in MergeStep

MergeStep.applySetClause() (engine/src/main/java/com/arcadedb/query/opencypher/executor/steps/MergeStep.java:1397-1425), which implements ON CREATE SET n:Label / ON MATCH SET n:Label, still does its own inline vertex-retype and was not switched over to LabelReplacements:

case LABELS: {
  ...
  final MutableVertex newVertex = context.getDatabase().newVertex(newTypeName);
  for (final String prop : vertex.getPropertyNames())
    newVertex.set(prop, vertex.get(prop));
  newVertex.save();
  ...
  for (final Edge edge : vertex.getEdges(Vertex.DIRECTION.OUT))
    newVertex.newEdge(edge.getTypeName(), edge.getVertex(Vertex.DIRECTION.IN));
  for (final Edge edge : vertex.getEdges(Vertex.DIRECTION.IN))
    edge.getVertex(Vertex.DIRECTION.OUT).newEdge(edge.getTypeName(), newVertex);
  vertex.delete();
  ((ResultInternal) result).setProperty(variable, newVertex);
  break;
}

This is exactly the pre-fix SetStep/RemoveStep code this PR replaces, so it reproduces the same three defects, and one of them is worse here:

  1. Dangling alias in the same row. executeMerge() seeds baseResult by copying every property of the upstream inputResult (line ~202-206), so a node the MERGE pattern binds under its own variable (n) can already be bound under a different alias from an earlier MATCH in the same row (e.g. MATCH (m) MERGE (n {id: m.id}) ON MATCH SET n:Extra). applySetClause only does result.setProperty(variable, newVertex) for n - it never redirects m, which is exactly the "second alias in the same row" scenario ArcadeDB 26.8.1: REMOVE after OPTIONAL MATCH and UNWIND raises RecordNotFoundException #6312 is about. There's no per-row LabelReplacements-style tracking here at all, not even the old propagateUpdateToSameNodeAliases that SetStep already had pre-PR.
  2. Edge properties silently dropped: newVertex.newEdge(edge.getTypeName(), edge.getVertex(...)) is called with no properties array, same as the bug fixed in SetStep/RemoveStep.
  3. Self-loops are actually worse than "duplicated" here. There's no originalRid.equals(...) substitution: for a self-loop, the OUT-direction pass reads edge.getVertex(Vertex.DIRECTION.IN), which is still the original vertex about to be deleted, so it recreates the edge as newVertex -[:R]-> <deleted original> - a dangling edge to a record that no longer exists, rather than merely a doubled edge. The IN-direction pass has the mirror problem via edge.getVertex(Vertex.DIRECTION.OUT).

There's also no test coverage anywhere in the suite for ON CREATE SET/ON MATCH SET label-rewriting (a search over OpenCypherMergeActionsTest and friends shows only property-SET cases exercised for MERGE's SET sub-clauses).

Since LabelReplacements was already factored out as a shared, public class specifically to be reused (per the PR description: "Both now share one LabelReplacements"), routing MergeStep's LABELS case through it looks like a small, mechanical follow-up rather than new design work - but as it stands, MERGE ... ON CREATE/ON MATCH SET n:Label remains a live route to RecordNotFoundException/dropped edge properties/dangling self-loop edges after this PR merges. Worth doing in this PR or immediately after, with a regression test mirroring CypherLabelWriteRowFanoutIssue6312Test.

Minor notes (non-blocking)

  • applyProjectionToScope's "*".equals(name) sentinel check relies on the star item's expression text literally being "*". That mirrors how the pre-existing code already modeled WITH * (it used to add the literal string "*" to the bound-variables set), so it's not a new fragility, just worth knowing if the Cypher AST for WithClause/ReturnItem ever changes how a star item is represented.
  • Nothing else stood out on performance or security - the new allocations (targetIdentityVars, the LabelReplacements maps) are all bounded by plan size / distinct relabelled nodes per step, not per-row scans of anything unbounded.

Nice, thorough write-up in the PR description, and I appreciate that the tests pin the two "control" cases (explicit WITH n0, n1, n2, and the variable-length pattern that turns out to be immune) rather than only the failing ones.

…rewrite as everything else

The third copy of the pre-fix code was in MergeStep, and its self-loop handling
was worse than the other two: the OUT pass re-created the loop against
edge.getVertex(IN), which is still the record about to be deleted, so a
relabelled node with a self-loop came out with an edge pointing at nothing.
Edge properties were dropped there too, and nothing redirected the aliases -
not even the propagateUpdateToSameNodeAliases that SET had before this branch,
so a node the input row also bound under another name was left on the deleted
record.

It now takes the shared LabelReplacements, one per running step, exactly as SET
and REMOVE do. Two tests: the alias case, which fails without this, and the
same node merged on three rows.
@lvca

lvca commented Aug 17, 2026

Copy link
Copy Markdown
Member Author

Good catch on MergeStep - fixed here rather than after, since it's the same defect on the same route.

It was the third copy of the pre-fix code, and you're right that its self-loop handling is worse than the other two were: the OUT pass re-created the loop against edge.getVertex(DIRECTION.IN), which is still the record about to be deleted, so a relabelled node with a self-loop came out with an edge pointing at nothing. Edge properties were dropped there too, and nothing redirected aliases - not even the propagateUpdateToSameNodeAliases SetStep already had, so a node the input row bound under a second name was simply left on the deleted record.

ON CREATE SET/ON MATCH SET n:Label now takes the shared LabelReplacements, one instance per running step, threaded through executeMerge → applySetClause exactly as SetStep and RemoveStep scope theirs to the running ResultSet. That brings all four things with it: the edges carried over with their properties, the self-loop migrated once and onto the replacement, the row's aliases redirected, and the cross-row idempotence.

Two tests: mergeOnMatchSetLabelKeepsEdgesAndRedirectsEveryAlias (the MATCH (m) + MERGE (n) second-alias case - fails without the change) and mergeOnMatchSetLabelSurvivesTheSameNodeOnSeveralRows.

On the "*" sentinel note - agreed it's not new fragility; it's the same representation the pre-existing code keyed on, just read instead of copied into the scope.

Re-verified: Cypher + MERGE lanes 7,085 green, openCypher TCK 3,897 green.

@claude

claude Bot commented Aug 17, 2026

Copy link
Copy Markdown

Review of #6326

I reviewed the diff across CypherExecutionPlan.java, the new LabelReplacements.java, MergeStep.java, RemoveStep.java, SetStep.java, and the three new test classes. Overall this is a well-scoped, carefully reasoned pair of fixes with strong test coverage; I did not find correctness bugs. Notes below are minor and non-blocking.

#6311 (WITH * scope)

  • applyProjectionToScope correctly distinguishes "forward incoming scope" (WITH *) from "reset to named items" (explicit projection), and WITH *, expr AS alias does both by not clearing scope while still adding the extra alias. Matches the description.
  • The targetIdentityVars snapshot (boundVariables + matchVariables-so-far) is taken at the point each hop is built, which is exactly what's needed since boundVariables is a live/mutable set that a following WITH clears. Good catch that this had to be fixed in both the optimizer path (buildMatchStep) and the legacy path (around the legacyBoundVariables/ExpandPathStep branch) - the legacy path is dead for parsed queries today per the commit message, but keeping both in sync avoids exactly the "two execution paths, one fixed" landmine CLAUDE.md calls out for this module.
  • The variable-length (*1..2) branch is correctly identified as immune by construction (ExpandPathStep reads its bound target from the row, not from a plan-time set), and it's still pinned by a regression test rather than just asserted in a comment - good practice given how easy it'd be for a future refactor to reintroduce the coupling.

#6312/#6313 (label write leaves dangling references)

  • LabelReplacements.resolve() correctly walks a multi-hop replacement chain (tested directly in LabelReplacementsTest.resolveFollowsAChainOfReplacements).
  • replace()'s outgoing-then-incoming edge migration order, with the incoming pass skipping originalRid.equals(edge.getOut()), correctly migrates a self-loop exactly once - this was a real bug in the old MergeStep copy (self-loop re-created against the about-to-be-deleted vertex) that's now fixed by sharing one implementation across SetStep/RemoveStep/MergeStep.
  • Edge properties are now carried over via propertiesOf() instead of being silently dropped by the old newEdge(type, target) re-link - a real, user-visible data-loss bug fixed here.
  • redirect()'s descent into List/Map/TraversalPath values (not just top-level row properties) closes a gap the original SET-only fix didn't have (aliases inside collect(), path variables). The "rebuild only if something inside actually moved, return the same instance otherwise" identity-preservation is a nice touch and is explicitly tested (redirectLeavesARowWithNothingToRewriteUntouched).
  • Lightweight edges are tracked correctly: LightEdgeRID keeps a real (positive) bucketId with a -1 offset, so track()'s rid.getBucketId() > -1 guard does include lightweight edges in the replacement map, consistent with the docstring's claim that they hash on (type, out, in) like a heavy edge's address. (This guard reads a little confusingly next to the docstring on first pass - worth a one-line comment noting why the check is on bucketId alone rather than RID.isValid(), since a future reader might reasonably wonder if it's meant to exclude lightweight edges.)
  • SetStep's writtenDocs.remove(originalRid) correctly uses the resolved (live) RID captured after labelReplacements.resolve(vertex), not a stale RID from the row - consistent with the invalidation actually needing to target the record that's about to be deleted by replace().

Tests

Coverage is thorough: unit tests for LabelReplacements in isolation (chain resolution, edge/property carry-over, self-loop dedup, redirect over nested/path-shaped values, lightweight edges), plus integration tests through Cypher covering UNWIND fanout, multiple aliases of the same node, MERGE's ON MATCH SET, and idempotency/statistics-counting across fanned-out rows. The PR description states reverting the fix fails 7/10 new tests with 3 controls still passing, and cites full engine + openCypher TCK suite runs as green.

Minor/non-blocking

  • LabelReplacements.track()'s rid.getBucketId() > -1 null/validity guard appears to be effectively always-true for edges reachable via vertex.getEdges() (both heavy and lightweight always have a real bucket id) - harmless defensive code, but if it's truly unreachable it could be simplified to just rid != null, or if it's guarding against something specific, a short note on what would make it false would help the next reader.
  • I wasn't able to run mvn verify/the new test classes in this review environment (build tool invocation was sandboxed here), so this review is based on static reading rather than an independent test run - the PR description's own verification numbers (15,730 engine tests + 3,897 TCK scenarios green) should stand in for that.

No blocking issues found. Sharing one LabelReplacements implementation across SET/REMOVE/MERGE instead of three near-duplicate copies (which is how the self-loop and edge-property bugs diverged in the first place) is the right call.

The bucket check read as if it were excluding lightweight edges, which is the
opposite of what it does. Every edge that came out of getEdges() has a bucket,
so only the null is worth guarding, and the comment now leads with the fact
that lightweight edges are tracked like any other.
@lvca

lvca commented Aug 17, 2026

Copy link
Copy Markdown
Member Author

Taken - the guard now says what it guards. You're right that it read backwards: the getBucketId() > -1 half looked like it was excluding lightweight edges when it does the opposite, and it can't be false for an edge that came out of getEdges() anyway. Reduced to the null check, with the comment leading on the fact that lightweight edges are keyed here like any other.

That's the last open point from my side: the three reported defects are fixed with regression tests that fail without them, the two latent ones the shared rewrite exposed (edge properties dropped, self-loop duplicated - dangling, in MERGE's copy) are fixed with it, and the one genuinely out-of-scope item is filed as #6328.

Final verification on this head: Cypher + MERGE lanes 7,085 green, openCypher TCK 3,897 green, full engine unit lane green.

@codacy-production

codacy-production Bot commented Aug 17, 2026 •

Copy link
Copy Markdown

Not up to standards ⛔

🔴 Issues 2 high

Alerts:
⚠ 2 issues (≤ 0 issues of at least minor severity)

Results:
2 new issues

Category Results
ErrorProne 2 high

View in Codacy

🟢 Metrics 36 complexity

Metric Results
Complexity 36

View in Codacy

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

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

View coverage diff in Codacy

Coverage variation details
Coverable lines Covered lines Coverage
Common ancestor commit (bdf46f9) 160346 127117 79.28%
Head commit (daba60d) 192796 (+32450) 140243 (+13126) 72.74% (-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 (#6326) 157 150 95.54%

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 17, 2026

Copy link
Copy Markdown

Review

This is a well-documented fix with solid regression coverage for the three reported issues (#6311, #6312, #6313), and the commit history shows real iteration in response to review (legacy plan builder parity, path/collection redirection, lightweight edges, MergeStep). The WITH * scope fix (applyProjectionToScope) and the snapshot-instead-of-live-reference fix for MatchRelationshipStep both look correct and are exercised well by CypherWithStarScopeIssue6311Test.

The LabelReplacements machinery for #6312/#6313 is well-designed in principle (one shared instance per step, redirect-before-touch), but I found two gaps in it that reproduce the same failure class the PR fixes, just for cases not covered by the new tests.

1. LabelReplacements.redirectValue() does not chain-follow edges, unlike resolve() for vertices

LabelReplacements.java:70-82 (resolve()) explicitly walks the replacement chain for vertices:

Vertex current = vertices.get(rid);
...
while ((next = vertices.get(current.getIdentity())) != null)
  current = next;

but the Edge branch of redirectValue() (LabelReplacements.java:120-125) does a single-hop lookup: edges.get(rid), with no equivalent loop.

replace() deletes the original vertex, which cascades and deletes its adjacent edges (GraphEngine.deleteVertex -> deleteEdgesOf, GraphEngine.java:1004-1014). So if an edge gets migrated twice in the same step, once when either of its endpoints is relabelled, the edges map ends up with a two-hop chain, e.g. R0 -> R1 then R1 -> R2, where R1 is itself now a deleted record.

Repro shape: MATCH (a)-[r]->(b), (x) SET a:X, b:Y where x fans a shared a/r/b out over several rows. The row currently being processed gets fixed up correctly because redirect(result) runs again after each replace() call within that row, so its r tracks R0 -> R1 -> R2 one hop at a time. A different, not-yet-processed row that still holds the original edge object (R0) is never touched by those intra-row calls; when it is processed later, the top-of-method redirect(result) resolves r via a single edges.get(R0), landing on the now-deleted intermediate R1 instead of the live R2. That reproduces the exact RecordNotFoundException class this PR sets out to fix, just one hop deeper and for the "both endpoints relabelled" case rather than the single-vertex case the new tests cover.

LabelReplacementsTest.resolveFollowsAChainOfReplacements only exercises the vertex chain with an edge-less vertex, so this path isn't covered. Suggest giving redirectValue()'s edge branch the same while loop resolve() has (or routing edges through resolve()-style chain following), plus a test with a fanned-out row sharing an edge whose two endpoints are relabelled in the same clause.

2. MergeStep.executeMerge reads baseResult for pattern matching before any redirect() call

MergeStep.java:205-210 builds baseResult by copying properties straight from inputResult:

final ResultInternal baseResult = new ResultInternal();
for (final String prop : inputResult.getPropertyNames())
  baseResult.setProperty(prop, inputResult.getProperty(prop));

mergeSingleNodeAll/mergePathAll/findAllMatchingPaths then read vertices out of baseResult for anchor/existing-binding checks (e.g. MergeStep.java:262, 373, 430) before any redirection happens. labelReplacements.redirect(result) is only called later, inside applySetClause (MergeStep.java:1311), which runs after the pattern-matching phase and only when ON CREATE SET/ON MATCH SET is present.

SetStep and RemoveStep both redirect the whole incoming row up front, before touching any variable (SetStep.java:139, and the equivalent in RemoveStep). MergeStep doesn't, so if an earlier row's ON MATCH SET n:Label relabelled a node, and a later fanned-out row's MERGE pattern reuses that same bound node (e.g. MATCH (n) MERGE (n)-[:R]->(m) ON MATCH SET n:Foo over several rows sharing n), the pattern-matching logic on the later row runs against the already-deleted original vertex, not the live replacement.

Suggest moving a labelReplacements.redirect(...) call to right after baseResult is populated in executeMerge, before mergeSingleNodeAll/mergePathAll are invoked, and adding a MERGE test where an earlier row relabels a node that a later row's pattern (not just its ON ... SET) still needs to match against.

Minor / non-blocking

  • LabelReplacements.replace()/track() re-implements "move an edge onto a different vertex" via delete-and-recreate, which is why it needs its own RID -> Edge map and the redirectValue() machinery. GraphEngine.moveEdge() already does this while preserving the edge's own identity and external-property/index bookkeeping; worth a look at whether that could be reused instead of two parallel "move an edge" implementations with different guarantees.
  • SetStep.java:456, RemoveStep's equivalent (~line 257), and MergeStep's equivalent (~line 1412) each call labelReplacements.resolve(vertex) again right after the enclosing method's own redirect(result) already resolved it, per the "today this only re-confirms it" comment. Cheap, but it's the same defensive block and near-identical comment duplicated three times, worth collapsing into LabelReplacements itself (e.g. a resolveForWrite(Result, String variable) helper) if it needs to change later.
  • MatchRelationshipStep's constructor still stores whatever Set<String> it's given by direct reference; the fix snapshots at the two call sites that broke rather than making the constructor itself reject/copy a live reference. A Set.copyOf(...) at the constructor boundary (or at minimum a javadoc note) would make it harder for a future third call site to reintroduce the ArcadeDB 26.8.1: WITH * changes OPTIONAL MATCH cardinality #6311 aliasing bug.

Test coverage

The new tests are thorough for the scenarios they target (idempotent re-removal/re-add across UNWIND fanout, edge property carryover, self-loop dedup, lightweight edges, paths, collected lists), and the AssertJ style and @author/no-System.out conventions all look clean. The two gaps above (edge chain-following, MERGE pattern-read-before-redirect) aren't covered by the current suite; both would need a fanout scenario where a different row than the one that triggered the replacement is the one that observes the stale reference, which is a slightly different shape than what's tested today.

Everything else I checked (self-loop handling, Vertex.newEdge varargs signature, LightEdgeRID identity/hashing for the edge map, private-method call-site consistency across SetStep/RemoveStep/MergeStep/CypherExecutionPlan, and CLAUDE.md conventions) checked out correctly.

@codecov

codecov Bot commented Aug 17, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 87.26115% with 20 lines in your changes missing coverage. Please review.
✅ Project coverage is 70.58%. Comparing base (bdf46f9) to head (daba60d).

Files with missing lines Patch % Lines
...b/query/opencypher/executor/LabelReplacements.java 86.60% 3 Missing and 12 partials ⚠️
...query/opencypher/executor/CypherExecutionPlan.java 85.71% 3 Missing ⚠️
...edb/query/opencypher/executor/steps/MergeStep.java 88.88% 1 Missing ⚠️
...adedb/query/opencypher/executor/steps/SetStep.java 85.71% 0 Missing and 1 partial ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #6326      +/-   ##
==========================================
+ Coverage   70.54%   70.58%   +0.04%     
==========================================
  Files        1848     1849       +1     
  Lines      160346   160431      +85     
  Branches    33724    33742      +18     
==========================================
+ Hits       113118   113247     +129     
+ Misses      33267    33218      -49     
- Partials    13961    13966       +5     

☔ 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
… 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.
lvca added a commit that referenced this pull request Aug 18, 2026
… same thing wherever the node sits, and the star is what the parser wrote rather than what it is called (#6348)

* 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

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

* fix(#6334, #6335): the duplicate-column check asks the item too, and 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.

* fix(#6338): a node pattern in expression position learns its disjunction 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.

* fix(#6338): the refusal keys on the disjunction, not on how many labels 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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

1 participant