Skip to content

Fix issues #7896, #7892, #7889, #7884, #7881 - #8091

Merged
lvca merged 13 commits into
mainfrom
fix/issues-7896-7892-7889-7884-7881
Sep 21, 2026
Merged

lvca merged 13 commits into
mainfrom
fix/issues-7896-7892-7889-7884-7881

Conversation

@lvca

@lvca lvca commented Sep 21, 2026 •

Copy link
Copy Markdown
Member

Five independent fixes, each with a regression test verified to fail on the unfixed code.

Closes #7896
Closes #7892
Closes #7889
Closes #7884
Closes #7881

#7896 - redundant parentheses renamed unaliased projections (sql, major)

The #7774 parenthesis fix made BaseExpression.rendersParentheses() answer yes for every parenthesised expression carrying a modifier chain. That method sits on the projection-naming path, so SELECT (name).asString() FROM T silently became the column (name).asString() where it had always been name.asString(); a client reading the result by its historical key got null.

The predicate now asks whether the parenthesised atom has a modifier* tail of its own in the grammar. It does not for a NUMBER, NULL, a boolean or RID literal, a parenthesised WHERE clause or an array concatenation - those keep their parentheses, which is all (42).asString() ever needed. It does for an identifier chain, a string literal, a function call, an input parameter, a map or array literal, a CASE block and a parenthesised statement, so for those the parentheses go back to being the noise they were. Anything the predicate does not recognise keeps its parentheses: a wrong "yes" is a statement that no longer parses, a wrong "no" is only a column name.

#7892 - removeSuperType left the ancestor's index over the detached subtree (engine, major)

removeSuperType undid the polymorphic BUCKET side of a linkage (#6935) and nothing else. The sub-indexes addSuperType creates over the subtype's buckets stayed attached to the ancestor's TypeIndex, so after the link was severed lookupByKey handed back records of a foreign type, countEntries() counted them, and the ancestor's UNIQUE constraint stayed enforced across them - refusing a key that was genuinely free. SELECT was spared because the planner filters index results by type downstream, which is why this survived #6935 unnoticed. The attachment also survived a reopen, since schema.json still listed the component under the ancestor.

The issue left the drop-versus-detach decision open. Dropped is the answer here, and it is what makes this the exact mirror of addSuperType: the components exist BECAUSE of the linkage, they index a property the subtype no longer even has, and a detachment alone would leave them on disk for the next reload to hook straight back up. Which buckets are no longer reached is read from the polymorphic caches unlinkSuperType has just recomputed - never subtracted from the detached subtree - so a bucket a diamond still reaches through another surviving path keeps its sub-index. Because the propagated set is getAllIndexes(true), the walk goes up the ancestor's own super types too, which is what catches a grandchild's buckets on the top ancestor's wrapper.

#7889 - a null argument to remove()/removeAll() meant two things by position (sql, major)

Both are varargs but gated the whole operation on the FIRST argument being non-null, so a leading null silently discarded every argument after it while the same null one position later was acted on. UPDATE ... SET tags = tags.remove(:a, :b) with a null first parameter left the property untouched and reported success.

The issue offered two normalisations. The one taken here is the second: keep the guard at "there is an argument" and make the removal null-safe, rather than skipping nulls the way append() does. A collection really can hold a null element, the loop already honoured a null in every position but the first, and skipping would delete a capability to fix an inconsistency. MultiValue.removeFromCollection now binds Objects.equals instead of iToRemove::equals - which throws from Objects.requireNonNull before the first element is even looked at - so the removeAll(x, null) NPE goes with it. The argument stays the receiver of the comparison, matching both the method reference it replaces and Collection.remove(Object).

#7884 - the overlay's add side dedupped by presence (concurrency, critical)

#7042 gave the deletion side of post-compaction re-application a multiplicity comparison; the add side still probed hasForwardEdge and skipped a buffered add whenever the fresh base held any occurrence of the pair. With parallel edges that drops a real edge: one occurrence of s -> t in the fresh run and a buffered add of a second one, and the second existed in neither the fresh base nor the overlay until the next compaction.

The subtraction is the same one, read the other way round: exactly max(0, fresh - before) of a pair's buffered additions were captured by the scan, and those - a prefix, so they are counted rather than probed - are the only ones skipped. The masked-as-deleted branch, the alreadyInFreshBase bookkeeping and the #6777 RID-reservation handling are unchanged. The residual this closes is struck from GraphAnalyticalView.countBetweenForType's javadoc; #6777's RID reuse stays, and so does the clamp.

#7881 - the transaction index overlay compared array-valued keys shallowly (audit, critical)

An index key is an Object[] whose elements may themselves be arrays - a BINARY property is a byte[] - and Arrays.equals compares such an element by identity. #7109 routed DocumentIndexer through Objects.deepEquals for exactly that reason; TransactionIndexContext.IndexKey and ComparableKey were left on the shallow form while ComparableKey.compareTo compared the very same elements by content through BinaryComparator. compareTo orders the TreeMap of pending entries and equals/hashCode key the HashMap inside each of its values, so the outer lookup found the key and the inner one missed it.

One correction to the issue's account of the damage: the in-transaction duplicate check does still fire, because the adjacent cross-sub-index sweep reads its per-key map by iteration rather than by lookup. That sweep is also what turned the real defect into something louder than a silent stale entry - it saw the stale ADD the REMOVE should have retired and refused a perfectly legitimate delete-and-reinsert of the same BINARY key in one transaction with a DuplicatedKeyException.

Rather than fix the two call sites, the policy now lives in one place, com.arcadedb.index.IndexKeyEquality, which both DocumentIndexer and TransactionIndexContext read from, so a third side cannot pick a fourth notion of equality.

Tests

New:

  • Issue7896UnaliasedParenthesizedProjectionNameTest (7 tests; 4 fail before the fix)
  • Issue7889NullArgumentPositionTest (6 tests; 5 failures + 1 NPE before the fix)
  • Issue7881TransactionIndexArrayKeyEqualityTest (4 tests; 2 fail before the fix)
  • Issue7892RemoveSuperTypeDetachesIndexesTest (5 tests; all 5 fail before the fix)
  • DeltaOverlayCompactionAddDedupTest (6 tests; 4 fail before the fix)

Regression runs, all green: the whole com.arcadedb.graph.olap package (302), com.arcadedb.schema + com.arcadedb.index (350 classes), com.arcadedb.query.sql (3133 tests). The one red in the SQL run was SQLMethodPrecisionTest.instant ("expected Millis but was Seconds"), a time-sensitive pre-existing flake that passes in isolation and is unrelated to anything here.

Summary by CodeRabbit

  • Bug Fixes

    • Fixed collection remove() and removeAll() handling when arguments include null.
    • Corrected index handling for binary and array-valued keys, including delete-and-reinsert operations within transactions.
    • Preserved parallel graph edges correctly during compaction and delta replay.
    • Prevented stale indexes and constraints after removing inherited type relationships.
    • Fixed projection names and parentheses for SQL expressions.
  • Tests

    • Added regression coverage for index keys, graph compaction, SQL projections, collection removal, and schema inheritance.

…ion (#7896)

The #7774 parenthesis fix made rendersParentheses() answer yes for EVERY
parenthesised expression carrying a modifier chain. That method sits on the
projection-naming path - an unaliased column is named after the text its
expression renders to - so SELECT (name).asString() FROM T silently became the
column "(name).asString()" where it had always been "name.asString()", and a
client reading the result by its historical key got null.

The parentheses are only load-bearing around an atom the grammar gives no
modifier* tail of its own: a NUMBER, NULL, a boolean or RID literal, a
parenthesised WHERE clause, an array concatenation. For an identifier chain, a
string literal, a function call, an input parameter, a map or array literal, a
CASE block or a parenthesised statement, X.method() parses exactly as
(X).method() means, so the parentheses go back to being the noise they were.

Anything the predicate does not recognise keeps its parentheses: a wrong yes is
a statement that no longer parses, a wrong no is only a column name.
… things by position (#7889)

Both are declared varargs but gated the WHOLE operation on the FIRST argument
being non-null, so a leading null silently discarded every argument after it
while the same null one position later was acted on:
[1,2,3].remove(null,2) answered [1,2,3] and reported success where
[1,2,3].remove(2,null) answered [1,3]. An UPDATE ... SET tags = tags.remove(:a,
:b) whose first bound parameter happened to be null left the property exactly as
it was and reported success. The sibling append() lost the same positional
contradiction under #7028.

The guard is now only "there is an argument", which keeps the ability to remove
a null ELEMENT - a collection really can hold one, and the loop already honoured
it in every position but the first. MultiValue.removeFromCollection binds
Objects.equals instead of iToRemove::equals, which throws from
Objects.requireNonNull before the first element is even looked at: that was the
NPE removeAll(2, null) raised where remove(2, null) was harmless. The argument
stays the receiver of the comparison, matching both the method reference it
replaces and Collection.remove(Object).
… by content (#7881)

An index key is an Object[] whose elements may themselves be arrays - a BINARY
property is a byte[] - and Arrays.equals compares such an element by IDENTITY.
#7109 routed DocumentIndexer through Objects.deepEquals for exactly that reason;
TransactionIndexContext.IndexKey and ComparableKey were left on the shallow form
while ComparableKey.compareTo compared the very same elements BY CONTENT through
BinaryComparator.

Both are used, on the same data, by the same code path: compareTo orders the
TreeMap of pending entries and equals/hashCode key the HashMap inside each of its
values. The outer lookup found the key and the inner one missed it, so the ADD
never found the REMOVE it was meant to retire and was not turned into a REPLACE
carrying the superseded oldRid - which is what commit keys the removal of the old
RID on. The adjacent cross-sub-index check reads its per-key map by iteration
rather than by lookup, so it still saw the stale ADD and refused a perfectly
legitimate delete-and-reinsert of the same BINARY key in one transaction with a
DuplicatedKeyException.

The policy now lives in one place, com.arcadedb.index.IndexKeyEquality, which
both sides read from, so a third side cannot pick a fourth notion of equality.
… too (#7892)

#6935 taught unlinkSuperType to rebuild the ancestor's polymorphic BUCKET caches
from what is still linked, so SELECT FROM <ancestor> no longer reaches the
detached subtree. The INDEX side was never undone: the sub-indexes addSuperType
creates over the subtype's buckets are attached to the ancestor's TypeIndex, and
nothing detached them when the link went away.

The ancestor's wrapper therefore kept fanning out over the detached subtree:
lookupByKey handed back records of a foreign type, countEntries() counted them,
and the ancestor's UNIQUE constraint stayed enforced across them, refusing a key
that was genuinely free. SELECT was spared only because the planner filters index
results by type downstream, which is why this survived #6935 unnoticed. The
attachment also survived a reopen, since schema.json still listed the component
under the ancestor.

Dropped rather than merely detached, which makes it the exact mirror of
addSuperType: the components exist BECAUSE of the linkage, they index a property
the subtype no longer even has, and a detachment alone would leave them on disk
for the next reload to hook straight back up. Which buckets are no longer reached
is read from the polymorphic caches unlinkSuperType has just recomputed, never
subtracted from the detached subtree, so a bucket a diamond still reaches through
another surviving path keeps its sub-index. Because the propagated set is
getAllIndexes(true), the walk goes up the ancestor's own super types too.
…ence (#7884)

#7042 gave the deletion side of post-compaction overlay re-application a
multiplicity comparison: it spends an exclusion budget only for as many
occurrences of a pair as the freshly scanned base still carries. The add side,
three hundred lines earlier in the same method, still dedupped by presence - it
probed hasForwardEdge and skipped the buffered add whenever the fresh base held
ANY occurrence of the pair.

With parallel edges that drops a real edge. One occurrence of s -> t in the fresh
run and a buffered add of a SECOND one, and the second existed in neither the
fresh base nor the overlay: getNeighborIds, isConnectedTo and countEdgesBetween
reported the pair once instead of twice until the next compaction rebuilt the
base from the store.

The symmetry with the deletion side is exact. There the scan SWALLOWING a change
led to an over-spent budget and the fix was to subtract forwardEdgeCount from the
pre-compaction count; here the scan MISSING a change leads to an under-count and
the same subtraction, read the other way round, is the fix: exactly
max(0, fresh - before) of a pair's buffered additions were captured by the scan,
and those - a prefix, so they are counted - are the only ones skipped.

The residual this left is struck from GraphAnalyticalView.countBetweenForType's
javadoc; #6777's RID reuse stays, and so does the clamp.
@lvca lvca added this to the 26.10.1 milestone Sep 21, 2026
@lvca lvca self-assigned this Sep 21, 2026
@coderabbitai

coderabbitai Bot commented Sep 21, 2026 •

Copy link
Copy Markdown

Review Change StackReview Change Stack

Understand this PR’s impact

Explore downstream dependencies and potential security impact with Blast Radius.

View blast radius →

Warning

Review limit reached

Next included review available in 7 minutes.

Check out review usage here.

View limit details

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

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

Learn how review limits work.

Review configuration:

⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Advanced

Run ID: 28de0797-16fb-4c57-b63c-109aa28380f0

📥 Commits

Reviewing files that changed from the base of the PR and between 657baf1 and 3edb18f.

📒 Files selected for processing (6)
  • engine/src/main/java/com/arcadedb/graph/olap/DeltaOverlay.java
  • engine/src/main/java/com/arcadedb/schema/LocalDocumentType.java
  • engine/src/main/java/com/arcadedb/schema/LocalSchema.java
  • engine/src/test/java/com/arcadedb/index/Issue7881TransactionIndexArrayKeyEqualityTest.java
  • engine/src/test/java/com/arcadedb/query/sql/method/Issue7896UnaliasedParenthesizedProjectionNameTest.java
  • engine/src/test/java/com/arcadedb/schema/Issue7892RemoveSuperTypeDetachesIndexesTest.java

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Advanced

Run ID: 47c99193-a1c3-4cdd-bdb7-4d10a49afb44

📥 Commits

Reviewing files that changed from the base of the PR and between b9bb24d and 657baf1.

📒 Files selected for processing (1)
  • engine/src/main/java/com/arcadedb/query/sql/antlr/SQLASTBuilder.java

Included review availability: Your plan provides up to 4 included reviews per hour; 1 remains after this review.


📝 Walkthrough

Walkthrough

The pull request adds shared content-aware index-key equality, multiplicity-aware graph overlay reapplication, corrected SQL expression rendering, null-safe collection removal, and cleanup of indexes detached by supertype removal. Regression tests cover each behavior.

Changes

Index key equality

Layer / File(s) Summary
Shared index-key equality policy
engine/src/main/java/com/arcadedb/index/IndexKeyEquality.java, engine/src/main/java/com/arcadedb/database/DocumentIndexer.java, engine/src/main/java/com/arcadedb/database/TransactionIndexContext.java, engine/src/test/java/com/arcadedb/index/*
IndexKeyEquality provides content-aware tuple equality and hashing. The indexer and transaction overlay use it for array-valued keys. Tests cover equality, hashing, duplicate detection, and delete-reinsert behavior.

Parallel-edge reapplication

Layer / File(s) Summary
Multiplicity-aware addition reapplication
engine/src/main/java/com/arcadedb/graph/olap/DeltaOverlay.java, engine/src/main/java/com/arcadedb/graph/olap/GraphAnalyticalView.java, engine/src/test/java/com/arcadedb/graph/olap/DeltaOverlayCompactionAddDedupTest.java
DeltaOverlay tracks additions absorbed by the fresh CSR according to pair multiplicity. Buffered parallel edges remain when the fresh scan did not capture them. Tests cover captured prefixes, masked deletions, and RID reuse.

Projection parentheses

Layer / File(s) Summary
Projection-name rendering rules
engine/src/main/java/com/arcadedb/query/sql/parser/BaseExpression.java, engine/src/main/java/com/arcadedb/query/sql/antlr/*Expression.java, engine/src/main/java/com/arcadedb/query/sql/antlr/SQLASTBuilder.java, engine/src/test/java/com/arcadedb/query/sql/method/Issue7896UnaliasedParenthesizedProjectionNameTest.java
Expression rendering keeps parentheses for literals and expressions that require them. Redundant parentheses around identifiers and other expressions no longer alter unaliased projection names.

Collection null arguments

Layer / File(s) Summary
Null-safe collection removal
engine/src/main/java/com/arcadedb/query/sql/executor/MultiValue.java, engine/src/main/java/com/arcadedb/query/sql/method/collection/SQLMethodRemove*.java, engine/src/test/java/com/arcadedb/query/sql/method/collection/Issue7889NullArgumentPositionTest.java
Removal methods process all supplied arguments when the first is null. MultiValue.removeFromCollection compares values with Objects.equals. Tests cover argument positions, null elements, and bound parameters.

Supertype index detachment

Layer / File(s) Summary
Detached subtree index cleanup
engine/src/main/java/com/arcadedb/schema/LocalDocumentType.java, engine/src/test/java/com/arcadedb/schema/Issue7892RemoveSuperTypeDetachesIndexesTest.java
Removing a supertype collects sub-indexes outside the recomputed bucket set, drops them, and removes empty TypeIndex wrappers. Tests cover descendants, diamond inheritance, relinking, uniqueness, and schema reopening.

Priority: ➖ Normal

Estimated code review effort: 4 (Complex) | ~60 minutes

Change: Bug fix · Severity of issue fixed: Medium

Suggested reviewers: robfrank

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 38.71% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 93 functions across 19 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly identifies the five issues addressed by the pull request and is concise.
Description check ✅ Passed The description explains all five fixes, motivation, related issues, implementation details, regression tests, and test results. It does not use the template headings or include the checklist, but the…
Linked Issues check ✅ Passed The pull request satisfies the coding requirements for all five linked issues. For [#7896], BaseExpression retains only required modifier parentheses, and regression tests verify unaliased projectio…
Out of Scope Changes check ✅ Passed The changes remain within the scope of [#7896], [#7892], [#7889], [#7884], and [#7881]. The shared IndexKeyEquality utility supports [#7881]. Parser comments, schema cleanup, graph bookkeeping, null…
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Commit to this branch
  • Create a new PR
🧪 Generate unit tests (beta)
  • Commit to this branch
  • Create a new PR

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

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@mergify

mergify Bot commented Sep 21, 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 Sep 21, 2026 •

Copy link
Copy Markdown

Up to standards ✅

🟢 Issues 0 issues

Results:
0 new issues

View in Codacy

🟢 Metrics 29 complexity

Metric Results
Complexity 29

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 Sep 21, 2026

Copy link
Copy Markdown

Review

I traced all five fixes against the actual source (not just the diff) since this touches some intricate paths (ANTLR AST wrapping, the delta-overlay compaction race, schema index linkage). Overall this is a strong PR: each fix is narrowly scoped, the reasoning in the doc comments is unusually precise, and the regression tests are well targeted at the exact race/edge case each issue describes.

#7896 (BaseExpression.rendersParentheses)

My first read made me suspect innerAtomCannotCarryAModifier() would mis-handle array literals and CASE blocks, since ArrayLiteralExpression/CaseExpression extend MathExpression directly rather than BaseExpression, and the method only special-cases expression.json before falling back to expression.mathExpression instanceof BaseExpression. Tracing SQLASTBuilder.visitArrayLit/visitCaseExpr/visitExtendedCaseExpr shows both are always wrapped as BaseExpression{expression = Expression{mathExpression = X}} before being attached to the parent, so the generic expression != null branch in carriesItsOwnModifierTail() correctly recognizes them regardless of what X is. This is a nice reuse of an existing AST invariant rather than special-casing every literal kind - worth a one-line comment in carriesItsOwnModifierTail() noting why expression != null is sufficient (every non-scalar atom is wrapped this way), since it's not obvious from this file alone and the next person touching the grammar could break the invariant without noticing.

#7892 (LocalDocumentType.dropSubIndexesNoLongerCovered)

The comment explaining why LocalSchema's own leaf-drop cleanup can't be reused here (it looks the wrapper up from the subtype's super-type chain, which was just severed) checks out against LocalSchema.dropIndexInternal - confirmed that path really would fail to find the ancestor wrapper post-unlink, so the supplementary cleanup loop is necessary, not defensive-programming cruft.

One gap: all five new tests exercise at most a 3-level hierarchy where the severed link is the direct super type. collectSubIndexesNoLongerCovered also recurses into formerSuperType.superTypes to catch indexes on a grandparent-of-the-ancestor that were transitively propagated down - that path isn't exercised by any test here. Given how much this PR already nails down, a 4-level fixture (Z <- A <- B <- C, sever B -> A, assert Z[...] also drops the orphaned components) would close the loop on that branch specifically.

#7889 (null-argument position in remove/removeAll)

Correct and minimal. Confirmed MultiValue.remove(..., iToRemove=null, iAllOccurrences=false) falls through the Collection/array/Map/Iterator instanceof checks safely to coll.remove(iToRemove), so the removeFromCollection null-safety fix is the only piece needed for both call shapes.

#7884 (DeltaOverlay add-side dedup by multiplicity)

Traced capturedByFreshScan against all 6 new tests and the production call site (GraphAnalyticalView around line 2446, which now threads the same PreCompactionPairCount used for the #7042 deletion-side fix into the add side). The formula is the exact mirror of the deletion side (max(0, fresh - before) vs. max(0, before - fresh)), the masked-as-deleted short-circuit still runs before the new check, and the preCount == null fallback correctly degrades to the pre-#7884 presence behavior for any caller that can't supply it. No issues found.

#7881 (IndexKeyEquality)

Logic is correct and the two former call sites (DocumentIndexer, TransactionIndexContext) are now provably using the same policy. Minor nit, not a bug: IndexKeyEquality.sameTuple/hashTuple hand-roll exactly what Arrays.deepEquals(Object[], Object[]) / Arrays.deepHashCode(Object[]) already do (same null/identity/length short-circuits, same element-wise deep-equals loop). Might as well delegate:

public static boolean sameTuple(final Object[] a, final Object[] b) {
  return Arrays.deepEquals(a, b);
}
public static int hashTuple(final Object[] tuple) {
  return Arrays.deepHashCode(tuple);
}

sameValue already delegates to Objects.deepEquals for the same reason - sameTuple doing its own loop instead of Arrays.deepEquals reads as a small inconsistency in an otherwise reuse-oriented file.

General

  • No leftover System.out/debug prints in the changed files.
  • No new dependencies.
  • I wasn't able to execute mvn test in this review environment (sandboxed, no approval available for build commands), so the above is static verification against the actual source rather than a fresh test run - the PR description's own test-run summary is the empirical evidence there, and none of the above changes my read of correctness.

Nice work - the doc comments on each fix make this unusually easy to review; the "why the old code was wrong" framing on every method is exactly what makes edge cases like the diamond-inheritance and RID-reuse tests legible.

lvca added a commit that referenced this pull request Sep 21, 2026
…nt, cover the grandparent walk

Three points from the PR #8091 review, none of them a defect:

- IndexKeyEquality.sameTuple hand-rolled exactly what Arrays.deepEquals already
  is - same identity and null short-circuits, same length check, same per-element
  comparison - in a file whose whole point is that one policy is reused. It
  delegates now, next to hashTuple's Arrays.deepHashCode, which also clears PMD's
  CompareObjectsWithEquals on the identity fast path.

- BaseExpression.carriesItsOwnModifierTail() recognises EVERY nested block through
  one  test, which works because of an invariant that lives in
  the AST builder and is invisible from this file: a map literal, an array literal
  and both CASE forms are each wrapped in a BaseExpression before being attached to
  a parent, although ArrayLiteralExpression and CaseExpression extend
  MathExpression directly. Named, with the sites that establish it, so a new
  grammar alternative that attaches one raw is recognisable as the thing that would
  break it.

- collectSubIndexesNoLongerCovered recurses into the FORMER SUPER TYPE'S own super
  types, and no test reached past a three-level hierarchy where the severed link was
  the direct one. Z6 <- A6 <- B6 <- C6 severing B6 -> A6 now pins it: Z6[n] keeps
  its component over A6's bucket and loses the ones over B6's and C6's. Verified to
  fail with that recursion removed.
…nt, cover the grandparent walk

Three points from the PR #8091 review, none of them a defect:

- IndexKeyEquality.sameTuple hand-rolled exactly what Arrays.deepEquals already
  is - same identity and null short-circuits, same length check, same per-element
  comparison - in a file whose whole point is that one policy is reused. It
  delegates now, next to hashTuple's Arrays.deepHashCode, which also clears PMD's
  CompareObjectsWithEquals on the identity fast path.

- BaseExpression.carriesItsOwnModifierTail() recognises EVERY nested block through
  one "expression != null" test, which works because of an invariant that lives in
  the AST builder and is invisible from this file: a map literal, an array literal
  and both CASE forms are each wrapped in a BaseExpression before being attached to
  a parent, although ArrayLiteralExpression and CaseExpression extend
  MathExpression directly. Named, with the sites that establish it, so a new
  grammar alternative that attaches one raw is recognisable as the thing that would
  break it.

- collectSubIndexesNoLongerCovered recurses into the FORMER SUPER TYPE'S own super
  types, and no test reached past a three-level hierarchy where the severed link was
  the direct one. Z6 <- A6 <- B6 <- C6 severing B6 -> A6 now pins it: Z6[n] keeps
  its component over A6's bucket and loses the ones over B6's and C6's. Verified to
  fail with that recursion removed.
@lvca
lvca force-pushed the fix/issues-7896-7892-7889-7884-7881 branch from 1801220 to 8381988 Compare September 21, 2026 16:54
@claude

claude Bot commented Sep 21, 2026

Copy link
Copy Markdown

Follow-up review

I re-traced this after the 83819881 follow-up commit, which folds in all three points from the prior claude-review pass on this PR. Verified each against the current source, not just the diff:

No new issues found in the delta. Two points worth having on the table, neither blocking:

  • IndexKeyEquality is a new shared-policy class consumed by three call sites (DocumentIndexer, TransactionIndexContext.IndexKey, TransactionIndexContext.ComparableKey) but has no test file of its own - it's only exercised indirectly through Issue7881TransactionIndexArrayKeyEqualityTest and the existing DocumentIndexer tests. Given the file's own docstring is explicitly about being the one place this policy lives, a small dedicated unit test (nested-array elements, mismatched lengths, null tuple vs. null element) would pin the contract directly rather than only through its callers.
  • I still can't execute mvn verify in this review sandbox (build commands require interactive approval that isn't available here), so this is static verification against the current source, same limitation as the previous pass. The PR description's reported test run (whole graph.olap, schema+index, query.sql packages green) is the empirical evidence for this diff.

Nothing else stood out on code quality, performance, or security across the five fixes - IndexKeyEquality/DeltaOverlay's new bookkeeping maps are scoped per-merge-call (no shared mutable state across concurrent compactions), no new dependencies, no leftover System.out/debug code in the diff.

…ough its callers

The class exists to be the ONE place the "are these the same index key?" policy
lives, and it was reachable only through the three call sites that read it. A
dedicated test states the contract itself: an array-valued element compared by
content (byte[], float[], int[] and a nested Object[] - the primitive arms are
where Arrays.equals differs from Arrays.deepEquals, and a BINARY property or a
dense vector key really is one), a scalar and a List keeping their own equality,
length mismatches, a null tuple against a null element, and equal tuples hashing
equally, which is the half of the contract a HashMap depends on and the half the
shallow form used to break.

Raised in the PR #8091 follow-up review.
@claude

claude Bot commented Sep 21, 2026

Copy link
Copy Markdown

Review

Went through all five fixes plus the follow-up "review" commit in detail (diff, surrounding call sites, and the grammar/AST-builder paths for the SQL fix). This is unusually well-documented and well-tested work; I traced each fix to its production call site to make sure it's actually wired in, not just covered by a unit test.

#7896 - parenthesized projection naming (BaseExpression)

Verified the new innerAtomCannotCarryAModifier() / carriesItsOwnModifierTail() predicates against SQLASTBuilder:

  • Map literals reach BaseExpression two different ways depending on whether a modifier follows (visitJsonLiteral sets Expression.json directly with no wrapper; visitMapLit wraps a BaseExpression{expression.json=...} inside mathExpression). The code handles both: the direct expression.json != null check catches the first, and the generic expression != null check inside carriesItsOwnModifierTail() catches the second.
  • Array literals, CASE, and extended CASE are all baseExpression grammar alternatives (visitArrayLit/visitCaseExpr/visitExtendedCaseExpr), so they always surface wrapped in an inner BaseExpression - matching the invariant the new javadoc calls out explicitly. Good call flagging that invariant as fragile to a new grammar alternative; that's exactly the kind of thing that bites later.
  • Function calls route through BaseIdentifier/LevelZeroIdentifier, so they're correctly covered by the identifier != null branch.

I didn't find a case the predicate mis-classifies. The "wrong no is only a column name, wrong yes breaks parsing" framing in the javadoc is a good safety property and the code lives up to it (everything unrecognized keeps its parentheses).

#7892 - removeSuperType index detachment

dropSubIndexesNoLongerCovered/collectSubIndexesNoLongerCovered reads bucket coverage from the current (post-unlinkSuperType) polymorphic cache rather than the detached subtree, which is the right call for the diamond case. The grandparent-walk test added in the follow-up commit (anIndexOwnedByTheGRANDPARENTOfTheSeveredLinkIsDetachedToo) is a good catch - without the recursion into type.superTypes, a multi-level chain would leave the top ancestor's wrapper still indexing the severed subtree. The wrapper-cleanup half (countIndexesOnBuckets() == 0 -> removeTypeIndexInternal + removeIndexDuringLoad) is correctly explained as necessary because the normal leaf-drop path in LocalSchema walks up from the subtype through super types to find the owner, and that's precisely the link that was just severed.

#7889 - null argument position in remove()/removeAll()

Straightforward and correct. Confirmed MultiValue.removeFromCollection's switch from iToRemove::equals to Objects.equals(iToRemove, element) - the NPE-on-bound-method-reference-with-null-receiver behavior described in the comment is accurate (JLS 15.13.3: the receiver of a bound instance method reference is evaluated, and NPE'd, at reference-creation time, not at invocation time). remove() (allOccurrences=false) was never affected since it goes straight to coll.remove(iToRemove), which is why only removeAll(x, null) used to throw. Good regression coverage for both the position contradiction and the NPE.

#7884 - DeltaOverlay add-side dedup by multiplicity

This is the one I checked most carefully since it's tagged critical/concurrency. Confirmed the production wiring: GraphAnalyticalView.java:2446 already passes the same preCompactionPairCount reference to merge() that the #7042 deletion-side fix uses, so this isn't a fix that only exists in test scaffolding - it's live on the real post-compaction re-application path. capturedByFreshScan's max(0, fresh - before) budget and the "prefix" accounting (via the shared absorbedAdditions map threaded through sequential merge() calls) mirrors the deletion side's logic correctly, and the RID-reuse test (aReusedRidOnTheSamePairIsCountedAsTheDistinctEdgeItIs) exercises the interaction between the two budgets on the same pair, which is exactly the kind of case that's easy to get wrong.

#7881 - IndexKeyEquality extraction

Clean extraction; sameTuple/hashTuple now delegate to Arrays.deepEquals/Arrays.deepHashCode, which is semantically identical to the previous hand-rolled loop (each already went through Objects.deepEquals per element) - the follow-up commit doing this delegation is a nice simplification with no behavior change. Single source of truth for DocumentIndexer and TransactionIndexContext closes the exact TreeMap/HashMap disagreement described.

Nitpicks (non-blocking)

  • None that I'd block on. Style, final usage, brace conventions, and @Tag usage (none of these need slow/benchmark/vector - they're all fast unit/DB tests) all look consistent with the rest of the codebase.
  • BaseExpression#carriesItsOwnModifierTail()'s javadoc already flags its own fragility to a future grammar alternative that attaches a raw ArrayLiteralExpression/CaseExpression without the BaseExpression wrap. Might be worth a one-line assertion or a grammar-level test hook for that invariant down the road, but that's a "nice to have," not something this PR owes.

Test coverage

Each fix has a focused regression test class that (per the PR description) was verified to fail pre-fix, plus the broader regression runs listed (olap, schema+index, sql). That matches the project's TDD guidance well. The diamond/grandparent/multiplicity edge cases in particular go beyond the minimum repro and test the actual invariants the fixes rely on.

Overall: solid, well-scoped fixes with real production wiring verified and good regression coverage. No correctness, performance, or security concerns found.

@claude

claude Bot commented Sep 21, 2026

Copy link
Copy Markdown

Review

Five independent, well-isolated fixes, each with a focused regression test that (per the PR description) fails on unfixed code. Overall this is high-quality, carefully reasoned work - the review below is mostly confirmation plus a couple of minor notes, no blockers found.

#7896 - BaseExpression.rendersParentheses() / innerAtomCannotCarryAModifier()

Traced the logic against the grammar for each branch (NUMBER/NULL/boolean/RID/WHERE/array-concat keep parens; identifier/string/function-call/map/array/CASE/parenthesized-statement drop parens). It's consistent with the AST-wrapping invariant described in carriesItsOwnModifierTail()'s javadoc (map/array/CASE nodes always arrive wrapped as BaseExpression{expression=Expression{...}}). The self-documented caveat - "a new grammar alternative that attaches one of those nodes RAW would slip past this and lose its parentheses" - is honest about the fragility; might be worth a short comment at the grammar/AST-builder call sites (visitMapLit/visitArrayLit/visitCaseExpr/visitExtendedCaseExpr) pointing back at this invariant, so a future change to those visitors doesn't silently break projection naming again. Not a blocker.

#7892 - removeSuperType / dropSubIndexesNoLongerCovered

Verified this is the correct mirror of addSuperType's propagation by tracing addIndexInternal: the per-bucket sub-index's typeName metadata is set to the subtype (since createSubIndexesFor calls schema.createBucketIndex(this, ...) with this = subtype), while the TypeIndex wrapper itself lives only in the ancestor's indexesByProperties map (the propIndex argument is non-null when propagated, so addIndexInternal's wrapper-creation branch never runs on the subtype). That confirms the javadoc's claim that LocalSchema's existing leaf-drop cleanup (type.removeTypeIndexInternal(parentTypeIndex), walking up from the subtype) can't reach the ancestor anymore once unlinkSuperType has already severed the link - so the new explicit owner.removeTypeIndexInternal(wrapper) step is genuinely necessary, not redundant with existing code. The diamond and grandparent test cases (aBucketStillReachedThroughAnotherPathOfADiamondKeepsItsSubIndex, anIndexOwnedByTheGRANDPARENTOfTheSeveredLinkIsDetachedToo) look like the right edge cases to pin.

#7889 - null-argument position in remove()/removeAll()

Straightforward and correct: the guard now only checks "is there an argument", and MultiValue.removeFromCollection was made null-safe with Objects.equals instead of binding iToRemove::equals (which threw on a null receiver before touching the first element). Matches the append() precedent from #7028.

#7884 - DeltaOverlay add-side dedup by multiplicity

capturedByFreshScan is the correct mirror of the #7042 deletion-side fix: capturable = fresh - before, clamped to a monotonically-consumed budget per packed pair via absorbedAdditions, threaded across the whole chain of buffered merge() calls the same way absorbedDeletedEdgesPerType already was. The "no identity dedup on the add side" note (an addition is a report of an edge appearing, never a duplicate reflecting the same in-flight change the way a delete can be) is correct and is exercised by the RID-reuse test (aReusedRidOnTheSamePairIsCountedAsTheDistinctEdgeItIs).

#7881 - IndexKeyEquality

Clean extraction of the one "same key?" policy into a shared class, used consistently by DocumentIndexer and both TransactionIndexContext.IndexKey/ComparableKey - removes the divergence between compareTo (already content-aware via BinaryComparator) and equals/hashCode (previously shallow Arrays.equals/hashCode). Good call putting it in com.arcadedb.index rather than leaving each side its own copy.

One minor, non-blocking note: Arrays.deepEquals/deepHashCode are a bit more expensive per-element (type dispatch) than the old shallow Arrays.equals/hashCode, on a hot path (every index key comparison). That's an unavoidable cost of the correctness fix, not something to defer, just flagging for awareness given this codebase's performance mantra - not asking for a change here.

General

  • Tests read well: they document the why as thoroughly as the production code, matching this repo's existing style in these packages.
  • No new dependencies, no security-sensitive surface touched; changes are additive/localized to the five call sites described.
  • Didn't spot anything else needing correction beyond the two minor notes above.

🤖 Generated with Claude Code

… they establish

BaseExpression#carriesItsOwnModifierTail() recognises a map literal, an array
literal and both CASE forms through one test for a non-null inner expression, and
that works only because each of them is wrapped in a BaseExpression here before
being attached to a parent - although ArrayLiteralExpression and CaseExpression
extend MathExpression directly and could be attached raw. The predicate documents
its dependence on that; the four visitors that establish it said nothing, so a
change to any of them could silently start renaming unaliased projection columns
again with nothing on the screen to suggest a connection.

Comments only, no behaviour change. Raised in two PR #8091 review rounds, both
times as a non-blocking note.
@claude

claude Bot commented Sep 21, 2026

Copy link
Copy Markdown

Review

Went through the diff for all five fixes plus the three follow-up review commits already on the branch. Overall this is careful, well-reasoned work: each fix is narrowly scoped, the reasoning for the chosen fix (vs. the alternative the issue offered) is spelled out in commit messages/javadoc, and every fix ships with a regression test that is stated to fail pre-fix.

Correctness - traced through the trickier ones by hand

Minor nit
A few of the new test helpers use fully-qualified names instead of imports (Issue7892RemoveSuperTypeDetachesIndexesTest.java: com.arcadedb.engine.Bucket, com.arcadedb.index.Index::getName, java.util.List return types), which CLAUDE.md asks to avoid. Not a blocker - there is precedent for this elsewhere in the test tree - but worth a quick pass since these are new lines.

Nothing else flagged
No leftover System.out, no new dependencies, no wire-protocol/module-boundary changes. Did not spot any security-relevant surface in this diff (all internal engine/SQL-parser logic, no new external input handling). Could not execute mvn verify in this review sandbox (build tooling required elevated approval that was not available here), so I verified behavior by tracing the logic and cross-checking against the existing call sites/tests rather than by running the suite. The PR description's reported regression run (olap + schema/index + sql packages, all green apart from an acknowledged pre-existing flake) covers the right surface area.

Nice work tightening up five separate longstanding bugs with this much care taken to keep each fix minimal and mirror existing patterns (the #7042/#7884 symmetry, the #7109/#7881 consolidation) rather than inventing new approaches.

CLAUDE.md asks for the class to be imported and used by its bare name; five
places in the two tests added here spelled the type out instead - Bucket and
Index in the schema test, List in both. Raised in a PR #8091 review round as a
non-blocking nit. No behaviour change.
@claude

claude Bot commented Sep 21, 2026

Copy link
Copy Markdown

Review

Went through all five fixes plus the new tests in detail. Overall this is a very high-quality PR: each fix is narrowly scoped, the reasoning is thoroughly documented in both commit messages and code comments, and every fix ships with a regression test that's stated (and plausible) to fail on the unfixed code. I traced the trickier interactions by hand rather than just reading the diff, notes below.

#7896 - BaseExpression.rendersParentheses() / carriesItsOwnModifierTail()

Traced how innerAtomCannotCarryAModifier() interacts with the four AST-builder wrap sites (visitMapLit, visitArrayLit, visitCaseExpr, visitExtendedCaseExpr) and the StatementExpression/SubqueryExpression overrides. The expression != null catch-all in carriesItsOwnModifierTail() really does rely on an invariant that's invisible from BaseExpression.java itself (those four visitors always wrap their node in BaseExpression{expression=Expression{...}} even though the underlying types extend MathExpression directly) - good that this round added comments at all four sites pointing at the dependency. The fallback ("anything unrecognized keeps its parentheses") is the safe direction, confirmed by walking a couple of unhandled cases (e.g. a bare ArrayLiteralExpression assigned directly to Expression.mathExpression in CREATE EDGE FROM ... TO ...) - they just stay conservative, no incorrect renaming.

#7892 - dropSubIndexesNoLongerCovered

This is the one I spent the most time on, since it interacts with LocalSchema.dropIndexInternal's own leaf-wrapper cleanup. Worth noting for reviewers: dropIndexInternal has its own "last sub-index removes the wrapper" cleanup, but it calls type.removeTypeIndexInternal(parentTypeIndex) where type is the subtype (bucket owner) - which walks up via superTypes to find the wrapper. Since unlinkSuperType already severed that link before dropSubIndexesNoLongerCovered runs, that internal cleanup silently fails to remove the wrapper from the ancestor's indexesByProperties (though it does still drop the name from the global index map, which is idempotent). The affectedWrappers loop in the new code correctly backstops this by calling removeTypeIndexInternal directly on the owner type instead of walking up from a now-disconnected subtype - so the double cleanup is redundant-but-safe rather than buggy. Good that anAbstractAncestorLosingItsLastSubIndexLeavesNoEmptyWrapperBehind pins exactly this path.

#7884 - DeltaOverlay add-side multiplicity dedup

Symmetric with the #7042 deletion-side fix, and I confirmed the capturedByFreshScan/absorbedAddedEdgesPerType bookkeeping is consistent across sequential merge() calls in GraphAnalyticalView's post-compaction replay loop (the preCount closure is fixed to the pre-compaction snapshot for the whole loop, which is what the "prefix" reasoning needs). One thing worth calling out explicitly for future readers even though it's not a bug: since the base CSR carries no RIDs, which specific buffered RID gets treated as "already captured" vs. kept in the overlay is arbitrary among parallel edges for the same pair - the doc comment says as much ("No identity dedup here, unlike the deletion side"), but it might be worth a one-line note in capturedByFreshScan's Javadoc that this arbitrariness is intentional and harmless only because per-edge RID identity for a base edge is meaningless until the next compaction anyway. Non-blocking.

#7881 - IndexKeyEquality

Clean extraction, and the delegation to Arrays.deepEquals/Arrays.deepHashCode (from the follow-up commit) is the right simplification - it's what the hand-rolled loop was reimplementing anyway. IndexKeyEqualityTest pins the contract directly (including the hash/equals consistency a HashMap depends on), which is good since the three original call sites only exercised it indirectly.

#7889 - null argument position in remove()/removeAll()

Verified the null-safety chain end to end: SQLMethodRemove/SQLMethodRemoveAll now gate on "there's an argument" rather than params[0] != null, and MultiValue.removeFromCollection's switch to Objects.equals(iToRemove, element) correctly avoids the NullPointerException iToRemove::equals used to throw from Objects.requireNonNull on a null receiver. Checked the remove() (non-removeAll) path too, where a null argument falls through to plain coll.remove(null), which is fine. The asymmetric-equals note in the comment (argument stays the receiver, matching Collection.remove(Object)) is accurate.

Nits (non-blocking, feel free to ignore)

  • The IndexKeyEquality.sameTuple/capturedByFreshScan arbitrariness point above.
  • Everything else style-wise (bare-name imports, @author tags, license headers, tag usage) looks consistent with the rest of the codebase and CLAUDE.md conventions already.

Test coverage / correctness

No issues found. I did not have Maven execution available in this environment to independently re-run the suite, but the described regression runs (whole graph.olap, schema+index, query.sql packages) are the right scope for the blast radius of these changes, and the new test classes are well-targeted regression tests rather than broad rewrites.

No security or performance concerns - all changes are either narrow correctness fixes on already-hot paths (using arrays/primitives as before) or infrequent DDL/compaction paths.

… matter

The method skips the first `capturable` of a pair's buffered additions in arrival
order, not the ones the scan actually saw - the base CSR is a run of neighbour
ids and cannot say which those were. That is deliberate rather than an
approximation nobody noticed: an edge the base run holds carries no RID there to
be told apart from another occurrence of the same pair until the next compaction
rebuilds the mapping, so a reader of the two can observe only the pair's total
multiplicity, which is the quantity the count is chosen to make right.

Comment only, no behaviour change. Raised in a PR #8091 review round as a
non-blocking note for future readers.
@claude

claude Bot commented Sep 21, 2026

Copy link
Copy Markdown

Review

Went through all five fixes plus the follow-up review commits already on this branch, tracing the trickiest one (LocalDocumentType.dropSubIndexesNoLongerCovered / #7892) all the way through LocalSchema.dropIndexInternal's existing cleanup path to make sure the two didn't double-handle or miss the wrapper unregistration. Summary below by area; I couldn't execute mvn verify in this sandbox (build tooling needs interactive approval here), so this is a manual trace rather than a fresh test run, but the PR description already documents the regression-suite results.

#7896 - unaliased parenthesized projection naming (sql)

BaseExpression.innerAtomCannotCarryAModifier() / carriesItsOwnModifierTail() line up correctly against Expression's actual fields (rid, json, booleanValue, whereCondition, arrayConcatExpression, mathExpression) and BaseExpression's own fields (number, identifier, string, inputParam, expression). The "unrecognized keeps its parentheses" fallback is the right conservative default. The four identical comments added in SQLASTBuilder (map/array/case/extended-case) are a deliberate, already-discussed duplication documenting a real invariant (the BaseExpression wrap), so that's fine as-is.

#7889 - null argument position in remove()/removeAll() (sql)

Verified the guard change doesn't reintroduce a regression for the zero-arguments case (params.length > 0 still evaluates false when empty). MultiValue.removeFromCollection's switch to Objects.equals(iToRemove, element) correctly keeps the argument as the receiver of the comparison, matching Collection.remove(Object)'s contract.

#7884 - overlay add-side dedup by multiplicity (concurrency/olap)

Traced capturedByFreshScan and the property-update loop that follows it in DeltaOverlay.merge(): alreadyInFreshBase is scoped to a single merge() call (i.e. one transaction), so the "arbitrary pick of which buffered addition is treated as captured" is safe for same-transaction property updates (a same-transaction update can only be safely no-op'd if the whole transaction, final values included, was already captured, which holds by construction). A later, separate transaction's property update on the same RID falls through to the ordinary dirty-type/full-rebuild path instead, so it isn't affected by the earlier arbitrary choice. This matches what the javadoc claims but is worth having spelled out, since it's easy to misread the "arbitrary" language as a real correctness gap.

#7881 - transaction index overlay array-key equality (engine/index)

IndexKeyEquality is a clean, minimal extraction (Arrays.deepEquals/deepHashCode), and both call sites (DocumentIndexer, TransactionIndexContext.IndexKey/ComparableKey) now agree with ComparableKey.compareTo's existing content-based comparison. IndexKeyEqualityTest pins the contract directly, which is valuable given three call sites now depend on it silently agreeing.

Minor/optional: Issue7881TransactionIndexArrayKeyEqualityTest only exercises the unique branch of IndexKey.equals()/hashCode(). The non-unique branch (Objects.equals(rid, ...) && IndexKeyEquality.sameTuple(...)) shares the same helper so risk is low, but a one-line addition there would close the loop completely.

#7892 - removeSuperType leaves the ancestor's index attached (schema)

This is the one I traced most carefully, since dropSubIndexesNoLongerCovered's wrapper-cleanup loop and LocalSchema.dropIndexInternal's own leaf-drop cleanup both touch indexesByProperties and schema.removeIndexDuringLoad(). Confirmed:

  • indexesByProperties is per-type, own-declared-only (not inherited), so collectSubIndexesNoLongerCovered's per-level stillCovered check against that level's own wrapper is correct and doesn't misfire against ancestor-owned buckets.
  • In the "last sub-index dropped" case, dropIndexInternal's own cleanup calls type.removeTypeIndexInternal(parentTypeIndex) on the subtype that owned the just-dropped bucket component, but that subtype's walk up to the wrapper's actual owner is exactly the link unlinkSuperType already severed, so it silently no-ops on the ancestor side while still unregistering the name from schema's index map. dropSubIndexesNoLongerCovered's own loop then calls owner.removeTypeIndexInternal(wrapper) directly (correct owner, identity-based removal) and calls removeIndexDuringLoad again, redundant with the first call but harmless since Map.remove is idempotent.
  • The grandparent-walk test (anIndexOwnedByTheGRANDPARENTOfTheSeveredLinkIsDetachedToo) is exactly the right regression to pin the multi-level recursion; glad to see it added in the follow-up round.

No bugs found here either, but this code path has enough moving parts (schema mutation during iteration, identity-based wrapper bookkeeping split across two classes) that it would benefit from a short comment at the dropIndexInternal call site (or a cross-reference the other way) noting that dropSubIndexesNoLongerCovered depends on this exact fallback behavior, so a future refactor of the leaf-drop cleanup doesn't quietly break the assumption.

General

  • Test coverage is thorough, and each new test class documents the failure mode it pins, in line with the repo's regression-test conventions.
  • No new dependencies, no security-sensitive surface touched (all internal engine/SQL logic).
  • Style matches the codebase conventions (no fully-qualified names, final used consistently, brace-free single-statement ifs).

Nice work tightening the reasoning across the review rounds already visible in the commit history (delegating to Arrays.deepEquals, naming the AST wrap invariant, adding the grandparent-walk test). No blocking findings from this pass; the two optional items above (non-unique IndexKey equality test, cross-reference comment on the schema fallback) are nice-to-haves, not blockers.

…he fallback the schema fix leans on

Two optional items from a PR #8091 review round:

- IndexKey.equals()/hashCode() have two branches and only the unique one was
  pinned. The non-unique branch keys on the tuple AND the RID, with the same
  helper doing the tuple half, so an edit to one branch could leave the other on
  a shallow comparison with nothing red to show for it.

- LocalSchema.dropIndexInternal's empty-wrapper cleanup finds the wrapper by
  walking UP from the subtype that owned the dropped component.
  dropSubIndexesNoLongerCovered calls in with that walk deliberately broken and
  repeats the cleanup itself against the real owner, so it depends on this one
  being a harmless no-op rather than on it working. Said so at the site, since a
  refactor there would otherwise look free.
@claude

claude Bot commented Sep 21, 2026

Copy link
Copy Markdown

Review

Went through all five fixes and their tests in detail (diff + surrounding code, not just the patch hunks). This is an unusually well-documented PR - each fix states the invariant it depends on, and several follow-up commits already address earlier review rounds (grandparent-walk test coverage, Arrays.deepEquals delegation, AST-invariant comments, import style). I did not find a correctness bug that survived those rounds. Notes below are non-blocking.

#7896 - parenthesis/projection-naming fix

Traced BaseExpression.rendersParentheses() -> innerAtomCannotCarryAModifier() -> carriesItsOwnModifierTail() against the Expression/BaseExpression field layout. The "wrap invariant" the comment relies on (map/array literals and both CASE forms are always attached as BaseExpression{expression=Expression{...}}, never raw) does hold at all four SQLASTBuilder call sites I checked (visitMapLit, visitArrayLit, visitCaseExpr, visitExtendedCaseExpr). StatementExpression/SubqueryExpression extending BaseExpression (rather than MathExpression directly) is what makes their carriesItsOwnModifierTail() override reachable through the instanceof BaseExpression inner check - worth keeping in mind if either class is ever refactored to extend MathExpression directly, since that would silently fall through to the conservative "keep parentheses" branch instead of breaking loudly.

Fallback direction is correctly conservative throughout: every "not recognised" branch keeps the parentheses (safe - worst case is a stale column name) rather than dropping them (unsafe - could produce unparseable text).

#7892 - removeSuperType index detachment

collectSubIndexesNoLongerCovered walks formerSuperType and its own super types only. Verified against the ownership model (indexesByProperties holds a TypeIndex only on the type that owns it, not copied into every subtype that inherits it via getAllIndexes(true)), so a shared wrapper like Z6[n] is visited exactly once even when the walk crosses multiple ancestor levels - no risk of schema.dropIndex() being called twice on the same orphaned component name. The visited set correctly guards the diamond case. The grandparent-walk test (anIndexOwnedByTheGRANDPARENTOfTheSeveredLinkIsDetachedToo) exercises exactly the case that would have caught a shallower walk.

#7884 - DeltaOverlay add-side dedup

The multiplicity math (capturable = fresh - before, clamped, tracked as a running per-pair counter in absorbedAddedEdgesPerType) mirrors the existing deletion-side pattern from #7042 and reuses CSRAdjacencyIndex.forwardEdgeCount, which is an O(log n + run-length) binary search - no new hot-path cost of note. capturable is recomputed on every call for the same pair rather than cached across the buffered additions for that pair within one merge(); harmless given the binary search cost, just flagging in case a caller ever pushes much larger batches through here.

#7881 - IndexKeyEquality

Clean extraction; Arrays.deepEquals/deepHashCode genuinely subsume the hand-rolled loop it replaced (confirmed via the follow-up commit). Verified both DocumentIndexer.java and TransactionIndexContext.java don't have leftover now-unused imports after the Objects/Arrays call sites were replaced - they don't; compilation should be unaffected on that front.

#7889 - null-argument position in remove()/removeAll()

MultiValue.removeFromCollection's switch from iToRemove::equals to Objects.equals(iToRemove, element) correctly flips the NPE-on-null-receiver behavior while preserving the (already asymmetric, pre-existing) comparison direction. SQLMethodRemove/SQLMethodRemoveAll's guard change (params.length > 0 instead of params[0] != null) is minimal and matches the stated intent.

General

  • No System.out, no new dependencies, license headers present on new files, no fully-qualified-name usage introduced, no em dashes in any new/changed content (found one pre-existing em dash in DeltaOverlay.java line 151, but it predates this PR and isn't part of the diff).
  • Test style consistently uses assertThat(...) per the repo convention.
  • Wasn't able to run mvn verify in this sandbox (build commands required interactive approval that wasn't available), so this review is based on static reading of the diff and surrounding code rather than an actual green run. The PR description states the relevant packages were run green locally, which lines up with what I traced through statically.

Nice work - the amount of care taken to state why each invariant holds (and to test the edge of it, like the grandparent-walk and non-unique-key-branch cases added in follow-up commits) is well above the norm for a bundle of five independent fixes.

… with it (#7892)

A regression of this PR's own #7892 fix, found by an integration lane that is
green on the merge base.

LocalSchema.dropType severs the doomed type's link to each of its super types
only so it can re-parent the SURVIVING sub types onto those same super types a
few lines later, and it re-links them with createIndexes=false precisely because
the propagated components are still on disk and still attached. Reading "which
buckets does the ancestor no longer reach" in that window reads a relationship
the schema is halfway through rewriting: at that moment the doomed type still
carries its whole subtree, so the answer includes the grandchildren, and their
components were dropped with nothing to put them back. DROP TYPE on a middle type
therefore left a surviving grandchild out of the ancestor's index and out of its
UNIQUE constraint - silently, since the schema still named the index.

The withdrawal is now skipped while that cascade is in flight, which is the only
caller that unlinks without meaning the subtree to stop being indexed; the doomed
type's own components are dropped by the cascade itself, as before.
@claude

claude Bot commented Sep 21, 2026

Copy link
Copy Markdown

Review

This is a well-scoped, well-documented PR: five independent fixes, each with a regression test that's been shown to fail on the unfixed code, plus follow-up commits that already tightened a few things a prior review round raised (delegating IndexKeyEquality.sameTuple to Arrays.deepEquals, naming the AST-builder wrap invariant, covering the grandparent walk in collectSubIndexesNoLongerCovered, and a real regression catch: DROP TYPE taking a surviving grandchild's index with it). I read through the full diff plus the current state of the touched files; I did not find a new correctness bug. Notes below are mostly confirmations and a couple of minor points.

#7896 - BaseExpression.rendersParentheses()

The new innerAtomCannotCarryAModifier() / carriesItsOwnModifierTail() split correctly separates "does the atom need parens to stay parseable" from "is there a modifier at all". I traced through Expression's fields (isNull, booleanValue, rid, whereCondition, arrayConcatExpression, json, mathExpression) and the enumerated cases line up with the grammar as described. The comment calling out that expression != null recognizing map/array/CASE literals depends on an AST-builder invariant (each is wrapped in a BaseExpression before attachment) is a good catch to leave documented at the four visitXxx sites - that's exactly the kind of implicit coupling that silently breaks under a future grammar change.

One thing I couldn't fully convince myself is exercised: StatementExpression/SubqueryExpression.carriesItsOwnModifierTail() is only consulted through expression.mathExpression instanceof BaseExpression inner in innerAtomCannotCarryAModifier(), but visitParenthesizedStmt returns the StatementExpression/SubqueryExpression node directly (not nested inside another BaseExpression.expression.mathExpression), and both override toString(...) to always render their own parens regardless of rendersParentheses(). The only other construction site (createStatementExpression, used for (SELECT ...) IN ...-style conditions) assigns into Expression.mathExpression outside of a projection-naming context. If that's right, the override is defensive/currently unreachable rather than dead-wrong - worth a quick double check that there isn't a projection path I'm missing, but not a blocker either way since a wrong "yes" here only fails safe (keeps parens on unaliased column names in an edge case, at worst).

#7889 - null-argument-by-position in remove()/removeAll()

The fix (gate on "there is an argument" instead of "the first argument is non-null") plus the MultiValue.removeFromCollection null-safety fix (Objects.equals(iToRemove, element) instead of iToRemove::equals) are both correct and match Collection.remove(Object) semantics. Good regression coverage, including the UPDATE ... SET tags = tags.remove(:a, :b) case from the original report.

#7884 - DeltaOverlay add-side dedup by multiplicity

This is the trickiest fix in the set and it's handled carefully. I checked the interaction between capturedByFreshScan's mutation of absorbedAdditions and short-circuit evaluation of !masked && capturedByFreshScan(...) - a masked (reinstated) addition correctly never consumes a captured-slot, matching anAdditionMaskedAsDeletedIsStillReinstated. The "prefix, not identity" framing and the choice to skip identity-dedup on the add side (unlike the delete side) is justified well in the javadoc and lines up with #6777's RID-reuse handling. The preCount == null fallback to pre-#7884 presence dedup is correctly scoped: I confirmed the only production caller that passes baseCsrPerType also always passes preCount (GraphAnalyticalView.java:2446); the 3-arg overload without preCount has no production call sites left, only tests.

#7881 - IndexKeyEquality

Good consolidation; TransactionIndexContext.IndexKey/ComparableKey and DocumentIndexer now share one policy, closing the gap between compareTo (content-aware via BinaryComparator) and equals/hashCode (previously shallow Arrays.equals). The follow-up test pinning the non-unique IndexKey branch (keyed on tuple + RID) separately from the unique branch is a good piece of defense-in-depth given they're easy to accidentally diverge again.

#7892 - removeSuperType index detachment

The dropSubIndexesNoLongerCovered / collectSubIndexesNoLongerCovered walk correctly reads "no longer covered" from the polymorphic bucket caches (never subtracting from the detached subtree), handles diamonds via the visited set, and the identity-based affectedWrappers set for the empty-wrapper cleanup is the right call given TypeIndex.equals() is content-based and would misbehave against an emptied wrapper. The isTypeBeingDropped() guard and its narrative in the follow-up commit (avoiding stripping a surviving grandchild's index mid-dropType-cascade) is exactly the kind of subtle state-machine interaction that's easy to get wrong, and it's now got a dedicated regression test (droppingAMiddleTypeLeavesTheSurvivingGrandchildIndexedByTheAncestor).

Style / minor

  • Code follows the project's final-everywhere and no-curly-braces-for-single-statement conventions consistently.
  • Comment density is high throughout - substantially more than the project's usual style - but given how non-local each of these invariants is (AST-builder-to-parser coupling, cross-call multiplicity bookkeeping, schema-cascade timing), I think it's earned here rather than noise.
  • I wasn't able to run mvn verify myself in this sandboxed review (tool approval blocked mvn/gh api invocations), so I'm relying on the PR description's claim of green targeted regression runs (graph.olap, schema+index, query.sql) rather than independently reproducing them - worth having CI confirm before merge if it hasn't already.

Overall: solid, well-tested, and the self-review history on this PR already closed the gaps I'd normally flag. No blocking issues found.

…7896)

A PR #8091 review round asked whether the StatementExpression/SubqueryExpression
override is reachable at all, or only defensive. It is reachable, and it is
load-bearing: a WRITTEN pair of parentheses around a node that already renders
its own - `((SELECT 1 AS v)).v` - is the redundant kind, and with the override
returning false the projection is named `((SELECT 1 AS v)).v` instead of
`(SELECT 1 AS v).v`. Verified by flipping it and watching the rendering change.

Pinned so the answer does not have to be re-derived, and so a refactor that made
either class extend MathExpression directly would fail here rather than silently
fall through to the conservative branch.
@claude

claude Bot commented Sep 21, 2026

Copy link
Copy Markdown

Review

Went through all 5 fixes plus the follow-up "review" commits already folded into this branch. Overall this is unusually careful work: each fix is isolated, comes with a regression test that's stated (and, per the description, verified) to fail pre-fix, and the commit history shows the author already caught and fixed a real regression of their own #7892 change (the DROP TYPE / surviving-grandchild case) via integration testing rather than shipping it. That's a good sign for correctness discipline.

Traced the two trickiest pieces of logic by hand against the AST builder / grammar wiring rather than taking the comments at face value:

#7896 (BaseExpression.rendersParentheses/innerAtomCannotCarryAModifier/carriesItsOwnModifierTail) — walked all the call sites in SQLASTBuilder (visitMapLit, visitArrayLit, visitCaseExpr, visitExtendedCaseExpr, visitFunctionCallExpr, visitParenthesizedExpr, visitNullBaseExpr, visitNullLiteral/visitTrueLiteral/visitRidLiteral/visitParenthesizedWhereExpr) to confirm the "does the grammar give this atom its own modifier* tail" predicate lines up with how each node actually gets attached (wrapped in BaseExpression{expression=...} vs. carrying identifier/string/inputParam directly vs. Expression-level isNull/booleanValue/rid/whereCondition set directly for the top-level-expression grammar alternatives). Both paths to NULL (the nullLiteral alternative and the nullBaseExpr alternative) end up correctly classified, just through different branches of the predicate. Didn't find a case that's misclassified.

#7884 (DeltaOverlay.capturedByFreshScan) — checked the wiring in GraphAnalyticalView (~line 2438-2446): preCount is bound once to the pre-compaction snapshot and held constant across the whole sequential merge() loop over buffered deltas, while absorbedAddedEdgesPerType carries forward correctly through the overlay's copy-on-merge pattern, so multiple buffered adds for the same pair correctly consume the max(0, fresh - before) budget in arrival order. Matches the deletion-side symmetry the PR claims.

#7881 / IndexKeyEquality — Arrays.deepEquals/Arrays.deepHashCode are legitimate drop-in replacements for the hand-rolled per-element loop (same null/length/recursive-array semantics), and centralizing it so DocumentIndexer and TransactionIndexContext.IndexKey/ComparableKey can't drift apart again is the right fix for a bug that was exactly that kind of drift.

#7892 — the IdentityHashMap-backed affectedWrappers set is the right call given TypeIndex.equals() is content-based and the wrappers are transiently empty mid-cleanup; the grandparent-walk recursion and the DROP TYPE carve-out (isTypeBeingDropped) are both covered by tests that target exactly the scenario each one exists for (diamond, 4-level chain, mid-cascade re-parenting).

#7889 — straightforward, and the MultiValue.removeFromCollection fix (binding Objects.equals instead of iToRemove::equals) correctly stays asymmetric-equals with the argument as receiver, matching Collection.remove(Object)'s own contract.

Nothing blocking. A couple of very minor, non-blocking notes:

  • The PR description says the full com.arcadedb.query.sql regression run (3133 tests) was green aside from one pre-existing time-sensitive flake (SQLMethodPrecisionTest.instant) — worth double-checking CI reproduces that same isolated flake rather than something new, since a few of the parenthesization tests interact with subquery rendering (SELECT ((SELECT 1 AS v)).v ...) that's easy to get subtly wrong across engines.
  • IndexKeyEqualityTest, being a pure unit test with no TestHelper/database dependency, is cheap and well-scoped — good to see the contract pinned directly rather than only through the three call sites, per the follow-up commit.

Nice use of @author tags and issue cross-references in the new Javadoc — makes the "why", not just the "what", traceable for anyone hitting this code later.

@lvca
lvca merged commit a7f7b8c into main Sep 21, 2026
27 of 29 checks passed
@lvca
lvca deleted the fix/issues-7896-7892-7889-7884-7881 branch September 21, 2026 19:05
@codacy-production

Copy link
Copy Markdown

Up to standards ✅

🟢 Issues 0 issues

Results:
0 new issues

View in Codacy

🟢 Metrics 29 complexity

Metric Results
Complexity 29

View in Codacy

🟢 Coverage 96.72% diff coverage · -6.19% coverage variation

Metric Results
Coverage variation ✅ -6.19% coverage variation
Diff coverage ✅ 96.72% diff coverage

View coverage diff in Codacy

Coverage variation details
Coverable lines Covered lines Coverage
Common ancestor commit (62aca77) 186737 155192 83.11%
Head commit (3edb18f) 219354 (+32617) 168718 (+13526) 76.92% (-6.19%)

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 (#8091) 61 59 96.72%

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.

@codecov

codecov Bot commented Sep 21, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 90.16393% with 6 lines in your changes missing coverage. Please review.
✅ Project coverage is 74.77%. Comparing base (62aca77) to head (3edb18f).
⚠️ Report is 46 commits behind head on main.

Files with missing lines Patch % Lines
...in/java/com/arcadedb/schema/LocalDocumentType.java 92.00% 1 Missing and 1 partial ⚠️
...com/arcadedb/database/TransactionIndexContext.java 83.33% 0 Missing and 1 partial ⚠️
.../arcadedb/query/sql/antlr/StatementExpression.java 0.00% 1 Missing ⚠️
...b/query/sql/method/collection/SQLMethodRemove.java 0.00% 0 Missing and 1 partial ⚠️
...uery/sql/method/collection/SQLMethodRemoveAll.java 0.00% 0 Missing and 1 partial ⚠️
Additional details and impacted files
@@             Coverage Diff              @@
##               main    #8091      +/-   ##
============================================
+ Coverage     74.76%   74.77%   +0.01%     
- Complexity     2561     2562       +1     
============================================
  Files          1998     1999       +1     
  Lines        186737   186809      +72     
  Branches      39109    39125      +16     
============================================
+ Hits         139612   139693      +81     
+ Misses        31584    31574      -10     
- Partials      15541    15542       +1     

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment