Skip to content

fix(engine) #5723: a copied type keeps its index definitions, its records' content, and index entries - #5734

Merged
lvca merged 5 commits into
mainfrom
worktree-issue-5723-rename-type-index-pagesize
Aug 2, 2026
Merged

lvca merged 5 commits into
mainfrom
worktree-issue-5723-rename-type-index-pagesize

Conversation

@lvca

@lvca lvca commented Aug 1, 2026

Copy link
Copy Markdown
Member

Closes #5723.

The issue reports that LocalSchema.copyType() loses the page size of every index on the copy. It does. Writing the regression test for it surfaced two more defects in the same thirty lines, and they are the ones that make the copy wrong rather than differently tuned.

(The issue names renameType(). There is no such method: ALTER TYPE ... NAME ... goes through LocalDocumentType.rename(), which renames buckets in place and never recreates an index. The affected method is copyType(), which is what a document-to-vertex conversion goes through.)

1. Every index on the copy came out EMPTY

The indexes were created inside the transaction that copies the records. TypeIndexBuilder.create() builds each bucket's index in its own transaction (joinCurrent=false), which from inside an enclosing transaction neither sees the records still pending in it nor commits the entries it produces. So the copy carried indexes with zero entries, and any query the planner routed through one answered nothing - silently, since an empty index is indistinguishable from a type with no matching rows.

schema.copyType("Doc", "Doc2", LocalVertexType.class, 1, 65_536, 1_000);
database.query("sql", "SELECT FROM Doc2 WHERE k = 'v1'");   // 0 rows, and the record is right there

Verified by experiment, not by reading: moving the loop back inside the transaction reproduces entries=0 exactly.

2. The copied records were EMPTY

ImmutableDocument.propertiesAsMap() was the one accessor of that class that did not call checkForLazyLoading() - it returned Collections.emptyMap() whenever buffer == null, which is the state of every record handed out by iterateType() and scanBucket(). copyType() reads each source record that way, so it faithfully created the right number of records, each with no properties. The same silent emptiness hit a DetachedDocument built off a record straight from a scan.

It now loads first, like get(), has(), getPropertyNames(), toMap() and toJSON() already did. The empty map remains the answer only for a record that genuinely cannot be materialised (no database, no RID, or an after-read event that filtered it away), so the class's exception-propagation contract from #2560 is preserved - the two new entries in ImmutableDocumentLazyLoadingInconsistencyTest's accessor list assert exactly that.

3. The reported one, wider than reported

The copy went through the three-argument createTypeIndex overload, so the index type, the uniqueness flag and the property list survived and everything else was replaced by a default: the tuned page size from the report, the null strategy, the collations that make a lookup case-insensitive, and the entire type-specific configuration. That last one is not a tuning difference - a copied FULL_TEXT index tokenized and ranked with the default analyzer, a copied GEOSPATIAL index dropped to the default geohash resolution, and a copied LSM_VECTOR index came up with dimensions 0.

The better alternative to the suggested fix

The issue suggests passing getPageSizeForNewFile() through. That fixes one attribute of five and leaves a copied full-text or vector index broken, so the fix generalises the accessor instead of the call:

  • IndexInternal.getMetadataForNewFile(), the companion of the getPageSizeForNewFile() that HASH index silently corrupts when created with a page size above 65536 (16-bit slot offsets, no validation) #5713 introduced. It exists because getMetadata() cannot answer this question for the wrapper index types: LSMTreeFullTextIndex keeps its analyzers and BM25 parameters in its own FullTextIndexMetadata and LSMTreeGeoIndex keeps its resolution and layout in plain fields, while both getMetadata()s delegate to the underlying LSM-Tree and hand back a definition with none of it.
  • IndexMetadata.copy(typeName, propertyNames, bucketId) promoted from LSMVectorIndexMetadata to a polymorphic method with overrides on all four subclasses, plus a final copyCommonTo() for the shared fields. There is no second field list to keep in sync, which is the point. Per-index RUNTIME state deliberately does not ride along - the dense vector index's build state, the full-text corpus counters - because the new file starts empty and inherited statistics would describe a different set of records.

A user-supplied index name is the one attribute deliberately not carried over: it is unique across the schema and still belongs to the source type, so the copy takes the auto-derived NewType[properties] form rather than colliding with it.

Deliberately out of scope

The other sites that rebuild an index from its own definition - TruncateTypeStatement, DatabaseChecker (CHECK DATABASE FIX), and both LocalDocumentType propagation paths - still read getMetadata() and so still lose a full-text or geospatial configuration. Each is a distinct user-visible operation that deserves its own regression test and its own blast radius, which is the same reasoning #5723 used to split itself off from #5717; a follow-up issue tracks them. RebuildIndexStatement is already correct - it reconstructs the typed metadata from the persisted JSON - and could now use the new accessor instead, but that is a refactor with no behaviour change.

Tests

Issue5723CopyTypeIndexConfigurationTest (new, 8 cases): page size on LSM_TREE and on HASH (where the value goes back through the validating creation path #5713 added), null strategy, CI collation asserted through a case-insensitive lookup on the copy, full-text analyzer/BM25/operator asserted through an English-stem lookup, geospatial precision asserted through a spatial query, vector dimensions and similarity, and the manual-index-name non-collision. Plus entries == 1 on the copy, which is what catches defect 1.

ImmutableDocumentLazyLoadingInconsistencyTest: propertiesAsMap() and propertiesAsMap(fields) added to the exception-propagation and happy-path accessor lists, and a new case asserting a record straight off iterateType() answers its properties.

Verified locally: com.arcadedb.query.** 10330 tests 0 failures, com.arcadedb.database.** 176 tests 0 failures, com.arcadedb.schema.** + com.arcadedb.index.** 942 tests with one unrelated timing flake (LSMVectorIndexRecoveryTest#vectorNeighborsShouldReturnCorrectCountAfterIncrementalInsertAndRebuild, an inactivity-rebuild deadline assertion, passes in isolation), com.arcadedb.graph.** + com.arcadedb.serializer.** 336 tests 0 failures.

🤖 Generated with Claude Code

https://claude.ai/code/session_01FjD6rXVew2fQhhh8n44GAz

…ords' content, and index entries

`Schema.copyType()` was reported as resetting every index's page size on the copy. It did, and that turned
out to be the least of it: the same thirty lines held three defects, and the two that were not reported are
the ones that made the copy wrong rather than differently tuned.

The copy had no data in its indexes. They were created inside the record-copy transaction, and each bucket's
build runs in its own `joinCurrent=false` transaction, which from inside an enclosing one neither sees the
records still pending in it nor commits the entries it produces. Every index on the copy came out empty, so
any query the planner routed through one answered nothing. The build now runs after the copy has committed.

The copied records were empty. `ImmutableDocument.propertiesAsMap()` was the one accessor of that class that
did not lazy-load: it answered an empty map whenever the record had not been materialised, which is the state
of every record from `iterateType()` / `scanBucket()`. `copyType()` created the right number of records, each
with no properties. Same silent emptiness for a `DetachedDocument` built off a scan.

And the index definitions were rebuilt from three attributes. The three-argument `createTypeIndex` overload
kept the index type, the uniqueness flag and the property list, and defaulted the tuned page size, the null
strategy, the collations, and the whole type-specific configuration - a copied FULL_TEXT index ranked with the
default analyzer, a copied GEOSPATIAL one dropped to the default resolution, a copied LSM_VECTOR one came up
with dimensions 0.

Carrying a definition into a new index file gets an accessor of its own, `IndexInternal.getMetadataForNewFile()`,
alongside the `getPageSizeForNewFile()` #5713 introduced. `getMetadata()` cannot answer it for the wrapper index
types: the full-text analyzers live on `FullTextIndexMetadata` and the geospatial resolution on plain fields,
while `getMetadata()` delegates to the underlying LSM-Tree. `IndexMetadata.copy()` is now polymorphic across all
five metadata classes, so no field list can be forgotten; per-index runtime state (the vector build state, the
full-text corpus counters) deliberately does not ride along, since the new file starts empty.
@mergify

mergify Bot commented Aug 1, 2026

Copy link
Copy Markdown
Contributor

Tick the box to add this pull request to the merge queue (same as @mergifyio queue).

  • Queue this pull request

@codacy-production

codacy-production Bot commented Aug 1, 2026 •

Copy link
Copy Markdown

Up to standards ✅

🟢 Issues 0 issues

Results:
0 new issues

View in Codacy

🟢 Metrics 4 complexity

Metric Results
Complexity 4

View in Codacy

🟢 Coverage 82.81% diff coverage · -6.83% coverage variation

Metric Results
Coverage variation ✅ -6.83% coverage variation
Diff coverage ✅ 82.81% diff coverage

View coverage diff in Codacy

Coverage variation details
Coverable lines Covered lines Coverage
Common ancestor commit (57b73c2) 150808 115267 76.43%
Head commit (0867503) 182975 (+32167) 127358 (+12091) 69.60% (-6.83%)

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 (#5734) 64 53 82.81%

Diff coverage is the percentage of lines that are covered by tests out of the coverable lines that the pull request added or modified: <covered lines added or modified>/<coverable lines added or modified> * 100%

NEW Get contextual insights on your PRs based on Codacy's metrics, along with PR and Jira context, without leaving GitHub. Enable AI reviewer
TIP This summary will be updated as you push new changes.

@claude

claude Bot commented Aug 1, 2026

Copy link
Copy Markdown

Code Review - PR #5734

Thorough, well-diagnosed change. The write-up traces three distinct defects hiding behind one reported symptom, each is root-caused rather than patched, and the regression coverage is genuinely strong (behavioural assertions like the English-stem lookup and the spatial query prove the effect of the carried-over configuration, not just a persisted attribute). A few observations, mostly confirmations with a couple of things worth a conscious decision.

Design - the parts I like

  • IndexMetadata.copy() made polymorphic with a final copyCommonTo() for the shared fields is the right call: it removes the second field-list that has to be kept in sync, which is exactly how the page size (HASH index silently corrupts when created with a page size above 65536 (16-bit slot offsets, no validation) #5713) and the rest drifted away in the first place. All four subclasses plus the base are covered (verified: FullText, Geo, LSMSparseVector, LSMVector all extend IndexMetadata directly, no missing leaf).
  • getMetadataForNewFile() as the companion of getPageSizeForNewFile() is a clean, discoverable pattern, and the Javadoc explaining why getMetadata() cannot answer for the wrapper indexes is excellent.
  • Moving the index build out of the record-copy transaction is the correct fix for the empty-index defect, and the inline comment captures the joinCurrent=false reasoning precisely.

Things worth a deliberate decision

  1. propertiesAsMap() now propagates where it previously swallowed. For a record with rid != null but buffer == null, the method now calls checkForLazyLoading(), which hits getBucketById(...).getRecord(rid). If that RID no longer resolves (e.g. a record deleted between a scan handing out the immutable and this read), it throws instead of returning an empty map as before. This is consistent with get()/has()/toJSON() and aligns with the ImmutableDocument: loading exception always turned into null in specific method only #2560 contract, so it looks intended - just flagging that any caller relying on "empty map for a vanished record" changes behaviour. The two new entries in the exception-propagation list cover the security-filter path; a case for the genuinely-unresolvable-RID path would nail down the intent.

  2. copyType() is now non-atomic across a wider window. Records commit, then each index builds in its own transaction. On an index-build failure the catch calls dropType(newTypeName), which does clean up the committed buckets/records, so there is no leak - but the operation now has two commit boundaries instead of one. Worth a one-line note in the method Javadoc that partial failure is handled by dropping the copy, since that is the safety net the correctness of the move depends on.

  3. LSMTreeGeoIndex.getMetadataForNewFile() is inconsistent with its siblings. The full-text and sparse-vector overrides just return their stored metadata instance; the geo override reconstructs a fresh GeoIndexMetadata and hand-copies collations/typeIndexName from the base - which copyIndexDefinition() then immediately redoes via sourceMetadata.copy(). Harmless (and correct), but the reconstruction is redundant work and reads differently from the other three. If GeoIndexMetadata is always the persisted metadata type here, returning it directly would match the pattern.

Minor

  • In propertiesAsMap(), checkForLazyLoading() already repositions the buffer to propertiesStartingPosition, then the method repositions again on the next line. Negligible cost, just noting the double position().

Test coverage

Strong. The 8 cases plus the lazy-loading regression cover page size (LSM_TREE and the HASH validating path), null strategy, CI collation, full-text analyzer/BM25, geospatial precision, vector dimensions, and the manual-name non-collision, and defect 1 (empty indexes) is asserted both via countEntries()==1 and behaviourally through the stem/spatial lookups. No @Tag needed - none are slow.

The deferred carry-over sites (TRUNCATE TYPE, CHECK DATABASE FIX, bucket/sub-type propagation) remain latent for full-text/geo, but scoping them out with a tracking follow-up is reasonable and the reasoning is sound.

Overall: solid fix, good tests, ready modulo the small clarifications above.

Automated review by Claude - please verify independently.

…pe atomicity contract, unresolvable-RID test

Review follow-ups on #5734.

`LSMTreeGeoIndex.getMetadataForNewFile()` reassembled the definition by hand, copying the base fields the
metadata hierarchy already knows how to copy. Moved into `GeoIndexMetadata.from(base, precision, tokenization)`,
where `copyCommonTo()` is reachable, so the wrapper reads like its full-text and sparse-vector siblings. It
cannot simply return a stored instance the way they do: this class holds the resolution and the layout as plain
fields and its underlying LSM-Tree carries only a base `IndexMetadata`, which is why the override exists at all.

`copyType()` now documents that it is deliberately not atomic. The index build has to run outside the
record-copy transaction to see the records, which puts a commit boundary mid-operation; the `catch` that drops
the new type is the safety net that makes that acceptable, and the source type is only ever read.

Added a case asserting `propertiesAsMap()` REPORTS a record whose RID no longer resolves rather than answering
an empty map. That is the deliberate half of the lazy-loading change - the same contract the other accessors of
the class have carried since #2560 - and it was worth pinning down rather than leaving to be inferred.

Left as is: the second `buffer.position()` in `propertiesAsMap()` reads redundant but is not.
`checkForLazyLoading()` leaves the buffer at 0 when an after-read event returns a different record and the
buffer is re-serialised, so removing it would break the encryption path. Commented in place so it survives the
next reader.
@claude

claude Bot commented Aug 1, 2026

Copy link
Copy Markdown

Code Review

Reviewed the full diff against the source. This is a strong, carefully-scoped fix. The root-cause analysis (three distinct defects in the same ~30 lines) is accurate, and each fix is targeted rather than papered over. A few notes below, mostly praise plus a couple of minor observations.

What's done well

  • Correctness of the ordering fix. Moving the index build out of the record-copy transaction is the right call: TypeIndexBuilder.create() opens its own joinCurrent=false transactions, so building inside the enclosing tx genuinely could not see pending records nor commit its entries. The inline comment at the call site (LocalSchema.java:640) explains why the commit boundary exists, which is exactly the kind of non-obvious rationale that should be captured in-code.
  • getMetadataForNewFile() design. Generalizing the accessor instead of threading getPageSizeForNewFile() through is the correct generalization: getMetadata() delegates to the underlying LSM-Tree for the wrapper index types (full-text, geospatial, sparse-vector) and structurally cannot answer with the type-specific config. Making IndexMetadata.copy() polymorphic across all five metadata classes with a shared copyCommonTo() removes the second field-list-to-keep-in-sync, which was the actual source of the bug. I confirmed all four subclasses now override copy.
  • Deliberate exclusions are principled. Not carrying runtime state (build state, corpus counters) into an empty file, and not reusing the unique user-supplied index name, are both correct and documented. metadata.typeIndexName = null guarantees the auto-derived NewType[properties] name.
  • Latent fix bonus. LSMVectorIndexMetadata.copy() switching to copyCommonTo() means typeIndexName now rides along where it previously didn't - a quiet improvement for the LSMVectorIndex and TruncateTypeStatement callers, and harmless for copyType() since it nulls the name afterward.
  • Test coverage is excellent. Behavioral assertions (CI-collation lookup, English-stem match, spatial query) rather than attribute-only checks, plus countEntries()/countdown == 1 which is what actually catches defect build support #1. HASH page-size going back through the validating creation path (HASH index silently corrupts when created with a page size above 65536 (16-bit slot offsets, no validation) #5713) is a nice edge case.

Minor observations (non-blocking)

  1. propertiesAsMap() is now a behavior change, not purely additive. For a record whose RID no longer resolves, it now throws RecordNotFoundException where it previously returned Collections.emptyMap(). This is the correct contract (consistent with #2560 and the other accessors) and you've added a test pinning it - but it's worth flagging as a potential compatibility surprise for any external caller that relied on the old silent-empty behavior. I checked the in-tree callers (GraphEngine, BinarySerializer, DetachedDocument, ScanWithFilterStep, MergeStep) and none appears to depend on the old behavior, so the blast radius looks contained.

  2. Misleading log message. LocalSchema.java:648 still logs "Error on renaming type '%s' into '%s'" inside copyType(). As the PR description itself notes, there is no rename happening here - this is a copy. Since you're already in this method, consider correcting the wording to "Error on copying type ..." to avoid future confusion during incident triage.

  3. collations shared by reference in copyCommonTo(). Documented as safe (assigned wholesale, never mutated in place). Agreed it's low-risk given current usage; just noting the aliasing exists so a future in-place mutation of collations would be a footgun. Not worth changing now.

Scope

Leaving TRUNCATE TYPE, CHECK DATABASE FIX, and the bucket/subtype propagation paths for a follow-up is a reasonable call given each has its own blast radius and deserves its own regression test - the same splitting rationale #5723 used. The getMetadataForNewFile() accessor you've added is exactly what those sites will need.

I was unable to run the compile/test suite in this environment (build command not permitted here), so I'm relying on the local run reported in the description (com.arcadedb.query.**, database.**, schema.**, index.**, graph.**, serializer.** green, one unrelated timing flake). The code changes are self-consistent and I found no compile-level concerns on inspection.

Nice work - the fix generalizes correctly and the tests assert behavior, not just fields.

Automated review by Claude Code.

Review follow-up on #5734. The SEVERE log in copyType() read "Error on renaming type", which is what sent
issue #5723 to a renameType() that does not exist - a rename goes through LocalDocumentType.rename(), renames
buckets in place, and never recreates an index. Nothing here renames anything and the source type is still
there afterwards, so the message now says what happened. The genuinely-renaming messages in LocalDocumentType
and LocalVertexType are correct as they stand and are left alone.
@claude

claude Bot commented Aug 1, 2026

Copy link
Copy Markdown

Review: #5734 - copyType keeps index definitions, record content, and index entries

Reviewed the full diff and traced the touched paths (LocalSchema.copyType, copyIndexDefinition, the getMetadataForNewFile() overrides, IndexMetadata.copy/copyCommonTo, and ImmutableDocument.propertiesAsMap). This is a strong, well-diagnosed PR: three genuinely distinct defects behind one report, each fix targeted and each backed by a behavioural assertion rather than just an attribute check. The getMetadataForNewFile() / polymorphic copy() design is the right generalization over the "just pass the page size" suggestion, and the rationale is documented where a future reader will need it.

A few observations, mostly minor.

1. Test coverage gap: the motivating conversion is document -> vertex, but no test copies to a vertex type

Every case in Issue5723CopyTypeIndexConfigurationTest uses LocalDocumentType.class. The scenario the issue and the PR description both cite (copyType(..., LocalVertexType.class, ...)) goes through the other branch in the record-copy loop (database.newVertex(...) at LocalSchema.java:618), which is never exercised here. The index-definition fixes are model-agnostic so they would hold, but a single LocalVertexType case (even just asserting countEntries() == 1 and one property survived) would cover the exact path that prompted the fix and guard the vertex record-creation branch. Low effort, closes the gap.

2. copyCommonTo now propagates typeIndexName through the two pre-existing .copy() callers

Moving typeIndexName into copyCommonTo() is correct for copyType() (which then nulls it), but LSMVectorIndexMetadata.copy() previously carried only collations, and it has two other callers that now inherit typeIndexName too: LSMVectorIndex.java:748 (index creation) and TruncateTypeStatement.java:176 (truncate/rebuild). This is almost certainly benign - and arguably more correct, since a manually-named vector index would now keep its name through truncate - but it is a behaviour change outside copyType's blast radius, in a path the PR explicitly lists as "out of scope / unchanged." Worth a quick confirm that truncating a manually-named LSM_VECTOR index still round-trips its name cleanly; if it does, it is a free bonus, but it is currently untested.

3. Dead-but-harmless branch in TypeIndex.getMetadataForNewFile()

TypeIndex.metadata is only ever null (both setMetadata overloads throw, and the constructor never assigns it), so the if (metadata != null) return metadata; guard cannot fire - the method always delegates to the first underlying index, which is what makes the full-text/geo/vector configs come through correctly. It mirrors the existing getMetadata() shape so I would not change it, just noting the branch is unreachable in case it reads as load-bearing.

4. Non-atomicity is well handled

The commit boundary in the middle of the operation is unavoidable (the index build must see committed records) and the catch -> dropType cleanup correctly leaves the schema as it was found on failure. Good that this is spelled out in the Javadoc rather than left implicit. No concern here.

Correctness spot-checks that held up

  • propertiesAsMap / propertiesAsMap(String...): the buffer == null && rid == null guard plus checkForLazyLoading() plus the post-load buffer == null re-check correctly preserves the ImmutableDocument: loading exception always turned into null in specific method only #2560 exception-propagation contract while fixing the silent-empty case; the extra re-check comment (encryption/after-read path replacing the buffer) is accurate.
  • withMetadata after withPageSize/withNullStrategy in copyIndexDefinition: no clobbering - page size and null strategy are separate builder fields, and withCollations writes straight into metadata.collations, so the copied collations survive create().
  • Builder ordering: withType() first (it may swap in a type-specific subclass), then configuring the returned reference - correct.

Nice work overall. The two items worth acting on before merge are the vertex-type test case (#1) and a sanity check on the vector-truncate name behaviour (#2); the rest are notes.

…index name across a truncate

Review follow-ups on #5734, both closing coverage gaps rather than changing behaviour.

The conversion that motivates copyType() is document to vertex, and it takes the other branch of the
record-copy loop, which every existing case missed: they all copy to a document type. The new case asserts the
copy is a vertex type, its index is populated, and the record content came across.

`LSMVectorIndexMetadata.copy()` carried only the collations before this PR and now goes through
`copyCommonTo()`, which also carries the user-supplied index name. That reaches one caller outside copyType():
TRUNCATE TYPE, which drops and recreates the index from its own definition. Confirmed by test that a manually
named LSM_VECTOR index now keeps its name across a truncate along with its dimensions and similarity, where it
previously reverted to the auto-derived form. Mutation-checked: dropping the typeIndexName line from
copyCommonTo() makes the new case fail.

Left alone: the `metadata != null` branch in TypeIndex.getMetadataForNewFile() is indeed unreachable today -
both setMetadata overloads throw - but it mirrors getMetadata() exactly, and the two should not drift if that
field ever becomes assignable.
@claude

claude Bot commented Aug 1, 2026

Copy link
Copy Markdown

Review: #5734 - copyType keeps index definitions, record content, and index entries

Reviewed the full diff plus the surrounding call sites (LocalSchema.copyType, ScanWithFilterStep, TypeIndexBuilder, IndexBuilder, the .copy()/getMetadataForNewFile() callers). This is a strong PR: three genuine defects fixed, each with a clear root-cause and a behavioral regression test rather than an attribute-equality check. A few notes below, none blocking.

What I verified as correct

  • Index build reorder. Moving the copyIndexDefinition loop out of the record-copy transaction is right: TypeIndexBuilder.create() opens its own joinCurrent=false transactions per bucket, so inside the enclosing tx it saw neither the pending records nor committed its own entries. At the new call site the record-copy tx has already committed and finally only rolls back if still active, so create() runs with no active tx and sees the data. countEntries() == 1 on the copy is the right assertion to catch it.
  • propertiesAsMap() lazy-load. The new guard database == null || (buffer == null && rid == null) correctly routes to checkForLazyLoading() when a RID is present, and the post-load buffer == null re-check preserves the ImmutableDocument: loading exception always turned into null in specific method only #2560 exception-propagation contract (deleted RID throws, after-read-filtered returns empty). Consistent with get()/has()/getPropertyNames()/toJSON().
  • withMetadata vs withPageSize/withNullStrategy/withUnique ordering. pageSize, nullStrategy, unique are separate builder fields from metadata, and createBucketIndex passes them independently, so calling withMetadata() last does not clobber them. Also good catch keeping the withType() return reference, since it can swap in a type-specific builder subclass.
  • Shared collations reference in copyCommonTo. Confirmed the field is only ever assigned wholesale, never mutated in place (the only in-place .add in the codebase is on a local var in CreateIndexStatement), so sharing rather than cloning is safe. Good that the comment states the invariant.
  • getPageSizeForNewFile() instead of getPageSize() for the HASH-index-predating-HASH index silently corrupts when created with a page size above 65536 (16-bit slot offsets, no validation) #5713 case, tested explicitly.

Worth a second look (non-blocking)

  1. Side effect of copyCommonTo now carrying typeIndexName. Because LSMVectorIndexMetadata.copy() previously copied only collations, routing it through copyCommonTo() now also propagates the user index name to the other two callers of the typed .copy(): TruncateTypeStatement (you test this - a truncated manually-named vector index keeps its name) and LSMVectorIndex create/load at line 748. The latter is a self-retarget during construction so it's harmless, but the TRUNCATE change is a real user-visible behavior change riding along with this PR. It's tested and arguably a fix, so fine - just flagging it's slightly broader than "copyType" and lives a bit outside the stated scope.

  2. propertiesAsMap fix also silently repairs a latent projection bug. ScanWithFilterStep:104 calls immutableDoc.propertiesAsMap(fieldNames) after the WHERE eval. For a query whose WHERE never touches the record buffer (e.g. no WHERE, projected columns), the buffer would still be null there and the old code returned an empty map, i.e. an empty projection. This PR fixes that too, but there is no direct query-level regression test for that path - a SELECT a, b FROM T with no WHERE against an ImmutableDocument would lock it in.

  3. Failure cleanup. The catch -> dropType(newTypeName) correctly rolls back partially-built copies, and non-atomicity is well documented. If dropType itself throws, it is logged WARNING and the original exception rethrown, potentially leaving a partial type - acceptable and consistent with the existing pattern, just noting the residual window.

Minor / style

  • toArray(new String[propertyNames.size()]) in copyIndexDefinition - new String[0] is marginally faster on modern JVMs, but this matches the surrounding file's style, so no change needed.

Tests

Excellent coverage - page size (LSM + HASH validating path), null strategy, CI collation asserted through a case-insensitive lookup, full-text analyzer/BM25 asserted through an English-stem query, geospatial precision through a spatial query, vector dimensions/similarity, manual-name non-collision, the vertex-conversion branch, and entries == 1. The ImmutableDocument additions correctly extend both the throws-list and the happy-path list.

Overall: well-reasoned, well-tested, ready to merge once the maintainer is comfortable with the TRUNCATE-name behavior change noted in (1).

…release notes

Review follow-up on #5734. Routing LSMVectorIndexMetadata.copy() through the shared copyCommonTo() also carries
the user-supplied index name, and that reaches TRUNCATE TYPE: a manually named LSM_VECTOR index now keeps its
name across a truncate instead of coming back auto-derived. It is a fix and it is covered by a test, but it is
the one effect of this PR outside copyType(), so it belongs in the notes rather than being left for someone to
discover.
@lvca

lvca commented Aug 1, 2026

Copy link
Copy Markdown
Member Author

Responses to the latest review.

(1) The TRUNCATE-name behaviour change is real, is a fix, and is covered by truncatingAManuallyNamedVectorIndexKeepsItsName (mutation-checked: dropping the typeIndexName line from copyCommonTo() makes it fail). It is now also written up in docs/release-26.8.1.md rather than left to be discovered - it is the one effect of this PR outside copyType(). Worth noting the asymmetry it removes: every other index type already kept its manual name through a truncate, because TruncateTypeStatement hands the original metadata object straight back and only LSM_VECTOR goes through .copy(). So this aligns vector with the rest rather than introducing a new behaviour.

(2) The ScanWithFilterStep projection push-down is not reachable, so there is nothing to regress-test. I wrote the suggested SELECT a, b FROM T case and it passed with the propertiesAsMap fix reverted, which sent me to the planner rather than to the test:

SelectExecutionPlanner.computeProjectedProperties() returns null whenever a WHERE clause is present:

// Extract from WHERE clause
if (info.whereClause != null) {
  // WHERE can reference arbitrary fields, so we need all properties if we can't analyze it
  // For safety, return null to indicate all properties needed
  return null;
}

ScanWithFilterStep only exists when there is a WHERE clause, so projectedProperties != null and whereClause != null cannot both hold in it - the if (projectedProperties != null && record instanceof ImmutableDocument) branch is dead code today. EXPLAIN SELECT a, b FROM Doc WHERE 1 = 1 confirms it empirically: the plan is SCAN WITH FILTER with no [projected: ...] marker, and the columns come from a separate CALCULATE PROJECTIONS step.

I removed the test rather than keep one that asserts nothing. The dead branch is pre-existing and out of scope here; it would be worth either wiring the push-down up or deleting it, separately.

(3) dropType throwing during cleanup - agreed, residual window, consistent with the existing pattern, left alone.

(4) new String[propertyNames.size()] - left as is to match the surrounding file.

@claude

claude Bot commented Aug 1, 2026

Copy link
Copy Markdown

Review: #5734 - copyType keeps index definitions, record content, and index entries

I read the full diff and traced the touched paths (LocalSchema.copyType, copyIndexDefinition, the getMetadataForNewFile/copy polymorphism, and ImmutableDocument.propertiesAsMap). This is a high-quality, carefully scoped fix. The PR description accurately reflects what the code does. Summary: looks solid, no blocking issues found. A few observations and one thing worth confirming.

Strengths

  • Root-causing beyond the reported symptom. The three defects are genuinely distinct (empty index entries from the in-transaction build, empty records from the one non-lazy-loading accessor, and the three-attribute rebuild), and each is fixed at the right layer rather than papered over at the call site.
  • getMetadataForNewFile() / IndexMetadata.copy() generalization is the correct abstraction. Making copy() polymorphic with a final copyCommonTo() for shared fields removes the "second field list to keep in sync" failure mode that caused this class of bug. The wrapper-type overrides (full-text, geo, sparse/dense vector) each read config that getMetadata() cannot reach through the underlying LSM-Tree - well justified in the Javadoc.
  • ImmutableDocument.propertiesAsMap() now matches the lazy-loading contract of get()/has()/toJSON(), and the buffer == null && rid == null guard plus the post-checkForLazyLoading() re-check (with the encryption/after-read comment) preserve the ImmutableDocument: loading exception always turned into null in specific method only #2560 exception-propagation contract. The added entries in ImmutableDocumentLazyLoadingInconsistencyTest's accessor lists lock that in.
  • Test coverage is excellent - 8 cases asserting on behavior (case-insensitive lookup, English-stem match, spatial query) rather than only persisted attributes, plus countEntries() == 1 which is what catches the empty-index defect, plus the vertex-branch case that mirrors the real doc->vertex conversion.
  • Honest scope statement. Explicitly leaving TRUNCATE TYPE, CHECK DATABASE FIX, and the bucket/subtype propagation paths for a follow-up (they still read getMetadata()) is the right call, and the reasoning matches how Renaming a type resets every index's page size to the default #5723 split from fix(engine) #5713: a HASH index refuses a page size its bucket pages cannot address #5717.

Observations / things to confirm

  1. copyType() is now non-atomic across a commit boundary (records commit, then indexes build in their own transactions). This is unavoidable given TypeIndexBuilder.create()'s joinCurrent=false, and the catch drops newType on any failure, so a failed copy leaves the schema clean. The Javadoc documents this well. Worth being aware that a hard crash between the record commit and the index build leaves a populated-but-unindexed copy - acceptable and consistent with the documented non-atomicity, but a note in the follow-up issue wouldn't hurt.

  2. propertiesAsMap() has wide reach. It is called from DetachedDocument.init, GraphEngine, BinarySerializer, ScanWithFilterStep, MergeStep, etc. The change means an unmaterialized-but-stale record (buffer null, rid present, record deleted) now throws RecordNotFoundException where it previously returned an empty map silently. This is the intended contract (and the correct one), but it is a behavioral change beyond copyType(). The broad accessor already behaved this way for get()/toJSON(), so callers robust to those are fine - the full-reactor test runs cited in the description are the reassurance here.

  3. Bundled behavior change in TRUNCATE TYPE. Routing LSMVectorIndexMetadata.copy() through copyCommonTo() means a manually named LSM_VECTOR index now keeps its name across a truncate. This is a reasonable improvement (and arguably a latent bug fix), is called out in the description, and is covered by truncatingAManuallyNamedVectorIndexKeepsItsName. Only flagging it because it is the one change reaching outside the PR's stated primary target - it's fine.

Style / minor

  • copyIndexDefinition correctly calls withType() first and keeps the returned builder reference (the comment explains the subclass swap) - good catch, easy to get wrong.
  • Uses final throughout, imports rather than FQNs, assertThat(...) style, and JSONObject/JSONArray conventions per CLAUDE.md. Benchmark/slow tagging is not needed here (functional tests, small fixtures).

Nice work - the diagnosis-by-experiment note ("moving the loop back inside the transaction reproduces entries=0 exactly") is exactly the kind of verification the project guidelines ask for.

@lvca

lvca commented Aug 1, 2026

Copy link
Copy Markdown
Member Author

Follow-up filed as #5742: the four remaining carry-over sites (TRUNCATE TYPE, CHECK DATABASE FIX, and both LocalDocumentType propagation paths), each of which the new getMetadataForNewFile() accessor is what they need. It also carries the crash-window note from observation (1) - a hard crash between the record commit and the index build leaves a populated-but-unindexed copy, which the catch/dropType path cannot cover.

@codecov

codecov Bot commented Aug 2, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 68.75000% with 20 lines in your changes missing coverage. Please review.
✅ Project coverage is 67.65%. Comparing base (57b73c2) to head (0867503).
⚠️ Report is 4 commits behind head on main.

Files with missing lines Patch % Lines
.../java/com/arcadedb/database/ImmutableDocument.java 25.00% 2 Missing and 4 partials ⚠️
.../arcadedb/schema/LSMSparseVectorIndexMetadata.java 0.00% 5 Missing ⚠️
...ne/src/main/java/com/arcadedb/index/TypeIndex.java 20.00% 2 Missing and 2 partials ⚠️
...src/main/java/com/arcadedb/schema/LocalSchema.java 87.50% 1 Missing and 1 partial ⚠️
.../arcadedb/index/fulltext/LSMTreeFullTextIndex.java 0.00% 0 Missing and 1 partial ⚠️
...adedb/index/sparsevector/LSMSparseVectorIndex.java 0.00% 1 Missing ⚠️
...ain/java/com/arcadedb/schema/GeoIndexMetadata.java 90.00% 0 Missing and 1 partial ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #5734      +/-   ##
==========================================
+ Coverage   67.62%   67.65%   +0.03%     
==========================================
  Files        1776     1776              
  Lines      150808   150951     +143     
  Branches    32002    32026      +24     
==========================================
+ Hits       101978   102125     +147     
+ Misses      35579    35551      -28     
- Partials    13251    13275      +24     

☔ 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 4140df2 into main Aug 2, 2026
31 checks passed
@lvca
lvca deleted the worktree-issue-5723-rename-type-index-pagesize branch August 2, 2026 16:07
robfrank pushed a commit that referenced this pull request Aug 14, 2026
…ords' content, and index entries (#5734)

* fix(engine) #5723: a copied type keeps its index definitions, its records' content, and index entries

`Schema.copyType()` was reported as resetting every index's page size on the copy. It did, and that turned
out to be the least of it: the same thirty lines held three defects, and the two that were not reported are
the ones that made the copy wrong rather than differently tuned.

The copy had no data in its indexes. They were created inside the record-copy transaction, and each bucket's
build runs in its own `joinCurrent=false` transaction, which from inside an enclosing one neither sees the
records still pending in it nor commits the entries it produces. Every index on the copy came out empty, so
any query the planner routed through one answered nothing. The build now runs after the copy has committed.

The copied records were empty. `ImmutableDocument.propertiesAsMap()` was the one accessor of that class that
did not lazy-load: it answered an empty map whenever the record had not been materialised, which is the state
of every record from `iterateType()` / `scanBucket()`. `copyType()` created the right number of records, each
with no properties. Same silent emptiness for a `DetachedDocument` built off a scan.

And the index definitions were rebuilt from three attributes. The three-argument `createTypeIndex` overload
kept the index type, the uniqueness flag and the property list, and defaulted the tuned page size, the null
strategy, the collations, and the whole type-specific configuration - a copied FULL_TEXT index ranked with the
default analyzer, a copied GEOSPATIAL one dropped to the default resolution, a copied LSM_VECTOR one came up
with dimensions 0.

Carrying a definition into a new index file gets an accessor of its own, `IndexInternal.getMetadataForNewFile()`,
alongside the `getPageSizeForNewFile()` #5713 introduced. `getMetadata()` cannot answer it for the wrapper index
types: the full-text analyzers live on `FullTextIndexMetadata` and the geospatial resolution on plain fields,
while `getMetadata()` delegates to the underlying LSM-Tree. `IndexMetadata.copy()` is now polymorphic across all
five metadata classes, so no field list can be forgotten; per-index runtime state (the vector build state, the
full-text corpus counters) deliberately does not ride along, since the new file starts empty.

* fix(engine) #5723: address code review - geo metadata factory, copyType atomicity contract, unresolvable-RID test

Review follow-ups on #5734.

`LSMTreeGeoIndex.getMetadataForNewFile()` reassembled the definition by hand, copying the base fields the
metadata hierarchy already knows how to copy. Moved into `GeoIndexMetadata.from(base, precision, tokenization)`,
where `copyCommonTo()` is reachable, so the wrapper reads like its full-text and sparse-vector siblings. It
cannot simply return a stored instance the way they do: this class holds the resolution and the layout as plain
fields and its underlying LSM-Tree carries only a base `IndexMetadata`, which is why the override exists at all.

`copyType()` now documents that it is deliberately not atomic. The index build has to run outside the
record-copy transaction to see the records, which puts a commit boundary mid-operation; the `catch` that drops
the new type is the safety net that makes that acceptable, and the source type is only ever read.

Added a case asserting `propertiesAsMap()` REPORTS a record whose RID no longer resolves rather than answering
an empty map. That is the deliberate half of the lazy-loading change - the same contract the other accessors of
the class have carried since #2560 - and it was worth pinning down rather than leaving to be inferred.

Left as is: the second `buffer.position()` in `propertiesAsMap()` reads redundant but is not.
`checkForLazyLoading()` leaves the buffer at 0 when an after-read event returns a different record and the
buffer is re-serialised, so removing it would break the encryption path. Commented in place so it survives the
next reader.

* fix(engine) #5723: copyType's failure log says copying, not renaming

Review follow-up on #5734. The SEVERE log in copyType() read "Error on renaming type", which is what sent
issue #5723 to a renameType() that does not exist - a rename goes through LocalDocumentType.rename(), renames
buckets in place, and never recreates an index. Nothing here renames anything and the source type is still
there afterwards, so the message now says what happened. The genuinely-renaming messages in LocalDocumentType
and LocalVertexType are correct as they stand and are left alone.

* test(engine) #5723: cover the document-to-vertex copy and the vector index name across a truncate

Review follow-ups on #5734, both closing coverage gaps rather than changing behaviour.

The conversion that motivates copyType() is document to vertex, and it takes the other branch of the
record-copy loop, which every existing case missed: they all copy to a document type. The new case asserts the
copy is a vertex type, its index is populated, and the record content came across.

`LSMVectorIndexMetadata.copy()` carried only the collations before this PR and now goes through
`copyCommonTo()`, which also carries the user-supplied index name. That reaches one caller outside copyType():
TRUNCATE TYPE, which drops and recreates the index from its own definition. Confirmed by test that a manually
named LSM_VECTOR index now keeps its name across a truncate along with its dimensions and similarity, where it
previously reverted to the auto-derived form. Mutation-checked: dropping the typeIndexName line from
copyCommonTo() makes the new case fail.

Left alone: the `metadata != null` branch in TypeIndex.getMetadataForNewFile() is indeed unreachable today -
both setMetadata overloads throw - but it mirrors getMetadata() exactly, and the two should not drift if that
field ever becomes assignable.

* docs(engine) #5723: state the TRUNCATE TYPE index-name change in the release notes

Review follow-up on #5734. Routing LSMVectorIndexMetadata.copy() through the shared copyCommonTo() also carries
the user-supplied index name, and that reaches TRUNCATE TYPE: a manually named LSM_VECTOR index now keeps its
name across a truncate instead of coming back auto-derived. It is a fix and it is covered by a test, but it is
the one effect of this PR outside copyType(), so it belongs in the notes rather than being left for someone to
discover.

(cherry picked from commit 4140df2)
tae898 pushed a commit to humemai/arcadedb-embedded-python that referenced this pull request Aug 29, 2026
…ite (ArcadeData#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 ArcadeData#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.
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.

Renaming a type resets every index's page size to the default

1 participant