Skip to content

fix(#6359): a propagated index joins the transaction that wrote the records, a negative literal is a number, and two modules that cannot share a Maven invocation - #6364

Merged
lvca merged 12 commits into
mainfrom
issue-6359
Aug 18, 2026
Merged

lvca merged 12 commits into
mainfrom
issue-6359

Conversation

@lvca

@lvca lvca commented Aug 18, 2026

Copy link
Copy Markdown
Member

Closes #6359.

Three findings collected while fixing #6324, none of which was that issue's to fix.

Item 1 - an index propagated to a super type's existing buckets missed uncommitted records

#6324 made CREATE INDEX see the writes of the transaction it runs in, through TypeIndexBuilder and
BucketIndexBuilder. LocalDocumentType.addSuperType uses neither: it calls LocalSchema.createBucketIndex
directly, over buckets that already hold records, and still built in a transaction of its own. A caller that
inserts and then links a super type in one transaction got exactly #6324's shape back - an index that is readable,
reported healthy by CHECK DATABASE, and answers the lookup it exists for with nothing.

It now takes the same two-transaction split: the components are created and committed on their own, then the builds
join the caller's transaction.

The issue offered two shapes for the fix - route the call site through a builder, or write the split a third time.
Neither is what landed, because the first is not free: BucketIndexBuilder.create() re-derives the key types from
the type's properties (the propagation has them on the index being propagated), passes null for the TypeIndex to
attach to (so a propagated sub-index would mint a NEW wrapper on the subtype instead of joining the super type's),
and quiesces the async executor once per call - N full quiesce cycles for one addSuperType. What is shared instead
is the three things the split actually needs, now written once in IndexBuilder:

  • callerTransactionHasChanges(database) - the transaction half of the predicate, on its own because this call site
    has to ask it before it knows which index families it is about to create;
  • buildCreatedIndex(index, batchSize, shares, callback) - the UNAVAILABLE -> AVAILABLE step;
  • dropPartiallyBuiltIndex(schema, index) - BucketIndexBuilder's private copy is gone.

Timing is the trap this cost the most on: the predicate has to be asked before anything is opened, because inside
the component-creation transaction there is always one, it is empty, and the answer would always be no. Asked from
the wrong place, the fix compiles, passes four of five tests, and does nothing.

The sibling call site in createBucket() is left alone deliberately, and now says why: the bucket it indexes has
just been created, so no transaction can hold uncommitted writes into it and there is nothing for the scan to miss.

Item 2 - a negative numeric literal rendered as an arithmetic expression

A unary minus was modelled as a subtraction from zero, so the AST for -1 was 0 - 1 and that is what
Expression.toString() produced. The rendering is not cosmetic: it is what EXPLAIN prints, what an unaliased
projection is named after, and what a statement re-reading one of its own settings parses - REBUILD INDEX ... WITH batchSize = -1 reached Integer.parseInt as the string "0 - 1".

The minus is now folded into the literal. It negates the already-parsed value rather than re-parsing a
"-"-prefixed text, so the folded literal keeps exactly the numeric type 0 - X used to produce (-2147483648
stays a Long, an L-suffixed literal stays a Long, a bare decimal stays a Float) and the sign lands correctly
on every literal shape the visitors accept, not only on plain decimal. A literal carrying a modifier is left alone,
since a suffix binds tighter than the sign.

Measuring that turned up the other half of the same defect, which the fold alone does not reach: the parentheses a
statement was written with were dropped as well.

written rendered before reads back as
SELECT 2 * -1 SELECT 2 * 0 - 1 -1, not -2
SELECT (1 + 2) * 3 SELECT 1 + 2 * 3 7, not 9
SELECT -(1 + 2) SELECT 0 - 1 + 2 1, not -3

BaseExpression.expression could not say on its own whether it held a parenthesised block - the builder also parks
map literals, array literals and CASE expressions there - so the node now records that the parentheses were written,
and prints them only where dropping them could change the meaning: around a compound arithmetic operand. Around
an atom they are decoration, and printing them would rename every unaliased projection written that way
(SELECT (name) FROM V has always been a column called name, and SELECT distinct(name), which the parser reads
as DISTINCT (name), with it).

And the numeric-setting readers are unified on DDLStatement.parsePositiveIntSetting, next to the boolean one that
was already shared - the sweep the issue asked for, done by removing the duplicate rather than by fixing each copy.
That also fixes REBUILD TYPE ... WITH batchSize, which read Expression.value - null for every numeric literal
the parser builds - and so refused every value it was given, legal ones included, with got: null.

Item 3 - graphql and gremlin could not share one Maven invocation

Pre-existing and invisible in CI, where the lanes run each module separately. Measured cause:

Caused by: java.lang.NoClassDefFoundError: org/apache/tinkerpop/gremlin/structure/Graph

It is the trap already documented for arcadedb-gremlin-it, one module wider. graphql consumes
arcadedb-gremlin's shaded classifier with a wildcard exclusion, so the uber-jar is self-contained; Maven
substitutes the reactor module for a classified dependency whose module is in the same invocation, the test phase
never runs the shade plugin, and the plain target/classes that stands in for it carries no TinkerPop.

mvn -o test    -pl gremlin,graphql   ->  Tests run: 45, Errors: 2
mvn -o verify  -pl gremlin,graphql   ->  Tests run: 45, Errors: 0
mvn -o test    -pl graphql           ->  Tests run: 45, Errors: 0

Inherent to how the artifact is resolved, so it is documented in CLAUDE.md's build-traps section where somebody
running that command will find it. What is fixed is the message: the failure named the engine ("Error on
initializing Gremlin query engine") rather than the classpath, and now names the classpath.

Checked, and NOT a bug

The issue's last section records that unique-index enforcement was measured and is sound. Nothing to do, not
re-opened.

Testing

  • Issue6359SuperTypeIndexPropagationTest (5): the propagation over uncommitted inserts through the API and through
    one SQL script, a record updated in the same transaction indexed under its new key, the propagated component
    surviving a rollback of the transaction that propagated it and still being writeable, and the createBucket()
    sibling asserted rather than merely asserted about.
  • Issue6359NegativeLiteralRenderingTest (6): the rendering of every negative literal shape, the parentheses rule
    both ways, a render-and-reparse round trip asserted on the computed VALUE, the column name of an unaliased
    parenthesised projection, and the setting readers refusing -1 by the value the user typed.
  • GremlinQueryEngineFactoryClasspathHintTest (2): the missing-TinkerPop message, and that an unrelated failure -
    including a missing class that is not TinkerPop - is not mislabelled as it.
  • mvn -o -pl engine -am test: 12587 tests, 0 failures.
  • mvn -o verify -pl gremlin,graphql,server,postgresw -am and mvn -o verify -pl gremlin-it -am: green.

🤖 Generated with Claude Code

https://claude.ai/code/session_01QF6LJaiD6ZRr6oA9WZxVBK

…ecords, and a negative literal is a number

Three findings collected while fixing #6324, none of which was that issue's to fix.

Item 1 - an index propagated to a super type's existing buckets missed uncommitted records.

#6324 made CREATE INDEX see the writes of the transaction it runs in, through TypeIndexBuilder and
BucketIndexBuilder. LocalDocumentType.addSuperType uses neither: it calls LocalSchema.createBucketIndex
directly, over buckets that ALREADY hold records, and still built in a transaction of its own. A caller that
inserts and then links a super type in one transaction got exactly #6324's shape back - an index that is
readable, reported healthy by CHECK DATABASE, and answers the lookup it exists for with nothing.

It now takes the same two-transaction split: the components are created and committed on their own, then the
builds join the caller's transaction. The predicate and the two steps it needs live once in IndexBuilder
(callerTransactionHasChanges, buildCreatedIndex, dropPartiallyBuiltIndex) rather than being written a third
time, and BucketIndexBuilder's private copy of the cleanup is gone. The transaction half of the predicate has
to be asked BEFORE anything is opened: inside the component-creation transaction there is always one, it is
empty, and the answer would always be no.

The sibling call site in createBucket() is left alone deliberately, and now says why: the bucket it indexes has
just been created, so no transaction can hold uncommitted writes into it and there is nothing for the scan to
miss.

Item 2 - a negative numeric literal rendered as an arithmetic expression.

A unary minus was modelled as a subtraction from zero, so the AST for -1 was 0 - 1 and that is what
Expression.toString() produced. The rendering is not cosmetic: it is what EXPLAIN prints, what an unaliased
projection is named after, and what a statement re-reading one of its own settings parses - REBUILD INDEX ...
WITH batchSize = -1 reached Integer.parseInt as the string "0 - 1" and came back as a raw
NumberFormatException naming neither the setting nor the problem.

The minus is now folded into the literal. It negates the already-parsed value rather than re-parsing a
"-"-prefixed text, so the folded literal keeps exactly the numeric type 0 - X used to produce and the sign
lands correctly on every literal shape; a literal carrying a modifier is left alone, since a suffix binds
tighter than the sign.

The parentheses a statement was written with are kept too, for the same round-trip reason: (1 + 2) * 3
rendered as 1 + 2 * 3, which is 7 rather than 9 when read back. Only parentheses that carry meaning are
printed - around an atom they are decoration, and printing them would rename every unaliased projection
written that way (SELECT (name) FROM V has always been a column called name).

And the numeric-setting readers are unified on DDLStatement.parsePositiveIntSetting, next to the boolean one
that was already shared. That also fixes REBUILD TYPE ... WITH batchSize, which read Expression.value - null
for every numeric literal the parser builds - and so refused every value it was given, legal ones included,
with "got: null".

Item 3 - graphql and gremlin could not share one Maven invocation.

Pre-existing and invisible in CI, where the lanes run each module separately. It is the trap already
documented for arcadedb-gremlin-it, one module wider: Maven substitutes the reactor module for the
shaded-classified dependency, the test phase never runs the shade plugin, and the plain target/classes that
stands in for it carries no TinkerPop. mvn -o verify -pl gremlin,graphql is green where mvn -o test is not.
Documented in CLAUDE.md's build-traps section, and the engine now names the real problem instead of leaving a
NoClassDefFoundError under a message that points at the engine.
@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 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 Aug 18, 2026

Copy link
Copy Markdown

Review

I read through the three fixes end-to-end (index propagation transaction split, negative-literal/parentheses rendering, Gremlin classpath hint) plus the new regression tests. Overall this is careful, well-reasoned work with strong regression coverage for the exact failure shapes described in the issue. A few notes, nothing I'd call a hard blocker.

Item 1 — LocalDocumentType.addSuperType index propagation

The two-transaction split (engine/.../LocalDocumentType.java:1981-2049) correctly:

  • computes callerTransactionHasChanges before opening the component-creation transaction (getting the timing trap called out in the PR description right),
  • creates+commits index components in their own transaction, then builds them in a joined transaction so the scan can see the caller's uncommitted writes,
  • cleans up (dropPartiallyBuiltIndex) on failure of the join-transaction build.

I traced the rollback test (aPropagatedIndexSurvivesTheRollbackOfTheTransactionThatPropagatedIt) against LocalSchema.createBucketIndex's build flag semantics and the two-phase status transition (UNAVAILABLE→AVAILABLE on build), and the design holds up: components persist across the caller's rollback, entries don't.

One thing I'd like to see covered that isn't yet: the PR's own comment on the join-transaction catch block explicitly anticipates DuplicatedKeyException as a newly-reachable outcome ("a duplicate is exactly what this build can hit, since it now sees the caller's own pending writes"). That's a direct, foreseeable consequence of this exact fix — a caller that inserts two records violating a unique super-type index in one transaction and then calls addSuperType will now get a DuplicatedKeyException where before it silently (and incorrectly) succeeded. None of the 5 new tests in Issue6359SuperTypeIndexPropagationTest exercise that path. Worth a regression test asserting (a) the exception surfaces clearly and (b) the partially-built components get cleaned up (dropPartiallyBuiltIndex), since that's exactly the scenario the code comments are defending against.

Minor/non-blocking: that same failure path bypasses the outer catch (IndexException e) (since DuplicatedKeyException/NeedRetryException aren't IndexException), so it propagates without the contextual "Error on creating implicit indexes from super type '...'" log line that an IndexException failure would get. Not a bug — the exception still reaches the caller and cleanup still runs — just a small diagnostic asymmetry.

Item 2 — negative literal folding + parenthesis rendering

tryNegateNumericLiteral and BaseExpression.rendersParentheses() look correct. I checked the type-preservation claims by hand against PInteger/PNumber and the two literal visitors (visitIntegerLiteral, visitFloatLiteral) in SQLASTBuilder: the ANTLR builder only ever produces PInteger (Integer/Long) or plain PNumber (Float/Double) — FloatingPoint (the JavaCC-era node with its own literal-text-preserving toString()) is never constructed there, so the instanceof PInteger / else-PNumber branch in the fold doesn't lose any literal formatting. Ordering against the pre-existing tryFoldLongMinValueLiteral overflow fold is safe (that one is checked first and returns before innerExpr is even computed). The rendersParentheses() guard (expression.mathExpression != null && !operators.isEmpty()) correctly scopes "print parens back" to compound arithmetic operands only, keeping map/array/CASE literals and atoms un-parenthesized, and parenthesized is propagated through both copy() and splitForAggregation(). The round-trip test table in the description matches what the code actually does.

Item 3 — Gremlin classpath hint

Small, self-contained, well-tested (GremlinQueryEngineFactoryClasspathHintTest), no concerns.

Other

  • DDLStatement.parsePositiveIntSetting consolidation looks correct; confirmed no existing tests assert on the old per-statement message text, so the message-format change is safe.
  • Didn't find any issue with the IndexBuilder static-method extraction (callerTransactionHasChanges, buildCreatedIndex, dropPartiallyBuiltIndex) — package-private visibility is consistent with BucketIndexBuilder/LocalDocumentType both being in com.arcadedb.schema.
  • I wasn't able to run mvn compile/mvn test in this review environment (tool permissions), so I verified by static reading + cross-referencing the referenced methods/fields rather than by building. The PR description states mvn -o -pl engine -am test (12587 tests) and the cross-module verify runs are green, which I have no reason to doubt given the diff, but flagging that I didn't independently confirm it.

Nice regression tests overall — they target the actual reported symptom (readable-but-empty index, mis-rendered projection name, mislabeled classpath error) rather than just the internal mechanism.

…, so the refusal reaches the caller

Both points from the code review on PR #6364, and the first one turned out to be a bug rather than a coverage
gap.

The review asked for a regression test on the DuplicatedKeyException the join-transaction catch block already
anticipates - a caller that inserts two records violating a unique super-type index and then links the super
type. Writing it showed the exception never reached the caller at all: LocalDatabase.transaction retries a
duplicate exactly once (#4959), and on that retry addSuperType found the super type already in superTypes,
returned early without propagating anything, and let the transaction COMMIT. Measured result was a linked
super type with entries=0 whose lookup answered nothing - this issue's own defect, reached through the retry
instead of through the scan.

So the failure path now hands the in-memory linkage back too, not only the half-built components:
unlinkSuperType undoes superTypes/subTypes and the polymorphic bucket caches, passing back exactly the lists
that were handed over (the caches are replaced rather than mutated). The retry is then a real attempt, and its
refusal is what the caller gets. The paired external buckets ensureExternalBucketsRecursive may have created
are deliberately left: additive, idempotent, and reused by the next attempt.

The second point was a diagnostic asymmetry: DuplicatedKeyException and NeedRetryException are not
IndexException, so they escaped the catch that names which super type's propagation they came out of. The
catch is RuntimeException now, so every failure shape gets the context line.

Issue6359SuperTypeIndexPropagationTest gains a sixth test asserting all of it: the exception reaches the
caller, the type is left unlinked, the caller's records went with the rollback, no sub-index survives on the
bucket the failed build scanned, the super type's own index still works, and the link can still be made once
the conflict is gone.
@claude

claude Bot commented Aug 18, 2026

Copy link
Copy Markdown

Review

Reviewed all three items in this PR (index propagation transaction split, negative-literal/parenthesis rendering, gremlin/graphql classpath diagnosis) plus the two new/updated test suites. Overall this is a well-documented, well-tested PR; the comments in the diff do a lot of the reviewer's work already. A few things worth a second look before merge.

1. Possible incomplete cleanup on a partial addSuperType failure (LocalDocumentType.java, around line 2068)

addSuperType now splits index propagation into "create components" (its own transaction) and "build" (joins the caller's transaction via toBuild), and on any RuntimeException from either step it calls unlinkSuperType(...) to reverse the schema link.

sharesCallerTransaction is computed per index family (callerTransactionHasChanges && index.getType().buildCanShareCallerTransaction()), so families that can't join a transaction (e.g. vector indexes) are built inline, synchronously, inside the first ("component creation") transaction, and are never added to toBuild. Only entries in toBuild get IndexBuilder.dropPartiallyBuiltIndex(...) on failure; unlinkSuperType only undoes the super/sub-type link and the polymorphic bucket cache.

Concrete shape: a super type carries both a vector index and an LSM index. The vector sub-index is built and committed inline during component creation; the LSM one is queued in toBuild and later fails the join build (e.g. DuplicatedKeyException against the caller's own pending inserts). unlinkSuperType runs, so the type is unlinked - but the already-built vector sub-index is never dropped, leaving an orphaned index component attached to a type relationship that no longer exists.

Worth double-checking whether this mixed-family case is reachable in practice, and if so whether cleanup needs to also cover indexes built inline in the component-creation step, not just the toBuild list.

2. parsePositiveIntSetting reads the setting via Expression.toString(), not evaluation (DDLStatement.java:115)

parsePositiveIntSetting renders the setting's Expression with .toString() (needed because Expression.value is null for numeric literals - the actual bug this PR fixes). But WITH batchSize = <expr> accepts any expression grammatically, including a bound input parameter (:bs or ?). For a bound parameter, toString() renders the placeholder text rather than the resolved value, so REBUILD INDEX x WITH batchSize = :bs would fail to parse the intended integer. This isn't a regression from this PR specifically (the old RebuildIndexStatement code had the same entry.getValue().toString() pattern), so it's a pre-existing gap rather than something newly broken here - but since the PR is already unifying/cleaning up this reader, it might be worth a follow-up (or at least a comment) noting bound parameters aren't supported for these numeric settings, unlike parseBooleanSetting's doc which explicitly expects an evaluated raw value.

Things that look solid

  • The transaction-timing fix itself (item 1's core idea): computing callerTransactionHasChanges before opening the component-creation transaction is correct and well-explained - asking it from inside that transaction would always answer "no" since it's freshly opened and empty. Good catch, and the comment explaining why is helpful for future readers.
  • BaseExpression.parenthesized: initially looked like it might duplicate ParenthesisExpression, but that class renders parens unconditionally and has no modifier-chaining support, so it isn't a substitute here. Not a reuse problem.
  • Negative literal folding: preserves the original literal's numeric type (Long/Float/etc.) and correctly skips folding when a modifier is attached (since a suffix binds tighter than the sign) - this is the kind of detail that's easy to get wrong.
  • GremlinQueryEngineFactory.classpathHint: small, contained, only touches the error-reporting path, cold path so no performance concern.
  • CLAUDE.md conventions: no em-dash violations, consistent final usage, correct brace style, no System.out, tests use the required assertThat(...).isXxx() AssertJ style, no missing @Tag (new test loops are small/fast).
  • Test coverage: genuinely thorough for the shape of bugs being fixed - Issue6359SuperTypeIndexPropagationTest covers the uncommitted-insert propagation via both API and SQL, updates in the same transaction, rollback recovery, and (after the second commit) the failure-path/rollback-of-the-link scenario; Issue6359NegativeLiteralRenderingTest covers every literal shape plus the parentheses round-trip; the gremlin classpath test checks both the positive message and that unrelated failures aren't mislabeled.

Nothing above blocks the PR in my view, but #1 is worth a direct answer from the author since it's about whether a failure path can leave a genuinely orphaned index component rather than just an inconsistent-but-harmless state.

… a numeric setting is evaluated rather than rendered

Both points from the second code review on PR #6364.

The first asked whether a mixed-family propagation can leave an orphaned component: a super type carrying
both a vector index and an ordinary one, where the vector sub-index is built INLINE during component creation
(its family cannot share the caller's transaction) while the ordinary one fails the joined build. It can, and
measuring it found two causes rather than one.

The cleanup was keyed on the pending-build list, which by construction never contains an index that was built
inline. It now tracks every sub-index the propagation created, and that is the list the refusal takes away.

The larger cause was underneath: LSMVectorIndex.getTypeIndex() answered null, with the comment "Not applicable
for this index type", which was never true - a vector index IS registered under a TypeIndex, and
LSMSparseVectorIndex has always wired it. The null made two callers do the wrong thing.
LocalSchema.dropIndexInternal skips parentTypeIndex.removeIndexOnBucket(...) when it is null, so a dropped
vector sub-index stayed listed by its wrapper - a reference to an index that no longer exists, on EVERY path
that drops one, not only this one. And LocalDocumentType.addSuperType compares it to decide whether a super
type's index is already propagated to a bucket, so it never recognised one and minted a duplicate on every
attempt. Measured before the fix: two orphaned vector sub-indexes on the subtype's bucket, one per attempt.

The second point was that the numeric-setting reader renders the expression, so a bound parameter resolves to
its placeholder text rather than to the number bound. Rendering was only ever a workaround for
Expression.value being null on numeric literals; EVALUATING covers literals and parameters alike, which is
what parseBooleanSetting next to it has always taken. parsePositiveIntSetting now takes the evaluated value,
its callers pass expression.execute((Result) null, context), and REBUILD INDEX's statsOnly moves to
parseBooleanSetting for the same reason - Boolean.parseBoolean on a rendered placeholder silently answered
false.

Two regression tests: the mixed vector/LSM refusal leaving neither wrapper holding a sub-index on the
subtype's bucket, and a bound parameter accepted for batchSize on both REBUILD statements and refused by its
bound value when it is not a legal batch size.
@claude

claude Bot commented Aug 18, 2026

Copy link
Copy Markdown

Review of #6364

Reviewed the three items in this PR (super-type index propagation transaction split, negative-literal/parentheses rendering, gremlin/graphql Maven-invocation trap). The negative-literal folding, parentheses tracking, and the shared parsePositiveIntSetting/parseBooleanSetting readers all look correct - traced the overflow-literal interaction (tryFoldLongMinValueLiteral runs before tryNegateNumericLiteral and short-circuits, so no double-handling), the copy()/splitForAggregation() propagation of the new parenthesized flag, and the gremlin classpath-hint matching. Good test coverage on those two items.

Two things worth a look on item 1 (LocalDocumentType.addSuperType, engine/src/main/java/com/arcadedb/schema/LocalDocumentType.java):

1. The propagation build isn't quiesced against async writers, unlike its siblings

TypeIndexBuilder.create() and BucketIndexBuilder.create() both wrap their build in try (AsyncQuiesce asyncPaused = database.quiesceAsync()) specifically because of issue #6303: a record written by an async worker in the window between the barrier and the index's registration is invisible to both the scan and the index, since it started before registration but wasn't committed at scan time either.

The new propagation path in addSuperType (lines ~1999-2069) calls schema.createBucketIndex(...) directly and never calls quiesceAsync(). Since this path exists specifically to close the same class of index-misses-records gap that #6324/#6359 item 1 is about, it looks like it reopens the #6303 sub-case for async-inserted records specifically: a database.async() insert into a bucket that's mid-propagation could land in the same missed window TypeIndexBuilder was fixed to avoid. Worth confirming this is intentionally out of scope (e.g. because addSuperType is assumed never to race an async writer) or adding the same quiesceAsync() guard for consistency. None of the new regression tests exercise an async writer, so this wouldn't currently be caught either way.

2. created/toBuild accumulate across an internal retry of the component-creation transaction

The relevant shape (around line 2006 onward):

final List<Index> created = new ArrayList<>();
final List<Index> toBuild = new ArrayList<>();
try {
  database.transaction(() -> {
    for (final TypeIndex index : indexes) {
      created.add(subIndex);
      if (sharesCallerTransaction)
        toBuild.add(subIndex);
    }
  }, false);          // joinCurrentTx=false, own transaction, default TX_RETRIES=3

created/toBuild are declared outside the database.transaction(..., false) call, so if that inner transaction internally retries on NeedRetryException (e.g. a page-version conflict from a concurrent schema mutation - checkForSchemaMutation() only checks permissions, it doesn't take a lock), the lambda re-runs from scratch on the next attempt but the two lists are never cleared. The failed attempt's Index objects (now rolled back and non-existent) stay in both lists alongside the successful attempt's objects.

For created this is harmless (dropPartiallyBuiltIndex guards with schema.existsIndex(...)), but toBuild entries feed straight into IndexBuilder.buildCreatedIndex(subIndex, ...) -> internal.setStatus(...) / internal.build(...) with no existence check, on an Index object whose backing component was already rolled back. That's a plausible source of a confusing failure unrelated to the actual conflict, in an admittedly narrow window (needs the component-creation transaction itself to retry, not the caller's transaction - TypeIndexBuilder's equivalent loop avoids this by assigning into a pre-sized array by index rather than appending to a list, so a retry just overwrites rather than accumulates).

Neither of these came up in the three commits' own regression tests (which is expected given both need a concurrent/async trigger to manifest), but given how carefully the transaction-sharing semantics were reasoned about elsewhere in this PR, they seemed worth flagging rather than assuming out of scope.

Everything else - the IndexBuilder refactor (callerTransactionHasChanges/buildCreatedIndex/dropPartiallyBuiltIndex consolidation), the unlinkSuperType rollback-of-linkage-on-failure logic (nice catch on the retry-swallows-the-exception case in the second commit), and the LSMVectorIndex.getTypeIndex() fix - all check out against the code they touch.

…s start empty on every attempt

Both points from the third code review on PR #6364.

The propagation build was not quiesced against async writers, unlike TypeIndexBuilder and BucketIndexBuilder,
which hold quiesceAsync() for exactly this (issue #6303, item 2): the barrier answers about the past, and a
build needs the other half too - that nothing WRITES during the scan. A record an async worker saves in the
window between the barrier and the sub-index's registration is in neither the scan nor the index, which is the
gap this propagation exists to close, reopened for async writers.

WHERE the quiescence is taken is the whole of it, and the first attempt got it wrong in a way the new test
caught. Taken around the propagation itself it sits inside recordFileChanges, which runs under the database
WRITE LOCK - the lock an async worker needs to commit its batch. The quiescence then waits for workers that
cannot proceed until it returns, and gives up sixty seconds later with a NeedRetryException. It is taken
around the recordFileChanges call instead, which is where both builders take it, and only when there are
indexes to propagate: the schema-load path passes createIndexes=false and scans nothing. The regression test
went from failing at 85s to passing at 0.44s.

The second point was that `created` and `toBuild` were declared outside the component-creation transaction and
never cleared, so an internal retry of that transaction - a NeedRetryException from a concurrent schema
mutation re-runs the lambda from scratch - left the rolled-back attempt's indexes in both lists. For `created`
that is harmless, since dropPartiallyBuiltIndex checks existence; `toBuild` feeds buildCreatedIndex, which does
not, so the surviving attempt would report a failure that has nothing to do with the conflict that caused the
retry. Both lists are emptied on entry to the lambda, which is the effect TypeIndexBuilder gets for free by
assigning into a pre-sized array by position.

Adds the async-writer regression test the review noted was missing: a thousand records in flight through
database.async() while the super type is linked, asserting the propagated index ends with an entry for every
one of them.
@claude

claude Bot commented Aug 18, 2026

Copy link
Copy Markdown

Review

Reviewed the full diff (engine + gremlin changes, plus the two new test classes). This is a well-scoped, well-tested PR, and the PR description itself documents that three rounds of review already caught and fixed real bugs (the DuplicatedKeyException retry hole, the mixed vector/LSM orphan cleanup, and the async-quiescence placement). I focused on what those rounds might not have covered.

Item 1 - super type index propagation (LocalDocumentType)

Traced the two-transaction split, the created/toBuild bookkeeping, and the failure/cleanup path against LocalDatabase.transaction's actual joinCurrentTx semantics (createdNewTx=false → NeedRetryException/DuplicatedKeyException rethrown immediately, no retry, matching the PR's description of issue #661). The logic is internally consistent:

  • callerTransactionHasChanges is correctly evaluated before any transaction is opened.
  • build=!sharesCallerTransaction passed to createBucketIndex correctly routes vector-family indexes to inline build and everything else to the deferred/joined build.
  • The alreadyCreated dedup check depends on getTypeIndex() no longer returning null for vector indexes (item covered below) - confirmed this is exactly why that fix was needed here, not just cosmetic.
  • created/toBuild being cleared at the top of the retryable lambda (not at declaration) is correct given TypeIndexBuilder's different (pre-sized array) approach doesn't apply here.

Minor, out of scope for this PR, worth a follow-up issue: unlinkSuperType is only invoked from the catch inside the if (createIndexes) block. If ensureExternalBucketsRecursive() (line ~1999) or the bucket-selection-strategy suitability check (line ~2123, which the comment notes can throw SchemaException) fails, superTypes/subTypes/updatePolymorphicBucketsCache linkage applied earlier in the same recordFileChanges block is not rolled back in memory. This predates this PR (there was no unlink logic at all before), so it's not a regression, but since this PR just built the machinery to do it correctly for one failure path, it might be worth widening the try/catch to cover the whole linkage rather than just the index-propagation section - or filing a follow-up issue so it doesn't get lost.

Item 2 - negative literal / parentheses rendering

tryFoldLongMinValueLiteral (pre-existing, Long.MIN_VALUE overflow case) and the new tryNegateNumericLiteral are mutually exclusive by construction (the former only returns non-null for the one overflow shape it targets), so there's no double-negation risk. The type-preservation logic (Integer/Long/Float/Double) and the "modifier binds tighter than sign" exclusion both look correct, and are covered by the round-trip tests (renderingAndReparsingPreservesTheValue).

rendersParentheses() correctly restricts re-printing to compound arithmetic operands only, avoiding the unaliased-projection-name regression (SELECT (name) FROM V) - and both copy() paths propagate the new parenthesized flag, so a query-rewrite pass that clones a BaseExpression won't silently lose it. Good catch on that being needed in two places.

Item 3 - Gremlin/GraphQL classpath hint

Small and low-risk. classpathHint walks the cause chain looking for tinkerpop in a NoClassDefFoundError/ClassNotFoundException message - reasonable, and the "unrelated failure adds nothing" test guards against over-matching.

Style / conventions

  • No System.out, no new dependencies, no FQN usage introduced.
  • final used consistently on new locals/params.
  • Tests use assertThat(...) per the project's preferred style, with @Timeout rather than wall-clock assertions.
  • LSMVectorIndex.typeIndex is added as a plain (non-volatile) field, but that matches the existing convention in every sibling index class (LSMTreeIndex, HashIndex, LSMTreeGeoIndex, LSMTreeFullTextIndex, LSMSparseVectorIndex all declare it the same way), so it's not a new risk introduced by this PR.

Test coverage

The Issue6359SuperTypeIndexPropagationTest suite is thorough - uncommitted inserts, an in-transaction update propagated under its new key, rollback survival, the unique-conflict refusal reaching the caller, the mixed vector/ordinary-index cleanup, and the async-writer race. Issue6359NegativeLiteralRenderingTest covers rendering, round-trip evaluation, and the parenthesization edge cases well. Nothing obvious missing.

Overall: solid, well-reasoned fix with strong regression coverage. Only actionable suggestion is the out-of-scope linkage-rollback gap noted above, which you may want to track separately rather than block this PR on.

…only on the one the propagation raises

The one actionable note from the fourth code review on PR #6364. It was flagged as out of scope with an offer
to file a follow-up, but the machinery to close it is what the previous commit already built, so it is closed
here rather than left.

Linking a super type applies the linkage first - superTypes, subTypes, the polymorphic bucket caches - and then
does three things that can each still refuse: pairing external buckets for a super type that has external
properties, propagating the super type's indexes, and inheriting its bucket selection strategy. Only the middle
one rolled the linkage back, so a refusal from either of the others handed the caller a type that IS a subtype
with none of what being one implies.

The guard now wraps the whole post-linkage region instead of the propagation alone, and unlinkSuperType is
called from there. The propagation's own catch keeps what is its own: dropping the sub-indexes it created and
naming the super type in the log.

Measured on the third of those paths, which is the one reachable without a fault injection: a partition that is
legal on the super type and unsuitable for the subtype, whose own index on the partition key is declared
COLLATE CI (#5637). It refuses with that message and now leaves both sides of the link as it found them, and a
subtype the partition IS suitable for still links afterwards - the refusal takes nothing away permanently.
@claude

claude Bot commented Aug 18, 2026

Copy link
Copy Markdown

Review

This is a well-scoped, well-tested fix (five commits, each closing a gap the previous review round found — the commit messages document that process clearly). I focused on the parts most likely to still hide something after four review passes: the transaction-splitting logic in LocalDocumentType.addSuperType, since that's the riskiest surface in the PR.

Correctness: a later refusal in addSuperTypeInternal can leave the just-propagated indexes orphaned

engine/src/main/java/com/arcadedb/schema/LocalDocumentType.java, addSuperTypeInternal (~lines 1983-2148).

The method wraps three fallible steps in one guard so a refusal from any of them unwinds the whole linkage:

try {
  if (embeddedSuperType.hasExternalProperties())
    ensureExternalBucketsRecursive();

  if (createIndexes) {
    final List<Index> created = new ArrayList<>();   // <-- scoped to this block
    final List<Index> toBuild = new ArrayList<>();
    try {
      ...propagate indexes, populate created/toBuild...
    } catch (final RuntimeException e) {
      for (final Index subIndex : created)
        IndexBuilder.dropPartiallyBuiltIndex(schema, subIndex);
      ...
      throw e;
    }
  }

  if (!superType.getBucketSelectionStrategy()...)
    setBucketSelectionStrategy(superType.getBucketSelectionStrategy().copy(), false);   // can throw SchemaException, #5637

} catch (final RuntimeException e) {
  unlinkSuperType(embeddedSuperType, linkedBuckets, linkedBucketIds);   // undoes the LINK only
  throw e;
}

created and toBuild are local to the if (createIndexes) block. If index propagation succeeds (no exception from the inner try) and the later setBucketSelectionStrategy step then throws — which is exactly the scenario the PR's own aRefusalFromOutsideTheIndexPropagationHandsTheLinkBackToo test exercises (an inherited partitioned('k') strategy that's unsuitable for the subtype's COLLATE CI index, #5637) — the outer catch only calls unlinkSuperType, which resets superTypes/subTypes/the polymorphic bucket caches. It does not call IndexBuilder.dropPartiallyBuiltIndex on the sub-indexes that were just committed in the inner block, because that list has already gone out of scope.

The result: the propagated sub-index component(s) stay committed and attached to the super type's TypeIndex, referencing a bucket that belongs to a type no longer linked as its subtype — structurally the same "index says it's healthy but is inconsistent with the schema" shape this whole PR exists to close, just reached through the third failure path instead of the first. The existing test doesn't catch it because it only asserts getSuperTypes()/getSubTypes() are empty; it never inspects ((TypeIndex) getIndexByName("Super[k]")).getIndexesOnBuckets() for a leftover sub-index on Sub's bucket.

Suggested fix: hoist created (or a running list of every sub-index the propagation attached) to the same scope as the outer try, and have the outer catch drop them too — mirroring what the inner catch already does — rather than only calling unlinkSuperType. A regression test extending aRefusalFromOutsideTheIndexPropagationHandsTheLinkBackToo to assert no sub-index survives on Sub's bucket after the COLLATE CI refusal would pin it down (parallel to how aRefusalTakesAwayTheIndexesThatWereBuiltInlineToo already checks this for the index-propagation failure path).

Everything else checked out

  • IndexBuilder.callerTransactionHasChanges / buildCreatedIndex / dropPartiallyBuiltIndex extraction is a clean, equivalent refactor of the existing predicate/steps; timing (asking before the component-creation transaction opens) is correct.
  • LSMVectorIndex.typeIndex is intentionally non-volatile, matching every sibling index family's field (LSMSparseVectorIndex, HashIndex, LSMTreeFullTextIndex, LSMTreeIndex, LSMTreeGeoIndex all use a plain field) — not an inconsistency despite indexName nearby being volatile for an unrelated (replication) reason.
  • SQLASTBuilder.tryNegateNumericLiteral: negating a parsed Integer/Long can't hit a MIN_VALUE overflow here, since a magnitude that doesn't fit a positive int/long is already promoted to a wider literal type upstream (the pre-existing MIN_VALUE-folding method handles the one case that needs it). Modifier-carrying literals are correctly left to the 0 - X fallback.
  • BaseExpression.rendersParentheses() correctly limits reprinting to compound arithmetic operands, keeping SELECT (name) FROM V and DISTINCT (name) unaffected; parenthesized is propagated through both copy() and the bind-params path.
  • DDLStatement.parsePositiveIntSetting / parseBooleanSetting are evaluated consistently now (fixing the real REBUILD TYPE ... batchSize "got: null" bug), and both RebuildIndexStatement/RebuildTypeStatement route through them.
  • GremlinQueryEngineFactory.classpathHint is a reasonable, narrowly-scoped diagnostic improvement; the CLAUDE.md addition documenting the test vs verify trap for gremlin+graphql is a good catch for future contributors.
  • Test coverage is thorough for the scenarios it does cover (uncommitted-record propagation, rollback survival, duplicate-key refusal, mixed vector/ordinary index cleanup, async-writer quiescence, SQL round-tripping of negative literals and parentheses) — the gap above is the one path it doesn't reach.

No security or performance concerns found; the async quiescence placement (around recordFileChanges rather than inside it, to avoid deadlocking against the write lock) is correctly reasoned and matches the pattern used by TypeIndexBuilder/BucketIndexBuilder.

…only on the propagation's own

The point from the fifth code review on PR #6364, and it was right: the previous commit widened the LINK
rollback to cover every refusal but left the INDEX cleanup where it was.

`created` was scoped to the index-propagation block, so it only reached the cleanup when the propagation itself
was what refused. The step after it can refuse too - inheriting a bucket selection strategy the subtype cannot
take (#5637) - and by then the propagated sub-indexes are committed and attached to the super type's TypeIndex.
The outer guard unlinked the type and left them there: a super type whose index points at buckets belonging to
a type that is no longer its subtype, which is the same "healthy-looking index inconsistent with the schema"
shape this issue exists to close, reached through the third failure path instead of the first.

It is hoisted to the outer guard's scope, and the outer catch drops every sub-index the propagation attached
before handing the link back. The propagation's own catch keeps only what is its own: naming which super type's
propagation the failure came out of.

The regression test for that path already existed - it asserted the link went back - and simply did not look at
the indexes. It does now, and it fails without this commit.
@claude

claude Bot commented Aug 18, 2026

Copy link
Copy Markdown

Review

I went through this diff (all 6 commits collapsed) independently of the review rounds already recorded in the commit history. Summary: the fixes are well-targeted, each is backed by a focused regression test, and I did not find a new correctness bug. A few observations below, none blocking.

Item 1 - addSuperType index propagation

  • The two-transaction split (created/toBuild cleared on entry to the retryable lambda, callerTransactionHasChanges asked before any transaction is opened, cleanup hoisted to the outer guard so a refusal from the bucket-selection-strategy step also unwinds committed sub-indexes) matches the trap it's closing and is covered by the Issue6359SuperTypeIndexPropagationTest suite, including the async-writer and rollback cases. The reasoning in the comments checks out against DatabaseAsyncExecutorImpl.quiesceWorkers() - the ReentrantLock there really is hold-count reentrant, so "a builder reached from below rides on this one" is accurate and not a deadlock risk.
  • addSuperTypeInternal is now a large method with nested try/catch and a lot of state threaded through comments rather than structure (created, toBuild, linkedBuckets/linkedBucketIds captured before the try). It's correct, but it's dense - a future change here has a real chance of missing which catch block is responsible for which cleanup. Not asking for a rewrite given how carefully it's already been iterated on, just flagging it as a spot that will need the same care next time, not a quick patch.

Item 2 - negative literal folding

  • tryNegateNumericLiteral and the pre-existing tryFoldLongMinValueLiteral are correctly ordered (overflow case checked first, against the raw parse context, before the general fold runs against the visited expression), so Long.MIN_VALUE handling isn't disturbed.
  • Verified there's only one SQL parser path (ANTLR); no legacy JavaCC grammar builds the old 0 - X shape in parallel, so this can't be a case of fixing one path and leaving another silently wrong.
  • The parenthesization fix (BaseExpression.parenthesized, only rendered around a compound operand) matches the round-trip cases in the PR description, including the -(1 + 2) case, which is fixed by the parens logic rather than the literal-folding logic since the operand there isn't a bare literal.

Item 3 - Gremlin/GraphQL classpath hint

  • Straightforward, classpathHint walks the cause chain defensively and the unrelated-failure-passes-through-unchanged case is tested.

LSMVectorIndex.getTypeIndex() - worth double-checking scope

The PR description calls out two callers this fix affects (LocalSchema.dropIndexInternal, LocalDocumentType.addSuperType), but getTypeIndex() on a vector bucket sub-index previously always returned null, and it has quite a few more callers across the engine: DatabaseChecker's CHECK-FIX rebuild path, RebuildIndexStatement's owner-name preservation, FetchFromSchemaIndexesStep's typeIndexName reporting, and three call sites in TransactionIndexContext for unique-index handling. I traced through each:

  • The TransactionIndexContext ones are gated by index.isUnique(), and LSMVectorIndex.isUnique() is hardcoded false, so those are unreachable for this index type either way.
  • DatabaseChecker and RebuildIndexStatement now correctly preserve the wrapper's explicit name across a vector index rebuild instead of minting a new implicit one - this looks like a second latent bug this same fix happens to close, not a regression.
  • FetchFromSchemaIndexesStep now reports the real owning TypeIndex name for typeIndexName instead of falling back to the bucket sub-index's own name - also an improvement.

So nothing looks broken, but since this is a null-to-non-null change on a shared interface method with more call sites than the PR body enumerates, it'd be worth explicitly confirming the vector-index test suite (rebuild, CHECK DATABASE FIX, and Studio's index listing if it's exercised) was run, beyond the two call sites named in the description.

Tests

Good coverage matching the PR description - 8 tests in Issue6359SuperTypeIndexPropagationTest (including rollback survival and the mixed vector/LSM partial-cleanup case), 6 in Issue6359NegativeLiteralRenderingTest, 2 in GremlinQueryEngineFactoryClasspathHintTest. The async-writer test is @timeout(180) - worth confirming it's not also meant to carry @tag("slow") per CLAUDE.md's convention for multi-second functional regression tests, since a thousand records in flight through database.async() sounds like it belongs in that lane. I didn't see a @tag on it in the diff.

Minor

  • CLAUDE.md's new build-trap entry is accurate and will save someone real time.
  • No new dependencies, no license concerns, no obvious security surface touched.

Nothing here blocks merging as far as I can tell; the vector-index scope note above is the one thing I'd actually ask about before approving.

… and why it is not in the slow lane

The reviewable half of the sixth code review on PR #6364, which asked whether the async-writer test belongs in
the slow lane given its @timeout(180).

It does not, and the number is the reason it looked like it might. Measured, the test runs in 12 ms: the
thousand records go through database.async() as QUEUED tasks, so the test never waits for them - the quiescence
the propagation takes is what settles them. The timeout is sized as a hang detector, not as a latency bound:
a quiescence that cannot park a worker gives up only after its own 60-second budget, and the failure has to
arrive as that refusal, naming the worker it could not park, rather than as a bare timeout that names nothing.
Tagging a 12 ms test `slow` would route it to a lane it does not belong in and say the opposite of what is
true.

Written down in the test rather than answered once in a review thread.
@claude

claude Bot commented Aug 18, 2026

Copy link
Copy Markdown

Review

I read through the full diff (schema/index changes, the negative-literal/parentheses rendering fix, DDLStatement.parsePositiveIntSetting, and the gremlin/graphql classpath hint) plus the new regression tests. Overall this is a careful, well-tested PR — the commit history shows the trickiest parts (transaction timing for callerTransactionHasChanges, the async quiescence placement relative to the write lock, the created/toBuild list scoping across retries, and rolling the link back on every post-linkage failure path, not just the index-propagation one) were already caught and fixed in earlier review rounds. I did not find any new correctness issues on this pass. A few smaller notes:

Code quality / maintainability

  • LocalDocumentType.addSuperTypeInternal (engine/src/main/java/com/arcadedb/schema/LocalDocumentType.java) is now a large method with nested try/catch blocks and several comments explaining non-obvious ordering constraints (quiescence placement, created/toBuild scoping, when the outer vs. inner catch applies). The comments are good and necessary, but the method's cyclomatic complexity is high enough that a future edit risks breaking one of these invariants without realizing it. Might be worth flagging as a candidate for extraction into a few smaller private methods (e.g. "propagate indexes", "apply post-linkage steps") once the dust settles here, purely to make the individual invariants easier to hold in your head. Not blocking.
  • IndexBuilder.callerTransactionHasChanges / buildCreatedIndex / dropPartiallyBuiltIndex are now static package-visible methods used by a non-builder call site (LocalDocumentType). That's a reasonable way to share the three things without forcing addSuperType through the BucketIndexBuilder API (which the PR description explains would re-derive key types and quiesce N times). Just worth double-checking there's no other existing call site that could now also collapse onto these statics as a follow-up cleanup.

Testing

  • Test coverage for item 1 (index propagation) and item 2 (literal rendering) is genuinely thorough — uncommitted-write visibility, update-in-same-tx, rollback survival, duplicate-key refusal via the API and reaching through the retry, mixed vector/ordinary index cleanup, async-writer quiescence, and refusal from a non-index post-linkage step (bucket selection strategy) are all exercised individually. The reparse-round-trip test for literal rendering directly protects the failure mode described in the PR (EXPLAIN/unaliased-projection naming/setting re-parsing).
  • One gap: I didn't see a test asserting LSMVectorIndex.getTypeIndex() behavior directly (only indirectly through the mixed-index propagation-cleanup test). A small direct unit test (create a vector index, assert getTypeIndex() returns the wrapper, drop it, assert the wrapper no longer references it) would pin down the LocalSchema.dropIndexInternal half of the fix independently of the addSuperType scenario that happens to exercise it. Not blocking given the existing coverage exercises the real bug.

Minor / non-blocking

  • GremlinQueryEngineFactory.classpathHint matches on missing.contains("tinkerpop") (lowercase) against the class name from NoClassDefFoundError/ClassNotFoundException. That's fine given JVM binary/class names for this package are always lowercase, but if TinkerPop ever added a differently-cased artifact this would silently stop matching — extremely low risk, just noting it since it's a string-contains match rather than a package-prefix check.
  • BaseExpression.parenthesized is copied in the two copy()/deep-copy paths that were touched, but I didn't check equals()/hashCode() (if any exist on this class) for whether they should also account for it. Since the field is documented as "rendering only," this is likely fine as-is.

Nice work tracking down the transaction-timing subtleties in item 1 — the callerTransactionHasChanges "ask before opening anything" point in particular is a sharp catch that's easy to get backwards.

…, independently of addSuperType

The one actionable note from the seventh code review on PR #6364: LSMVectorIndex.getTypeIndex() was only
covered indirectly, through the mixed vector/ordinary propagation-cleanup test that happened to exercise it.

The drop path is the wider half of that fix and deserves to be asserted on its own. LocalSchema.dropIndexInternal
skips parentTypeIndex.removeIndexOnBucket(...) when getTypeIndex() answers null, so before this every path that
dropped a vector sub-index - DROP INDEX, REBUILD INDEX, CHECK DATABASE ... FIX, removing a bucket - left the
wrapper holding a reference to an index that no longer existed. None of that has anything to do with linking a
super type.

Two buckets, so dropping one sub-index leaves the wrapper alive to be asked about the other: each sub-index
names the wrapper it was registered under, and the wrapper lets go of the one that was dropped while keeping
the one that was not. It needs no vector rebuild, so it stays out of the vector lane and runs in 0.27 s.
@claude

claude Bot commented Aug 18, 2026

Copy link
Copy Markdown

Review

Went through all three items in detail, including tracing the transaction-join semantics (Database.transaction(txBlock, joinCurrentTx)), the LocalSchema.createBucketIndex(..., build) overload, the PInteger/PNumber literal representation, and the DDLStatement.parsePositiveIntSetting/parseBooleanSetting evaluation path. This is unusually well-documented and well-tested work; I didn't find a correctness bug. Notes below are minor.

Item 1 - addSuperType two-transaction split

  • The callerTransactionHasChanges check is correctly evaluated before the component-creation transaction opens (verified against IndexBuilder.callerTransactionHasChanges and the comment explaining why timing matters). Good catch calling that out explicitly - it's the kind of thing that "compiles, passes most tests, and does nothing" if placed wrong.
  • created/toBuild are cleared at the top of the retryable component-creation transaction lambda rather than at declaration, which correctly avoids leaking a rolled-back retry attempt's indexes into the build/cleanup lists.
  • The cleanup path (IndexBuilder.dropPartiallyBuiltIndex + unlinkSuperType) is invoked from a single outer catch covering the whole propagation block, so it correctly fires for every kind of post-linkage failure (index build, external bucket pairing, bucket-selection-strategy inheritance) rather than only IndexException, matching aRefusalFromOutsideTheIndexPropagationHandsTheLinkBackToo.
  • One thing worth a one-line callout somewhere (comment or PR description, not necessarily code): index families that can't share the caller's transaction (vector) are still built inline in the component-creation transaction, which does not join the caller's. So addSuperType's propagation of a vector index still won't see the caller's uncommitted writes - the fix here guarantees no orphaned/duplicate sub-index on failure, but doesn't extend "sees uncommitted writes" to that index family. That's consistent with the rest of the codebase (vector builds never join), so not a regression, just easy to misread as "fully fixed" from the PR title alone.

Item 2 - negated literal / parentheses rendering

  • Confirmed tryNegateNumericLiteral mirrors exactly how visitIntegerLiteral/visitFloatLiteral populate PInteger/PNumber (fluent setValue vs. direct .value =), so the folded literal round-trips through the same toString() path as an ordinary parsed one - no divergent formatting.
  • The modifier != null guard correctly prevents folding -1.toString() into a negated literal (which would wrongly move the negation inside the call).
  • rendersParentheses() gating on "compound operand" rather than "was parenthesized" is the right call for not renaming unaliased projections like SELECT (name) FROM V. Not tested: doubly-nested parens around a compound expression, e.g. SELECT ((a + b)) * c. Low risk (worst case is a redundant paren surviving, not a semantic change), but might be worth one assertion given how much rides on this renderer now (EXPLAIN, projection naming, WITH-setting round-trip).

Item 3 - Gremlin classpath hint

  • classpathHint walking the cause chain and checking both NoClassDefFoundError/ClassNotFoundException with a "tinkerpop" substring match is a reasonable, low-risk heuristic; the "unrelated failure" test guards against over-matching.

Nit

  • RebuildTypeStatement/RebuildIndexStatement now evaluate settings via entry.getValue().execute((Result) null, context) - confirmed the (Result) cast is load-bearing (disambiguates the Identifiable vs. Result overload of Expression.execute), not dead code.

Nothing blocking from my pass. Nice regression-test coverage on all three items, including the negative cases (rollback, duplicate key mid-propagation, refusal from a non-index step).

…ed parentheses render as

Both notes from the eighth code review on PR #6364, neither of which was a defect.

The first is a scope statement that was easy to over-read from the title. An index family that cannot share the
caller's transaction - the vector ones - is built inline inside the component-creation transaction, and that one
does not join the caller's, so a propagated vector index sees the caller's uncommitted writes no more than it
did before. Nothing regressed, since no vector build has ever joined a caller's transaction, but "the propagated
index now covers uncommitted records" is true of the families that can share one, not of every family. Said at
the decision site, where the per-family split is made, rather than left to be inferred from it.

The second pins what redundant parentheses render as, since a great deal now rides on that renderer - EXPLAIN,
the name of an unaliased projection, and the round trip of a WITH setting. Each layer is judged on the operand
it wraps, so a layer around an already-parenthesised block wraps something that renders as one atom and prints
nothing: `((a + b)) * c` renders `(a + b) * c`, `(((1 + 2))) * 3` renders `(1 + 2) * 3`, and `((a))` renders
`a`. Redundancy collapses to the one pair that carries the meaning, and the worst case was only ever a spare
pair of parentheses rather than a change of meaning - now asserted instead of assumed.
@claude

claude Bot commented Aug 18, 2026

Copy link
Copy Markdown

Review

This PR bundles three independent fixes discovered while working #6324; all three are self-contained, well-scoped, and each carries its own regression tests. The PR description and inline comments are unusually thorough, and the commit history shows the three items already went through 8 rounds of review with real bugs caught and fixed along the way (the retry-swallows-the-exception bug, the vector-index cleanup gap, the async-quiescence deadlock-by-lock-ordering, the outer-vs-inner rollback scope). I re-checked the current diff end to end rather than re-litigating what's already been fixed; notes below are what's left.

Item 1 — index propagation on addSuperType

  • The rollback story checks out: unlinkSuperType calls the same recursive updatePolymorphicBucketsCache used to apply the link, so multi-level super type chains (grandparent caches) are correctly unwound too, not just the immediate super type.
  • AsyncQuiesce is correctly taken outside recordFileChanges/the write lock, matching the deadlock hazard documented in engine/CLAUDE.md (quiescing while holding the write lock a worker needs would hang until the 60s budget). Good catch to have moved it there.
  • The two-list (created/toBuild) + outer/inner try-catch scoping is correct for the mixed vector/ordinary-index case and for the "refusal from the bucket-selection-strategy step after indexes already committed" case — both are exercised by dedicated tests and match the code.
  • LSMVectorIndex.typeIndex as a plain (non-volatile) field is consistent with every sibling index family (LSMTreeIndex, HashIndex, LSMTreeGeoIndex, LSMSparseVectorIndex, LSMTreeFullTextIndex all do the same), so this isn't introducing a new concurrency profile.

Item 2 — negative literal folding / parenthesis rendering

  • tryNegateNumericLiteral's type dispatch (Integer/Long/Float/Double) lines up with what visitIntegerLiteral/visitFloatLiteral actually produce, and the Long.MIN_VALUE overflow case is handled earlier by the pre-existing tryFoldLongMinValueLiteral, so there's no double-negation or precision-loss path I could find.
  • Minor/non-blocking: rendersParentheses() gates only on expression.mathExpression having operators. Expression also has a whereCondition (and arrayConcatExpression/json) slot for other compound shapes parked in the same BaseExpression.expression field. If any of those can ever appear as a plain parenthesized operand, round-tripping through toString() could still drop meaningful parens the same way the old code always did — but that's pre-existing behavior this PR narrows rather than a regression, and the PR is explicit that it scoped the fix to "compound arithmetic operand" only. Worth a quick sanity check if you know of a code path where a boolean/case sub-expression gets parenthesized as a math operand, otherwise not worth chasing.
  • Behavioral note rather than a bug: parseBooleanSetting used to silently coerce any unrecognized value to false (via Boolean.parseBoolean); it now throws CommandSQLParsingException. That's clearly the right fix (silent-false was itself the bug called out for statsOnly), but it is a user-visible behavior change for anyone who had e.g. a typo'd WITH statsOnly = yes that used to silently no-op and will now error. Might be worth a line in release notes.

Item 3 — gremlin/graphql classpath hint

  • classpathHint's substring match on "tinkerpop" works for both NoClassDefFoundError's slash-form and a dot-form ClassNotFoundException message, and the "unrelated failure" test confirms it doesn't mislabel other missing classes.

Tests

Coverage is thorough and each test's docstring explains why it exists rather than just what it checks, which matches the file's own standard. The async-quiescence test is correctly reasoned to not need the slow tag (records are queued, not awaited — the 180s timeout is a hang detector). No System.out/debug leftovers found in the diff.

Overall: I didn't find any unresolved correctness bugs in the current state — the multi-round review already surfaced and fixed the substantive ones. The two notes above are minor/informational rather than blocking.

…se notes

The second note from the ninth code review on PR #6364: the boolean setting reader used to coerce anything it
did not recognise to false, and now refuses it, which is a user-visible change worth stating rather than
leaving to be discovered.

`REBUILD INDEX i WITH statsOnly = yes` did not fail before - Boolean.parseBoolean answers false for anything
unrecognised, so the typo silently selected the OTHER behaviour, and for statsOnly that is the difference
between recomputing index statistics and rebuilding the whole index. Anyone carrying such a typo has been
getting the expensive path all along and now gets told.

Added to docs/release-26.9.1.md along with the two numeric fixes that come with it and the negative-literal
and parentheses rendering change, plus a docs/6359-*.md page with the before/after table for the three
statement shapes whose behaviour differs.
@claude

claude Bot commented Aug 18, 2026

Copy link
Copy Markdown

Review

I read through the full diff (all 8 files under engine/, the gremlin classpath-hint change, and the 4 new test classes) rather than re-deriving the history already captured in the very detailed commit messages. Overall this is a well-scoped, well-tested fix; the transaction-join logic in LocalDocumentType.addSuperType is intricate but the cleanup/rollback paths line up correctly with the tests that exercise them. A few notes, nothing blocking:

Correctness (looked but found no bugs)

  • Traced IndexBuilder.callerTransactionHasChanges / buildSharesCallerTransaction and confirmed the timing concern called out in the comments is actually respected: the predicate is evaluated once, before the component-creation transaction opens, and is captured in a final boolean that survives that transaction's internal retries (since created/toBuild are cleared on every retry attempt but callerTransactionHasChanges is not re-derived from a transaction that would, by then, always be empty).
  • Traced the two-level try/catch in addSuperTypeInternal: the inner catch (around the index-propagation transactions) only logs and rethrows, and the outer catch does the real cleanup (dropPartiallyBuiltIndex over every entry in created, then unlinkSuperType). Since created is declared outside the inner try, a refusal from the later bucket-selection-strategy step (after indexes are already committed) still drops the propagated sub-indexes — matches aRefusalFromOutsideTheIndexPropagationHandsTheLinkBackToo.
  • tryNegateNumericLiteral: checked the Integer/Long negation for overflow at the boundary (Integer.MIN_VALUE/Long.MIN_VALUE). Both are unreachable here because a bare positive literal can never parse to Integer.MIN_VALUE's magnitude as an int, and Long.MIN_VALUE's magnitude is intercepted earlier by tryFoldLongMinValueLiteral before this function ever sees it. No wraparound bug.
  • Manually traced the nested-parentheses collapse (((a + b)) * c → (a + b) * c) through rendersParentheses() — the "redundant outer layer wraps something that itself renders as one atom" reasoning holds up under actual tree-shape tracing, it's not just asserted by the tests.
  • LSMVectorIndex.setTypeIndex/getTypeIndex now match the pattern already used by LSMSparseVectorIndex, so this isn't introducing a new/different convention.

Minor observations (optional, not required)

  1. DDLStatement.parsePositiveIntSetting (engine/.../DDLStatement.java:120-139): a String setting value that doesn't parse as a plain integer (e.g. "5.0") is refused, even though the Number branch a few lines above would happily accept a Double with the same value. This is a pre-existing-shape asymmetry rather than a regression, and probably never hit in practice since WITH batchSize = ... settings are either numeric literals or bound parameters — just flagging it in case a future caller feeds it a numeric string.
  2. GremlinQueryEngineFactory.classpathHint matches on missing.contains("tinkerpop") (lowercase only). Since the real package is org.apache.tinkerpop..., this is fine in practice, but it's doing a plain substring check rather than something more structural — a very unlikely false positive if an unrelated class happened to embed "tinkerpop" in its name. Not worth guarding against.
  3. The addSuperType quiescing + two-transaction split adds meaningful complexity to an already-complex method (now ~190 lines with three nesting levels of try/catch). The extensive comments make it navigable, but this is a good candidate to keep an eye on if issue Follow-ups from #6324: a propagated index still misses uncommitted records, a negative literal renders as 0 - 1, and two modules cannot share a Maven invocation #6359-adjacent bugs show up later — the logic is dense enough that a future change touching it should re-read the whole method rather than patch a single spot.

Test coverage

Good coverage of the tricky cases: uncommitted-record propagation (API + SQL script), update-in-same-transaction, rollback-then-reuse, duplicate-key refusal with full cleanup verification (both the index side and the link side), the mixed vector/ordinary-index cleanup gap, the async-quiescence race, and the "refusal from a later step" case. The negative-literal test suite is thorough on the rendering/reparse round-trip. I didn't find gaps worth calling out.

Not independently verified

I did not re-run mvn verify/the module test suites myself in this review pass (the PR description already reports specific green runs: mvn -o -pl engine -am test 12587/0 failures, plus verify on gremlin/graphql/server/postgresw and gremlin-it) — CI will confirm those results.

…hape it arrives in

The one taken note from the tenth code review on PR #6364. The other two - the substring match in the Gremlin
classpath hint, and the density of addSuperTypeInternal - were raised and dismissed by the reviewer, and the
second by two reviewers before it; neither is changed.

parsePositiveIntSetting had two branches that disagreed. A Number went through a whole-number test, so 1000.0
was accepted as 1000; anything else went through Integer.valueOf, so the string "1000.0" was refused while
"1000" was not. Which branch a value took is an accident of how it reached the reader - a literal, a bound
parameter, a quoted setting - and not something a user chooses, so the two shapes of one value have to give
one answer.

Both now go through the same test: read as a double, refuse anything absent, unparseable, fractional, out of
int range, or below one. NaN fails the whole-number test as surely as 1.5 does, and infinity fails the range
test.

The test asserts the equivalence directly rather than the branches: 1000, 1000.0 and '1000' are all accepted,
1000.5, '1000.5', 'not a number' and 0 are all refused by name.
@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 28 complexity

Metric Results
Complexity 28

View in Codacy

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

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

View coverage diff in Codacy

Coverage variation details
Coverable lines Covered lines Coverage
Common ancestor commit (1c219a7) 160695 127699 79.47%
Head commit (411a0ef) 193095 (+32400) 140736 (+13037) 72.88% (-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 (#6364) 107 95 88.79%

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

This PR bundles three fixes discovered while working #6324 (index propagation on addSuperType, negative-literal/parentheses rendering, and the gremlin+graphql Maven trap), with an unusually thorough iteration history already baked in (11 commits, each closing a gap a prior review round found). Most of the obvious correctness issues I'd normally flag - link rollback on every refusal path, created/toBuild list resets across transaction retries, quiescing async writers around the right lock scope, LSMVectorIndex#getTypeIndex() wiring - are already addressed with regression tests. Nice work overall. A few remaining notes:

Code quality

  • Comment density in production code. Several methods (LocalDocumentType.addSuperTypeInternal, IndexBuilder.callerTransactionHasChanges/buildCreatedIndex, BaseExpression.parenthesized/rendersParentheses, DDLStatement.parsePositiveIntSetting) carry multi-paragraph Javadoc/inline comments narrating the bug history and issue numbers (#6324, #6359, #5637, #661, #4959...). That's valuable once, but as inline comments they'll rot: the issue numbers won't mean anything to someone reading this in a year, and the sheer volume makes the actual logic harder to scan. Since you've already written docs/6359-rebuild-setting-validation.md and the release-26.9.1.md entry to carry the narrative, consider trimming the in-code comments down to the invariant itself (e.g. "asked before the component-creation transaction opens one" is useful; the blow-by-blow of how the first attempt got it wrong is not) and let the docs/PR description carry the rest.

Potential bugs / correctness

  • Nothing new turned up beyond what the review history already caught. One path is explicitly not covered by a regression test: the ensureExternalBucketsRecursive() failure branch inside the new outer guard in addSuperTypeInternal (the PR description says this honestly - "reachable without a fault injection" only for the bucket-selection-strategy path). Worth a follow-up issue/TODO if there's a way to fault-inject external bucket pairing failure, since it's currently reasoned about but not asserted.
  • tryNegateNumericLiteral in SQLASTBuilder looks correct for the four literal shapes it handles (Integer/Long/Float/Double), and the Integer.MIN_VALUE-shaped edge case is safe because the literal parser already promotes an out-of-int-range magnitude to Long before this code sees it (confirmed by the existing overflow-folding method above it and the -2147483648/-9223372036854775808 test cases).
  • Confirmed BaseExpression.parenthesized/rendersParentheses() is scoped to MathExpression-shaped arithmetic only; WHERE-clause boolean precedence (AndBlock/OrBlock, a separate BooleanExpression hierarchy) isn't touched by this change, so there's no equivalent (a OR b) AND c precedence risk introduced here - it's simply out of scope for this fix.

Performance

  • Quiescing async writers on every addSuperType(..., createIndexes=true) call adds real cost, but it's gated on createIndexes (schema-load path passes false and skips it entirely) and mirrors the existing TypeIndexBuilder/BucketIndexBuilder pattern, so this is the correct tradeoff for correctness over the alternative of a silently-incomplete index.
  • parsePositiveIntSetting reading everything through Double (rather than branching straight to int/long parsing) is a fine tradeoff for a DDL-setting parser that runs once per REBUILD statement, not a hot path.

Security

  • No injection or permission-check concerns spotted. RebuildIndexStatement/RebuildTypeStatement still evaluate settings through the existing Expression/CommandContext machinery rather than any new string concatenation, and the new parsePositiveIntSetting/parseBooleanSetting readers make invalid input fail loudly (a behavior change called out clearly in the release notes) instead of silently coercing to a cheaper/wrong operation - a net security-adjacent improvement given the statsOnly typo example in the PR description.

Test coverage

  • Very thorough: Issue6359SuperTypeIndexPropagationTest covers the uncommitted-write propagation, in-transaction update-then-link, rollback survival, duplicate-key refusal (including the retry-swallowing bug found mid-review), the mixed vector/ordinary-index cleanup, the async-writer race, and the "refusal from any of the three post-link steps unwinds the link" case. Issue6359NegativeLiteralRenderingTest round-trips render→reparse on computed values rather than just string comparison, which is the right level of assertion for a renderer bug. GremlinQueryEngineFactoryClasspathHintTest is a nice small addition given the failure mode was previously undiagnosable from the error message alone.
  • Minor: the @Timeout(180) async-writer test is explicitly justified as a hang detector rather than a latency bound in its own Javadoc and the @Timeout class-level guidance in CLAUDE.md - good adherence to the project's own stall-aware testing convention.

Nothing here is blocking; this reads like a PR that's already been through its adversarial review rounds. The comment-trimming point is the one thing I'd actually act on before merge.

…rry the history

The one point the eleventh code review on PR #6364 said it would act on: several comment blocks narrated how
the bug behaved and how an earlier attempt got it wrong, which is worth writing once but not worth carrying
in the code once docs/6359-rebuild-setting-validation.md and the release notes entry exist to hold it.

Trimmed to the invariant a future editor has to not break, keeping the issue numbers - they are how a reader
finds the full story, and they are the convention in every neighbouring comment in these files. What went is
the retelling: which of the three post-linkage steps used to roll the link back and which did not, the
step-by-step of how a record saved before the index existed ends up in neither the scan nor the index, and
the walk-through of the retry that used to swallow the duplicate. What stayed is why the predicate is asked
before any transaction opens, why the cleanup cannot hang off a transaction's error callback, why the link
has to go back for the retry to be a real attempt, and the limit of the fix for the vector families.

Net 25 lines of comment removed, 18 added; no code change.
@claude

claude Bot commented Aug 18, 2026

Copy link
Copy Markdown

Review

I read through the full diff (engine, gremlin, docs) against the current main HEAD and traced the key correctness claims against the actual runtime code (LocalDatabase.transaction's joinCurrentTx/retry semantics, AsyncQuiesce, LSMTreeIndex.build, PInteger/PNumber, and the sibling LSMSparseVectorIndex.typeIndex field). This PR clearly already went through many rounds of self-review (the commit history shows 11+ iterations fixing real bugs each round), so I focused on trying to find anything that survived that process rather than repeating it.

Correctness

I did not find a remaining bug. Specifically, I verified:

  • Item 1 (super type index propagation). IndexBuilder.callerTransactionHasChanges is asked before the component-creation transaction opens, matching the documented "timing is the whole trap" reasoning — inside that transaction there's always an empty one open, which would make the predicate always answer false if asked from inside it. Confirmed against LocalDatabase.transaction: joinCurrentTx=false for the component-creation transaction (isolated, matches "components created and committed on their own"), joinCurrentTx=true for the build step (joins the caller, so the scan sees uncommitted writes) — and LocalDatabase.transaction's #661 guard (immediate rethrow of NeedRetryException/DuplicatedKeyException when createdNewTx==false) is exactly what makes the joined build's duplicate propagate to the caller instead of being retried out from under it.
  • The created/toBuild list split correctly accounts for index families built inline (vector) vs. joined (LSM tree etc.) — created covers both for cleanup, toBuild only the latter for the joined build step. The outer catch (RuntimeException e) around the whole post-linkage region (external buckets, index propagation, bucket-selection-strategy inheritance) correctly unwinds both the index components and the in-memory link on any of the three steps failing, not just the propagation.
  • LSMVectorIndex.getTypeIndex()/setTypeIndex() now mirror the existing LSMSparseVectorIndex field exactly (same non-volatile field, same pattern) — no new visibility/consistency issue introduced.
  • Item 2 (negative literal folding). tryNegateNumericLiteral runs after the pre-existing tryFoldLongMinValueLiteral special case, so there's no double-negation/overflow interaction for Long.MIN_VALUE. PInteger.setValue(Number) stores the value as-is (no truncation), so the type-preservation claims in the Javadoc hold. parenthesized is correctly propagated through copy() and splitForAggregation, and deliberately excluded from getIdentityElements() since it affects rendering only, not the evaluated tree shape — consistent with the stated "rendering only" design.
  • IndexBuilder.buildCreatedIndex(..., null) (null callback for the call site that isn't a builder) is safe — LSMTreeIndex.build() and the bulk-build path both null-check the callback before invoking it.

Code quality

Very good. The two-transaction split, the shared IndexBuilder/DDLStatement helpers, and unlinkSuperType are reasonable factorings that avoid a third copy of logic that was starting to drift (per the PR description). Comments are dense but each one earns its place — they explain why, not what, per the repo's own convention, and the ones narrating debugging history were already trimmed down to invariants in the last commit.

Test coverage

Strong. The new tests cover the propagation over uncommitted/updated records, rollback survival, the duplicate-key refusal path (both the simple and mixed-vector/ordinary shapes), the async-writer race, the deliberately-untouched createBucket() sibling, and — for item 2 — the literal/parentheses rendering round-trip plus the setting-reader unification (bound parameters, mixed value shapes). The vector TypeIndex wiring fix also got its own focused test on the DROP path rather than only being exercised indirectly.

Minor/non-blocking observations

  • SELECT -a AS n (unary minus over a non-literal) still renders as SELECT 0 - a AS n, and SELECT -(1 + 2) still renders as SELECT 0 - (1 + 2) rather than folding further — both are explicitly out of scope per the Javadoc/tests, just flagging for visibility since a future reader might wonder why those weren't folded too.
  • The @Timeout(180) on aPropagationRunWhileTheExecutorIsBusyCoversEveryRecord is well-justified in the docstring (hang detector, not a latency bound — test runs in ~12ms), consistent with CLAUDE.md's guidance on StallAwareStopwatch/timeout usage.

Security / Performance

No concerns. No new dependencies, no new I/O or network surface. The added quiesceAsync() call in addSuperType is correctly skipped when createIndexes=false (schema-load path), and the literal folding removes an arithmetic evaluation from every read of a negative literal rather than adding one.

Nice work — this is a thorough fix with the regression tests to back it up.

@codecov

codecov Bot commented Aug 18, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 83.17757% with 18 lines in your changes missing coverage. Please review.
✅ Project coverage is 70.76%. Comparing base (1c219a7) to head (411a0ef).
⚠️ Report is 8 commits behind head on main.

Files with missing lines Patch % Lines
...adedb/gremlin/query/GremlinQueryEngineFactory.java 0.00% 9 Missing ⚠️
...in/java/com/arcadedb/schema/LocalDocumentType.java 93.93% 2 Missing and 2 partials ⚠️
...va/com/arcadedb/query/sql/antlr/SQLASTBuilder.java 86.95% 1 Missing and 2 partials ⚠️
...rc/main/java/com/arcadedb/schema/IndexBuilder.java 71.42% 0 Missing and 2 partials ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #6364      +/-   ##
==========================================
+ Coverage   70.74%   70.76%   +0.02%     
==========================================
  Files        1851     1852       +1     
  Lines      160695   160715      +20     
  Branches    33779    33773       -6     
==========================================
+ Hits       113687   113736      +49     
+ Misses      33037    33019      -18     
+ Partials    13971    13960      -11     

☔ 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 lvca added this to the 26.9.1 milestone Aug 18, 2026
@lvca
lvca merged commit edce9bd into main Aug 18, 2026
32 of 33 checks passed
@lvca
lvca deleted the issue-6359 branch August 18, 2026 14:52
lvca added a commit that referenced this pull request Aug 18, 2026
…'s value is every field that carries one (#6407)

* fix(#6401): a hash code is a property of the value, and an expression'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.

* docs(#6401): ValueExpression carries its meaning in the value slot, so 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.
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