Skip to content

fix(#6401): a hash code is a property of the value, and an expression's value is every field that carries one - #6407

Merged
lvca merged 2 commits into
mainfrom
issue-6401
Aug 18, 2026
Merged

lvca merged 2 commits into
mainfrom
issue-6401

Conversation

@lvca

@lvca lvca commented Aug 18, 2026

Copy link
Copy Markdown
Member

Closes #6401.

Four follow-ups collected while fixing #6359. Items 3 and 4 turned out to be each other's cover, so they are fixed together.

Item 4 - SimpleNode.hashCode() hashed the ARRAY

There is no Objects.hashCode(Object...) overload, so the Object[] returned by getIdentityElements() bound to
Objects.hashCode(Object) and the answer was the array's IDENTITY hash - of an array allocated fresh on every call. So:

  • node.hashCode() != node.hashCode() across two calls on the same object;
  • a.equals(b) true while a.hashCode() != b.hashCode(), which is the Object.hashCode contract broken outright.

Arrays.hashCode(elements) is what the code reads as if it says, and it walks the elements exactly as equals() a few
lines above does.

Item 3 - the identity of an expression left out fields that carry its value

  • BaseExpression: number and expression were missing, so for a bare numeric literal every listed field is
    null/false and the parsed forms of SELECT 1 and SELECT 2 compared EQUAL. Same for two different wrapped
    sub-expressions.
  • Expression: whereCondition and the inherited value slot were missing, and both are read by execute().
    value is where the three WITH ... settings builders (IMPORT, EXPORT, BACKUP DATABASE) park a setting NAME,
    so every key of a WITH clause was a node whose every other field is null - equal to every other key.
  • PNumber gained an identity of its own, for the same reason PInteger has always had one: without it, listing
    number on BaseExpression would compare two literals by object identity and answer "not equal" for two parses of
    the very same statement.

parenthesized is deliberately left out of BaseExpression's identity: it is rendering-only, the parentheses are
already in the tree SHAPE, so two nodes differing in it alone mean the same thing.

Neither fix is safe alone. equals() said yes where it should have said no, the hash codes said no to everything,
and a HashMap keyed on a parsed node came out almost right by accident. Fixing the hash first collapses the five
Map<Expression, Expression> settings maps to a single entry - which is precisely what
ImportDatabaseStatementTestParserTest.copyKeepsTheWithSettings caught on the first full engine run.

Item 1 - the external-bucket arm of addSuperType's rollback now has a regression test

It needs no fault injection, contrary to what PR #6364 assumed: ensureExternalBucketFor already refuses to adopt a
bucket that is a primary bucket of another user type. Naming a primary bucket after the one the subtype's pairing would
want (<subtypePrimaryBucket>_ext) reaches the refusal from step ONE, before an index is propagated or a strategy
inherited. The test pins that the link goes back on both sides, that nothing is half-adopted, and that with the
collision gone the same link is made and the pairing creates the bucket it could not adopt.

Verified non-vacuous: removing the unlinkSuperType call from the guard makes it red.

Item 2 - addSuperTypeInternal extracted along its seams

~170 lines with three nesting levels of try/catch, split into linkSuperType (symmetric with unlinkSuperType),
applyPostLinkageSteps (the three steps, numbered), propagateSuperTypeIndexes and createSubIndexesFor. No behaviour
change. The ordering constraints that were only in comments are now the method's javadoc checklist: the quiescence
outside recordFileChanges, the share predicate asked before any transaction opens, created declared outside the
propagation, both lists cleared on entry to the retrying lambda.

Verification

  • New Issue6401NodeIdentityTest (10 cases): hash stability across calls, equal nodes hash equally, different literals
    / wrapped sub-expressions / collection literals / inline conditions are different nodes, an Expression used as a
    hash key behaves like a key, every setting key of a WITH clause is its own key, PNumber compares by value, and a
    node with no identity elements still honours the contract. Mutation-checked: reverting either Expression field
    turns two of them red.
  • New Issue6359SuperTypeIndexPropagationTest#aRefusalFromTheExternalBucketPairingHandsTheLinkBackToo.
  • engine: 12764 tests, 0 failures. server: 794, 0 failures. gremlin/graphql/postgresw/mongodbw/
    integration/console: green.

…'s value is every field that carries one

Four follow-ups from #6359, and two of them turned out to be each other's cover.

`SimpleNode.hashCode()` hashed the ARRAY that `getIdentityElements()` returns instead of its contents: there is no
`Objects.hashCode(Object...)` overload, so an `Object[]` binds to `Objects.hashCode(Object)` and the answer was the
array's identity hash - of an array allocated fresh on every call. So a node did not agree with itself twice in a
row, and two nodes `equals()` to each other hashed differently, which is the `Object.hashCode` contract broken
outright. `Arrays.hashCode` is what the code reads as if it says.

The other half is that identity left out fields that carry a value. `BaseExpression` omitted `number` and
`expression`, so `SELECT 1` and `SELECT 2` parsed to nodes that were `equals()`; `Expression` omitted
`whereCondition` and the inherited `value` slot, and `value` is where `IMPORT`, `EXPORT` and `BACKUP DATABASE` park a
setting NAME - so every key of a `WITH` clause was equal to every other key. `PNumber` gained an identity of its own
for the same reason `PInteger` has always had one: without it, listing `number` would compare two literals by object
identity and say "not equal" for two parses of the same statement.

Neither fix is safe alone. `equals()` said yes where it should have said no, the hash codes said no to everything,
and a `HashMap` keyed on a parsed node came out almost right by accident: fixing the hash first collapses the five
`Map<Expression, Expression> settings` maps to one entry, which is exactly what `ImportDatabaseStatementTestParserTest`
caught.

Also here, from the same batch:

- the external-bucket arm of `addSuperType`'s rollback gets its regression test. It needs no fault injection:
  `ensureExternalBucketFor` refuses to adopt a bucket that is already some user type's primary bucket, so naming a
  primary bucket after the one the subtype's pairing would want reaches the refusal from step one, before an index is
  propagated or a strategy inherited. The link has to go back on both sides, and nothing may be half-adopted;
- `addSuperTypeInternal` is split along the two seams four review rounds on #6364 asked for once the logic stopped
  moving: `linkSuperType` (symmetric with `unlinkSuperType`), `applyPostLinkageSteps`, `propagateSuperTypeIndexes` and
  `createSubIndexesFor`. No behaviour change; the ordering constraints that were only in comments are now the
  method's javadoc checklist.
@lvca lvca self-assigned this Aug 18, 2026
@mergify

mergify Bot commented Aug 18, 2026

Copy link
Copy Markdown
Contributor

Tick the box to add this pull request to the merge queue (same as @mergifyio queue).

  • Queue this pull request

@codacy-production

codacy-production Bot commented Aug 18, 2026 •

Copy link
Copy Markdown

Up to standards ✅

🟢 Issues 0 issues

Results:
0 new issues

View in Codacy

🟢 Metrics 13 complexity

Metric Results
Complexity 13

View in Codacy

🟢 Coverage 96.55% diff coverage · -6.58% coverage variation

Metric Results
Coverage variation ✅ -6.58% coverage variation
Diff coverage ✅ 96.55% diff coverage

View coverage diff in Codacy

Coverage variation details
Coverable lines Covered lines Coverage
Common ancestor commit (90b0959) 160706 127762 79.50%
Head commit (f62d2f5) 193301 (+32595) 140962 (+13200) 72.92% (-6.58%)

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 (#6407) 58 56 96.55%

Diff coverage is the percentage of lines that are covered by tests out of the coverable lines that the pull request added or modified: <covered lines added or modified>/<coverable lines added or modified> * 100%

NEW Get contextual insights on your PRs based on Codacy's metrics, along with PR and Jira context, without leaving GitHub. Enable AI reviewer
TIP This summary will be updated as you push new changes.

@claude

claude Bot commented Aug 18, 2026

Copy link
Copy Markdown

Review

Overall this is a well-scoped, well-tested fix for a genuinely nasty pair of bugs (broken hashCode() contract + incomplete identity fields), plus a clean, behavior-preserving extraction of addSuperTypeInternal. Nice work tracing the Objects.hashCode(Object...)-doesn't-exist trap and explaining why the two fixes had to land together.

Note on verification: I wasn't able to run mvn compile/test in this review sandbox (Maven invocations require an approval this session doesn't have), so the notes below come from careful static tracing of the field lists rather than an executed build. Given the PR description already reports a full green run (12764 engine / 794 server tests), treat this as a secondary check rather than a substitute.

Correctness

  • SimpleNode.hashCode() (Arrays.hashCode instead of Objects.hashCode): correct, and consistent with equals(), which already compares getIdentityElements() element-by-element via Objects.equals (shallow, non-deep, matching Arrays.hashCode's shallow semantics, so no new equals/hashCode mismatch for elements that happen to be arrays themselves).
  • BaseExpression.getIdentityElements(): cross-checked against every field declared on the class (number, identifier, expression, inputParam, string, modifier, isNull, parenthesized); the new list covers all value-carrying fields, and parenthesized is correctly excluded (rendering-only, shape is already in the tree).
  • Expression.getIdentityElements(): cross-checked against the class's full field list (singleQuotes, doubleQuotes, isNull, rid, mathExpression, arrayConcatExpression, json, booleanValue, whereCondition) plus inherited value; the new list is complete.
  • PNumber.getIdentityElements(): consistent with the existing PInteger/FloatingPoint siblings' own overrides.
  • One thing worth a second thought (not a blocker, just flagging since I can't run it): Expression.value is now part of identity, and ValueExpression ("only used by the query executor to store pre-calculated values… not produced by parsing") extends Expression without its own getIdentityElements() override, so it now compares/hashes by whatever arbitrary object got stashed in value at execution time. I didn't find any Map<...>/Set<...> keyed on Expression outside the five DDL settings maps this PR targets, so this looks like a pure correctness improvement (previously all-default-fields-null made every ValueExpression "equal" to every other one too) rather than a new risk, but if a future change ever puts a ValueExpression into a hash-based collection, it's worth remembering its hash now depends on the wrapped runtime value's own equals/hashCode.

LocalDocumentType.addSuperTypeInternal refactor

Traced the extracted methods (linkSuperType, applyPostLinkageSteps, propagateSuperTypeIndexes, createSubIndexesFor) against the pre-refactor code path line by line; the try/catch nesting, the outer catch's index-cleanup + unlinkSuperType rollback, and the ordering constraints called out in the new Javadoc (quiescence taken by the caller, callerTransactionHasChanges computed before any of our own transactions, created declared outside the propagation, both lists cleared on lambda entry) are all preserved. Good call documenting these as a checklist; they were previously only inline comments and easy to violate silently in a future edit.

New tests

  • Issue6401NodeIdentityTest: solid coverage - hash stability, equal-nodes-equal-hashes, the two previously-missing BaseExpression fields, the WITH settings map collapse scenario, PNumber value equality, and the whereCondition case. The "reverting either field turns two cases red" mutation check mentioned in the description is a good sign this isn't a coincidentally-passing test.
  • aRefusalFromTheExternalBucketPairingHandsTheLinkBackToo: good target - confirms ensureExternalBucketFor's "already a primary bucket of another user type" refusal is reached without fault injection, and asserts the rollback is symmetric on both sides of the link plus "nothing half-adopted." The follow-up re-attempt after clearing the collision, and the final write to Sub to confirm the external bucket is actually usable (not just registered), is a nice touch that goes beyond just checking the exception.

Minor/style

  • The Javadoc throughout (especially LocalDocumentType) is quite dense/narrative - multiple paragraphs per method explaining historical rationale and issue numbers. That's consistent with this PR's own body text and clearly deliberate, but worth keeping an eye on whether this level of density becomes the norm across the codebase or stays scoped to unusually load-bearing methods like this one, per CLAUDE.md's "WHY, not WHAT" comment guidance.
  • No System.out debug leftovers, no new dependencies, no license concerns; all consistent with repo conventions.

Nothing here blocks merging; the identified item is an observation for future awareness, not a defect in this PR.

…o it inherits the identity that now reads it

Answers the one substantive point of the review on #6407: ValueExpression extends Expression without an identity of
its own, so adding 'value' to Expression's identity changes how it compares. That is the right answer for it - it
stores a pre-calculated value in exactly that slot, and before the change every ValueExpression was equals() to every
other one - but the class said nothing about it. The caveat worth remembering is now written down: the identity is
only as well-behaved as the wrapped object's own equals/hashCode.
@lvca lvca added this to the 26.9.1 milestone Aug 18, 2026
@lvca
lvca merged commit 715c5cc into main Aug 18, 2026
27 of 28 checks passed
@lvca
lvca deleted the issue-6401 branch August 18, 2026 17:20
@codecov

codecov Bot commented Aug 18, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 93.10345% with 4 lines in your changes missing coverage. Please review.
✅ Project coverage is 70.83%. Comparing base (90b0959) to head (f62d2f5).
⚠️ Report is 2 commits behind head on main.

Files with missing lines Patch % Lines
...in/java/com/arcadedb/schema/LocalDocumentType.java 93.10% 2 Missing and 2 partials ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #6407      +/-   ##
==========================================
+ Coverage   70.81%   70.83%   +0.01%     
==========================================
  Files        1852     1853       +1     
  Lines      160706   160914     +208     
  Branches    33763    33820      +57     
==========================================
+ Hits       113806   113980     +174     
- Misses      32983    32998      +15     
- Partials    13917    13936      +19     

☔ 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
…, fix node identity for CASE/ORDER BY/INSERT SET (#6413)

* fix(#6409): a WITH setting key means one shape everywhere, a duplicate always refuses, and identity holds for CASE, ORDER BY and INSERT SET

Follow-ups from #6401/#6407 collected while asking, for each parser node, "does identity actually work
here now":

- Item 1: IMPORT, EXPORT and BACKUP DATABASE built their WITH setting keys as a raw value parked in the
  node's inherited value slot, while REBUILD INDEX and REBUILD TYPE already built a proper identifier
  expression. All five now build the key the same way (new Expression(Identifier)), and every reader
  recovers it the same way (toString()), removing the defensive raw-value read in BackupDatabaseStatement
  that existed only because the old shape was fragile.
- Item 2: only REBUILD TYPE refused a duplicate WITH setting; the other four silently accepted one, last
  one wins. A shared SQLASTBuilder#putSetting helper now refuses a repeat - keyed on the lowercased name,
  matching the equalsIgnoreCase every reader already uses - in all five statements.
- Item 3: a sweep for parser nodes whose identity does not work, widening the corpus test #6401 left as a
  starting point. Confirmed and fixed: ArrayRangeSelector (a[1..3] under-matched, comparing unequal to
  itself), OrderByItem and InsertSetExpression (same under-match, breaking identity for any statement
  carrying an ORDER BY or an INSERT ... SET), and CaseExpression (the opposite failure: no identity
  override of its own meant it inherited MathExpression's, which reads fields CaseExpression never
  populates, so two structurally different CASE WHEN expressions over-matched as equal).
- Item 4: SimpleNode.equals() indexed the other node's identity array by this node's length with no
  guard; harmless today because every override returns a fixed-length array, but one built conditionally
  would throw ArrayIndexOutOfBoundsException out of equals(). Added the length guard.
- Item 5 (hashCode is now O(subtree)) is a documented cost, not a defect - no code change.

* fix(#6409): correct the putSetting javadoc's claim about case-insensitive readers

Review on #6413 caught it: the comment said every reader recognises a setting with
equalsIgnoreCase, which is only true for REBUILD INDEX and REBUILD TYPE.
BackupDatabaseStatement's setting switch is exact-case, and Import/ExportDatabaseStatement
hand the key through as-is to the integration-module setter, so for those three the
lowercased dedup is a defensive choice rather than a fix for an existing case-insensitive
read. No behavior change.

* fix(#6409): IMPORT/EXPORT DATABASE identity ignored the WITH settings

Code review on this PR caught it: ImportDatabaseStatement#equals() only compared url,
and ExportDatabaseStatement#getIdentityElements() only listed url, so two statements
with the same URL but different WITH settings compared equal. For IMPORT DATABASE this
was the sharper case: a CSV import has no URL at all, so the settings are the statement.
BackupDatabaseStatement already included settings in its identity; the other two now
match it. Same over-match direction as the CaseExpression fix in this PR, on a statement
node instead of an expression node.
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