Repository navigation
fix(#5791): REBUILD INDEX preserves an explicitly-named FULL_TEXT/GEOSPATIAL index - #5925
Conversation
…SPATIAL index RebuildIndexStatement.buildIndex() drops and recreates a TypeIndex without carrying its own name through the new TypeIndexBuilder, so create() never sets metadata.typeIndexName and LocalDocumentType.addIndexInternal falls back to the auto-derived "typeName[properties]" form. A plain LSM_TREE rebuild happened to keep its name because its metadata object is reused as-is, but FULL_TEXT and GEOSPATIAL reconstruct their metadata from the index's persisted JSON to recover analyzer/precision settings, and typeIndexName isn't part of that JSON - so the name silently reverts and every name-based lookup (SEARCH_INDEX has no other way to reference an index) breaks after a rebuild. Fix: pass withIndexName(idx.getName()) into the rebuild so the name survives regardless of which metadata path the index type takes. The other two symptoms reported in #5791 (FULL_TEXT build over existing data indexing nothing matchable, and an NPE on prefix queries against a churned index) do not reproduce on current main: a stress test replaying the reporter's SCD2-style churn pattern (thousands of staggered inserts, growing updates that force placeholder relocations, and deletes, crossing the 5,000-record build-batch boundary) shows every pre-existing row matchable after CREATE INDEX ... FULL_TEXT, and prefix/wildcard queries against the same churned index complete without error - already covered by prior fixes (#4732's build-through-put() rewrite and #5635's IndexCursor contract change that makes next() never return null). Regression tests: RebuildIndexPreservesNameTest (plain/FULL_TEXT/GEOSPATIAL index rebuild keeps its name) and FullTextBuildOverChurnedDataTest (the full churn-then-build-then-rebuild-then-prefix-query scenario from the report).
|
Tick the box to add this pull request to the merge queue (same as
|
Up to standards ✅🟢 Issues
|
| Metric | Results |
|---|---|
| Complexity | 0 |
🟢 Coverage 75.00% diff coverage · -6.37% coverage variation
Metric Results Coverage variation ✅ -6.37% coverage variation Diff coverage ✅ 75.00% diff coverage Coverage variation details
Coverable lines Covered lines Coverage Common ancestor commit (ea4f6af) 152855 117429 76.82% Head commit (a95cb1e) 185202 (+32347) 130482 (+13053) 70.45% (-6.37%) 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 (#5925) 4 3 75.00% 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.
ReviewI traced the fix through the full metadata path ( Correctness
Test coverage
Style / minor
Performance / securityNo concerns. This is a schema-metadata bugfix with no new allocations on a hot path and no new dependencies. Overall: a well-scoped, correctly-targeted fix with tests that match the actual root cause rather than just the symptom. Nice investigative work distinguishing the one reproducible symptom from the two that no longer apply on |
…ngle-bucket types
Follow-up to the previous commit, prompted by a code review question this
PR's own automated review raised ("why doesn't the * sweep need the same
fix?"). Verifying that assumption with a test instead of taking it on faith
showed it was wrong: REBUILD INDEX * targets bucket sub-indexes rather than
the TypeIndex wrapper directly, but LocalSchema.dropIndex removes a
TypeIndex once it has no sub-index left - which is exactly what happens on
a single-bucket type (the common default), since its one sub-index is
always the last one. The freshly rebuilt sub-index then finds no existing
TypeIndex to reattach to, mints a new one, and hits the same auto-derived-
name fallback the previous commit fixed for the direct named-index rebuild
path.
BucketIndexBuilder.create() never carried a caller-supplied name onto the
metadata it hands to createBucketIndex(), unlike TypeIndexBuilder. Give it
the same carry-over, and have RebuildIndexStatement.buildIndex() capture
the owning TypeIndex's name (via IndexInternal.getTypeIndex()) before the
drop and pass it through withIndexName(...) on the bucket-index rebuild
branch too.
Extended RebuildIndexPreservesNameTest with a REBUILD INDEX * case over the
single-bucket FULL_TEXT/GEOSPATIAL indexes from the earlier tests, which
fails without this commit's fix.
|
placeholder-test |
|
Review I traced the fix through the full call chain (RebuildIndexStatement.buildIndex -> TypeIndexBuilder/BucketIndexBuilder.create() -> LocalSchema.createBucketIndex -> LocalDocumentType.addIndexInternal) and it holds up. Summary of what I verified: Root cause and fix are correctly diagnosed. LocalSchema.dropIndexInternal really does remove the TypeIndex wrapper once its last bucket sub-index is dropped (confirmed at LocalSchema.java:786-789), which is exactly the single-bucket-type trap the second commit describes. addIndexInternal only reads index.getMetadata().typeIndexName when it has to mint a new wrapper (propIndex == null branch, LocalDocumentType.java:1294-1306); when the wrapper survives (multi-bucket case), the passed-through name is simply unused, so the fix is a no-op there rather than a risk of unwanted renames. I checked this by hand for both the "last sub-index" and "not-last sub-index" cases and the logic is sound either way. ownerTypeIndex capture is correctly ordered. It is read via ((IndexInternal) idx).getTypeIndex() before dropIndex() runs (RebuildIndexStatement.java:358 vs :395), so it always reflects the live wrapper name pre-drop, regardless of iteration order across the REBUILD INDEX * bucket sweep. No aliasing hazard from the new metadata.typeIndexName mutation. For FULL_TEXT/GEOSPATIAL, rebuildMetadata is a freshly constructed object, so mutating it is safe. For the plain-index path, ((IndexInternal) idx).getMetadata() does return a live reference to the old index metadata object (confirmed in LSMTreeIndex.getMetadata()), but that reuse pattern already existed before this PR (per the PR description: "its metadata object is reused as-is") - the new .typeIndexName = indexName write onto it is harmless since the old index is already dropped by that point. Persistence path is unaffected. LocalDocumentType.toJSON() derives whether a name is "custom" by comparing i.getName() against the recomputed auto-derived form (LocalDocumentType.java:1797-1798), not by checking whether metadata.typeIndexName is set, so setting typeIndexName unconditionally (even to an auto-derived value, for previously-unnamed indexes) does not cause schema.json to start persisting spurious typeIndexName entries. Minor, non-blocking observations
Test coverage No blocking issues found. |
…DEX * Round out RebuildIndexPreservesNameTest per the second code-review round: on a multi-bucket type, the TypeIndex wrapper always has a surviving sub-index while another one is being rebuilt, so it is never dropped and addIndexInternal reattaches to it directly - the withIndexName(...) this PR threads through is unused on that path. Passes as-is, confirming the review's own analysis that the multi-bucket path was never at risk; locks it in against a future change to the sweep. Also filed #5934 for a related, out-of-scope defect the same review round surfaced: DatabaseChecker's CHECK DATABASE FIX path rebuilds a corrupted bucket index via buildBucketIndex(...).create() with neither withIndexName(...) nor any metadata at all, so it can both rename an index and drop FULL_TEXT/GEOSPATIAL settings entirely. Left for a separate PR since it is a different command with a wider blast radius than this one.
|
Addressed the second review round:
|
ReviewI traced the fix through the full metadata-propagation chain and it holds up. Mechanism verified correct.
The Minor observations, none blocking:
Test coverage is solid: the four cases in Not verified in this review: I wasn't able to run Nice write-up in the PR description distinguishing "fixed" from "does not reproduce" with concrete reasoning for each - that's the right way to close out a multi-symptom report. |
Codecov Report❌ Patch coverage is
Additional details and impacted files@@ Coverage Diff @@
## main #5925 +/- ##
==========================================
+ Coverage 68.03% 68.09% +0.06%
==========================================
Files 1797 1797
Lines 152855 152859 +4
Branches 32397 32399 +2
==========================================
+ Hits 103999 104095 +96
+ Misses 35466 35376 -90
+ Partials 13390 13388 -2 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
* fix: batch fixes for #5934, #5937, #5958 - #5934: CHECK DATABASE FIX's index-rebuild path dropped and rebuilt a corrupted bucket sub-index with no withIndexName()/withMetadata(), the same defect #5925 fixed for REBUILD INDEX. A single-bucket type lost its explicitly-named TypeIndex wrapper, and a FULL_TEXT/ GEOSPATIAL index lost its analyzer/precision settings, every time the check repaired one of their bucket sub-indexes. - #5937: the plain (unshaded) arcadedb-gremlin Maven coordinate crashed with a raw ExceptionInInitializerError/InvalidClassException the first time it ran a textual Gremlin query, because a downstream consumer's classpath resolves only the engine's ANTLR 4.13.2 runtime while TinkerPop's precompiled grammar needs 4.9.1's ATN format. ArcadeGremlin now recognizes that specific failure shape and raises an actionable CommandExecutionException pointing at the arcadedb-gremlin:shaded classifier, instead of leaking ANTLR internals. Textual Gremlin still requires the shaded classifier; this only makes the failure diagnosable. - #5958: Cypher25AntlrParser attached its CypherErrorListener to the parser but never to the lexer, unlike SQLAntlrParser after #5951/ #5957. Fixed for consistency and to guard future grammar changes; the regression test pins that lexically malformed input still raises CommandParsingException. * fix: address code review on #6031 - ArcadeGremlin.translateAntlrAtnMismatch: Codacy flagged the reference-identity cycle guard (next == c) as a raw == comparison on Throwable. Switched to Objects.equals(), which is null-safe and behaviorally identical since Throwable does not override equals(). - Cypher25AntlrParser.parseQuery: reuse a single CypherErrorListener instance for both lexer and parser, matching SQLAntlrParser's pattern (minor stylistic note from review; CypherErrorListener is stateless so this is behavior-preserving). * fix: address code review on #6031 (file-locking coverage) DatabaseChecker's index-rebuild loop dropped and rebuilt a corrupted bucket sub-index without holding the file lock RebuildIndexStatement.buildIndex() takes for the same drop+rebuild sequence. Wrap both steps in executeLockingFiles(idx.getFileIds(), ...), matching the sibling implementation, so a concurrent writer can't observe the index gone-then-back with entries missing and the commit-time lock-coverage check can't throw on the newly-created file. * fix: address code review on #6031 (deduplicate FULL_TEXT/GEOSPATIAL rebuild metadata) DatabaseChecker's new auto-fix rebuild path and RebuildIndexStatement.buildIndex() now had the same ~10-line FULL_TEXT/GEOSPATIAL metadata-reconstruction block copy-pasted verbatim. Factored into IndexMetadata.reconstructForRebuild(idx, typeName, propertyNames), a static helper both call, so a future third case or a bugfix to this logic only needs to be applied once. * fix: address code review on #6031 (retry the index-rebuild lock) DatabaseChecker's drop+rebuild lock (added to mirror RebuildIndexStatement's file-locking coverage) had no retry loop for lock contention, unlike RebuildIndexStatement.buildIndex(), which retries NeedRetryException / LockTimeoutException up to MAX_ATTEMPTS with backoff. Widening the locked section to cover both the drop and the create - the whole point of that fix - widens the window a concurrent writer can contend on, so add the same bounded retry. Unlike RebuildIndexStatement, which silently returns once attempts are exhausted, this rethrows: CHECK DATABASE FIX should fail loudly rather than quietly leave an index unrepaired while still reporting success. * fix: address code review on #6031 (document auto-mode fail-fast) Add the one-line comment code review suggested at the 'auto' -> java engine try/catch in ArcadeGremlin.executeStatement(boolean): the ATN-mismatch CommandExecutionException is unchecked, so it propagates past the catch (ScriptException e) used for the auto -> Groovy fallback, meaning 'auto' mode fails fast on this classpath defect instead of silently falling back to the insecure Groovy engine. Intentional, now documented at the call site. * docs: address code review on #6031 (document pre-existing retry race) Review round 5 correctly noted that retrying the whole drop+create body can re-enter with the drop already committed if create()'s bucket scan raises NeedRetryException, restarting from a different state than a clean retry assumes. Confirmed this exact shape already exists, unchanged, in RebuildIndexStatement.buildIndex() - not introduced by this PR, just given a second call site and (via the rethrow-on-exhaustion choice from the prior review round) more likely to surface if it happens. A proper fix (skip the drop on retry, or scope retry to lock acquisition only) needs to touch both call sites together, which is out of scope for this batch fix; documented the known race at the call site instead, and trimmed the now-lengthy comment block per the review's other minor note. * fix: address code review on #6031 (isolate lock-contention failure per index) DatabaseChecker's retry loop previously rethrew once LOCK_MAX_ATTEMPTS was exhausted, unwinding out of check() entirely. Since CheckDatabaseStatement has no catch around checker.check(), that aborted the WHOLE CHECK DATABASE FIX run - discarding every corrupted record already found and fixed, every index already rebuilt earlier in the affectedIndexes iteration, skipping every index still to come, and skipping the compress step - all because one index stayed lock-contended on a busy database (exactly the scenario the retry was added to survive). Isolate the failure to that one index instead: on exhausted retries, remove it from the reported rebuiltIndexes set (so the result doesn't claim a rebuild that didn't happen) and record a warning via addWarning(), matching this class's existing "reported, never silent" convention, then continue rebuilding the rest of affectedIndexes. An InterruptedException during the backoff sleep still aborts immediately, since that is a stop request rather than contention to ride out. * fix: address code review on #6031 (comment accuracy + plain-index test) - Refine the "known pre-existing race" comment on DatabaseChecker's retry loop: dropIndex() itself does not throw on retry (LocalSchema.dropIndexInternal no-ops once the name is gone); the actual risk is create() running a second time after a prior attempt's drop already committed, not resuming from where create() failed. Also note that capturing rebuildMetadata/ownerTypeIndex once before the loop (vs RebuildIndexStatement recomputing them per-attempt) is a hoist, not a behavior change, since both read idx before any attempt's drop. - Add fixPreservesExplicitNameOnPlainIndex to CheckDatabaseFixPreservesIndexMetadataTest, covering the plain (non-FULL_TEXT/GEOSPATIAL) TypeIndex-name-preservation case for CHECK DATABASE FIX's rebuild path, matching RebuildIndexPreservesNameTest's equivalent coverage for REBUILD INDEX. * fix: address code review on #6031 (recompute rebuild metadata per retry attempt) Real bug caught by review: rebuildMetadata was computed once, before the retry loop, so a retried FULL_TEXT rebuild reused the same FullTextIndexMetadata instance whose BM25 corpus counters (totalDocs/sumDocLength) had already been partially incremented by the failed attempt's create() call - addDocument() mutates the instance in place and is not reversed on rollback. Attempt N+1 then indexed every record again on top of attempt N's partial counts, inflating the corpus stats and skewing BM25 relevance scoring on any FULL_TEXT index whose rebuild needed more than one attempt. GEOSPATIAL was unaffected (GeoIndexMetadata has no equivalent mutable accumulator). Move IndexMetadata.reconstructForRebuild(...) inside the retry loop so each attempt gets a fresh, zeroed metadata instance, matching RebuildIndexStatement.buildIndex()'s per-attempt recomputation. ownerTypeIndex stays hoisted: it is a plain name read off idx, unaffected by attempt count. * docs: address code review on #6031 (explain hoisted retry-loop locals) Comment-only change: document why bucketName/indexType/unique/propNames/ typeName/pageSize/nullStrategy are safe to read once before the retry loop (plain idempotent reads off pre-drop idx/schema state, no mutable accumulator), unlike rebuildMetadata just below them, which for FULL_TEXT wraps a live BM25 counter and is recomputed per attempt for exactly that reason. * fix: address code review on #6031 (do not blame lock contention unconditionally) The retry-exhaustion warning unconditionally said "due to lock contention", but NeedRetryException reaching that branch can also come from the documented pre-existing race (a later attempt's create() failing after an earlier attempt's drop already committed) - in which case the index may be genuinely missing, not merely un-rebuilt, and "lock contention" is the wrong diagnosis to hand an operator. Reworded to state the rebuild did not finish and the index may be missing, point at re-running CHECK DATABASE FIX, and give a SELECT FROM schema:indexes query to verify - without claiming a specific root cause the code cannot actually distinguish from lastRetryFailure alone.
Summary
Investigation of #5791 (a follow-up report to #4732) found three claimed symptoms; only one still reproduces on
main.Confirmed and fixed:
REBUILD INDEX <name>silently renames an explicitly-namedFULL_TEXT/GEOSPATIALindex back to its auto-derivedtypeName[properties]form.RebuildIndexStatement.buildIndex()drops and recreates theTypeIndexthrough a freshTypeIndexBuilderbut never callswithIndexName(...), soTypeIndexBuilder.create()never populatesmetadata.typeIndexNameandLocalDocumentType.addIndexInternalfalls back to the default name. A plainLSM_TREErebuild happened to keep its name because its metadata object is reused as-is, butFULL_TEXT/GEOSPATIALreconstruct their metadata from the index's persisted JSON to recover type-specific settings (analyzers, GeoHash precision), andtypeIndexNameisn't part of that JSON - so it silently reverts. Every name-based lookup breaks after the rebuild, includingSEARCH_INDEX, which has no other way to reference an index. Fixed by passingwithIndexName(idx.getName())into the rebuild.Does not reproduce on
main: the core reported defect ("CREATE INDEX ... FULL_TEXTover pre-existing rows indexes nothing matchable") and the NPE on prefix queries. A stress test (FullTextBuildOverChurnedDataTest) replays the reporter's SCD2-style churn pattern - ~6,800 staggered inserts, several rounds of growing updates that force some records into placeholder relocation, and interleaved deletes, crossing the 5,000-record build-batch-commit boundary - then builds theFULL_TEXTindex and checks every marked row is matchable, exercises the sameREBUILD INDEXpath, and runs a prefix query against the churned index. All pass cleanly. This is consistent with BUG: FULL_TEXT index (re)build over existing data is broken -CREATE INDEXon a populated type indexes nothing matchable, andREBUILD INDEXcrashes and drops the index #4732's build-through-put()rewrite (already in 26.7.1+) and Index cursor follow-ups from #5601: LSMTreeIndexCursor.next() returns null after hasNext(), FetchFromIndexStep.reset() leaks its cursors #5635'sIndexCursorcontract change (next()never returnsnull, so the class of NPE reported can no longer occur) - neither of which the reporter had confirmed againstmainwhen filing.Changes
engine/src/main/java/com/arcadedb/query/sql/parser/RebuildIndexStatement.java: preserve the index's name acrossREBUILD INDEX.engine/src/test/java/com/arcadedb/index/RebuildIndexPreservesNameTest.java: regression test covering plainLSM_TREE,FULL_TEXT, andGEOSPATIALnamed-index rebuilds.engine/src/test/java/com/arcadedb/index/fulltext/FullTextBuildOverChurnedDataTest.java: reproduces the reporter's exact churn/build/rebuild/prefix-query scenario as a@Tag("slow")regression test.Test plan
mvn -pl engine install -DskipTestscompiles cleanlycom.arcadedb.index.fulltext.**,com.arcadedb.index.RebuildIndex*,com.arcadedb.query.sql.parser.RebuildIndexStatement*, andcom.arcadedb.function.sql.fulltext.**suites: 245 tests, 0 failurescom.arcadedb.schema.**suite: 612 tests, 0 failures🤖 Generated with Claude Code