Skip to content

fix(#9506): an LSM_VECTOR build over a populated index replaces each record's vector instead of adding a second one - #9591

Merged
robfrank merged 3 commits into
mainfrom
fix/9506-lsm-vector-build-populated-duplicates
Oct 9, 2026
Merged

robfrank merged 3 commits into
mainfrom
fix/9506-lsm-vector-build-populated-duplicates

Conversation

@robfrank

@robfrank robfrank commented Oct 9, 2026 •

Copy link
Copy Markdown
Collaborator

Closes #9506

Summary

LSMVectorIndex.build() over an index that already held entries queued a fresh ADD per record and never retired the record's committed vector id, so every record ended with two live ids: countEntries() doubled, a delete then tombstoned two ids per record, and a search (whose graph is keyed by RID) kept one of them and disagreed with the count - which is what made the nodes of #9428's cluster disagree. The bulk load now captures, once, whether the index starts populated; when it does, every record that already has a live vector id gets a REMOVE queued on the build's transaction before its ADD. The commit replays every REMOVE before any ADD (TransactionIndexContext.commit()), so the record's committed ids are tombstoned and the ADD writes its one fresh id, in the same chunk. A build over an empty index (every schema path: CREATE INDEX, REBUILD INDEX, which drops and recreates) pays nothing.

The REMOVE is queued under a NaN-filled key on purpose. The transaction keeps one entry per (key, RID), so a REMOVE under the same key as the following ADD is displaced by it and never reaches the index. The record's own vector is therefore the wrong key, and so is removalKey()'s all-zero placeholder: an all-zero vector is a valid embedding under EUCLIDEAN (#8962). NaN components are refused by put() before anything is queued, so no ADD key can collide. Checked by mutation: with a zero-filled key the new engine test fails at 11 entries instead of 10 (the origin record keeps its duplicate).

A side effect: a build now also repairs records that already carry duplicates from an earlier build, because remove() tombstones every live id of the RID.

Completeness

Invariant: after build(), every record of the bucket has exactly one live vector id in the index.

Entry point Status
build(callback, graphCallback) owning its transaction (chunked) fixed, aBuildOverAPopulatedIndexKeepsOneEntryPerRecord
build(batchSize, sharesCallerTransaction=true, cb) inside a caller's transaction fixed, aBuildSharingTheCallersTransactionKeepsOneEntryPerRecord
Build that commits in several chunks (1MB chunk, ~3MB estimated: 2 chunk commits + final, verified by temporary instrumentation) fixed, aBuildOverAPopulatedIndexAcrossSeveralChunksKeepsOneEntryPerRecord
Delete after a populated build fixed, aDeleteAfterABuildOverAPopulatedIndexRemovesExactlyOneEntry
Search after a populated build fixed, aSearchAfterABuildOverAPopulatedIndex... (count asserted before AND after the search)
Follower build on a 3-node cluster, then search, then delete fixed, Issue9506BuildOverPopulatedIndexHATest
CREATE INDEX / REBUILD INDEX (LocalSchema.createBucketIndex, RebuildIndexStatement drop+recreate) argued: always an empty index, the guard is not taken

Test plan

  • Issue9506BuildOverPopulatedIndexTest (engine, new): 3 of 4 red before the fix (20 entries instead of 10, 18 after a delete instead of 9), green after
  • Issue9506BuildOverPopulatedIndexHATest (ha-raft, new)
  • Issue9428FollowerVectorInsertHATest: the TODO(#9506) expectations (2 * BATCH) are now BATCH / BATCH + 1
  • Issue8905VectorBuildHATest, Issue8905BuildWithUnloadedGraphHATest: now assert the exact record count instead of whatever the index reported
  • Whole com.arcadedb.index.vector engine package (148 classes, 636 tests)

The chunking estimate (dimensions * 4 + 32 per record) was left unchanged. A tombstone page entry is at most 21 bytes, and an unquantized vector entry measures ~9, so the estimate still covers both. A first version charged tombstones separately, but that pushed Issue8905VectorBuildCommitsReachTheWrapperTest's one-chunk fixtures over 1MB, so it was reverted.

Coverage

Entry points: see the Completeness table above.

Known gaps: None for the invariant. Out of scope, as with every LSM index build: entries for RIDs that are no longer in the bucket (orphans) are not removed by a build.

Adversarial pass

Not run: this workflow session had no subagent tool to spawn the independent reviewer. The author checked these by hand instead: the REMOVE/ADD key collision (fixed by the NaN key and pinned with the origin record), the undo journal's disjointness assertion (tombstoned ids are pre-existing, allocated ids are new), and the HA replication of the tombstones (the HA tests above).

Review cycles

  • cycle 1: 9dec1e4b7a - claude approved with non-blocking points. Applied: the first test now asserts that the ids from before the build are tombstoned and the new ids are fresh (replace semantics, not only the count) -> f69772414f
  • cycle 2: f69772414f - claude approved with non-blocking points. Applied: a multi-chunk populated build test, and the getBulkLoadChunkSizeBytes javadoc now names the uncharged tombstones as part of what the half-cap headroom absorbs -> 7a641ef8d6. Checked: VectorLocationIndex.size() is the live count, so a fully deleted index does not take the supersede path
  • cycle 3: 7a641ef8d6 - claude: "LGTM pending CI", only non-blocking points, all raised and declined in earlier cycles

Deferred items

  • "getVectorIdsForRid(rid) allocates an int[] for every scanned record on a populated index" (cycles 1-3) - skipped: VectorLocationIndex has no allocation-free per-RID check. The lookup is O(1), and only the rare populated-index build pays for it; the empty-index path (CREATE INDEX, REBUILD INDEX) does not.
  • "A record whose vector property is null ... gets its old ids tombstoned and no replacement ... a small test" (cycles 1-2) - skipped: that state (a live index entry for a record whose vector is null) cannot be built through the public API, because the update that nulls the vector already removes the entry. Tombstoning it is the intended rebuild behaviour.
  • "A test with a quantized index and a small INDEX_BUILD_CHUNK_SIZE_MB over a populated index" (cycles 1-3) - skipped: the replicated chunk is clamped to half the entry cap, and that headroom is now documented to include these tombstones. A worst-case INT8 2-dimension entry plus its tombstone exceeds the estimate by a few bytes per record, which is well inside a 2x margin.
  • "Consider @Tag(\"slow\")" for the multi-chunk test (cycle 3) - skipped: the whole class runs in ~1.4s.

Final state

clean-approval (merge stays with the maintainer)

🤖 Generated with Claude Code

Summary by CodeRabbit

  • Bug Fixes
    • Rebuilding a populated vector index now replaces existing entries instead of creating duplicates, keeping index counts accurate.
    • Vector index rebuilds now maintain consistent results across replicated servers, including when builds are processed in chunks.
    • Deleting a record after a rebuild removes its index entry, and searches return each matching record only once.

…record's vector instead of adding a second one

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
@robfrank robfrank added this to the 26.11.1 milestone Oct 9, 2026
@mergify

mergify Bot commented Oct 9, 2026 •

Copy link
Copy Markdown
Contributor

This pull request does not currently match the merge queue conditions, so it cannot be queued from here. The box comes back if it matches again.

@claude

claude Bot commented Oct 9, 2026

Copy link
Copy Markdown

Review of #9591

The fix is small, well reasoned and well tested. I have no blocking concerns.

What works

  • Capturing existingLocations.size() > 0 once keeps the empty-index path (CREATE INDEX, REBUILD INDEX) at zero extra cost.
  • The NaN-filled supersede key is a good choice. The reasoning is sound: one entry per (key, RID) in the transaction, put() refuses NaN, and an all-zero vector is valid under EUCLIDEAN. The javadoc states it clearly.
  • The tests cover both transaction modes, delete, and search with the count asserted before and after. The mutation check is convincing, and the HA test covers cross-node agreement. Removing the TODO(#9506) expectations from the existing HA tests is the right cleanup.

Points to consider (non-blocking)

  1. Records no longer indexable. If a record already has live ids but its vector is now null or invalid, the REMOVE is queued and the ADD is skipped or throws. Dropping the stale entry is arguably correct. A test for a populated index with a record whose vector was nulled out would pin that down.
  2. Chunk accounting. The comment says the tombstone size is covered by the per-record estimate, and that holds for the typical case. It rests on the headroom argument for quantized indexes with very few dimensions. A test with a quantized populated index and a small chunk size would back that up, but it is not required.
  3. Repeated builds. The first test runs a second build and checks the count. Also asserting that the live ids differ between builds, or that the old ids are tombstoned, would show the replace semantics directly rather than only through the count.
  4. Lookup cost. getVectorIdsForRid allocates an int[] per record on a populated build. That is acceptable for this rare path. If an exists-style check is available on VectorLocationIndex, use it to avoid the allocation.
  5. Style. The comment blocks are long compared with the surrounding code. The CLAUDE.md conventions are otherwise followed: imports, final, and the assertThat style.

Approve from my side, pending CI.

@codacy-production

codacy-production Bot commented Oct 9, 2026 •

Copy link
Copy Markdown

Up to standards ✅

🟢 Issues 0 issues

Results:
0 new issues

View in Codacy

🟢 Coverage 100.00% diff coverage

Metric Results
Coverage variation Report missing for 9fba1561
Diff coverage ✅ 100.00% diff coverage

View coverage diff in Codacy

Coverage variation details
Coverable lines Covered lines Coverage
Common ancestor commit (9fba156) Report Missing Report Missing Report Missing
Head commit (7a641ef) 254922 203870 79.97%

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 (#9591) 9 9 100.00%

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

1 Codacy didn't receive coverage data for the commit, or there was an error processing the received data. Check your integration for errors and validate that your coverage setup is correct.

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

@coderabbitai

coderabbitai Bot commented Oct 9, 2026 •

Copy link
Copy Markdown

Review in Change Stack →

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration
  • Configuration used: defaults
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: cacf9a99-48b4-47ac-912a-80130d531ca0

📥 Commits

Reviewing files that changed from the base of the PR and between 4141f12 and 7a641ef.


📒 Files selected for processing (6)
  • engine/src/main/java/com/arcadedb/index/vector/LSMVectorIndex.java
  • engine/src/test/java/com/arcadedb/index/vector/Issue9506BuildOverPopulatedIndexTest.java
  • ha-raft/src/test/java/com/arcadedb/server/ha/raft/Issue8905BuildWithUnloadedGraphHATest.java
  • ha-raft/src/test/java/com/arcadedb/server/ha/raft/Issue8905VectorBuildHATest.java
  • ha-raft/src/test/java/com/arcadedb/server/ha/raft/Issue9428FollowerVectorInsertHATest.java
  • ha-raft/src/test/java/com/arcadedb/server/ha/raft/Issue9506BuildOverPopulatedIndexHATest.java

Included review availability: This review used your included allowance. Your plan provides up to 4 included reviews per hour; 0 remain after this review.



📝 Walkthrough

Walkthrough

Bulk loading a populated LSM vector index now queues removal of existing vector IDs before adding replacements. Local and HA tests check entry counts and vector behavior after rebuilds.

Changes

Vector index rebuild

Layer / File(s) Summary
Replace existing vectors
engine/src/main/java/com/arcadedb/index/vector/LSMVectorIndex.java
For records with existing vector IDs, bulk loading queues a REMOVE before the ADD. The REMOVE uses a NaN-filled key. The chunk-size comment includes tombstones in its headroom accounting.
Local rebuild checks
engine/src/test/java/com/arcadedb/index/vector/Issue9506BuildOverPopulatedIndexTest.java
Tests check repeated and chunked builds, builds within a caller transaction, deletion after a build, and search results. They verify one live vector ID per record.
HA rebuild checks
ha-raft/src/test/java/com/arcadedb/server/ha/raft/Issue8905BuildWithUnloadedGraphHATest.java, ha-raft/src/test/java/com/arcadedb/server/ha/raft/Issue8905VectorBuildHATest.java, ha-raft/src/test/java/com/arcadedb/server/ha/raft/Issue9428FollowerVectorInsertHATest.java, ha-raft/src/test/java/com/arcadedb/server/ha/raft/Issue9506BuildOverPopulatedIndexHATest.java
Tests assert expected vector-entry counts across servers after builds, searches, inserts, and deletion.

Priority: ➖ Normal

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

Change: Bug fix · Severity of issue fixed: Medium


Merge Risk: ⚪ Minimal · up to 7a641

The populated-index rebuild replacement path has no identified merge-blocking issue. Merge after normal checks.

🚥 Pre-merge checks | ✅ 4 | ❓ 1

❌ Failed checks (1 inconclusive)

Check name Status Explanation Resolution
Docstring Coverage Inconclusive Docstring coverage is 26.32% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 19 functions across 5 files. (1 skipped: … Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check Passed The PR addresses #9506. LSMVectorIndex now detects a populated index, queues a REMOVE for existing vector IDs, and queues the replacement ADD. Commit processing applies removals before additions…
Out of Scope Changes check Passed The changed production code directly implements #9506. The engine tests verify the required replacement behavior. The HA test changes update expectations for the corrected one-entry invariant, and the…
Title check Passed The title clearly describes the main change: populated LSM vector index builds replace existing vectors instead of creating duplicates. It is specific and related to issue #9506.
Description check Passed The description is detailed and covers the change, motivation, related issues, scope, tests, coverage, and known gaps. It does not use the template headings exactly and does not include the required b…

Full details: Docstring Coverage

Explanation

Docstring coverage is 26.32% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 19 functions across 5 files. (1 skipped: 1 too large.)



✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Commit to this branch
  • Create a new PR

🧪 Generate unit tests (beta)
  • Commit to this branch
  • Create a new PR


  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

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

… ids, not only the count

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
@claude

claude Bot commented Oct 9, 2026

Copy link
Copy Markdown

Review

The fix is small, targeted and well reasoned. I read the diff only and did not build or run the tests.

What I like

Points to check (none blocking)

  1. existingLocations.size() > 0: confirm VectorLocationIndex.size() counts live ids and not allocated ids including tombstones. If it counts tombstones, a build over a fully deleted index would take the slow path. That is harmless but wasteful.
  2. A record whose vector property is null, or one that addToIndex skips, now gets its old ids tombstoned and no replacement. That is probably the right behaviour for a rebuild, but no test pins it. A small test with one null-vector record in a populated index would document it.
  3. The tombstone is not charged to the chunk estimate, and the PR explains why (dimensions * 4 + 32 covers it, and the one-chunk fixtures overflow 1MB otherwise). For a quantized index with very few dimensions, the headroom argument depends on getBulkLoadChunkSizeBytes staying at half the cap. A short comment at that method pointing back here would keep the two from drifting apart.
  4. Each record costs a getVectorIdsForRid lookup on a populated index. This is fine for a one-off build, but it would be good to have a rough number for a large bucket (for example 1M records).
  5. Tests: Issue9506BuildOverPopulatedIndexTest covers the owned-transaction and shared-transaction paths, delete, and search. A case where the build spans several chunks over a populated index would pin the "REMOVE and ADD land in the same chunk" claim at the engine level. Today only the HA capped test covers it.

Style matches CLAUDE.md: final usage, imports, AssertJ syntax and no stray System.out. Nice work overall.

…headroom to the uncharged tombstones

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
@claude

claude Bot commented Oct 9, 2026

Copy link
Copy Markdown

Review

Overall this is a well-scoped fix with strong tests. I found no blocking issues.

What I checked

  • The REMOVE is queued under a NaN-filled key. That avoids the (key, RID) displacement by the following ADD, and it avoids the all-zero collision under EUCLIDEAN. put() rejects NaN, so no ADD can collide with it.
  • The empty-index fast path means CREATE INDEX and REBUILD INDEX pay nothing. The guard is captured once, outside the scan.
  • The REMOVE and the ADD land in the same chunk, so a chunk commit can't leave a record with zero or two live ids. The multi-chunk test covers this.
  • The shared-caller-transaction path is covered, and the HA test checks all three nodes after a build, a search and a delete.

Minor suggestions (non-blocking)

  1. getVectorIdsForRid(rid) allocates an int[] for every scanned record on a populated index. If a cheaper existence check exists, use it. Otherwise this is acceptable, since only the populated-index path pays.
  2. The tombstones aren't charged to the chunk-size estimate. The comment justifies this, but a quantized index with very few dimensions and a tight replicated entry cap could get close to the cap. A test with a quantized index and a small INDEX_BUILD_CHUNK_SIZE_MB over a populated index would pin that assumption.
  3. The multi-chunk test (1,500 records of 512 dimensions) may be noticeably long. Consider @Tag("slow") if it is.

LGTM pending CI.

@codecov

codecov Bot commented Oct 9, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 88.88889% with 1 line in your changes missing coverage. Please review.
✅ Project coverage is 77.37%. Comparing base (971a424) to head (7a641ef).
⚠️ Report is 10 commits behind head on main.

Files with missing lines Patch % Lines
...java/com/arcadedb/index/vector/LSMVectorIndex.java 88.88% 0 Missing and 1 partial ⚠️
Additional details and impacted files
@@             Coverage Diff              @@
##               main    #9591      +/-   ##
============================================
- Coverage     77.37%   77.37%   -0.01%     
+ Complexity     4279     4277       -2     
============================================
  Files          2160     2160              
  Lines        222278   222305      +27     
  Branches      47619    47631      +12     
============================================
+ Hits         171990   172007      +17     
+ Misses        32061    32058       -3     
- Partials      18227    18240      +13     

☔ 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.

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.

LSM_VECTOR build() over a populated index appends a second entry per record; nodes then disagree on countEntries after a search or a delete

1 participant