Skip to content

fix(engine) #5675: CREATE INDEX IF NOT EXISTS answers for the index asked for, not for any index on those properties - #5740

Merged
lvca merged 5 commits into
mainfrom
fix/5675-create-index-if-not-exists-conflict
Aug 2, 2026
Merged

lvca merged 5 commits into
mainfrom
fix/5675-create-index-if-not-exists-conflict

Conversation

@lvca

@lvca lvca commented Aug 1, 2026

Copy link
Copy Markdown
Member

Fixes #5675.

The bug

IF NOT EXISTS matched a pre-existing index on the auto-derived index name. That name is built from the indexed property set alone, so it says nothing about what the index does:

CREATE INDEX ON T (Scalar) NOTUNIQUE;
CREATE INDEX IF NOT EXISTS ON T (Scalar) UNIQUE;   -- reported success, created no constraint
INSERT INTO T SET Scalar = 'x';
INSERT INTO T SET Scalar = 'x';                    -- accepted

Migration DDL uses IF NOT EXISTS precisely so it can be re-applied, so tightening an index from NOTUNIQUE to UNIQUE did nothing while the application carried on believing a uniqueness constraint protected its data.

Two more problems found underneath

  1. withIgnoreIfExists(true) dropped the caller's index. TypeIndexBuilder.create() reacted to a uniqueness mismatch by dropping the existing index and rebuilding it. That is not recoverable: when the stored data has duplicates the rebuild fails and the type is left with no index at all. builderIgnoreIfExistsNeverDropsAConflictingIndex in the new test reproduced exactly that before the fix. On an inherited index the same code took away the parent type's index, which is issue Multiple warning over lost indexes on massive insert with gRPC #4083.
  2. The kind of index was ignored too. A FULL_TEXT index satisfied a request for a range index on the same properties, silently. And the null-strategy half of the condition was dead code: existingTypeIndex.getNullStrategy() != null && existingTypeIndex.getNullStrategy() == null is never true.

The rule now

IF NOT EXISTS is satisfied only when the existing index provides what was asked for:

  • same index kind, and
  • a uniqueness constraint at least as strong.

So a UNIQUE index still satisfies a NOTUNIQUE request (it indexes the same keys, and is never weakened into a plain index), while a NOTUNIQUE index does not satisfy a UNIQUE request. Anything the existing index does not provide is reported, naming both definitions, as an IllegalArgumentException -> HTTP 400.

Nothing is dropped implicitly

Refusal is the answer even where the request could technically be granted by rebuilding, because the rebuild is the unsafe part. A caller that genuinely means "make this the definition" opts in:

database.getSchema().buildTypeIndex("T", new String[] { "Scalar" })
    .withType(Schema.INDEX_TYPE.LSM_TREE).withUnique(true)
    .withReplaceIfIncompatible(true)     // new
    .create();

and even then the drop happens as late as possible (after every remaining validation) and the previous definition — kind, uniqueness, null strategy, properties, metadata — is restored if the new index cannot be built. An inherited index is never replaced.

Cypher stays Neo4j-compatible

CREATE CONSTRAINT ... IS UNIQUE and ... IS NODE KEY are statements about the data rather than "create it if missing", so they are the callers that opt into the replacement. Neo4j keeps the range index and the constraint as two objects; ArcadeDB has one index per property set and a unique index covers both roles, so the upgrade is the equivalent end state and a Neo4j migration script that creates indexes and then constraints keeps working. Cypher's own CREATE INDEX does not opt in — it finds a unique index sufficient and leaves it alone rather than replacing it with a plain one, which closes a silent weakening of a constraint that existed before.

Alternative considered

The issue offers "create the unique index" or "fail". Doing the first implicitly is what the code already did, and it is the thing that can lose an index — so this PR does the second by default and makes the first an explicit, restorable opt-in rather than a side effect of a guard clause.

Tests

  • engine/.../Issue5675IndexIfNotExistsConflictTest — 11 cases: the reported scalar and BY ITEM forms, the reverse direction staying a no-op, index-kind mismatch, manual index names, the builder never dropping a conflicting index, the Cypher constraint upgrade, and a failed constraint upgrade leaving the plain index in place (mutation-checked: reverting the restore fails this test).
  • server/.../Issue5675CreateIndexIfNotExistsHttpTest — the 400 and its detail message over HTTP, plus the idempotent 200 with created: false so the refusal test cannot pass by refusing everything.

Full engine suite: 1237 test classes green. (ACIDTransactionTest#indexCreationWhileAsyncMustFail failed once while three engine suites ran concurrently on this machine and passes in isolation — a contention flake, unrelated: it kills the database mid-build and asserts on recovery.) Server index + HTTP suites green.

🤖 Generated with Claude Code

https://claude.ai/code/session_01W8C35vrQkW1y1gaEvWzRPc

…sked for, not for any index on those properties

The guard matched on the auto-derived index name, which is built from the indexed property set alone and says
nothing about what the index does. A NOTUNIQUE index therefore reported success to a request for a UNIQUE one,
and the schema migration that asked for the constraint carried on without it. An index of a different KIND on
the same properties was ignored the same way.

IF NOT EXISTS is now satisfied only when the existing index provides what was asked for: the same index kind,
and a uniqueness constraint at least as strong. A UNIQUE index still covers a NOTUNIQUE request; a NOTUNIQUE
index does not cover a UNIQUE one, and the mismatch is reported naming both definitions (HTTP 400).

Underneath, TypeIndexBuilder.create() with withIgnoreIfExists(true) used to DROP the existing index and rebuild
it on a uniqueness mismatch. When the stored data cannot satisfy the new definition the rebuild fails and the
type is left with no index at all; on an inherited index it took away the parent type's index (#4083). That
implicit rebuild is gone. A caller that genuinely means "make this the definition" opts in with the new
withReplaceIfIncompatible(), and even then the previous index is restored if the new one cannot be built.

Cypher's CREATE CONSTRAINT ... IS UNIQUE / IS NODE KEY are the callers that opt in, so a Neo4j migration script
that creates indexes and then constraints keeps working. Cypher's own CREATE INDEX does not: it finds a unique
index sufficient rather than replacing it with a plain one.

Also removes a dead null-strategy condition in the same branch (`x != null && x == null`).
@mergify

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

Copy link
Copy Markdown

Up to standards ✅

🟢 Issues 0 issues

Results:
0 new issues

View in Codacy

🟢 Metrics 15 complexity

Metric Results
Complexity 15

View in Codacy

🟢 Coverage 90.63% diff coverage · -6.90% coverage variation

Metric Results
Coverage variation ✅ -6.90% coverage variation
Diff coverage ✅ 90.63% diff coverage

View coverage diff in Codacy

Coverage variation details
Coverable lines Covered lines Coverage
Common ancestor commit (1449cf1) 150880 115409 76.49%
Head commit (e21743f) 182961 (+32081) 127330 (+11921) 69.59% (-6.90%)

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 (#5740) 64 58 90.63%

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

Copy link
Copy Markdown

Review: CREATE INDEX IF NOT EXISTS conflict handling (#5675)

Solid, well-reasoned fix. The core insight is right: matching on the auto-derived name (which encodes only the property set) let a NOTUNIQUE index answer "already there" to a UNIQUE request, and the old withIgnoreIfExists drop-and-rebuild was the genuinely dangerous part. Separating "I can live with what's there" (ignoreIfExists) from "make this the definition" (withReplaceIfIncompatible), deferring the drop until after every remaining validation, and restoring the old definition on failure are all the right calls. Test coverage is excellent - engine + HTTP, the reverse-direction no-op, kind mismatch, manual-name path, the mutation-checked failed-upgrade case, and status-code assertions that can't pass by refusing everything.

A few points worth a look, none blocking:

1. Restore loses the original page size (and reuses a persisted bucket's metadata)

ReplacedIndexDefinition captures kind, uniqueness, null strategy, properties and metadata, but not the page size. restoreReplacedIndex() never calls withPageSize(...), so an index that had a custom page size (TypeIndex.getPageSize()) comes back on the implementation default after a failed upgrade. The PR text promises the previous definition is "restored" - page size is the one attribute silently not restored.

Separately, ReplacedIndexDefinition.of() stashes onBuckets[0].getMetadata() - the live, persisted metadata of the old first bucket (stale associatedBucketId, old typeIndexName) - and hands that same instance to the restore builder, which then mutates it in create(). It works in the tested LSM case, but constructing a fresh IndexMetadata (copying propertyNames/collations/typeName) would be less fragile than templating off a bucket-level object. Capturing getPageSize() into the record and passing it through would close both gaps.

2. Manual index name reused across types compares properties but not the type

In CreateIndexStatement, the manual-name branch compares existing.getPropertyNames() to the requested properties, then satisfiesRequest, then falls through to a created:false no-op. Since index names are global, CREATE INDEX MyIdx IF NOT EXISTS ON B (x) UNIQUE where MyIdx already exists on type A(x) with a matching kind/uniqueness passes the property check (both [x]) and returns a created:false no-op pointing at A's index - the requested index on B is never created and the caller isn't told why. Narrow (requires a manual name colliding across types), and arguably no worse than before, but comparing existing.getTypeName() against the requested type here would make it precise.

3. indexType == null check moved to the top of create() is a behavior change

It now throws DatabaseMetadataException before the existing-index lookup. Previously, buildTypeIndex(...).withIgnoreIfExists(true).create() with no withType and a matching existing index returned that index. satisfiesRequest needs a non-null indexType, so the move is necessary - and every in-tree caller sets withType - but it's a public-builder behavior change (the deprecated getOrCreate-style path). Worth a one-line note in the changelog or a guard test so it isn't a surprise regression for embedded API users.

4. Minor: null-strategy comment vs. behavior

satisfiesRequest's Javadoc says the null strategy is excluded because "it can be changed on the index in place." True, but the satisfied ignoreIfExists path just returns the existing index and does not apply a requested null-strategy change - which is correct IF NOT EXISTS semantics (a no-op), just not quite what "can be changed in place" implies. A word tweak would avoid the read that it reconciles the strategy.

Non-issue, for the record

The drop-then-rebuild window in the replaceIfIncompatible path is non-transactional, so a crash between existingTypeIndex.drop() and a successful build loses the index with no restore (restore only runs on caught exceptions). This is inherent to DDL here and strictly better than the old code, which dropped on any mismatch under IF NOT EXISTS - now it only happens on explicit opt-in. Fine to leave; noting it so the crash window is a known property rather than an oversight.

Nice work - the reasoning in the comments and the mutation-checked restore test are especially good.

…x name to its type

Review follow-ups on #5740:

- The restore after a failed replacement left the page size behind, so an index with a custom one came back at
  the implementation default. Captured through getPageSizeForNewFile(), the same accessor a rebuild uses, so a
  page size the current file carries but creation would refuse cannot turn the restore into a second failure
  (#5713). Mutation-checked: without it the test index returns as 262144 instead of 16384.

- Index names are global, so a manual one can already name an index on ANOTHER type. The IF NOT EXISTS branch
  compared the properties but not the type, and would have answered "already exists" pointing at a different
  type's index while creating nothing.

- Guard test for the indexType null-check moving ahead of the existing-index lookup (a builder with no
  withType and ignoreIfExists used to hand back the existing index), plus a changelog note naming the shape.

- Documented why the replaced definition is templated off a bucket-level IndexMetadata: only its concrete
  subclass carries the index-type settings, and LocalSchema.createBucketIndex reads it as a template, so the
  bucket id it carries never reaches the restored index. Resetting that field instead breaks the drop path.

- Reworded the null-strategy note on satisfiesRequest: it is excluded for being non-structural, and a satisfied
  request stays a plain no-op rather than reconciling the strategy.
@lvca

lvca commented Aug 1, 2026

Copy link
Copy Markdown
Member Author

Thanks — pushed 63f8ffd for the review points.

1. Page size not restored — fixed. Captured in ReplacedIndexDefinition via getPageSizeForNewFile() rather than getPageSize(): the value goes back through the creation path, and #5713 established that an index whose current page size is not one creation would accept has to answer with a legal one instead — otherwise the restore fails on exactly the index it exists to save. Mutation-checked (aFailedUpgradeRestoresThePageSizeToo): without the fix the index comes back at 262144 instead of the 16384 it had.

1b. Metadata templated off a live bucket object — kept, documented. I tried the suggested reset of associatedBucketId and it broke the drop path: Index 'T_0_...' is not valid. Probably has been dropped or rebuilt, because of() runs while the old index is still live. Reverted. The comment now records why the template is deliberate — only the concrete IndexMetadata subclass carries the index-type settings (analyzers, geospatial precision, vector dimensions) and there is no generic way to copy them — and why the stale bucket id is inert: LocalSchema.createBucketIndex reads the object as a template, taking the collations and TypeIndex name off it and leaving the rest to the per-bucket index it builds, exactly as on the normal creation path.

2. Manual name reused across types — fixed. The branch now compares getTypeName() as well, with guardedCreateWithANameTakenByAnotherTypeIsReported covering it.

3. indexType == null moved to the top — noted and pinned. Added aBuilderWithoutAnIndexTypeIsRefused and a changelog section naming the affected shape (no withType + withIgnoreIfExists(true) + a matching existing index used to hand that index back).

4. Null-strategy wording — reworded. It is excluded for being non-structural (settable through ALTER), and the Javadoc now says explicitly that a satisfied request stays a plain no-op rather than reconciling the strategy.

Crash window — agreed, left as-is and now a known property rather than an oversight.

Verification: 1414 engine tests in the schema + index packages and the server index/HTTP suites, all green except LSMVectorIndexRecoveryTest#vectorNeighborsShouldReturnCorrectCountAfterIncrementalInsertAndRebuild, which asserts a background vector rebuild has drained its delta buffer and passes in isolation — a contention flake (three engine suites were running concurrently on this machine), unrelated to this change.

@claude

claude Bot commented Aug 1, 2026

Copy link
Copy Markdown

Review: CREATE INDEX IF NOT EXISTS conflict handling (issue 5675)

Solid fix. The core insight, that a name/property match says nothing about whether the existing index actually provides what the statement asked for, is correct, and the directional satisfiesRequest rule (same kind plus uniqueness at least as strong) is the right semantics. Replacing the old silent drop-and-rebuild with an explicit, restorable withReplaceIfIncompatible opt-in is a genuine safety improvement, and it also closes the 4083 inherited-index footgun. Docs and tests are unusually thorough (the mutation-checked restore test is a nice touch).

A few observations, none blocking:

1. The restore loses a custom index name. ReplacedIndexDefinition captures kind, uniqueness, null strategy, page size, properties and metadata, but not the index name. restoreReplacedIndex() rebuilds via buildTypeIndex(type, props) with no withIndexName(...), so a restored index gets the auto-derived name. The only in-tree caller of withReplaceIfIncompatible is the Cypher constraint path, which uses auto-derived names, so this is not triggered today, but withReplaceIfIncompatible is public API and composes with withIndexName. Capturing and restoring the original name would make the restore fully faithful to its promise (the previous definition is restored).

2. Public embedded-API behavior change worth a release note. LocalSchema.getOrCreateTypeIndex(...) sets withIgnoreIfExists(true) but not withReplaceIfIncompatible, so any embedded caller that previously relied on it to upgrade an incompatible existing index (the old drop-and-recreate) now gets an IllegalArgumentException instead. That is the intended correctness fix, but the release note is framed around SQL/Cypher; a line calling out the changed getOrCreateTypeIndex contract for embedded users would help anyone hitting the new exception. Same goes for the reordered indexType-null check, which the doc already mentions.

3. Durability window in drop then create then restore. The design explicitly accepts that the replacement cannot be perfectly atomic, and the exception path is handled (restore, addSuppressed, SEVERE log) with a passing test. The residual gap is a hard crash between existingTypeIndex.drop() and the new index being created, or a restore that itself fails: the type is then left with no index and only a log line. Could you confirm whether the whole create() sequence runs under a single schema transaction so the drop rolls back on failure, rather than relying solely on the best-effort in-catch restore? If it is not transactional, that is worth a comment noting the accepted risk.

4. Minor test-coverage gaps.

  • No explicit test that withReplaceIfIncompatible(true) against an inherited incompatible index still refuses (the 4083 path). The code handles it via the existingTypeIndex.getTypeName().equals(metadata.typeName) guard, but it is untested.
  • No test for the page-size restore combined with a custom index name (see item 1).

Nits.

  • describeDefinition renders LSM_TREE (unique=false) in error messages; for a UNIQUE_HASH request the user typed, that internal kind name may read as unfamiliar, but it is accurate and consistent, so fine.
  • List.of(fields) in CreateIndexStatement will NPE if calculateProperties ever returns null; not reachable for a valid statement, just noting.

Logic, imports, and the branch table in TypeIndexBuilder.create() all check out on read (including the satisfied && ignoreIfExists early return, the own-vs-inherited replacement guard, and the deferred drop after all remaining validation). I was not able to run the Maven build in this environment, so I relied on static analysis plus the PR reported green suites.

Reviewed by Claude Code.

…, and the non-atomic replacement window

Round-two review follow-ups on #5740:

- Test that a failed replacement restores a MANUAL index name along with the page size. The name was already
  restored - it travels on the captured IndexMetadata.typeIndexName, which LocalSchema.createBucketIndex copies
  onto each bucket index and addIndexInternal honours when minting the TypeIndex (#4139), the same route a manual
  name takes on the normal creation path - but nothing pinned it. Mutation-checked: dropping the metadata
  pass-through fails the test.

- Test that withReplaceIfIncompatible does NOT reach an index the type only inherits, which was handled by the
  own-vs-inherited guard but untested (#4083).

- The replacement is not atomic: LocalSchema.dropIndex commits its own recordFileChanges and so does the build,
  so a process that dies between them leaves the type without an index. Recorded at the drop site, with why the
  alternatives do not work: a schema transaction held across a full index build is the wrong trade, and building
  the new index alongside the old one is not representable while indexesByProperties keeps one index per
  property set.

- Release note for the embedded getOrCreateTypeIndex contract: it sets withIgnoreIfExists(true), so a uniqueness
  mismatch now raises instead of rebuilding, with the migration path.
@lvca

lvca commented Aug 1, 2026

Copy link
Copy Markdown
Member Author

Round two addressed in 727b853.

1. Restore loses a custom index name — it doesn't, and now a test says so. The name never travelled through withIndexName: it rides on the captured IndexMetadata.typeIndexName, which LocalSchema.createBucketIndex copies onto each bucket index and LocalDocumentType.addIndexInternal honours when minting the TypeIndex — the same #4139 route a manual name takes on the normal creation path. aFailedUpgradeRestoresAManualIndexNameAndItsPageSize pins it (name and page size, as asked in item 4), and it is mutation-checked: remove the metadata pass-through from restoreReplacedIndex and the test fails.

2. getOrCreateTypeIndex release note — added. It sets withIgnoreIfExists(true), so a uniqueness mismatch now raises where it used to drop and rebuild. The note names the changed contract and gives the two ways forward (drop the old index explicitly, or buildTypeIndex(...).withReplaceIfIncompatible(true) if replacing really is the intent).

3. Transactionality — confirmed NOT atomic, and now documented. LocalSchema.dropIndex wraps itself in recordFileChanges and commits, and the build below opens its own, so the two cannot roll back as one. The comment at the drop site records the accepted risk and why the alternatives are worse: holding a schema transaction across a full index build is the wrong trade for a statement that already rebuilds every entry, and building the new index alongside the old one is not representable while LocalDocumentType.indexesByProperties keeps one index per property set. Only an explicit withReplaceIfIncompatible is exposed to the window.

4. Test gaps — both filled. Added replaceIfIncompatibleStillRefusesAnInheritedIndex (the #4083 path through the own-vs-inherited guard) and the name+page-size case above.

Nits. describeDefinition left as is, per your own read. List.of(fields) needs calculateProperties to return null, which needs propertyList == null — the grammar cannot produce it, and a guard there would be a branch no statement can reach; left alone.

Verification: 1305 tests across the engine schema + index packages, 0 failures / 0 errors, vector tests included this time.

@claude

claude Bot commented Aug 1, 2026

Copy link
Copy Markdown

Review: CREATE INDEX IF NOT EXISTS conflict handling (#5675)

Reviewed the diff statically (Maven is not runnable in my environment; relying on the author's report of green engine + server suites). Overall this is a high-quality, well-reasoned fix that closes a genuinely dangerous silent-data-integrity hole: a guarded UNIQUE request being answered "already exists" by a NOTUNIQUE index. The three-part framing (name-only match, kind ignored, and the destructive drop-and-rebuild under withIgnoreIfExists) is accurate, and the fix addresses each. The code is careful, the comments explain the why (not just the what), and the test coverage is excellent.

What I especially liked

  • satisfiesRequest semantics are correct and minimal: kind must match exactly, uniqueness is directional (UNIQUE satisfies NOTUNIQUE, not the reverse). The old dead condition getNullStrategy() != null && getNullStrategy() == null is gone, and treating null-strategy as non-structural (settable via ALTER) is the right call.
  • Deferring the drop to the last moment (after every remaining validation) plus restoreReplacedIndex in both catch arms is the right design. Refusing by default and making replacement an explicit, restorable opt-in (withReplaceIfIncompatible) is a sound safety posture, and never replacing an inherited index correctly handles Multiple warning over lost indexes on massive insert with gRPC #4083.
  • getPageSizeForNewFile() over getPageSize() for the restore (avoiding a restore failing on the very page size it is trying to preserve, HASH index silently corrupts when created with a page size above 65536 (16-bit slot offsets, no validation) #5713) is a subtle and correct detail.
  • Test suite is thorough: reverse-direction no-op, kind mismatch, manual names, cross-type name collision, inherited refusal, the mutation-checked failed-upgrade restore (page size + manual name), and the HTTP 400 + created:false pair. The comment noting the 200/created:false test exists so the 400 test "can't pass by refusing everything" shows good adversarial test design.

Points worth considering (none blocking)

  1. satisfiesRequest still ignores index sub-configuration (vector dimensions, full-text analyzers, geospatial precision). For same-kind indexes it only checks uniqueness, so CREATE INDEX IF NOT EXISTS ... LSM_VECTOR with different dimensions over an existing vector index remains a silent no-op - the same class of bug as Index create regression #5675, one level down. This is not a regression (the old code no-op'd there too since it only compared isUnique), and arguably out of scope, but it is the natural next question a reader will ask. A one-line note in the Javadoc of satisfiesRequest that sub-configuration is intentionally not compared would pre-empt it.

  2. Public (deprecated) API behavior change: LocalSchema.getOrCreateTypeIndex(...) now throws IllegalArgumentException on an incompatible existing index instead of drop-and-rebuild. This is the intended fix and is documented in the release notes, but it is a runtime (not compile-time) semantic change for embedded callers using it as an "ensure this index" helper across a schema tightening. Good that the docs call it out explicitly.

  3. Non-atomic drop/rebuild window is honestly documented in the code (a process death between the committed drop and the build leaves the type indexless until re-created). Only reachable via explicit withReplaceIfIncompatible, so it is a deliberate opt-in trade - just flagging that keeping the release note's mention of it visible matters for the Cypher CREATE CONSTRAINT path, since that is the one in-tree caller that hits this window.

  4. Minor - error message consistency: the satisfied && replaceIfIncompatible && !ignoreIfExists case (e.g. a Cypher CREATE CONSTRAINT without IF NOT EXISTS where the unique index already exists) falls through to the generic "Found the existent index ..." message rather than a constraint-aware one. Functionally correct (it is an error either way); just slightly less specific than the other arms.

Style/conventions

Adheres to the repo conventions: final used consistently, assertThat(...) style, @author header, no System.out debug, Apache license headers on new files. No new dependencies. The List.of(fields) vs getPropertyNames() equality check in the manual-name path is safe because both carry the same space-separated by item/by key/by value form (only the derived name strips spaces).

Nice work - the fix is correct, defensive, and unusually well documented.

…int an unguarded repeat at IF NOT EXISTS

Round-three review follow-ups on #5740, both documentation-level:

- satisfiesRequest compares the structural definition only, so two same-kind indexes configured differently
  (vector dimensions, full-text analyzers, geospatial precision) still satisfy each other. Not a regression -
  the old code compared isUnique alone - but it is the next question a reader asks, so the Javadoc now says it
  is deliberate and why: those settings live in per-index-type IndexMetadata subclasses with no common notion
  of "provides at least what was asked for", which needs a per-type rule rather than this comparison.

- The unguarded "Found the existent index" error now ends with the guard that makes the statement idempotent
  when the existing index already satisfies the request, and with the drop hint when it does not. The
  long-standing sentence is kept verbatim as the prefix so anything matching on it still matches.
@lvca

lvca commented Aug 1, 2026

Copy link
Copy Markdown
Member Author

Round three addressed in 7cbd6ab — both documentation-level, since nothing here was blocking.

1. Sub-configuration not compared — noted in the Javadoc, as suggested. satisfiesRequest compares the structural definition only, so two same-kind indexes configured differently (vector dimensions, full-text analyzers, geospatial precision, collations) still satisfy each other. The Javadoc now states that this is deliberate and gives the reason it is not simply an oversight: those settings live in per-index-type IndexMetadata subclasses with no common notion of "provides at least what was asked for" — is a 768-dimension index acceptable to a request for 384? is a stricter analyzer? — so answering it needs a per-type rule rather than the structural comparison, and inventing one here would be guessing.

4. Generic message in the satisfied-but-unguarded case — improved. It now ends with . It already provides what was requested: use IF NOT EXISTS to make this statement idempotent when the existing index satisfies the request, and . Drop it first if the definition has to change when it does not. That covers the Cypher CREATE CONSTRAINT without IF NOT EXISTS case you named. The long-standing sentence is kept verbatim as the prefix, so anything already matching on it still matches.

2 and 3 — no change; both are already covered in the release notes (the getOrCreateTypeIndex contract) and at the drop site (the non-atomic window, with why the alternatives are worse), which is what you were checking for.

Verification: 1356 tests across the engine schema + index packages plus the Cypher index/statistics tests. One failure, LSMVectorIndexRecoveryTest#vectorNeighborsShouldReturnCorrectCountAfterIncrementalInsertAndRebuild, which asserts a background vector rebuild has drained its delta buffer within a timeout — it passed in the immediately preceding run of the same suite and passes in isolation, so it is the machine being busy (parallel suites), not this change. Nothing in this commit is reachable from the vector build path.

@claude

claude Bot commented Aug 1, 2026

Copy link
Copy Markdown

Review: CREATE INDEX IF NOT EXISTS conflict handling (#5675)

Reviewed all four commits, the engine + SQL + Cypher changes, and both new test classes. This is a well-reasoned fix with unusually thorough documentation and mutation-checked tests. Overall it looks correct and safe to merge; comments below are mostly confirmations plus a couple of minor points.

What I checked and confirmed

  • satisfiesRequest semantics. Kind must match exactly; uniqueness is directional (a UNIQUE index covers a NOTUNIQUE request, not the reverse). This closes both the silent constraint-weakening and the ignored index-kind mismatch. The HASH variants (UNIQUE_HASH/NOTUNIQUE_HASH) are handled correctly since they differ from LSM_TREE on kind.
  • The removed dead condition (getNullStrategy() != null && getNullStrategy() == null) was indeed unreachable, and excluding null-strategy from the comparison is justified (it is ALTER-able in place).
  • The branch matrix in TypeIndexBuilder.create() (satisfied / ignoreIfExists / replaceIfIncompatible / own-vs-inherited) is complete and each arm is exercised by a test, including the inherited-index refusal (Multiple warning over lost indexes on massive insert with gRPC #4083) and the "already provides what was requested / use IF NOT EXISTS" message.
  • The BY ITEM SQL-guard path. getCompleteKey() yields "Items by item" and TypeIndex.getPropertyNames() stores the same suffixed form, so the existing.getPropertyNames().equals(List.of(fields)) comparison matches and the request correctly reaches satisfiesRequest rather than mis-reporting a name clash.
  • The restore-on-failure path. Page size (via getPageSizeForNewFile(), the creation-validated accessor - good call re HASH index silently corrupts when created with a page size above 65536 (16-bit slot offsets, no validation) #5713), null strategy, manual index name (carried on IndexMetadata), and per-type metadata are all restored, and the restore failure is attached via addSuppressed so the root cause survives. The drop is correctly deferred to the last moment before build so earlier validations cannot cost the caller their index.

Minor / worth flagging

  1. Public embedded-API behavior change. LocalSchema.getOrCreateTypeIndex(...) (including the non-deprecated 2-arg overload) now throws IllegalArgumentException on a uniqueness/kind mismatch instead of silently dropping+rebuilding. This is the correct fix and it is documented in the release notes, but it is a semantic break for any embedded caller that used getOrCreateTypeIndex as an "ensure/upgrade" helper across a schema change. Worth calling out prominently in the upgrade notes since it surfaces at runtime rather than compile time.

  2. Non-atomic replacement window. The drop and rebuild are separate committed schema changes, so a crash between them leaves the type index-less until re-created. The PR documents this clearly at the drop site and explains why the atomic alternatives were rejected; only the explicit withReplaceIfIncompatible opt-in is exposed to it. Acceptable trade-off, just noting it is a real (documented) limitation.

  3. Error messages read well and name both definitions, which is exactly what the HTTP 400 test asserts travels to the client.

Tests

Coverage is excellent: reported scalar + BY ITEM forms, reverse no-op, kind mismatch, manual names (including a name taken by another type), the builder never dropping a conflicting index, inherited-index refusal, the Cypher constraint upgrade, and a failed upgrade restoring name + page size + uniqueness - several explicitly mutation-checked. The HTTP test pins both the 400+detail and the idempotent 200/created:false, so the refusal test cannot pass by refusing everything. Nicely done.

Nit (non-blocking): the pre-existing System.out.print(".") progress callback in CreateIndexStatement is untouched by this PR, so no action needed - just noting it is unrelated debug-style output that predates these changes.

LGTM.

It is a runtime semantic change for embedded callers using it as an ensure/upgrade helper, so it belongs under the
same BREAKING heading convention the rest of the file uses rather than a plain one.
@lvca

lvca commented Aug 1, 2026

Copy link
Copy Markdown
Member Author

Thanks — LGTM noted. One last change in e21743f, documentation only.

1. getOrCreateTypeIndex — promoted to a BREAKING: heading. You are right that it deserves prominence: it is the one change here that surfaces at runtime rather than at compile time. It now sits under the same ### BREAKING: convention the rest of this release file uses, with a line saying exactly that, so it reads at the same level as the withPageSize(0) break above it.

2. Non-atomic window — agreed on all counts, no change; it is documented at the drop site with the rejected alternatives, and only the explicit opt-in reaches it.

Nit: the pre-existing System.out.print(".") progress callback in CreateIndexStatement — leaving it as you suggested. It predates this PR and removing it would be unrelated churn in a diff that is already about one thing; it is worth its own issue rather than a drive-by here.

This closes out every point raised across the four rounds. Ready for your review.

@claude

claude Bot commented Aug 2, 2026

Copy link
Copy Markdown

Review: CREATE INDEX IF NOT EXISTS conflict handling (#5675)

Reviewed the full diff plus the surrounding code in CreateIndexStatement, IndexBuilder, TypeIndexBuilder, and the two new test classes. This is a strong, carefully-reasoned fix. Summary and a few observations below.

What works well

  • The core correctness fix is right. satisfiesRequest() cleanly captures the rule (same kind + at-least-as-strong uniqueness). Directional uniqueness (UNIQUE satisfies NOTUNIQUE, not the reverse) is the correct semantics, and it removes the dead getNullStrategy() != null && getNullStrategy() == null condition that was silently a no-op before.
  • Not dropping implicitly is the right default. The old drop-and-rebuild on withIgnoreIfExists(true) was genuinely dangerous (leaves a type with no index when the rebuild fails on stored duplicates, and wipes a parent's index on the inherited case, Multiple warning over lost indexes on massive insert with gRPC #4083). Making the destructive path an explicit withReplaceIfIncompatible(true) opt-in is the correct call.
  • The restore-on-failure path is thoughtful: dropping as late as possible (after every other validation), capturing the full definition, using getPageSizeForNewFile() rather than the raw page size (HASH index silently corrupts when created with a page size above 65536 (16-bit slot offsets, no validation) #5713), and attaching restore failures via addSuppressed rather than masking the root cause. The mutation-checked test (aFailedConstraintUpgradeLeavesThePlainIndexInPlace) is a nice touch.
  • Error -> HTTP 400 mapping via IllegalArgumentException is correct and asserted end-to-end, including the detail message and the idempotent created:false 200 (so the refusal test can't pass by refusing everything).
  • Test coverage is excellent - the reported case, BY ITEM, reverse-direction no-op, kind mismatch, manual names, inherited-index refusal, and the builder-level reproduction.

Observations / questions

  1. getOrCreateTypeIndex runtime behavior change reaches the importers. Neo4jImporter (line 219) and OrientDBImporter (line 1070) call getOrCreateTypeIndex(...), which now throws instead of upgrading when an incompatible index already exists on those properties. On a fresh import this never triggers, but a re-import into a database that already carries a differing index would now fail where it previously rebuilt. This is the documented BREAKING change, so it's intentional - just flagging that these are the in-tree callers most likely to meet it, and they aren't covered by a regression test.

  2. ReplacedIndexDefinition.of() templating off a bucket-level IndexMetadata is the subtlest part of the change. The reasoning in the comment is sound and aFailedUpgradeRestoresAManualIndexNameAndItsPageSize covers the manual-name + page-size path, but the restore's correctness hinges on createBucketIndex reading only collations + name off that metadata and ignoring the carried bucket id. Worth a one-line assertion in a test that the restored index's collations survive too, since that's the other thing the template carries.

  3. Non-atomic replacement window is clearly documented in the comment and is a reasonable trade for DDL. No action needed - just confirming it's a conscious decision that only an explicit withReplaceIfIncompatible is exposed to it.

  4. Minor (test quality): guardedUniqueOverNotUniqueByItemIsReported asserts only that the message contains L[Itemsbyitem], which both the property-mismatch branch and the satisfiesRequest branch would satisfy - so it does not strictly pin which refusal fired. For an auto-derived name only the satisfiesRequest path is reachable, so it is fine in practice; a hasMessageContaining("NOTUNIQUE") or similar would make the intent explicit.

I could not run the compile/test suite in this environment (sandbox restriction), but I verified every referenced method (getPageSizeForNewFile, getNullStrategy, getIndexesOnBuckets, getMetadata, static satisfiesRequest/conflictWithExistingIndex) exists and resolves, and the imports are correct.

Overall: correct, well-tested, and the design choices (refuse-by-default, explicit restorable opt-in, 400 mapping, Neo4j-compatible Cypher upgrade) are all the right ones. Nice work.

Automated review by Claude.

@codecov

codecov Bot commented Aug 2, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 84.37500% with 10 lines in your changes missing coverage. Please review.
✅ Project coverage is 67.65%. Comparing base (1449cf1) to head (e21743f).
⚠️ Report is 3 commits behind head on main.

Files with missing lines Patch % Lines
...ain/java/com/arcadedb/schema/TypeIndexBuilder.java 75.00% 6 Missing and 4 partials ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #5740      +/-   ##
==========================================
- Coverage   67.67%   67.65%   -0.02%     
==========================================
  Files        1776     1776              
  Lines      150880   150937      +57     
  Branches    32016    32027      +11     
==========================================
+ Hits       102103   102114      +11     
- Misses      35512    35565      +53     
+ Partials    13265    13258       -7     

☔ 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 self-assigned this Aug 2, 2026
@lvca lvca added this to the 26.8.1 milestone Aug 2, 2026
@lvca
lvca merged commit 4966b4b into main Aug 2, 2026
28 of 31 checks passed
@lvca
lvca deleted the fix/5675-create-index-if-not-exists-conflict branch August 2, 2026 16:13
robfrank pushed a commit that referenced this pull request Aug 14, 2026
…sked for, not for any index on those properties (#5740)

* fix(engine) #5675: CREATE INDEX IF NOT EXISTS answers for the index asked for, not for any index on those properties

The guard matched on the auto-derived index name, which is built from the indexed property set alone and says
nothing about what the index does. A NOTUNIQUE index therefore reported success to a request for a UNIQUE one,
and the schema migration that asked for the constraint carried on without it. An index of a different KIND on
the same properties was ignored the same way.

IF NOT EXISTS is now satisfied only when the existing index provides what was asked for: the same index kind,
and a uniqueness constraint at least as strong. A UNIQUE index still covers a NOTUNIQUE request; a NOTUNIQUE
index does not cover a UNIQUE one, and the mismatch is reported naming both definitions (HTTP 400).

Underneath, TypeIndexBuilder.create() with withIgnoreIfExists(true) used to DROP the existing index and rebuild
it on a uniqueness mismatch. When the stored data cannot satisfy the new definition the rebuild fails and the
type is left with no index at all; on an inherited index it took away the parent type's index (#4083). That
implicit rebuild is gone. A caller that genuinely means "make this the definition" opts in with the new
withReplaceIfIncompatible(), and even then the previous index is restored if the new one cannot be built.

Cypher's CREATE CONSTRAINT ... IS UNIQUE / IS NODE KEY are the callers that opt in, so a Neo4j migration script
that creates indexes and then constraints keeps working. Cypher's own CREATE INDEX does not: it finds a unique
index sufficient rather than replacing it with a plain one.

Also removes a dead null-strategy condition in the same branch (`x != null && x == null`).

* fix(engine) #5675: restore the page size too, and scope a manual index name to its type

Review follow-ups on #5740:

- The restore after a failed replacement left the page size behind, so an index with a custom one came back at
  the implementation default. Captured through getPageSizeForNewFile(), the same accessor a rebuild uses, so a
  page size the current file carries but creation would refuse cannot turn the restore into a second failure
  (#5713). Mutation-checked: without it the test index returns as 262144 instead of 16384.

- Index names are global, so a manual one can already name an index on ANOTHER type. The IF NOT EXISTS branch
  compared the properties but not the type, and would have answered "already exists" pointing at a different
  type's index while creating nothing.

- Guard test for the indexType null-check moving ahead of the existing-index lookup (a builder with no
  withType and ignoreIfExists used to hand back the existing index), plus a changelog note naming the shape.

- Documented why the replaced definition is templated off a bucket-level IndexMetadata: only its concrete
  subclass carries the index-type settings, and LocalSchema.createBucketIndex reads it as a template, so the
  bucket id it carries never reaches the restored index. Resetting that field instead breaks the drop path.

- Reworded the null-strategy note on satisfiesRequest: it is excluded for being non-structural, and a satisfied
  request stays a plain no-op rather than reconciling the strategy.

* fix(engine) #5675: pin the manual-name restore, the inherited refusal, and the non-atomic replacement window

Round-two review follow-ups on #5740:

- Test that a failed replacement restores a MANUAL index name along with the page size. The name was already
  restored - it travels on the captured IndexMetadata.typeIndexName, which LocalSchema.createBucketIndex copies
  onto each bucket index and addIndexInternal honours when minting the TypeIndex (#4139), the same route a manual
  name takes on the normal creation path - but nothing pinned it. Mutation-checked: dropping the metadata
  pass-through fails the test.

- Test that withReplaceIfIncompatible does NOT reach an index the type only inherits, which was handled by the
  own-vs-inherited guard but untested (#4083).

- The replacement is not atomic: LocalSchema.dropIndex commits its own recordFileChanges and so does the build,
  so a process that dies between them leaves the type without an index. Recorded at the drop site, with why the
  alternatives do not work: a schema transaction held across a full index build is the wrong trade, and building
  the new index alongside the old one is not representable while indexesByProperties keeps one index per
  property set.

- Release note for the embedded getOrCreateTypeIndex contract: it sets withIgnoreIfExists(true), so a uniqueness
  mismatch now raises instead of rebuilding, with the migration path.

* fix(engine) #5675: say what satisfiesRequest does not compare, and point an unguarded repeat at IF NOT EXISTS

Round-three review follow-ups on #5740, both documentation-level:

- satisfiesRequest compares the structural definition only, so two same-kind indexes configured differently
  (vector dimensions, full-text analyzers, geospatial precision) still satisfy each other. Not a regression -
  the old code compared isUnique alone - but it is the next question a reader asks, so the Javadoc now says it
  is deliberate and why: those settings live in per-index-type IndexMetadata subclasses with no common notion
  of "provides at least what was asked for", which needs a per-type rule rather than this comparison.

- The unguarded "Found the existent index" error now ends with the guard that makes the statement idempotent
  when the existing index already satisfies the request, and with the drop hint when it does not. The
  long-standing sentence is kept verbatim as the prefix so anything matching on it still matches.

* docs(engine) #5675: mark the getOrCreateTypeIndex change BREAKING

It is a runtime semantic change for embedded callers using it as an ensure/upgrade helper, so it belongs under the
same BREAKING heading convention the rest of the file uses rather than a plain one.

(cherry picked from commit 4966b4b)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Index create regression

1 participant