Skip to content

fix(schema): carry the whole index definition over at every rebuild site (#5742) - #6869

Merged
lvca merged 1 commit into
mainfrom
fix/5742-index-metadata-carryover
Aug 28, 2026
Merged

lvca merged 1 commit into
mainfrom
fix/5742-index-metadata-carryover

Conversation

@lvca

@lvca lvca commented Aug 28, 2026 •

Copy link
Copy Markdown
Member

Fixes #5742.

The defect

Any site that rebuilds an index from its own configuration has to read that configuration back and feed it through the creation path. They read it with IndexInternal.getMetadata(), which for the WRAPPER index types answers with the underlying LSM-Tree's plain IndexMetadata:

  • LSMTreeFullTextIndex keeps its analyzers, query-parser options and BM25 parameters in its own FullTextIndexMetadata
  • LSMTreeGeoIndex keeps its geohash resolution and storage layout as plain fields
  • LSMSparseVectorIndex keeps its dimensionality, scoring modifier and weight quantization in its own LSMSparseVectorIndexMetadata

None of that is reachable through the underlying index, so each site silently recreated the index with the DEFAULT configuration - a different analyzer and a different ranking for a full-text index, a different cell size for a geospatial one. Nothing logged, and the index kept working.

What changed

Every site now reads getMetadataForNewFile(), the accessor #5734 added for exactly this.

Site Was Now
TRUNCATE TYPE getMetadata(), carried over only for LSM_VECTOR, behind an explicit per-index-type branch getMetadataForNewFile().copy(...), one polymorphic withMetadata() for every index type
REBUILD INDEX / CHECK DATABASE FIX (IndexMetadata.reconstructForRebuild) FULL_TEXT/GEOSPATIAL reconstructed from the index's persisted JSON, everything else getMetadata() one accessor + copy(), keeping the two adjustments only a rebuild may make
ALTER TYPE ... BUCKET +... getMetadata() getMetadataForNewFile()
ALTER TYPE ... SUPERTYPE +... getMetadata() getMetadataForNewFile()

TRUNCATE TYPE loses its per-index-type branch entirely: withType() has already swapped in the builder subclass that owns those settings, so the polymorphic call lands on the override that reinstates them and there is no list to forget an index type from.

LSM_SPARSE_VECTOR was worse than a silent loss. Falling through to getMetadata() handed the sparse builder a plain IndexMetadata, which it refuses outright, so REBUILD INDEX and CHECK DATABASE FIX on a sparse-vector index failed:

Error on rebuilding index 'Doc[dims,weights]'
  (error=An LSM_SPARSE_VECTOR index requires LSMSparseVectorIndexMetadata but got com.arcadedb.schema.IndexMetadata)

The half of the definition the accessor did not carry

A wrapper index's definition is split in two: the base settings (collations, the user-supplied index name) belong to the underlying LSM-Tree's metadata, the type-specific ones to the wrapper's own. Creation populates one instance carrying both halves, but a schema RELOAD rebuilds the type-specific half from the bucket-level index JSON, which carries no typeName key - so fromJSON() skips the base-field read and those settings stay only on the underlying half. Switching the carry-over sites to the accessor without fixing that would have traded one silent loss for another: right analyzer, lost index name. The two halves are joined back at load through the new IndexMetadata.inheritCommonSettingsFrom(), and truncateAfterAReopenKeepsBothHalvesOfTheDefinition fails without it.

Bucket/super-type propagation hands the instance over as-is

Not copied, unlike the other two sites: the sub-index minted there belongs to the SAME logical index. That is what index creation itself does when it passes one metadata instance to every bucket sub-index, and it is what keeps the full-text corpus counters type-wide instead of restarting them at zero for the new bucket.

copyType()'s crash window

The issue also asks for a story on copyType()'s deliberate non-atomicity. The existing catch covers a failure on either side of the commit boundary by dropping the copy; a hard crash in the same window leaves a populated type with empty or partial indexes, and CHECK DATABASE does not report it because its index check is STRUCTURAL (checkIntegrity() walks the key order of the index's own pages, so an index merely missing entries looks healthy). Rather than pay for atomicity - which would mean holding every copied record in one transaction - the javadoc now names the window explicitly and names REBUILD INDEX <name> as the repair.

Tests

New Issue5742IndexConfigurationCarryOverTest, one case per user-visible operation - all five fail on main:

  • truncateTypeKeepsTheFullTextConfiguration - asserts behaviourally, on the English stem still matching after the truncate, not only on the attribute
  • truncateTypeKeepsTheGeospatialPrecision
  • addingABucketKeepsTheFullTextConfiguration
  • addingASuperTypeKeepsTheFullTextConfiguration
  • rebuildIndexKeepsTheSparseVectorConfiguration
  • checkDatabaseFixKeepsTheSparseVectorConfiguration
  • truncateAfterAReopenKeepsBothHalvesOfTheDefinition

Also fixed a vacuous existing test: Issue5723CopyTypeIndexConfigurationTest.truncatingAManuallyNamedVectorIndexKeepsItsName ran its TRUNCATE TYPE inside a transaction, which takes the record-by-record path and never drops the index at all (#6220), so it asserted on a carry-over that had not happened.

Full engine module suite green (13745 tests, 0 failures); vector lane green.

Summary by CodeRabbit

  • Bug Fixes

    • Preserved index configuration—including analyzers, collations, geospatial settings, sparse-vector dimensions, and manual names—when indexes are rebuilt, truncated, repaired, or recreated.
    • Improved index metadata preservation when adding buckets or propagating indexes across related types.
    • Documented recovery guidance for copied schemas whose indexes may be incomplete after a crash.
  • Tests

    • Added regression coverage across index rebuild, truncation, repair, schema reopening, and bucket operations.

…ite (#5742)

An index rebuilt from its own definition read that definition with
IndexInternal.getMetadata(), which on the WRAPPER index types answers with the
underlying LSM-Tree's plain IndexMetadata. A full-text index keeps its analyzers,
query-parser options and BM25 parameters in its own FullTextIndexMetadata, a
geospatial one keeps its geohash resolution and storage layout as plain fields,
and a sparse-vector one keeps its dimensionality, scoring modifier and weight
quantization in its own metadata: none of that is reachable through the
underlying index, so the recreated index silently came back with the DEFAULT
configuration - a different analyzer and a different ranking, a different cell
size - with nothing logged.

Every site now reads getMetadataForNewFile(), the accessor added by #5734:

- TRUNCATE TYPE recreated only an LSM_VECTOR index's metadata, through an
  explicit per-index-type branch. withType() has already swapped in the builder
  subclass that owns the type-specific settings, so one polymorphic
  withMetadata() call covers every index type and leaves no branch to forget.
- REBUILD INDEX and CHECK DATABASE FIX share IndexMetadata.reconstructForRebuild,
  which reconstructed FULL_TEXT and GEOSPATIAL from the index's persisted JSON
  and fell through to getMetadata() for everything else. For LSM_SPARSE_VECTOR
  that did not merely lose the settings: the sparse builder refuses a plain
  IndexMetadata, so both operations FAILED on a sparse-vector index with
  "requires LSMSparseVectorIndexMetadata but got IndexMetadata". It now reads the
  one accessor and copies, keeping the two adjustments only a rebuild is entitled
  to make (zeroed BM25 corpus counters, GEOSPATIAL republished on the FRONTIER
  layout).
- ALTER TYPE ... BUCKET +... and ALTER TYPE ... SUPERTYPE +... mint a sub-index
  for the new bucket. They hand the definition over as-is rather than copied:
  that sub-index belongs to the SAME logical index, which is what index creation
  does when it passes one metadata instance to every bucket sub-index, and what
  keeps the full-text corpus counters type-wide.

A wrapper's definition is split in two, and schema RELOAD rebuilt the
type-specific half from the bucket-level index JSON, which carries no "typeName"
key - so fromJSON() skipped the base-field read and the collations and the manual
index name stayed only on the underlying half. Reading the accessor would then
have traded one silent loss for another (right analyzer, lost index name), so the
two halves are joined back at load through IndexMetadata.inheritCommonSettingsFrom().

Also documents the one window copyType() cannot cover - a hard crash between the
record commit and the index build leaves a populated type with empty indexes,
which CHECK DATABASE does not report because its index check is structural - and
names REBUILD INDEX as the repair.

Issue5723CopyTypeIndexConfigurationTest.truncatingAManuallyNamedVectorIndexKeepsItsName
ran its TRUNCATE TYPE inside a transaction, which takes the record-by-record path
and never drops the index at all, so it asserted on a carry-over that had not
happened.
@lvca lvca added this to the 26.9.1 milestone Aug 28, 2026
@lvca lvca self-assigned this Aug 28, 2026
@mergify

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

Copy link
Copy Markdown

Up to standards ✅

🟢 Issues 0 issues

Results:
0 new issues

View in Codacy

🟢 Metrics 0 complexity

Metric Results
Complexity 0

View in Codacy

🟢 Coverage 87.50% diff coverage · -6.43% coverage variation

Metric Results
Coverage variation ✅ -6.43% coverage variation
Diff coverage ✅ 87.50% diff coverage

View coverage diff in Codacy

Coverage variation details
Coverable lines Covered lines Coverage
Common ancestor commit (9cf4d26) 167849 134907 80.37%
Head commit (7504fd4) 200238 (+32389) 148055 (+13148) 73.94% (-6.43%)

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 (#6869) 16 14 87.50%

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.

@coderabbitai

coderabbitai Bot commented Aug 28, 2026 •

Copy link
Copy Markdown

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 2f98c91a-4603-426e-b7c1-3bf808581778

📥 Commits

Reviewing files that changed from the base of the PR and between 9cf4d26 and 7504fd4.

📒 Files selected for processing (7)
  • engine/src/main/java/com/arcadedb/query/sql/parser/RebuildIndexStatement.java
  • engine/src/main/java/com/arcadedb/query/sql/parser/TruncateTypeStatement.java
  • engine/src/main/java/com/arcadedb/schema/IndexMetadata.java
  • engine/src/main/java/com/arcadedb/schema/LocalDocumentType.java
  • engine/src/main/java/com/arcadedb/schema/LocalSchema.java
  • engine/src/test/java/com/arcadedb/schema/Issue5723CopyTypeIndexConfigurationTest.java
  • engine/src/test/java/com/arcadedb/schema/Issue5742IndexConfigurationCarryOverTest.java

Included review availability: Your plan provides up to 10 included reviews per hour; 3 remain after this review.


📝 Walkthrough

Walkthrough

Changes

Index configuration carry-over

Layer / File(s) Summary
Metadata reconstruction and inheritance
engine/src/main/java/com/arcadedb/schema/IndexMetadata.java, engine/src/main/java/com/arcadedb/query/sql/parser/RebuildIndexStatement.java
Rebuild metadata now uses new-file metadata and copies shared settings such as collations and manual type-index names.
Index recreation and schema propagation
engine/src/main/java/com/arcadedb/query/sql/parser/TruncateTypeStatement.java, engine/src/main/java/com/arcadedb/schema/LocalDocumentType.java, engine/src/main/java/com/arcadedb/schema/LocalSchema.java
Truncation, bucket creation, supertype propagation, and schema loading preserve wrapper-specific index configuration.
Configuration preservation regression coverage
engine/src/test/java/com/arcadedb/schema/Issue5742IndexConfigurationCarryOverTest.java, engine/src/test/java/com/arcadedb/schema/Issue5723CopyTypeIndexConfigurationTest.java
Tests cover full-text, geospatial, vector, and sparse-vector settings across truncation, rebuild, repair, bucket changes, supertype propagation, and schema reopen.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Merge Risk: ⚪ Minimal · up to 7504f

This change preserves full index definitions across rebuild, truncate, bucket, supertype, and reload paths, including type-specific settings. The supplied tests and engine suite are green, and no actionable merge-blocking risk remains beyond normal checks and review.

Suggested reviewers: robfrank

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 32.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 25 functions across 7 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the primary change: preserving complete index definitions during rebuild operations.
Description check ✅ Passed The description is detailed and explains the defect, implementation, linked issue, affected operations, crash-window documentation, and regression tests. It does not use the repository template headin…
Linked Issues check ✅ Passed The changes address issue #5742 by using getMetadataForNewFile(), preserving type-specific and common index settings, covering all affected rebuild and propagation sites, and adding regression tests f…
Out of Scope Changes check ✅ Passed The code, documentation, test correction, and regression coverage are directly related to preserving index configuration and validating the fix for issue #5742. No unrelated changes are identified.
Full details: Description check

Explanation

The description is detailed and explains the defect, implementation, linked issue, affected operations, crash-window documentation, and regression tests. It does not use the repository template headings or include the checklist, but it provides the required substantive information.

Full details: Linked Issues check

Explanation

The changes address issue #5742 by using getMetadataForNewFile(), preserving type-specific and common index settings, covering all affected rebuild and propagation sites, and adding regression tests for the required operations.

  • Fix all pre-merge checks with AI
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/5742-index-metadata-carryover

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

@claude

claude Bot commented Aug 28, 2026

Copy link
Copy Markdown

Review

Solid fix, and the write-up in the PR description makes the bug easy to verify against the code. The core idea (getMetadataForNewFile() as the single polymorphic accessor, copy() overrides per wrapper type owning their own field lists) checks out in each of the four sites touched:

  • TruncateTypeStatement.recreateIndex / IndexDefinition.from - confirmed withType() swaps in the right builder subclass and the polymorphic withMetadata() lands on the override that validates/reinstates the type-specific fields (TypeFullTextIndexBuilder, TypeGeoIndexBuilder, TypeLSMSparseVectorIndexBuilder, TypeLSMVectorIndexBuilder all guard the cast).
  • IndexMetadata.reconstructForRebuild - getMetadataForNewFile() + copy() + the two rebuild-only adjustments (BM25 counters reset via FullTextIndexMetadata.copy, GEOSPATIAL tokenization forced to DEFAULT_TOKENIZATION after the copy) is correct and null-safe (source == null short-circuits before copy() would NPE).
  • LocalDocumentType.addBucketInternal / createSubIndexesFor - handing the same getMetadataForNewFile() instance to every new bucket sub-index (not copying) is consistent with how the initial multi-bucket creation path already works, so full-text corpus counters correctly stay type-wide instead of resetting per bucket.
  • LocalSchema.readConfiguration - inheritCommonSettingsFrom is called on FULL_TEXT/LSM_SPARSE_VECTOR (which keep a separate metadata instance) but correctly not called on GEOSPATIAL, since LSMTreeGeoIndex.getMetadataForNewFile() re-derives from the live underlying index's getMetadata() on every call via GeoIndexMetadata.from(...) rather than caching a stale instance - so it never needed the extra hop. Good attention to detail there.

Test coverage for the four sites plus the reopen/reload edge case is thorough and each case is asserted through the same getMetadataForNewFile() accessor being fixed, which is the right way to pin this regression.

One more call site with the same bug pattern

TypeIndexBuilder.ReplacedIndexDefinition.of() (engine/src/main/java/com/arcadedb/schema/TypeIndexBuilder.java:557) still reads:

final IndexMetadata metadata = onBuckets.length > 0 ? onBuckets[0].getMetadata() : null;

onBuckets[0] here is the bucket-level wrapper instance (TypeIndex.indexesOnBuckets stores the LSMTreeFullTextIndex/LSMTreeGeoIndex/LSMSparseVectorIndex wrappers themselves, confirmed by the instanceof LSMTreeFullTextIndex checks elsewhere in TypeIndex.java), and each wrapper's getMetadata() override forwards to underlyingIndex.getMetadata() - the same plain base IndexMetadata this PR is fixing everywhere else. This definition is used in restoreReplacedIndex():

if (replaced.metadata() != null)
  restore.withMetadata(replaced.metadata());

where restore is the type-specific builder returned by withType(replaced.indexType()). For FULL_TEXT/GEOSPATIAL/LSM_SPARSE_VECTOR, withMetadata(IndexMetadata) on those builders throws ("A FULL_TEXT index requires FullTextIndexMetadata but got ...", etc.) when handed anything but its own metadata subtype.

This path is reached by withReplaceIfIncompatible(true) (e.g. CREATE INDEX ... IF NOT EXISTS/constraint-style callers) whenever an existing wrapper-type index's settings don't satisfy the request: the existing index is dropped, and if the replacement creation then fails for any reason, restoreReplacedIndex() tries to put the original back. With today's code that restore call throws instead of recreating the index, and the exception is only attached as addSuppressed on the original failure and logged - so the type is silently left with no index at all on a FULL_TEXT/GEOSPATIAL/LSM_SPARSE_VECTOR property, which is exactly the failure mode issue #5675 (referenced in the surrounding comments) was supposed to prevent. Swapping to onBuckets[0].getMetadataForNewFile() looks like the same one-line fix applied everywhere else in this PR, and it'd be worth a regression test alongside Issue5742IndexConfigurationCarryOverTest (e.g. force a replace-then-fail on a FULL_TEXT index and assert the original index and its analyzer survive).

Minor

  • TruncateTypeStatement.recreateIndex: if (def.metadata != null) builder.withMetadata(...) - worth double-checking there's no index type where getMetadataForNewFile() legitimately returns null for a type whose builder actually requires non-null metadata (e.g. a HASH index created without a METADATA clause) to make sure this silently-skip branch can't mask a real loss the way the bug being fixed did. From what I can see plain LSM/HASH builders tolerate a null metadata fine, so this looks fine, just flagging as something to double check given the general shape of this issue.

Nothing else stood out on security or performance - this is schema/DDL-path code, not a hot path, and no new dependencies or unsafe patterns were introduced.

@codecov

codecov Bot commented Aug 28, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 75.00000% with 4 lines in your changes missing coverage. Please review.
✅ Project coverage is 71.79%. Comparing base (9cf4d26) to head (7504fd4).

Files with missing lines Patch % Lines
...c/main/java/com/arcadedb/schema/IndexMetadata.java 66.66% 2 Missing and 2 partials ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #6869      +/-   ##
==========================================
+ Coverage   71.78%   71.79%   +0.01%     
==========================================
  Files        1881     1881              
  Lines      167849   167851       +2     
  Branches    35559    35559              
==========================================
+ Hits       120485   120517      +32     
+ Misses      32981    32954      -27     
+ Partials    14383    14380       -3     

☔ 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 merged commit 2cb1941 into main Aug 28, 2026
45 of 54 checks passed
@lvca
lvca deleted the fix/5742-index-metadata-carryover branch August 28, 2026 21:14
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.

An index rebuilt from its own definition still loses its full-text and geospatial configuration at four sites

1 participant