Skip to content

fix(engine) #5765: creating a manual index no longer fences the database, and a guarded request answers for the index asked for - #5775

Merged
lvca merged 6 commits into
mainfrom
issue-5765-manual-index-builder
Aug 2, 2026
Merged

lvca merged 6 commits into
mainfrom
issue-5765-manual-index-builder

Conversation

@lvca

@lvca lvca commented Aug 2, 2026

Copy link
Copy Markdown
Member

Closes #5765.

All four items of the issue, plus four defects found while fixing item 1 - each of which the previous one was hiding.

Item 1 was sitting on top of a bigger one: buildManualIndex(...).create() did not work at all

ManualIndexBuilder.create() registered the new index's file under index instanceof PaginatedComponent. That test never matched: LSMTreeIndex and HashIndex wrap their paginated component rather than being one. The file stayed unknown to the schema, and the commit that creates it then failed resolving that file id - after its WAL append, which fences the whole database for recovery (#5053):

database.getSchema().buildManualIndex("idx", new Type[] { Type.STRING })
    .withType(Schema.INDEX_TYPE.LSM_TREE).withUnique(false).create();
// DatabaseOperationException: database is fenced after a failure past the WAL commit point

Worse, the builder's own error callback then called drop() on the fenced database, so the exception the caller saw was a bare fence error with the real cause nowhere in it. Registration goes through index.getComponent() now - the same accessor the type-index path uses - and the cleanup callback logs instead of throwing.

Three more defects, each surfaced by fixing the one before it:

  • Schema.createManualIndex(indexType, ...) dropped its indexType argument, so every call through that deprecated overload failed with a NullPointerException inside the index factory.
  • A UNIQUE manual index could not commit an entry. Both TransactionIndexContext.addFilesToLock and checkUniqueIndexKeys resolved the index's type name to reach the polymorphic index over the same properties; a manual index has neither, and the null reached getType(). A manual index is now recognised as its own whole search space, which it is - nothing else indexes its keys.
  • withNullStrategy(null) installed the null instead of leaving the default, and the index constructor refused it with "Index null strategy is null". null now means "not specified", the convention withPageSize already follows.

An index kind that cannot be built without a type (FULL_TEXT, GEOSPATIAL, LSM_VECTOR, LSM_SPARSE_VECTOR) is refused by name instead of failing inside the factory with a NullPointerException or a ClassCastException.

The IF NOT EXISTS half, as filed

The guarded branch carried the two defects #5675 removed from TypeIndexBuilder: a request differing only in uniqueness dropped the existing index and recreated it (behind the dead x != null && x == null null-strategy test), and the index kind was not compared at all. It follows the same rule as the type path now.

One departure from the issue's suggestion, deliberately. There is no withReplaceIfIncompatible opt-in on this path - the setter raises UnsupportedOperationException on a manual builder. On a type index the replacement is a rebuild from the type's records; a manual index has no records behind it, so the same operation is an unrecoverable delete of the only copy of its entries. Refusing at the setter rather than at create() puts the answer at the call that expresses the intent.

One correction to the issue text

Item 1 says the defect is "reachable through Schema.buildManualIndex(...), including RemoteSchema". It is not: RemoteSchema.buildManualIndex and RemoteSchema.createManualIndex both throw UnsupportedOperationException. This is embedded-API only.

Item 3: IF NOT EXISTS compares the settings the METADATA clause named

CREATE INDEX ON Doc (embedding) LSM_VECTOR METADATA {"dimensions": 384};
CREATE INDEX IF NOT EXISTS ON Doc (embedding) LSM_VECTOR METADATA {"dimensions": 768};  -- was a silent no-op

Every vector written afterwards is 768 long, none is indexed, and nothing said so.

Only the settings the clause actually NAMED are compared, which is what keeps this from reaching any statement that did not ask for it: a guarded statement with no METADATA names nothing and stays the plain no-op it has always been. Everything named IS compared, including the tuning knobs a rebuild would not be needed to change - writing a value into a statement and having it silently discarded is the surprise being removed, and a caller who means the no-op leaves the key out.

The clause is read through the index type's own reader before comparing, so {"dimensions": "384"} matches 384 and {"similarity": "euclidean"} matches EUCLIDEAN. Both entry points ask through one helper - the IF NOT EXISTS shortcut of CreateIndexStatement, which answers before a builder exists, and TypeIndexBuilder.create().

The read side of each per-type key set (getUserMetadataValue) mirrors applyUserMetadata, and a setting present in only one of the two would fail silently - an unreadable key compares null against null. IndexMetadataUserSettingComparisonTest closes that: each key gets a pair of distinct valid values, so it does not depend on knowing any default, and adding a key to getUserMetadataKeys() without adding it there fails the key-set assertion.

Item 2: the vector rebuild waits

The two Thread.sleep(6_000) + hard-assertion pairs are Awaitility now. I extended the same treatment to LSMVectorIndexRebuildTest: four of its tests failed in a whole-package run here and passed in isolation, the exact shape the issue describes. Their ceilings were computed as a multiple of the inactivity timeout, which makes the wait shortest exactly where the work is slowest - what varies under load is how long the rebuild takes, not how long the timer waits before starting it. They share one absolute ceiling now, and the class also got faster (24.6s -> 16.7s), since a poll returns as soon as the rebuild lands.

Item 4

CREATE INDEX and REBUILD INDEX log their per-100k progress instead of printing a dot to System.out.

Verification

  • New: Issue5765ManualIndexIfNotExistsTest (12), Issue5765IndexSettingsIfNotExistsTest (8), IndexMetadataUserSettingComparisonTest (7)
  • Every fix mutation-checked: reverting the file registration, either TransactionIndexContext guard, the withType, or the guarded-branch rule fails a test
  • Full engine suite: 10977 tests, 0 failures, 0 errors
  • All modules compile

🤖 Generated with Claude Code

https://claude.ai/code/session_01W8C35vrQkW1y1gaEvWzRPc

…ase, and a guarded request answers for the index asked for

ManualIndexBuilder.create() registered the new index's file under `index instanceof PaginatedComponent`, a test that
never matched: LSMTreeIndex and HashIndex WRAP their paginated component rather than being one. The file stayed unknown
to the schema, and the commit that creates it then failed resolving that file id AFTER its WAL append - which fences the
database for recovery (#5053). Every manual index creation ended there, and the builder's own error callback threw on
the fenced database, replacing the real cause with a bare fence error. Registration goes through index.getComponent()
now, the same accessor the type-index path uses, and the cleanup callback no longer throws.

Three defects the first one hid, each found by fixing the previous:

- Schema.createManualIndex(indexType, ...) dropped its indexType argument, so every call through that deprecated
  overload failed with a NullPointerException inside the index factory.
- A UNIQUE manual index could not commit an entry: TransactionIndexContext's lock collection and its uniqueness check
  both resolved the index's type name to reach the polymorphic index over the same properties, and a manual index has
  neither. It is now recognised as its own whole search space, which it is.
- withNullStrategy(null) installed the null instead of leaving the default, and the index constructor refused it with
  "Index null strategy is null". null now means "not specified", the convention withPageSize already follows.

An index kind that cannot be built without a type (FULL_TEXT, GEOSPATIAL, LSM_VECTOR, LSM_SPARSE_VECTOR) is refused by
name instead of failing inside the factory with a NullPointerException or a ClassCastException.

The guarded branch still carried the two defects #5675 removed from TypeIndexBuilder: a request differing only in
uniqueness DROPPED the existing index behind a dead `x != null && x == null` null-strategy test, and the index kind was
not compared at all. It follows the same rule as the type path now. There is no withReplaceIfIncompatible here: the
setter raises on a manual builder, because the replacement it authorises elsewhere is a rebuild from the type's records
and here it would be an unrecoverable delete of the only copy of the entries.

fix(engine) #5765: CREATE INDEX IF NOT EXISTS compares the settings the METADATA clause named

The guard compared the structural definition only - kind and uniqueness - so a guarded statement asking for 768
dimensions over a 384-dimension vector index was a silent no-op, and every vector written afterwards went unindexed.
Same for full-text analyzers and geospatial precision.

Only the settings the clause actually NAMED are compared, so a statement with no METADATA compares none and stays the
no-op it has always been. The clause is read through the index type's own reader before comparing, so "384" and 384,
"cosine" and COSINE are the one value each denotes. Both entry points ask the same question through one helper: the
IF NOT EXISTS shortcut of CreateIndexStatement, which answers before a builder exists, and TypeIndexBuilder.create().
The read side of each per-type key set is covered by a test that fails if a key is added to one list and not the other.

test(engine) #5765: poll for the vector rebuild instead of sleeping a fixed interval

Two Thread.sleep(6_000) + hard assertion pairs in LSMVectorIndexRecoveryTest, and the ceilings in
LSMVectorIndexRebuildTest computed as a multiple of the inactivity timeout - which makes the wait shortest exactly
where the work is slowest. Four of them failed in a whole-package run here and passed in isolation. They share one
absolute ceiling now; the class also runs faster, since a poll returns as soon as the rebuild lands.

chore(engine) #5765: CREATE INDEX and REBUILD INDEX log their progress instead of printing dots to stdout
@mergify

mergify Bot commented Aug 2, 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

…ex-builder

# Conflicts:
#	docs/release-26.8.1.md
@codacy-production

codacy-production Bot commented Aug 2, 2026 •

Copy link
Copy Markdown

Up to standards ✅

🟢 Issues 0 issues

Results:
0 new issues

View in Codacy

🟢 Metrics 62 complexity

Metric Results
Complexity 62

View in Codacy

🟢 Coverage 88.98% diff coverage · -6.78% coverage variation

Metric Results
Coverage variation ✅ -6.78% coverage variation
Diff coverage ✅ 88.98% diff coverage

View coverage diff in Codacy

Coverage variation details
Coverable lines Covered lines Coverage
Common ancestor commit (876635c) 151275 115849 76.58%
Head commit (5bb7116) 183416 (+32141) 128023 (+12174) 69.80% (-6.78%)

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 (#5775) 118 105 88.98%

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

Copy link
Copy Markdown

Review: PR #5775 - manual index fencing + guarded-request settings comparison

Reviewed the full diff and cross-checked the moving parts against the codebase (IndexInternal.getComponent(), the copy() overrides in every IndexMetadata subclass, the getFileIds() coverage that the new addFilesToLock guard depends on, and the conflictWithExistingIndex message path). This is a strong, carefully-reasoned PR - the root-cause analysis is correct, the comments explain why rather than what, and the test coverage is genuinely good (the getUserMetadataKeys() vs getUserMetadataValue() cross-check in IndexMetadataUserSettingComparisonTest is a nice way to keep the two switches from drifting apart).

Correctness - verified, looks right

  • The fencing fix is the real bug. index instanceof PaginatedComponent never matched because LSMTreeIndex/HashIndex wrap their component; switching to index.getComponent() matches the type-index path (LocalSchema already uses index.getComponent() for the same purpose). Good.
  • TransactionIndexContext null-type guards are correct: for a manual index the index's own files are already added earlier via getFileIds() (line 341), so skipping the type fan-out loses no coverage, and checkUniqueIndexKeys still keeps the idx != null guard. Confirmed both.
  • Error callback no longer throwing is the right call - a throw there was masking the real cause. Removing from indexMap before the best-effort drop() is also correct regardless of how far creation got.

One behavior change worth calling out explicitly

findUserSettingMismatches compares every setting the METADATA clause names, including runtime-tunable knobs that don't require a rebuild (efSearch, inactivityRebuildTimeoutMs, cache sizes, ...). So a script that previously relied on CREATE INDEX IF NOT EXISTS ... METADATA {"efSearch": 120} being a silent no-op over an index built with a different efSearch will now get a hard conflict error instead of a no-op.

This is clearly deliberate and well-argued in the javadoc/release note (silent discard is the worse surprise), so I'm not asking to change it - just flagging that it's a semantic change to a previously-idempotent path. Two small asks:

  1. Make sure the release note frames this as "may now raise where it previously no-op'd" so users with existing idempotent-create scripts aren't caught out.
  2. Since the engine suite passed but this touches the shared DDL path, it'd be worth a run of the server/IT modules that exercise CREATE INDEX IF NOT EXISTS with a METADATA clause, in case any existing test re-creates with a differing tuning value.

Minor notes (non-blocking)

  • In TypeIndexBuilder.create(), findUnsatisfiedSettings(...) is not wrapped in a try/catch, unlike the IF NOT EXISTS shortcut in CreateIndexStatement (which maps a bad clause to a 400). In practice the builder path has already validated via withMetadata(...), so a re-parse on the copy won't throw - but if withUserMetadata is ever set through the API without a prior withMetadata, an invalid value would surface as a raw IndexException instead of the friendly message. A comment noting the invariant (or the same guard) would future-proof it.
  • The single REBUILD_SETTLE_TIMEOUT = 120s shared across all the vector waits is a good simplification; the reasoning (bound the rebuild, not a multiple of the timer) is sound.
  • System.out.print(".") to LogManager at INFO every 100k records is the right move inside a server process.

Style / conventions

Matches the repo: final used consistently, JSONObject/JSONArray from com.arcadedb.serializer.json, assertThat(...) assertion style, Apache headers on new files, no System.out left behind. No new dependencies.

Nice work - the "each defect was hiding the next" writeup made this easy to follow. The behavior-change callout above is the only thing I'd want confirmed before merge.

…ING, and say why the builder path does not re-wrap the clause

Review follow-ups on #5775, both documentation-level.

- The release note now frames the settings comparison as what it is for anyone with a re-runnable schema script: a
  guarded CREATE INDEX naming a setting MAY NOW RAISE where it used to be a no-op, including for the runtime-tunable
  keys a rebuild would not be needed to change (efSearch, mutationsBeforeRebuild, inactivityRebuildTimeoutMs, the cache
  sizes). Both ways back to an idempotent statement are spelled out: drop the keys the script does not actually
  require, or align the value with the existing index.

- TypeIndexBuilder.create() calls findUnsatisfiedSettings without the try/catch the CreateIndexStatement shortcut wraps
  its own call in, and the invariant that makes that safe is now written down rather than implied: the SQL branches
  call withMetadata and withUserMetadata inside one try, so the clause has already been read - and any unreadable value
  already reported - before create() runs. A caller that sets the user clause without the parsed one has skipped that
  validation and gets the reader's own message; there is no such caller, and adding a second error path would only
  re-type an exception the reader already words correctly.

Verified against the review's third ask: no CREATE INDEX IF NOT EXISTS with a METADATA clause exists outside engine/,
and RemoteSchema.getOrCreateTypeIndex builds its guarded statement without one, so nothing outside the engine reaches
the new comparison. Server module re-run against a freshly installed engine: 687 tests, 0 failures.
@lvca

lvca commented Aug 2, 2026

Copy link
Copy Markdown
Member Author

Thanks - all three asks addressed in 9f17194.

1. Release-note framing. Added a ### BREAKING: a guarded create naming a setting MAY NOW RAISE where it used to be a no-op subsection. It calls out that the runtime-tunable keys are included (efSearch, mutationsBeforeRebuild, inactivityRebuildTimeoutMs, the cache sizes) and gives both routes back to an idempotent statement: drop the keys the script does not actually require, or align the value with what the existing index carries. The error names each differing setting with both values, so it says which of the two applies.

2. Server/IT run. Done, and worth reporting how it went, because my first attempt produced a false regression.

mvn -pl server test resolves arcadedb-engine from ~/.m2, not from the working tree. That jar was stale, so the run was exercising an engine that predates #5740 - which is exactly why Issue5675CreateIndexIfNotExistsHttpTest.aGuardedUniqueOverANotUniqueIndexIsAClientError came back 200 instead of 400. My "but it passes on main" comparison was invalid in the same way, in reverse: building that worktree ran install first and so refreshed ~/.m2 before testing.

With the engine actually installed from this branch: server module 687 tests, 0 failures, BUILD SUCCESS, that test included. A temporary diagnostic confirmed the values reaching satisfiesRequest are the right ones (existing unique=false, requested unique=true -> refused); it has been removed.

On the specific worry - an existing test re-creating with a differing tuning value - I also grepped the repo: there is no CREATE INDEX IF NOT EXISTS carrying a METADATA clause anywhere outside engine/, and RemoteSchema.getOrCreateTypeIndex builds its guarded statement without one. Nothing outside the engine reaches the new comparison.

3. findUnsatisfiedSettings not wrapped in TypeIndexBuilder. Went with the comment rather than the guard, and wrote down the invariant instead of implying it: the SQL branches call withMetadata and withUserMetadata inside one try, so the clause has already been read - and any unreadable value already reported as a 400 - before create() runs. A caller that sets the user clause without the parsed one has skipped that validation and gets the reader's own message; there is no such caller, and adding a second error path would only re-type an exception the reader already words correctly.

Full engine suite remains green at 10977 tests.

@claude

claude Bot commented Aug 2, 2026

Copy link
Copy Markdown

Review: PR 5775 - manual index no longer fences the database, guarded requests answer for the index asked for

Reviewed the full diff, the touched engine sources, and the new/changed tests. This is a high-quality, well-scoped fix. The commit messages and release notes explain not just what changed but why the previous code was wrong, and each fix is a real defect with a clear root cause.

Strengths

  • Correct root-cause fix. Replacing index instanceof PaginatedComponent with schema.registerFile(index.getComponent()) is the right call: both LSMTreeIndex and HashIndex wrap their PaginatedComponent rather than being one (confirmed both expose getComponent() returning a PaginatedComponent), so the old instanceof never matched and the file stayed unregistered until the post-WAL commit fenced the DB. Using the same accessor the type-index path uses is the right consolidation.
  • Cleanup callback no longer throws. Wrapping indexToRemove.drop() in try/catch and logging matters: an exception in that error callback would replace the real failure the caller needs to see.
  • TransactionIndexContext null-guards are minimal and correct. Both addFilesToLock and checkUniqueIndexKeys recognize a manual index (no type) as its own whole search space, and the manual index files are already covered by the earlier getFileIds() loop. Added cost is a single null check on the commit path.
  • findUserSettingMismatches design is sound. Comparing on the internal representation (copy existing, overlay only named keys via fromUserMetadata, compare only requested.keySet()) correctly makes "384"/384 and "cosine"/COSINE equal and limits comparison to keys the clause named. Sorting for stable messages is a nice touch.
  • IndexMetadataUserSettingComparisonTest is a real guard: asserting getUserMetadataKeys() matches the samples means adding a key to applyUserMetadata but not getUserMetadataValue (or vice versa) fails a test instead of silently becoming a no-op comparison.
  • Breaking change is called out explicitly in the release note, including the runtime-tunable keys and both escape hatches. Honest framing for a change to an idempotent path.
  • Awaitility migration removes real flakiness. One absolute REBUILD_SETTLE_TIMEOUT instead of a multiple of timeoutMs is correct: what varies under load is rebuild duration, not the timer delay, so the old scaling made the wait shortest exactly where the work is slowest.

Minor points / questions

  1. Refusing runtime-tunable settings on a guarded create is the most debatable choice. For keys a rebuild would not be needed to change (efSearch, cache sizes, inactivityRebuildTimeoutMs), raising on a re-runnable script is stronger than ignore-with-warning. Documented as BREAKING with a clear rationale, so defensible - just flagging it as the part most likely to surprise users with idempotent migration scripts.
  2. Shared JSONObject reference between withMetadata and withUserMetadata. In the vector/full-text/geo branches the same jsonMetadata instance is passed to both setters. Works today, but if a builder ever mutates the metadata it receives, the stored userMetadata changes too. A defensive copy in withUserMetadata (or a comment noting the shared reference is intentional) would harden it. Low priority.
  3. TypeIndexBuilder.create() calls findUnsatisfiedSettings without the try/catch the SQL shortcut uses. The added comment documents the invariant (SQL branches read the clause via withMetadata first, so unreadable values are already reported), which holds for current callers - but it is enforced only by convention; a future caller setting withUserMetadata without withMetadata gets the raw reader exception. The comment is the right mitigation; noting it as a latent sharp edge.
  4. Test gap: no direct assertion that a mid-creation failure leaves the DB usable (not fenced). indexKindsThatNeedATypeAreRefused exercises the early validation path (fails before any WAL work), and the fence fix is covered only indirectly by later tests running fine. An explicit "creation fails after the WAL append, DB still accepts a write" regression test would pin the exact behavior the PR title promises. Optional but valuable.
  5. Nit: the mismatch message key= (requested ) reads slightly oddly (current-first). Tested, so no action needed unless you want to align it with other conflict messages.

Conventions / correctness checks

  • Imports verified present (LogManager/Level in both statements; IndexInternal/JSONObject/List in IndexBuilder; List in TypeIndexBuilder).
  • System.out progress prints correctly replaced with LogManager logging on both CREATE INDEX and REBUILD INDEX, per the no-System.out rule.
  • withNullStrategy(null) now meaning "not specified" matches the withPageSize convention and cannot break a previously-working caller (passing null used to fail at construction).
  • Tests use the preferred assertThat(...).isTrue()/isEqualTo(...) style and real RIDs for the unique path.

I could not run mvn in this sandbox (blocked), so I relied on the PR-stated verification (engine 10977/0/0, server 687/0, all modules compile) plus static review. Nothing in the diff suggests a compile or logic problem.

Overall: clean, well-tested, well-explained. The minor points above are suggestions, not blockers.

…d assert the file registration directly

Round-two review follow-ups on #5775.

- withUserMetadata deep-copies the clause. The callers hand the SAME JSONObject to withMetadata(JSONObject) and to
  withUserMetadata, and the two are read at different times: the first now, the second at create(). No withMetadata
  overload mutates it today - all four read it through fromUserMetadata - but the copy costs nothing at DDL time and
  means a future one could not silently change what a guarded request ends up comparing against.

- A test asserts the registration itself rather than inferring it from the other tests happening to run. The index's
  file must resolve through the schema by its id, which is the call TransactionContext.commit2ndPhase makes for every
  file whose page count changed - past the WAL append, which is why an unregistered file fenced the database instead of
  failing the creation. The test pins the cause (getFileById resolves to the index's own component) and the consequence
  (the database still commits an unrelated write afterwards, which a fenced one cannot). Mutation-checked: restoring
  the `instanceof PaginatedComponent` test reproduces "commit of tx 4 failed after its WAL append".

Three other review points taken as no-action, with reasons: refusing runtime-tunable settings on a guarded create is
the intended semantics and is already documented as BREAKING; the TypeIndexBuilder invariant comment is the right
mitigation for a caller shape that does not exist; and the mismatch message wording is already covered by tests.
@lvca

lvca commented Aug 2, 2026

Copy link
Copy Markdown
Member Author

Thanks - acted on the two points that harden something, declined three with reasons. 9ffb5f1.

2. Shared JSONObject between withMetadata and withUserMetadata - fixed rather than commented. withUserMetadata now deep-copies (JSONObject.copy()). You're right that it works today - all four withMetadata(JSONObject) overloads only read the clause through fromUserMetadata - but the two setters are read at different times (one now, one at create()), which is exactly the shape where a future mutation would be invisible. A copy costs nothing at DDL time.

4. Test gap: nothing asserted the DB is not fenced - agreed, and this was the best of the five. Added aManualIndexRegistersItsFileAndLeavesTheDatabaseUsable, which asserts the fix directly instead of inferring it from the other tests happening to run:

  • the cause: schema.getFileById(index.getComponent().getFileId()) resolves to the index's own component. That call is precisely what TransactionContext.commit2ndPhase makes for every file whose page count changed, past the WAL append.
  • the consequence: the database still commits an unrelated write afterwards, which a fenced one cannot.

Mutation-checked: putting the instanceof PaginatedComponent test back makes it fail with Database ... fenced for recovery: commit of tx 4 failed after its WAL append.

1. Refusing runtime-tunable settings - keeping as is. It is the intended semantics and the release note now carries it under a BREAKING heading with both escape hatches. Agreed it is the part most likely to surprise; that is why it is documented rather than softened.

3. TypeIndexBuilder try/catch as a latent sharp edge - keeping the comment. Adding a second error path would mean re-typing an exception the reader already words correctly, for a caller shape (withUserMetadata without withMetadata) that does not exist in tree.

5. key=<current> (requested <wanted>) ordering - leaving it. In the full sentence it reads as intended: ... already exists on the same properties as LSM_VECTOR (unique=false) with a different configuration: dimensions=384 (requested 768), i.e. what is there, then what was asked for.

Engine tests for the touched areas: 44/44 green (Issue5765ManualIndexIfNotExistsTest now 13).

@claude

claude Bot commented Aug 2, 2026

Copy link
Copy Markdown

Review of #5775 - manual index creation and guarded-create settings comparison

Reviewed the full diff plus surrounding source (getComponent() on LSMTreeIndex/HashIndex, IndexMetadata.copy(), fromJSON/applyUserMetadata on the metadata subtypes, TransactionIndexContext). Overall this is a high-quality, carefully-motivated fix. The root-cause diagnosis (registering under instanceof PaginatedComponent, a test that can never match a wrapping index, so the file stays unknown and the commit fences the DB after the WAL append) is correct, and each of the four secondary defects is real and independently fixed. Commit messages and the release note are exemplary.

Verified as correct

  • File registration: index.getComponent() returns the real PaginatedComponent (the bucket/mutable) for both LSMTreeIndex and HashIndex; registerFile accepts it. The new aManualIndexRegistersItsFileAndLeavesTheDatabaseUsable test pins both cause (getFileById resolves) and consequence (DB still commits) rather than inferring it - much stronger.
  • TransactionIndexContext: both null-typeName guards are correct. A manual unique index has associatedBucketId == -1 and its own files are already added via getFileIds(), so skipping the type fan-out is right; checkUniqueIndexKeys treating the index as its own whole search space is sound.
  • findUserSettingMismatches: copy() is polymorphically overridden in every metadata subtype, so asRequested is the correct concrete type and the per-key read/apply round-trips. Comparing on the internal representation ("384"==384, "euclidean"==EUCLIDEAN) is the right call.
  • Round-trip of runtime-tunable keys: efSearch, mutationsBeforeRebuild, inactivityRebuildTimeoutMs, graphBuildCacheSize are all persisted in fromJSON, so a matching guarded request over a reopened index genuinely stays a no-op rather than falsely raising.
  • withNullStrategy(null): default is SKIP, so treating null as "unspecified" is correct and matches the withPageSize convention.

Minor observations (non-blocking)

  1. IndexMetadataUserSettingComparisonTest is the strongest part of the change - requiring every getUserMetadataKeys() entry to have a distinct-value sample means adding a key to one switch and not the other fails a test. Good defense against the silent null==null trap.
  2. Directive-only keys: buildGraphNow is stripped because it is a statement directive, not a stored setting. If any future index type grows a similar "do X now" key, it would leak into the comparison and fromUserMetadata would reject it as unknown (a 400 on an otherwise-idempotent guarded statement). Worth treating "strip directive keys in one shared place" as a convention. Not an issue today.
  3. asRequested is built from a fresh default copy with only the named keys applied. Fine given each setter validates its value independently, but a future setter that cross-validates against another field (e.g. pqSubspaces vs dimensions) could validate against the default rather than the existing index's value when only one of the pair is named. No such coupling exists now; flagging for future setters.
  4. Moving the per-100k progress dot from System.out to LogManager at INFO is the right fix; the 100k interval keeps it from being noisy.

Test coverage

Excellent. Manual-index creation, unique-constraint commit, reopen persistence, the full guarded-branch matrix (unique-over-notunique, kind mismatch, notunique-over-unique no-op, idempotent, unguarded refusal), the deprecated overload, unsupported kinds, and the settings comparison across all four metadata types are covered. The BREAKING semantic change is clearly documented with both remediation paths.

Nice work - no blocking concerns from my side.

…e instead of stripping them per site

Round-three review follow-up on #5775, the one observation with something to act on.

"buildGraphNow" was removed at two sites - the IF NOT EXISTS reader and the LSM_VECTOR creation branch - because it
directs the statement rather than configuring the index, so no index stores it and everything that reads the clause as
configuration rejects it: fromUserMetadata refuses an unknown key, and the guarded comparison would report a mismatch
for something an existing index cannot have. Both turn a well-formed statement into a 400.

The key space is now one named DIRECTIVE_METADATA_KEYS set behind a stripDirectives() helper, so a future "do X now"
key on another index type has an obvious place to be declared rather than being stripped at whichever site happens to
notice it. No behaviour change: the same one key is removed in the same two places.

Two other observations in that review need no change and are recorded here as judged: a future setter that
cross-validates one METADATA key against another could validate against the default rather than the existing index's
value when only one of the pair is named (no such coupling exists - every setter validates its own value), and the
per-100k progress logging interval is already where it should be.
@lvca

lvca commented Aug 2, 2026

Copy link
Copy Markdown
Member Author

Thanks. One of the four had something to act on; the other three are compliments or forward-looking notes that need no change. 9735b71.

2. Directive-only keys - done. You're right that this deserved to be a convention rather than a habit: "buildGraphNow" was being stripped at two sites (the IF NOT EXISTS reader and the LSM_VECTOR creation branch) because it directs the statement rather than configuring the index. It is now one named DIRECTIVE_METADATA_KEYS set behind a stripDirectives() helper, so a future "do X now" key on another index type has an obvious place to be declared instead of being stripped wherever someone happens to notice. No behaviour change - same key, same two places.

3. asRequested built from a fresh default copy - no change. Correct as a hazard, and it genuinely does not exist today: every setter validates its own value in isolation. Worth noting the copy is not a fresh default in the sense that matters - it is existing.copy(...), so every unnamed setting already carries the existing index's value; only a setter that cross-validated during applyUserMetadata would see a stale partner field, and none do. Recorded in the commit message so a future setter that does introduce such a coupling has a pointer.

1 and 4 - no action.

Tests re-run after the refactor: 50/50 green across the manual-index, settings-comparison, #5675 and DDL-parser suites.

That is every point from all three rounds either implemented or judged with a reason, and no round raised a blocking concern - so this is ready for your review whenever you want it.

@claude

claude Bot commented Aug 2, 2026

Copy link
Copy Markdown

Review of #5765 fix: manual index creation + guarded-request settings comparison

I read all four commits and traced the changed engine paths (TransactionIndexContext, IndexBuilder/IndexMetadata, ManualIndexBuilder, CreateIndexStatement, the per-type metadata readers). Overall this is a high-quality, well-scoped fix with unusually good tests and documentation. The commit-message forensics (each defect surfaced by fixing the previous one) match what the code actually does. I did not find a correctness bug. Notes below are ordered by importance.

Strengths

  • Root-cause fix is right. Registering through index.getComponent() instead of the never-matching index instanceof PaginatedComponent is the correct accessor (both LSMTreeIndex and HashIndex wrap their component), and Issue5765ManualIndexIfNotExistsTest.aManualIndexRegistersItsFileAndLeavesTheDatabaseUsable pins both cause (getFileById resolves) and consequence (DB not fenced). Mutation-checked per the PR description.
  • Error-callback hardening. Making the cleanup callback log-and-continue instead of throwing on the fenced database is the correct call: a throw there replaces the real cause. indexMap.remove before the best-effort drop() is also correct.
  • TransactionIndexContext null-guards in both addFilesToLock and checkUniqueIndexKeys are minimal and correct: a manual index is its own whole search space, its files are already added via getFileIds(), and skipping the polymorphic fan-out is right.
  • The settings-comparison design is clean. Reading the request through the type's own applyUserMetadata onto a copy so "384"/384 and "cosine"/COSINE compare as one value (rather than string-diffing JSON) is the right approach. Stable-sorted mismatch messages are a nice touch.
  • The coverage-guard test (IndexMetadataUserSettingComparisonTest) that asserts getUserMetadataKeys() and getUserMetadataValue() stay in lockstep is excellent - it closes the exact silent-failure mode (unreadable key compares null==null, reverting to a no-op) that this feature exists to remove.
  • Test-flakiness work is a genuine improvement: replacing Thread.sleep(6_000) + hard assertion with Awaitility, and (importantly) sharing one absolute REBUILD_SETTLE_TIMEOUT instead of ceilings scaled off timeoutMs - the reasoning that "the wait was shortest exactly where the work is slowest" is correct.

The one thing to confirm before merge (already flagged BREAKING)

The IF NOT EXISTS settings comparison now compares every named key, including runtime-tunable ones a rebuild would not need (efSearch, mutationsBeforeRebuild, inactivityRebuildTimeoutMs, cache sizes). A re-runnable migration script that names a tunable key and used to be a silent no-op can now raise HTTP 400 if the live index differs on any named key. The PR documents this as BREAKING in release-26.8.1.md and gives both escape hatches (drop the key, or align the value), which is the right way to ship it. Worth a second maintainer opinion on whether tunable-only mismatches should ideally warn rather than hard-fail, but the "don't silently discard a value the caller wrote" principle is defensible and consistently applied.

Minor / non-blocking

  • Float comparison via Objects.equals in findUserSettingMismatches is safe here only because both sides are parsed through the same applyUserMetadata reader, so identical inputs yield identical bit patterns. That invariant holds today; if any setter ever derives a float rather than storing the parsed value verbatim, this could report a spurious mismatch. Not actionable now, just noting the assumption.
  • ManualIndexBuilder.SUPPORTED_INDEX_TYPES (LSM_TREE, HASH) is the correct allow-list, and refusing the rest by name beats an NPE/CCE from the factory.
  • TypeIndexBuilder.create() calls findUnsatisfiedSettings without the try/catch the SQL shortcut wraps around it. The added comment documents why (the clause is already validated by withMetadata before create(), and no caller sets withUserMetadata without withMetadata). Fine as documented, though it leaves a latent sharp edge for any future embedded caller that sets the user clause directly.

Security / performance

No security concerns: the UPDATE_SCHEMA permission check is preserved, and mapping client-supplied METADATA errors to 400 rather than 500 reduces internal-error leakage. Performance-wise the withUserMetadata deep-copy is DDL-time only (negligible), and dropping the System.out.print(".")/flush() off the build hot path is a small win.

Verification I did / did not do

I verified the referenced APIs exist and are used correctly (JSONObject.copy() deep-copies, IndexInternal.getComponent(), the polymorphic IndexMetadata.copy(...) returning the right subclass, LogManager/Level imports present). I did not re-run the build or the suite locally; the PR reports 10977 engine tests green and all modules compiling, and the changes are consistent with that.

Nice work - this is a thorough fix that leaves the paths better documented than it found them.

@codecov

codecov Bot commented Aug 2, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 82.20339% with 21 lines in your changes missing coverage. Please review.
✅ Project coverage is 67.87%. Comparing base (2ee91ae) to head (5bb7116).
⚠️ Report is 2 commits behind head on main.

Files with missing lines Patch % Lines
...n/java/com/arcadedb/schema/ManualIndexBuilder.java 76.92% 6 Missing ⚠️
...rc/main/java/com/arcadedb/schema/IndexBuilder.java 71.42% 1 Missing and 3 partials ⚠️
...va/com/arcadedb/schema/LSMVectorIndexMetadata.java 86.36% 2 Missing and 1 partial ⚠️
...ava/com/arcadedb/schema/FullTextIndexMetadata.java 85.71% 1 Missing and 1 partial ⚠️
...ain/java/com/arcadedb/schema/GeoIndexMetadata.java 50.00% 1 Missing and 1 partial ⚠️
...c/main/java/com/arcadedb/schema/IndexMetadata.java 86.66% 1 Missing and 1 partial ⚠️
.../arcadedb/schema/LSMSparseVectorIndexMetadata.java 60.00% 1 Missing and 1 partial ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #5775      +/-   ##
==========================================
+ Coverage   67.77%   67.87%   +0.10%     
==========================================
  Files        1783     1783              
  Lines      151332   151370      +38     
  Branches    32100    32108       +8     
==========================================
+ Hits       102562   102748     +186     
+ Misses      35491    35328     -163     
- Partials    13279    13294      +15     

☔ 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 0b2ccfb into main Aug 2, 2026
9 of 11 checks passed
@lvca
lvca deleted the issue-5765-manual-index-builder branch August 2, 2026 21:14
@claude

claude Bot commented Aug 2, 2026

Copy link
Copy Markdown

Review

I read through the full diff and traced the touched paths in TransactionIndexContext, IndexBuilder, IndexMetadata (+ subclasses), ManualIndexBuilder, TypeIndexBuilder and CreateIndexStatement. This is a careful, well-tested PR. The root-cause narrative (the instanceof PaginatedComponent test that never matched because LSMTreeIndex/HashIndex wrap their component, surfacing only after the WAL append and fencing the DB) is convincing and the fix - registering via index.getComponent(), the same accessor the type path uses - is the right one.

Verified as correct

  • addFilesToLock / checkUniqueIndexKeys null-guard: a manual index's own files are already added by the getFileIds() loop above, so skipping the type fan-out for typeName == null is safe, and treating the manual index as its own whole search space in the uniqueness check is correct (nothing else indexes its keys).
  • withNullStrategy(null): the field defaults to NULL_STRATEGY.SKIP, so ignoring a null argument correctly leaves the default rather than installing a null the constructor rejects. Matches the withPageSize convention.
  • findUserSettingMismatches: copy(...) is overridden in every metadata subclass, so asRequested is the right runtime type and reading the request through fromUserMetadata before comparing gives "384"==384 / "cosine"==COSINE equivalence for free. getUserMetadataValue mirrors applyUserMetadata key-for-key, and IndexMetadataUserSettingComparisonTest guards the two staying in sync - nice touch.
  • Error-callback cleanup in ManualIndexBuilder: removing from indexMap + swallowing drop() failures so the callback can't replace the real cause is a good fix, and the pre-indexMap.put failure case degrades to a harmless no-op remove.

One thing worth a look (minor)

There is an asymmetry for a plain (UNIQUE/NOTUNIQUE) index carrying a METADATA clause. First creation ignores the clause (no metadata branch consumes it for plain indexes), but a guarded re-run reaches findUnsatisfiedSettings -> base IndexMetadata.fromUserMetadata, which throws IllegalArgumentException on any key, caught and rethrown as HTTP 400:

CREATE INDEX ON Doc (x) NOTUNIQUE METADATA {"foo": 1};                -- succeeds, silently ignores foo
CREATE INDEX IF NOT EXISTS ON Doc (x) NOTUNIQUE METADATA {"foo": 1};  -- now 400

So a re-runnable script that previously worked can start failing on its second run for a plain index. It is an edge case (metadata on a plain index is meaningless), but the create/guarded-recreate inconsistency is a little surprising. Two clean options: skip the comparison when the index type declares no user-metadata keys, or validate metadata on the plain-index creation path too so both ends agree.

Notes (not blockers)

  • Documented BREAKING change: a guarded CREATE INDEX naming a setting can now raise where it used to be a no-op, including runtime-tunable knobs (efSearch, cache sizes). It is clearly called out in the release notes - good - but since this touches an idempotent path used by migration scripts, it is worth making sure it lands prominently in the user-facing changelog/upgrade notes too, not only the internal release doc.
  • Awaitility conversions: consolidating onto an absolute REBUILD_SETTLE_TIMEOUT (120s) instead of ceilings scaled off the inactivity timeout is the right reasoning (the rebuild duration is what varies under load, not the timer). Small tradeoff: a genuinely broken rebuild now takes up to 120s to fail instead of 30-60s, so real regressions in these tests surface a bit slower in CI. Acceptable given these are liveness assertions.

Style / conventions

Adheres well to the repo conventions: final throughout, imported names (no FQNs), assertThat(...).isTrue() style, @author header without Claude attribution, System.out progress dots replaced with LogManager. Test coverage is strong - 3 new classes plus the mutation-check discipline described in the PR body, and the "worse off than a type index because the drop destroys the only copy" reasoning is pinned by guardedUniqueOverNotUniqueKeepsTheIndexAndItsEntries.

Overall: solid, well-reasoned work. Only the plain-index + METADATA asymmetry seems worth deciding on before merge; everything else is either correct or a documented tradeoff.

Reviewed by Claude Code.

robfrank pushed a commit that referenced this pull request Aug 14, 2026
…ase, and a guarded request answers for the index asked for (#5775)

* fix(engine) #5765: creating a manual index no longer fences the database, and a guarded request answers for the index asked for

ManualIndexBuilder.create() registered the new index's file under `index instanceof PaginatedComponent`, a test that
never matched: LSMTreeIndex and HashIndex WRAP their paginated component rather than being one. The file stayed unknown
to the schema, and the commit that creates it then failed resolving that file id AFTER its WAL append - which fences the
database for recovery (#5053). Every manual index creation ended there, and the builder's own error callback threw on
the fenced database, replacing the real cause with a bare fence error. Registration goes through index.getComponent()
now, the same accessor the type-index path uses, and the cleanup callback no longer throws.

Three defects the first one hid, each found by fixing the previous:

- Schema.createManualIndex(indexType, ...) dropped its indexType argument, so every call through that deprecated
  overload failed with a NullPointerException inside the index factory.
- A UNIQUE manual index could not commit an entry: TransactionIndexContext's lock collection and its uniqueness check
  both resolved the index's type name to reach the polymorphic index over the same properties, and a manual index has
  neither. It is now recognised as its own whole search space, which it is.
- withNullStrategy(null) installed the null instead of leaving the default, and the index constructor refused it with
  "Index null strategy is null". null now means "not specified", the convention withPageSize already follows.

An index kind that cannot be built without a type (FULL_TEXT, GEOSPATIAL, LSM_VECTOR, LSM_SPARSE_VECTOR) is refused by
name instead of failing inside the factory with a NullPointerException or a ClassCastException.

The guarded branch still carried the two defects #5675 removed from TypeIndexBuilder: a request differing only in
uniqueness DROPPED the existing index behind a dead `x != null && x == null` null-strategy test, and the index kind was
not compared at all. It follows the same rule as the type path now. There is no withReplaceIfIncompatible here: the
setter raises on a manual builder, because the replacement it authorises elsewhere is a rebuild from the type's records
and here it would be an unrecoverable delete of the only copy of the entries.

fix(engine) #5765: CREATE INDEX IF NOT EXISTS compares the settings the METADATA clause named

The guard compared the structural definition only - kind and uniqueness - so a guarded statement asking for 768
dimensions over a 384-dimension vector index was a silent no-op, and every vector written afterwards went unindexed.
Same for full-text analyzers and geospatial precision.

Only the settings the clause actually NAMED are compared, so a statement with no METADATA compares none and stays the
no-op it has always been. The clause is read through the index type's own reader before comparing, so "384" and 384,
"cosine" and COSINE are the one value each denotes. Both entry points ask the same question through one helper: the
IF NOT EXISTS shortcut of CreateIndexStatement, which answers before a builder exists, and TypeIndexBuilder.create().
The read side of each per-type key set is covered by a test that fails if a key is added to one list and not the other.

test(engine) #5765: poll for the vector rebuild instead of sleeping a fixed interval

Two Thread.sleep(6_000) + hard assertion pairs in LSMVectorIndexRecoveryTest, and the ceilings in
LSMVectorIndexRebuildTest computed as a multiple of the inactivity timeout - which makes the wait shortest exactly
where the work is slowest. Four of them failed in a whole-package run here and passed in isolation. They share one
absolute ceiling now; the class also runs faster, since a poll returns as soon as the rebuild lands.

chore(engine) #5765: CREATE INDEX and REBUILD INDEX log their progress instead of printing dots to stdout

* docs(engine) #5765: mark the guarded-create settings comparison BREAKING, and say why the builder path does not re-wrap the clause

Review follow-ups on #5775, both documentation-level.

- The release note now frames the settings comparison as what it is for anyone with a re-runnable schema script: a
  guarded CREATE INDEX naming a setting MAY NOW RAISE where it used to be a no-op, including for the runtime-tunable
  keys a rebuild would not be needed to change (efSearch, mutationsBeforeRebuild, inactivityRebuildTimeoutMs, the cache
  sizes). Both ways back to an idempotent statement are spelled out: drop the keys the script does not actually
  require, or align the value with the existing index.

- TypeIndexBuilder.create() calls findUnsatisfiedSettings without the try/catch the CreateIndexStatement shortcut wraps
  its own call in, and the invariant that makes that safe is now written down rather than implied: the SQL branches
  call withMetadata and withUserMetadata inside one try, so the clause has already been read - and any unreadable value
  already reported - before create() runs. A caller that sets the user clause without the parsed one has skipped that
  validation and gets the reader's own message; there is no such caller, and adding a second error path would only
  re-type an exception the reader already words correctly.

Verified against the review's third ask: no CREATE INDEX IF NOT EXISTS with a METADATA clause exists outside engine/,
and RemoteSchema.getOrCreateTypeIndex builds its guarded statement without one, so nothing outside the engine reaches
the new comparison. Server module re-run against a freshly installed engine: 687 tests, 0 failures.

* fix(engine) #5765: copy the user METADATA clause into the builder, and assert the file registration directly

Round-two review follow-ups on #5775.

- withUserMetadata deep-copies the clause. The callers hand the SAME JSONObject to withMetadata(JSONObject) and to
  withUserMetadata, and the two are read at different times: the first now, the second at create(). No withMetadata
  overload mutates it today - all four read it through fromUserMetadata - but the copy costs nothing at DDL time and
  means a future one could not silently change what a guarded request ends up comparing against.

- A test asserts the registration itself rather than inferring it from the other tests happening to run. The index's
  file must resolve through the schema by its id, which is the call TransactionContext.commit2ndPhase makes for every
  file whose page count changed - past the WAL append, which is why an unregistered file fenced the database instead of
  failing the creation. The test pins the cause (getFileById resolves to the index's own component) and the consequence
  (the database still commits an unrelated write afterwards, which a fenced one cannot). Mutation-checked: restoring
  the `instanceof PaginatedComponent` test reproduces "commit of tx 4 failed after its WAL append".

Three other review points taken as no-action, with reasons: refusing runtime-tunable settings on a guarded create is
the intended semantics and is already documented as BREAKING; the TypeIndexBuilder invariant comment is the right
mitigation for a caller shape that does not exist; and the mismatch message wording is already covered by tests.

* refactor(engine) #5765: declare the METADATA statement directives once instead of stripping them per site

Round-three review follow-up on #5775, the one observation with something to act on.

"buildGraphNow" was removed at two sites - the IF NOT EXISTS reader and the LSM_VECTOR creation branch - because it
directs the statement rather than configuring the index, so no index stores it and everything that reads the clause as
configuration rejects it: fromUserMetadata refuses an unknown key, and the guarded comparison would report a mismatch
for something an existing index cannot have. Both turn a well-formed statement into a 400.

The key space is now one named DIRECTIVE_METADATA_KEYS set behind a stripDirectives() helper, so a future "do X now"
key on another index type has an obvious place to be declared rather than being stripped at whichever site happens to
notice it. No behaviour change: the same one key is removed in the same two places.

Two other observations in that review need no change and are recorded here as judged: a future setter that
cross-validates one METADATA key against another could validate against the default rather than the existing index's
value when only one of the pair is named (no such coupling exists - every setter validates its own value), and the
per-100k progress logging interval is already where it should be.

(cherry picked from commit 0b2ccfb)
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.

Follow-ups from #5675: ManualIndexBuilder still silently drops indexes, plus three smaller items

1 participant