Skip to content

perf(engine) #5588: lay the vector location index out in primitive arrays (~90 -> ~32 bytes per live vector) - #5861

Merged
lvca merged 10 commits into
mainfrom
issue-5588
Aug 7, 2026
Merged

lvca merged 10 commits into
mainfrom
issue-5588

Conversation

@lvca

@lvca lvca commented Aug 6, 2026

Copy link
Copy Markdown
Member

Closes #5588.

What

VectorLocationIndex held one boxed entry per live vector in a ConcurrentHashMap<Integer, VectorLocation> plus a ConcurrentHashMap<RID, int[]> reverse index, retaining ~90 bytes per live vector to carry ~20 bytes of payload. Vector ids are dense and monotonically assigned, so they address arrays directly.

The mapping is now four primitive arrays indexed by vector id - the file offset with its compacted flag packed into one long, the RID's bucket id and position, and one presence bit - at ~21 bytes per id plus 8 to 16 per live vector for the reverse index. A 10M-vector index goes from ~900MB resident to ~320MB, with no per-entry objects at all.

On the measurement in the issue thread

@tae898 measured, with JFR jdk.ObjectCount, VectorLocation at 24 B and RID at 24 B, both exactly 1:1 with the vector count, and read that as the ~90 B figure being high. jdk.ObjectCount reports per class, and those are two of the five contributors the constant enumerates - the other three (ConcurrentHashMap$Node, the boxed java.lang.Integer key, and the ridToVectorIds node with its int[]) are separate lines in the same histogram. The measurement is sound; ~90 B is not refuted by it. Both process findings in that thread are correct and worth keeping: asprof -e alloc --live cannot answer a retained-heap question, and JFR needs no JDK.

This PR stops the number being arguable: estimatedLocationIndexBytes is now summed off the arrays the index has actually allocated instead of live count x a per-entry constant. It steps down ~3x on the same index, which is operator-visible and is in the release note - together with the note that the 3.75x step up in 26.8.1 was an accounting correction and not a regression, which is the point @tae898 raised.

The parts that are load-bearing

The arrays are chunked (128 ids) and a chunk is released as soon as its last live id is tombstoned. Not an optimisation: it is what preserves the property #5516 exists for, that residency follows the live vectors and not the ids handed out. A re-embedding workload hands out 9.3M ids for a 4K live set, and a flat id-indexed array would retain ~190MB where the map it replaces retained ~360KB. aDrainedIdSpaceIsHandedBack fails on a flat array and on a missing release.

Publication is release/acquire on the array element itself, at both levels. A plain element store into an already-published array carries no happens-before edge for a reader that read the enclosing field earlier, and re-publishing the array reference does not create one. On the directory that would mean reading null for a chunk that exists, i.e. dropping a just-inserted vector out of every search.

Three orderings are documented where they are implemented:

  • the offset and its compacted flag share one 64-bit word. applyReplicatedPageUpdate re-points a live id at the compacted file, on a replica, with no index lock held, while searches run; split across two arrays a reader pairs the new flag with the stale offset, and a misaligned read of an INT8/BINARY page parses into a well-formed vector of the right dimension that passes every guard and is scored at the wrong distance. theOffsetAndItsCompactedFlagCannotBeReadFromDifferentGenerations fails within milliseconds on the split layout;
  • a chunk is dropped only after its bits are cleared (asserted), or a reader holding the stale reference resurrects a tombstoned vector;
  • clear() zeroes the live chunks before publishing the empty directory - it is the one path that reuses ids.

The reverse index stores no keys. A candidate slot is verified by reading the id's RID back out of the location arrays, which makes it unable to produce a wrong id (only to miss one) and makes a tombstoned id structurally unreachable rather than something callers re-check. Nothing is ever removed, because a dead slot is already unreachable; dead slots are reclaimed at a rehash sized from the live count and never from the current capacity. Sizing it the other way is what would let dead entries grow the table without bound in the #5516 workload.

No new search allocation. Every reader moved onto accessors that answer one field - isLive, a packed getOffsetAndFlag, isLocationOf - so the liveness filter each search applies per traversed graph ordinal still costs one presence bit. getLocation stays as a materializing convenience.

The graph-build snapshot is the same structure now. It was a Map<Integer, VectorLocation> copy of the whole live set, held for the duration of every rebuild, on top of the live index and at the same per-vector cost: a transient ~900MB spike on a 10M index, now ~200MB. ArcadePageVectorValues is built through forSearch(...) / forGraphBuild(...) factories instead of six constructors, since the two roles now take the same argument types.

Suggested alternative to the issue's proposal

The issue proposed plain arrays and flagged sparse ids as something to measure before committing. Measuring is not needed: the #5516 workload is the sparse case and a flat array regresses it by three orders of magnitude, so chunking with release-on-empty is a precondition, not a variant. The issue also targeted ~20 B by counting the location store alone; the honest all-in figure is ~32 B because the reverse index still needs a table. Packing the RID into a single long would take the store from 21 to 17 B/id but needs an overflow escape hatch for large buckets - not worth the risk inside this rewrite.

The structural fix for the one weakness left - a partially drained chunk retaining 2.7 KB per live id it still holds - is to renumber ids during rewriteDataFileWithLiveEntries, which already reissues every offset and every tombstone and is the one place a dense renumbering is safe. It has to move ordinalToVectorId and the persisted tombstone set in lockstep, so it is its own PR; a TODO in the class points at it.

Verification

New Issue5588PrimitiveLocationIndexTest (11 tests), each written against a specific wrong implementation rather than against the happy path: chunk release, payload atomicity under a concurrent rewriter, reverse-index survival across constant rehashing, ascending traversal and the SORTED characteristic (load-bearing - ordinalToVectorId is read with Arrays.binarySearch), the offset range and its no-page-entry sentinel, tombstoning a non-resident id, a model-based property test over random operation sequences including clear() and id reuse, and the retained-heap acceptance figure. The chunk-release test was mutation-checked by disabling the release. What is deliberately NOT tested is the release/acquire on the presence word: dropping it is invisible on x86, so a green test would only be evidence about the runner.

Plus a new guard in LSMVectorIndexTombstoneMemoryTest that the id sequence survives an index where every vector was deleted, across a reopen - the reopen path derives the high-water mark from the location index's own sequence, and reusing an id a tombstone still refers to would bury the new vector with the old one.

Green: 1153 tests in com.arcadedb.index.**, 516 in com.arcadedb.schema/com.arcadedb.engine/LowRamProfileTest, the server Issue5559LocationCacheSizeHttpIT, and a full reactor build.

🤖 Generated with Claude Code

https://claude.ai/code/session_0131GDFM4QGFC5URdReusH4A

…rays

VectorLocationIndex held one boxed entry per live vector in a
ConcurrentHashMap<Integer, VectorLocation> plus a ConcurrentHashMap<RID,
int[]> reverse index, retaining ~90 bytes per live vector to carry ~20
bytes of payload. Vector ids are dense and monotonically assigned, so
they address arrays directly.

The mapping is now four primitive arrays indexed by vector id - the file
offset with its compacted flag packed into one long, the RID's bucket id
and position, and one presence bit - at ~21 bytes per id plus 8 to 16
bytes per live vector for the reverse index. A 10M-vector index goes
from ~900MB to ~320MB with no per-entry objects at all.

The arrays are CHUNKED (128 ids) and a chunk is released as soon as its
last live id is tombstoned. That is not an optimisation: it is what
preserves the property #5516 exists for, that residency follows the live
vectors and not the ids handed out. A re-embedding workload hands out
9.3M ids for a 4K live set, and a flat id-indexed array would retain
~190MB where the map it replaces retained ~360KB.

Publication is by release/acquire on the array element itself, at both
levels - the chunk directory slot and the presence word - because a
plain element store into an already-published array carries no
happens-before edge for a reader that read the enclosing field earlier.
Three orderings are load-bearing and documented where they live:

- the offset and its compacted flag share one 64-bit word, so they can
  never be read from two generations. applyReplicatedPageUpdate
  re-points a live id at the compacted file on a replica with no index
  lock held, and a misaligned page read parses into a well-formed vector
  that passes every guard;
- a chunk is dropped only after its bits are cleared, asserted, or a
  reader holding the stale reference resurrects a tombstoned vector;
- clear() zeroes the live chunks before publishing the empty directory,
  since it is the one path that reuses ids.

The reverse index stores no keys: a candidate slot is verified by
reading the id's RID back out of the location arrays, which makes it
unable to produce a wrong id and makes a tombstoned id structurally
unreachable through it. Nothing is ever removed - a dead slot is already
unreachable - and dead slots are reclaimed at a rehash sized from the
live count, never from the current capacity.

Every reader moved onto accessors that answer one field without
materializing anything, so no search path allocates where it did not
before. The graph-build snapshot is the same structure now instead of a
Map<Integer, VectorLocation>, which removes a transient ~900MB copy of
the live set from every rebuild on a 10M-vector index.

estimatedLocationIndexBytes is measured off the arrays actually
allocated rather than count x a constant, and steps down ~3x.
APPROX_RETAINED_BYTES_PER_LOCATION is re-based from 90 to 32 together
with the prose that quotes it.
@mergify

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

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

codacy-production Bot commented Aug 6, 2026 •

Copy link
Copy Markdown

Up to standards ✅

🟢 Issues 0 issues

Results:
0 new issues

View in Codacy

🟢 Metrics 104 complexity

Metric Results
Complexity 104

View in Codacy

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.

@lvca lvca self-assigned this Aug 6, 2026
@lvca lvca added this to the 26.9.1 milestone Aug 6, 2026
@lvca

lvca commented Aug 6, 2026

Copy link
Copy Markdown
Member Author

@claude please review this

@claude

claude Bot commented Aug 6, 2026 •

Copy link
Copy Markdown

Claude finished @lvca's task in 4m 55s —— View job


Review of #5861

Tasks

  • Gather context (PR description, diff, changed files)
  • Read VectorLocationIndex.java (core rewrite) in detail
  • Read ArcadePageVectorValues.java, GrowableVectorValues.java, LSMVectorIndex.java diffs
  • Read LiveVectorBitsFilter.java, GroupedRIDBitsFilter.java diffs
  • Read new test Issue5588PrimitiveLocationIndexTest.java and the other touched tests
  • Check config/schema/docs changes and downstream/cross-module API usage
  • Post review findings

Summary

This is a careful, well-scoped rewrite. I read VectorLocationIndex.java end to end plus every call site touched in LSMVectorIndex.java, ArcadePageVectorValues.java, GrowableVectorValues.java, LiveVectorBitsFilter.java, GroupedRIDBitsFilter.java, and the test suite (including the new Issue5588PrimitiveLocationIndexTest). I verified by hand:

  • The offset/compacted-flag bit packing: OFFSET_MASK/OFFSET_BIAS/COMPACTED_FLAG boundary arithmetic is correct - the max legal packed value (-2L) is exactly one below ABSENT (-1L), so no legitimate entry can ever collide with the sentinel.
  • put()'s write ordering (bucketId/position → offsetAndFlag → ridIndex.insert → presence bit last with setRelease) matches what the class Javadoc claims and is consistent with the "insert into the reverse index only before the presence bit goes up" invariant RidIndex.insert() depends on.
  • removeLocation() clears the presence bit before decrementing/dropping the chunk, and the assert noBitsSet(chunk) before dropping is a reasonable belt-and-suspenders check.
  • RidIndex's "no stored keys, verify against the live location" design is self-consistent - a stale/dead slot is naturally rejected by isLocationOf, and the rehash sizing from liveCount (not current capacity) does prevent unbounded growth under the dead-entry-heavy workload the PR describes.
  • clear() zeroes chunk bits before nulling the directory slot and before resetting nextId, which is the ordering needed to avoid a stale reader resolving a reused id 0 to the wrong record.
  • Checked for leftover callers of the now-private ArcadePageVectorValues constructors and the old getLocation()-based readers across the whole repo (not just the touched files) - nothing outside this PR's own changes references the removed constructors, and the untouched tests (VectorLocationIndexRidReverseTest, VectorLocationIndexConcurrencyTest, LSMVectorIndexTest, etc.) only use APIs that are unchanged or already updated for issue LSM_VECTOR: setting locationCacheSize silently truncates the index - count and search only see the last N vectors #5559's -1 sentinel rejection.
  • The Issue5588PrimitiveLocationIndexTest tests are genuinely targeted at specific failure modes (torn offset/flag reads, chunk-not-released, rehash losing entries, non-ascending traversal) rather than happy-path checks, and the model-based random-operations test cross-checks size() against getActiveCount() independently, which is a good property test design.

I did not find any correctness bugs in this diff.

One minor nit (non-blocking)

RidIndex.rehash() (VectorLocationIndex.java around L364-393) already has chunk/slot in hand while walking the presence bits, but computes each live id's hash via the private hash(int vectorId) overload, which re-derives the chunk with a second chunkOf(vectorId) lookup instead of hashing chunk.bucketId[slot]/chunk.position[slot] directly. It's correctness-neutral (rehash always runs under writeLock, so there's no concurrent mutation to race with) and rehash isn't a hot path, but since this PR's whole point is trimming per-op cost on the write side, it's a small missed opportunity worth a one-line follow-up if it's ever touched again.

Verification note

I was not able to run mvn compile/mvn verify or git fetch in this environment - both require approval that isn't available non-interactively here, so I could not independently execute the test suite. The PR description states 1153 tests in com.arcadedb.index.** plus a full reactor build are green; I read the new test file closely enough to be confident it exercises the properties it claims to (each test's failure-mode comment matches what the assertions actually check), but I'd suggest treating CI's build/test run as the authoritative confirmation rather than this review alone.

@claude

claude Bot commented Aug 6, 2026

Copy link
Copy Markdown

Review: primitive-array vector location index (issue 5588)

I read VectorLocationIndex in full and traced the LSMVectorIndex, ArcadePageVectorValues, LiveVectorBitsFilter, GroupedRIDBitsFilter and GrowableVectorValues call sites, plus the new tests. This is exceptionally careful work: the concurrency reasoning is documented where it lives, and each test is written against a named wrong implementation rather than the happy path. Overall it looks correct and ready. Notes below are mostly confirmations and a couple of latent-trap flags, not blockers.

Strengths

  • The offset+compacted-flag-in-one-word invariant is the right call, and theOffsetAndItsCompactedFlagCannotBeReadFromDifferentGenerations exercises the torn-read window rather than asserting a shape.
  • Chunk-release-on-drain is verified per id handed out (aDrainedIdSpaceIsHandedBack), so a flat-array regression fails it: the bound is placed exactly where a plausible simplification would break issue 5516.
  • The keyless reverse index is correct-by-construction (verify RID back out of the store), and the rehash-sizes-from-live-count / probe-bounded-by-length details keep it from growing without bound under dead-entry pressure. theReverseIndexNeverLosesALiveEntryAcrossARehash pins both.
  • size() (counter) vs getActiveCount() (popcount) are computed independently and cross-checked in the model test, so agreement is evidence, not a tautology.
  • The API cleanup to forSearch(...) / forGraphBuild(...) factories reads well and no dangling references remain (the one surviving getLocation caller at LSMVectorIndex.java:2148 is intentional; getLocation is retained as the materializing convenience).

Things worth a second look (non-blocking)

  1. In-place RID change transiently drops a live vector from lock-free searches. In put(), the wasPresent && ridChanged branch clears the presence bit (setRelease) before rewriting bucketId/position and re-setting the bit. For that window a concurrent search reads the id as absent and skips it. The ConcurrentHashMap this replaces had no such window (a put was an atomic reference swap). It is safe today only because, as the comment says, no current path changes the RID of a live id in place (an update takes a new id). That is a real precondition a future caller could silently violate; consider strengthening it beyond a comment, e.g. an assert !wasPresent || !ridChanged on the write paths that should never hit it, so a regression fails loudly instead of intermittently dropping vectors from searches. The single-threaded model test covers the path functionally but nothing exercises it under concurrent reads.

  2. getActiveCount() and estimatedRetainedBytes() are O(directory length). On a 9.3M-id space that is ~73K chunks scanned with a getAcquire per slot. Both are documented as off the query path (estimatedRetainedBytes via getStats(); getActiveCount via countEntries(), which engine/CLAUDE.md already says never to call on a query path), so this is a confirm-callers-stay-honest note, not a defect; the prior CHM streaming was also O(n).

  3. LSMVectorIndexMetadata message reuses APPROX_RETAINED_BYTES_PER_LOCATION for two quantities: bytes per live vector and MB per million. Numerically correct (1 byte/vector == 1 MB/million, so both render 32) and it stays consistent if the constant changes, but at a glance it reads like a copy-paste slip. A one-line comment noting the identity would spare the next reader the double-take.

Style / conventions

Consistent with the surrounding code and CLAUDE.md (final params, imported names, no System.out, no new dependencies). The concurrency tests bound themselves in the low-hundreds-of-ms, so a @Tag("slow") is not warranted. Tests follow the assertThat(...) style.

Verification

Reviewed statically; confirmed no stale references to the removed six-constructor API or the old vectorSnapshot / admissibleLocation surface. I did not independently run the reactor build or the vector suite in this pass; the PR reports both green (1153 tests in com.arcadedb.index, plus schema/engine and the server IT), and the static picture is consistent with that.

Nice work: the memory reduction is real and the reasoning is unusually well documented.

Reviewed by Claude Code

lvca added 3 commits August 6, 2026 19:32
# Conflicts:
#	docs/release-26.9.1.md
#	engine/src/main/java/com/arcadedb/index/vector/GroupedRIDBitsFilter.java
#	engine/src/main/java/com/arcadedb/index/vector/LSMVectorIndex.java
#	engine/src/main/java/com/arcadedb/index/vector/LiveVectorBitsFilter.java
- rehash() hashes from the bucketId/position it already has in hand
  instead of re-resolving the chunk through the hash(vectorId) overload
- the "no engine path re-points a live vector id" precondition is now
  counted rather than only documented. An assert would have been louder
  and wrong: the branch does the safe thing and has tests that prove it,
  so asserting would fire on them. inPlaceRidRewriteCount() must stay
  zero, pinned by LSMVectorIndexTombstoneMemoryTest across the
  re-embedding cycles that would trip it first, and the counter itself
  is covered so it cannot rot into dead code
- getActiveCount() and estimatedRetainedBytes() document their
  O(allocated chunks) cost and point at size() as the O(1) answer
- the LSMVectorIndexMetadata message notes that quoting the same
  constant as bytes-per-vector and MB-per-million is the same number in
  two units, not a copy-paste slip

Also carries the merge of main: #5786 withdrew GroupedRIDBitsFilter and
rewrote the grouped search, so that file is gone and the two getLocation
call sites the new grouped path introduced were moved onto getRid().
@claude

claude Bot commented Aug 6, 2026

Copy link
Copy Markdown

Review: #5588 primitive-array vector location index

Reviewed the full diff statically (I couldn't run Maven in my sandbox, so the notes below are from reading, not from a local build - see the CI note at the end). Overall this is an excellent, unusually well-reasoned change: the memory model is stated precisely, the release/acquire discipline is applied consistently at both levels, and the test suite is written against specific wrong implementations rather than the happy path. I went looking for correctness holes and did not find one.

Concurrency - traced and looks correct

  • Packed offset+flag word. Storing the offset and isCompacted in one long (setRelease) genuinely closes the torn-read window applyReplicatedPageUpdate could open on a replica. The ABSENT == -1L sentinel is provably unambiguous because put() rejects offsets >= OFFSET_MASK - OFFSET_BIAS, so a real biased offset can never set all 63 low bits.
  • Presence bit as the visibility gate. Payload fields are written before the present bit is published with setRelease, and every reader reads present with getAcquire first. The wasPresent && ridChanged path correctly clears the bit first, and because ridIndex.insert() runs before the bit is re-set, a rehash triggered mid-insert rebuilds from the present bits without double-counting the in-flight id; liveCount stays consistent through that window (only bumped on !wasPresent). Verified against the random-op model test, which does exercise the RID-change branch (op <70 can re-point an existing id).
  • Reverse index without stored keys. The "verify by reading the id's RID back out" design is correct by construction, and the never-write-EMPTY-back invariant preserves probe chains under the no-removal policy. Sizing the rehash from liveCount rather than capacity is the right call for the LSM_VECTOR index in-memory bloat: VectorLocation objects never removed from ConcurrentHashMap (OOM after weeks of operation) #5516 churn workload; the dedup in get() handles an id owning two slots.
  • Chunk release ordering (present cleared with release before the directory slot is nulled) and clear() (bits zeroed before publishing EMPTY_DIRECTORY, guarding id-0 reuse) are both handled.

Caller compatibility - checked

getVectorIdsForRid changed semantics from "includes tombstoned ids, caller re-checks" to "live-only, ascending". Both remaining callers (LSMVectorIndex:3625 and :4696) immediately re-verify with isLocationOf(...), so the narrower contract is safe. nextId monotonicity across a rebuild is preserved: LSMVectorIndex keeps its own authoritative AtomicInteger nextId, and publishLocationIndex carries it into the rebuilt index.

Minor / non-blocking

  • VectorLocationIndex.getBucketId(int) / getPosition(int) appear to be used only by the new test - no production caller. If they're purely test hooks, consider dropping them to package-private (like chunkCount() / reverseTableCapacity()); otherwise they read as dead public API.
  • getActiveCount() and estimatedRetainedBytes() now walk the whole directory (O(live chunks), since drained slots are null). Fine off the hot path - just noting estimatedRetainedBytes() feeds getStats() and getActiveCount() feeds countEntries(), so neither should land on a query path (the class docs already say so).
  • assert noBitsSet(chunk) is a -ea-only guard - correct as a debug invariant, won't fire in production (the "(asserted)" comment already implies it).
  • The residual weakness (a partially drained chunk pinning CHUNK_RETAINED_BYTES for a single live id) is acknowledged and tracked in fix(#5812): make the @props JSON type hint opt-in, off by default #5860 - agree that dense renumbering during the data-file rewrite is its right home and belongs in its own PR.

Tests

Strong coverage: chunk release, packed-word atomicity under a concurrent rewriter, reverse-index survival across constant rehashing, ascending traversal + SORTED, offset-range guard + no-page-entry sentinel, the model-based property test (with size() vs getActiveCount() cross-checked from independent sources), and the retained-heap acceptance figure. The explicit note about not testing the presence-word release/acquire (invisible on x86) is the honest call.

One ask before merge

I couldn't run the reactor build in this environment. The description reports green - please just confirm CI is green on the final commit, since a couple of these files (ArcadePageVectorValues factory migration, the LiveVectorBitsFilter/GroupedRIDBitsFilter signature change) touch several call sites.

Nice work - the layout change is a clear win (~900MB -> ~320MB on a 10M index, plus removing the transient graph-build snapshot copy) and it's documented well enough to maintain.

@codecov

codecov Bot commented Aug 7, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 81.48148% with 80 lines in your changes missing coverage. Please review.
✅ Project coverage is 68.01%. Comparing base (a759e16) to head (3a9826b).
⚠️ Report is 5 commits behind head on main.

Files with missing lines Patch % Lines
...com/arcadedb/index/vector/VectorLocationIndex.java 89.63% 16 Missing and 18 partials ⚠️
...java/com/arcadedb/index/vector/LSMVectorIndex.java 55.07% 16 Missing and 15 partials ⚠️
...om/arcadedb/index/vector/GrowableVectorValues.java 0.00% 9 Missing ⚠️
.../arcadedb/index/vector/ArcadePageVectorValues.java 71.42% 3 Missing and 3 partials ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #5861      +/-   ##
==========================================
+ Coverage   67.93%   68.01%   +0.08%     
==========================================
  Files        1794     1794              
  Lines      152340   152610     +270     
  Branches    32279    32347      +68     
==========================================
+ Hits       103488   103805     +317     
+ Misses      35496    35433      -63     
- Partials    13356    13372      +16     

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

No engine caller needs half a RID - the readers either compare one via
isLocationOf() or need the object via getRid(). The two survive only so
a test can read the words straight out of the arrays and check getRid()
against them instead of against itself, which is not a reason to expose
them.
@lvca

lvca commented Aug 7, 2026

Copy link
Copy Markdown
Member Author

One ask before merge: I couldn't run the reactor build in this environment. The description reports green - please just confirm CI is green on the final commit.

Confirmed, with one caveat that matters: Java CI - test is red on this PR, and it is red on main for the same reason.

The three failing jobs on run 31131778011 are unit-tests, ha-integration-tests and integration-tests. The last four Java CI - test runs on main fail the same three jobs, on commits that are not in this branch:

run branch head failing jobs
31131326836 main 2724575 unit-tests, ha-integration-tests, integration-tests
31131107983 main a759e16 (failure)
31130786349 main 64cb88f (failure)
31130490721 main c67740b (failure)

Everything else on this PR is green: build-and-package, slow-unit-tests, coverage-report, all six e2e job sets, builder-tests, Codacy (0 new issues) and all six CodeQL analyses.

Locally on the merged branch: 1162 tests in com.arcadedb.index.** green, plus com.arcadedb.schema / com.arcadedb.engine / LowRamProfileTest (516), the server Issue5559LocationCacheSizeHttpIT, and a full reactor install. That covers the call sites you flagged - the ArcadePageVectorValues factory migration and the LiveVectorBitsFilter signature change - since every one of them is exercised by the vector suite.

Note the branch also carries a merge of main that landed after the first review: #5786 withdrew GroupedRIDBitsFilter and rewrote the grouped search, so that file is gone here and the two getLocation call sites its new grouped path introduced were moved onto getRid().

The two review points, addressed

  • getBucketId(int) / getPosition(int) read as dead public API - correct, no engine caller. Now package-private (45efc707), with the reason stated: the readers either compare a RID via isLocationOf(...) or need the object via getRid(...), and these two survive only so the model test can read the words straight out of the arrays and check getRid() against them rather than against itself.
  • getActiveCount() / estimatedRetainedBytes() walking the directory - documented on both, pointing at size() as the O(1) answer. No regression either way: the ConcurrentHashMap versions were O(live vectors), these are O(allocated chunks).

Also from the earlier review pass: rehash() no longer re-resolves the chunk it is already standing in, and the "no engine path re-points a live vector id" precondition is now counted rather than asserted - an assert would have fired on the tests that exist to prove that branch does the safe thing, so inPlaceRidRewriteCount() must stay zero instead, pinned by LSMVectorIndexTombstoneMemoryTest across the re-embedding cycles that would trip it first.

@claude

claude Bot commented Aug 7, 2026

Copy link
Copy Markdown

Review: primitive-array vector location index (#5588)

I reviewed the core rewrite (VectorLocationIndex), every migrated consumer (ArcadePageVectorValues, GrowableVectorValues, LiveVectorBitsFilter, LSMVectorIndex search/rebuild/PQ paths), and the new/updated tests. This is high-quality work: the memory win is real, the concurrency reasoning is spelled out where it is implemented, and the tests are written against specific wrong implementations rather than the happy path. Below is what I checked and the few things worth a second look.

What holds up well

  • Publication ordering is correct. In put() the write order is payload (bucketId/position/offsetAndFlag) then ridIndex.insert then the presence bit last with setRelease; readers acquire the presence bit first in every accessor (isPresent -> getAcquire). The release/acquire edge on the presence word carries the plain payload writes, and the directory slot gets its own setRelease/getAcquire. Reasoning in the class javadoc matches the code.
  • Offset+flag in one word genuinely removes the tear the replica-repoint path (applyReplicatedPageUpdate, no index lock) could otherwise produce. theOffsetAndItsCompactedFlagCannotBeReadFromDifferentGenerations exercises exactly that.
  • Keyless reverse index is correct by construction. Verifying every candidate via isLocationOf against the resident RID means the table can only miss, never fabricate; the "never remove, rehash-from-live-count" trigger correctly avoids unbounded growth under the LSM_VECTOR index in-memory bloat: VectorLocation objects never removed from ConcurrentHashMap (OOM after weeks of operation) #5516 dead-entry pressure. Multi-slot dedup in get() is handled and tested (theReverseIndexNeverLosesALiveEntryAcrossARehash).
  • Chunk release preserves the LSM_VECTOR index in-memory bloat: VectorLocation objects never removed from ConcurrentHashMap (OOM after weeks of operation) #5516 property (residency follows live vectors, not ids handed out) and is mutation-tested via aDrainedIdSpaceIsHandedBack.
  • Consumer migration is consistent. Every getLocation(id) != null && !loc.deleted became getOffsetAndFlag(...) != ABSENT / getRid(...) != null / isLive(...), and the split reads correctly fall through to the sentinel/continue/false branch when liveness flips between the two calls (weakly consistent, same as the ConcurrentHashMap it replaces). No stale references to the removed public constructors remain.

Things worth a second look

  1. The in-place RID-rewrite window is a latent hazard, not a current bug. put()'s wasPresent && ridChanged branch clears the presence bit and re-sets it, making a live vector transiently invisible (and getActiveCount() transiently one below size()) to a lock-free reader. The PR correctly argues no engine path reaches it today and pins inPlaceRidRewriteCount() at zero in LSMVectorIndexTombstoneMemoryTest. That guard is only as good as the workload that trips it: if a future path ever rewrites a present id's RID in place, this fails silently by dropping a live vector from searches, not loudly. The counter + test is a reasonable defense; flagging that its safety depends entirely on that invariant holding.

  2. estimatedRetainedBytes() hardcodes a compressed-oops object layout. CHUNK_RETAINED_BYTES and the 16L + 16L + ... terms assume 64-bit + compressed oops. Under -XX:-UseCompressedOops (heaps >32GB) the figure drifts. It is only an operator-facing stat (and the javadoc says so), so a documentation caveat rather than a defect - but a 10M-vector index is exactly where someone runs a >32GB heap and reads this number.

  3. VectorLocation.deleted is now vestigial (always false on anything this index produces). Kept deliberately so page-read call sites can stay loc != null && !loc.deleted; reasonable, just noting the dead field for future readers.

  4. Non-hot-path rescans (getActiveCount, estimatedRetainedBytes, chunkCount, reverseTableCapacity) each walk the directory. All are documented as stats/test-only and size() is the O(1) query-path answer, so this is fine - worth keeping the "never call on a query path" discipline for future callers.

Test coverage

Excellent. The 11-test Issue5588PrimitiveLocationIndexTest covers chunk release, offset/flag atomicity under a concurrent rewriter, reverse-index survival across constant rehashing, ascending traversal + SORTED, the offset range/sentinel, non-resident tombstone counting, clear()/id-reuse via a model-based property test, the in-place-rewrite branch, and the retained-heap acceptance figure. The honesty about what is not tested (release/acquire on the presence word being invisible on x86) is the right call.

Verification note

I could not run the reactor build in my sandbox (Maven execution not permitted here), so I am relying on the PR's stated green build + com.arcadedb.index.** suite. Worth confirming CI is green on the merge commit before landing, particularly LSMVectorIndexTombstoneMemoryTest (the inPlaceRidRewriteCount()==0 pin) and the concurrency tests on a slow CI runner.

Nice work - the packing, chunk-release, and keyless reverse index are each justified against a concrete failure mode, and the tracked follow-up (#5860, dense renumbering of the partially drained band) is the right thing to defer.

Automated review by Claude Code.

…tained-heap estimate

estimatedRetainedBytes() assumes a 64-bit JVM with compressed oops, and
a 10M-vector index is exactly the deployment that runs a heap above the
~32GB threshold where they turn off. State what changes there rather
than leaving the reader to guess: array headers 16 -> 24 bytes and the
Chunk object 40 -> 56, so 2728 per chunk instead of 2680 - 1.8%. The
layout is 97% primitive payload, whose size does not depend on the oop
width, so reading the VM option back to correct for it would buy less
than the rounding already in "~21 bytes per id".
@lvca

lvca commented Aug 7, 2026

Copy link
Copy Markdown
Member Author

Thanks - taking the four points in order.

1. In-place RID-rewrite window. Agreed on the characterisation, and agreed the guard is only as good as the workload that trips it. Two things make me comfortable leaving it as a counter rather than escalating it: the branch is the safe answer (the alternative is a torn (bucketId, position) pair, which is how a delete of record A tombstones the vector of record B - strictly worse than a transient miss), and the pin is on updateCyclesDoNotAccumulateStaleLocations, which is 10 re-embedding cycles over 100 vertices - the exact shape that would tempt someone to reuse an id instead of minting a new one. An assert was the first thing I tried and it is wrong here: it fires on rewritingALiveIdsRidInPlaceIsCountedAndStillCorrect, the test that exists to prove the branch still leaves the index consistent.

2. estimatedRetainedBytes() hardcodes a compressed-oops layout. Fair, and the "10M vectors is exactly where someone runs a >32GB heap" point is the right one. I measured the drift instead of documenting it vaguely (ccc3290b): above the threshold, array headers go 16 -> 24 bytes and the Chunk object 40 -> 56, so a chunk is 2728 instead of 2680 - +1.8%. The layout is 97% primitive payload, whose size does not depend on the oop width, so the error is smaller than the rounding already in "~21 bytes per id". That is now stated on both CHUNK_RETAINED_BYTES and estimatedRetainedBytes(). Reading the VM option back to correct for 1.8% would cost more clarity than it buys.

3. VectorLocation.deleted is vestigial. Correct, and deliberate - the javadoc on the field says so. It stays because a location read straight off a page can carry the flag, and it is the definition every loc != null && !loc.deleted reader is written against.

4. Non-hot-path rescans. Documented on both, pointing at size() as the O(1) query-path answer.

On the slow-runner concern

Worth being concrete rather than hopeful, so I measured every test in the new class:

test time its timeout headroom
theOffsetAndItsCompactedFlagCannotBeReadFromDifferentGenerations 0.546s 30s join (0.5s of it is a fixed sleep) 55x
theIndexMatchesAReferenceModelUnderRandomOperations 0.509s none -
concurrentAddsAndReadsAgreeOnTheFinalState 0.277s 120s join 430x
aDrainedIdSpaceIsHandedBack 0.093s none -
theReverseIndexNeverLosesALiveEntryAcrossARehash 0.067s 60s join 900x
aVectorIsVisibleToAConcurrentReaderAsSoonAsItIsAdded 0.037s 60s join 1600x
the other six <= 0.011s none -

Every timeout has two to three orders of magnitude of headroom, and none of the assertions is timing-derived - the concurrency tests assert invariants (no torn read, the pinned id never disappears, no id answers twice), not durations. The one count-based assertion, reads > 1000 in the torn-read test, guards against the loop being vacuous rather than measuring throughput; it observes millions locally.

On CI

Java CI - test is red on this branch and red on main for the same reason - same three jobs (unit-tests, ha-integration-tests, integration-tests), on the last four main runs, on commits not in this branch. Detail and run links in the previous comment. Everything else is green here, including build-and-package, slow-unit-tests, coverage-report, all six e2e sets, Codacy (0 new issues) and all six CodeQL analyses.

@claude

claude Bot commented Aug 7, 2026

Copy link
Copy Markdown

Review: primitive-array layout for the vector location index (#5588)

Reviewed the full diff (VectorLocationIndex rewrite + the ArcadePageVectorValues/GrowableVectorValues/LiveVectorBitsFilter/LSMVectorIndex read-side migration + tests + docs). This is a high-quality, unusually well-documented change. The javadoc that pins each memory-ordering decision to the concrete failure it prevents is exemplary, and the tests are written against specific wrong implementations rather than the happy path, which is exactly right for a lock-free structure. I confirmed every removed public API (new ArcadePageVectorValues(...), getLocation(...) on the read paths) has a migrated call site - no stragglers outside the class itself and the test doubles.

Note: I was unable to run mvn in the review environment, so the comments below are from reading, not from a green build. CI still needs to confirm compilation and the test runs the PR claims.

Things I like / verified by reasoning

  • ABSENT == -1L is provably unreachable by a real packed value: put() rejects absoluteFileOffset >= OFFSET_MASK - OFFSET_BIAS, so a compacted entry can never pack to all-ones.
  • The present-bit-last / getAcquire-first discipline and the single-word offset+flag are consistent everywhere they need to be (put, removeLocation, clear, the spliterator, rehash).
  • The reverse index "verify against the resident RID, store no key" invariant is correct-by-construction, and the dedup + ascending-sort in get() matches the SORTED contract callers depend on.
  • The estimatedRetainedBytes() / getActiveCount() split from the O(1) size() counter is a genuine cross-check, and the random model-based test exercises it well.

Questions / minor observations (none blocking)

  1. addOrUpdate re-add path ordering (please confirm intent). The delete path raises the tombstone bit before dropping the location, so a lock-free reader never sees "no location + not deleted" (which the reconstruction path reads as "scan pages and resurrect"). The non-deleted re-add path does the mirror image:

    if (deletedIds.contains(id)) deletedIds.remove(id);  // now: not deleted
    put(...);                                            // present bit set last
    

    Between the remove and the final present-bit store there is a transient "not deleted + no location" window - the same combination the delete path exists to avoid. I believe it is benign here (the id is genuinely becoming live, so a concurrent page-scan resolves to the new live entry, not a resurrected dead one), but given how load-bearing this ordering is elsewhere, a one-line comment stating why the window is safe on this path would match the rigor of the rest.

  2. Double chunk resolution on the non-quantized search path (micro). ArcadePageVectorValues.getVector now calls locations.getOffsetAndFlag(vectorId) and then, on the document-fallback branch, locations.getRid(vectorId) - two independent chunkOf resolutions per vector where the old single getLocation did one. Quantized indexes never reach getRid, so this only affects document-read searches, and at ~7.5 ns/lookup it is noise. Flagging only because the stated goal is "same per-ordinal cost" and this is a small, real per-vector increase on one path. Not worth reintroducing an allocation to fix; just noting the asymmetry with the claim.

  3. Test double coupling. CountingLocationIndex extends VectorLocationIndex and overrides only a subset of accessors, relying on the delegate for storage while its own superclass state stays empty. It works because the exercised path only touches overridden methods, but a future call to a non-overridden method (e.g. getAllVectorIds()) on the counting instance would silently read empty superclass state. A short comment, or not extending the real type, would harden it. Test-only, low priority.

Coverage

Excellent. Chunk release, payload atomicity under a concurrent rewriter, reverse-index survival across constant rehashing, ascending/SORTED traversal, offset-range guard, no-page-entry sentinel, the model-based property test with clear()/id-reuse, the retained-heap acceptance figure, and the reopen-with-every-vector-deleted sequence guard. The deliberate non-test of the release/acquire on x86 is called out honestly rather than papered over with a green-on-this-runner test.

Overall: strong work, no blocking issues found. The two documentation nits (item 1 especially) would bring the couple of remaining implicit invariants up to the standard the rest of the file sets.

… the counting test double

- addOrUpdate's live path leaves the same not-deleted-and-no-location
  window the delete path is ordered to avoid. It is benign, and the
  asymmetry is the interesting part: on the delete path a reader falling
  through to the pages finds the id's PRE-tombstone entry, an older
  generation than the one being installed, while here the pages hold the
  very entry the call is installing. Ordering it the other way would be
  worse - a resident location whose id still reads as deleted makes the
  delta scan skip a live vector.
- ArcadePageVectorValues.getVector resolves the chunk twice on the
  document fallback where the getLocation it replaces resolved it once.
  Quantized indexes never reach it and the second resolution is an array
  index against the lookupByRID on the next line, so it is noted rather
  than fixed with an accessor that would exist for one caller.
- CountingLocationIndex has to extend VectorLocationIndex, so its own
  inherited state is permanently empty and any un-overridden read
  answers about nothing instead of about the delegate - silently. Every
  read LSMVectorIndex performs is now forwarded, not just the counted
  ones.
@claude

claude Bot commented Aug 7, 2026

Copy link
Copy Markdown

Review: primitive-array vector location index (#5588)

I read the full VectorLocationIndex rewrite, every call site touched in LSMVectorIndex, ArcadePageVectorValues, GrowableVectorValues, LiveVectorBitsFilter, and the new/updated tests. This is a high-quality change: the memory reasoning is sound, the concurrency argument is spelled out where it is implemented, and the test suite is unusually good. Notes below, ordered by how much they matter.

Correctness / concurrency (verified, no blockers found)

  • Packed offset+flag and the ABSENT sentinel are airtight. put() rejects offset >= OFFSET_MASK - OFFSET_BIAS, so the max biased value stored is Long.MAX_VALUE - 1; ABSENT == -1L would require a biased value of Long.MAX_VALUE, which is unreachable. offsetOf/isCompactedOf round-trip correctly for the NO_FILE_OFFSET = -1 sentinel in both compacted and non-compacted forms.
  • Reverse index get() dedup + ascending sort is correct across all branches (single-match fast path, growth of found, and the final unique compaction). The "no key stored, verify against the resident location" design genuinely makes a wrong id impossible and a tombstoned id free to reject.
  • Rehash sized from liveCount, not capacity, with an occupied-slot trigger, is the right call for the LSM_VECTOR index in-memory bloat: VectorLocation objects never removed from ConcurrentHashMap (OOM after weeks of operation) #5516 re-embedding workload, and theReverseIndexNeverLosesALiveEntryAcrossARehash pins exactly that. The probes <= mask bound and the 2^30 clamp both degrade safely.
  • The release/acquire discipline (element-level setRelease/getAcquire at both directory and presence levels, presence bit written last) is applied consistently, and the "clear bit before dropping chunk" / "zero chunks before publishing empty directory in clear()" orderings are each covered by a test.

Behavioral change worth calling out explicitly

getVectorIdsForRid changed semantics from "returns ids including tombstoned ones, caller must re-check getLocation().deleted" to "returns only live ids". Both production callers were checked:

  • remove() -> now isLocationOf(vectorId, rid), equivalent.
  • collectAllowedOrdinals() -> a tombstoned id that survived in ordinalMap from a prior rebuild is now filtered at the source instead of by scoreOrdinal's getRid == null guard. Same final result, strictly cleaner.

No regression, but this is a public method whose contract inverted; the javadoc update is present, just flagging it for reviewers of downstream/embedding code.

Minor observations (non-blocking)

  • size() vs getActiveCount() can transiently disagree during an in-place RID rewrite: the presence bit is momentarily down while liveCount still counts the id. This is invisible on every engine path (inPlaceRidRewrites stays 0, pinned by the tombstone test) and readers are weakly consistent by design, so it is not a bug, but the two cross-checked counters are only guaranteed equal at quiescence. The random-model test asserts them only in a quiescent state, which is correct.
  • VectorLocation.deleted is now vestigial (always false on anything this index produces). Kept, and documented, for the loc != null && !loc.deleted page-read callers - reasonable, though a future cleanup could drop it.
  • Partially-drained chunk retention (up to CHUNK_RETAINED_BYTES for a single live id) is the one honest weakness, acknowledged and tracked in fix(#5812): make the @props JSON type hint opt-in, off by default #5860. CHUNK_SIZE = 128 is a sensible interim.
  • IdSpliterator reports SORTED for an IntStream; IntStream.sorted() does not consult that characteristic the way Stream<T>.sorted(cmp) does, so the "no-op" claim is a touch optimistic. Purely cosmetic - the traversal is genuinely ascending so output is correct either way.

Test coverage

Excellent. Each test targets a specific wrong implementation (flat array vs released chunks, split offset/flag words, rehash-loses-entry, non-ascending traversal, id-reuse via clear()), plus a model-based random-operation property test that cross-checks the whole observable surface. The honesty about what is not tested (release/acquire on the presence word being invisible on x86) is the right call rather than a false-green test. Mutation-checking the chunk-release test by disabling the release is a nice touch.

One thing I could not verify

I did not run the reactor build in this environment (no dependency-resolution network). Static review found no compile concerns: getBucketId/getPosition are package-private and only used by same-package tests, all call sites were migrated off the old Map/getLocation-tuple APIs, and the Issue5748 delegating wrapper was updated to override the new accessors. The PR reports a green reactor build; worth a maintainer confirming CI is green before merge.

Nice work - this is the kind of change where the comments carry as much value as the code.

Reviewed with Claude Code.

… exists, and pin the SORTED elision

The class javadoc referenced issue #5860 as the tracked follow-up for
renumbering ids during the data file rewrite. #5860 is an unrelated,
already-merged PR - the follow-up had never been filed. Filed as #5870
and the reference corrected.

Also pins the JDK behaviour the ascending traversal relies on, since a
review round questioned it: IntPipeline.sorted() returns the sink
unchanged when StreamOpFlag.SORTED is known, and the flag propagates
from a spliterator whose getComparator() is null and survives the
filter() the call sites apply first. A spliterator that claims sorted
and yields descending values comes back descending, which is what makes
declaring SORTED load-bearing rather than decorative - if the traversal
were ever not ascending, ordinalToVectorId would go unsorted and the
Arrays.binarySearch over it would quietly stop finding ordinals.

Release note records that getVectorIdsForRid's contract inverted: live
ids only, ascending, where it used to include tombstoned ones and ask
the caller to re-check.
@lvca

lvca commented Aug 7, 2026

Copy link
Copy Markdown
Member Author

Two of the four observations produced changes, and one of them found something real that none of the earlier rounds caught.

The SORTED observation is not correct - and pinning that was worth it

IdSpliterator reports SORTED for an IntStream; IntStream.sorted() does not consult that characteristic the way Stream<T>.sorted(cmp) does, so the "no-op" claim is a touch optimistic.

It does consult it. SortedOps.OfInt.opWrapSink returns the sink unchanged when StreamOpFlag.SORTED.isKnown(flags), and the flag propagates from a spliterator whose getComparator() returns null (StreamOpFlag.fromCharacteristics only strips SORTED when a non-natural comparator is present). Measured rather than argued - a spliterator that claims SORTED and yields descending values:

plain sorted():         [5, 4, 3, 2, 1]
filter().sorted():      [5, 4, 3, 2, 1]
SORTED survives filter: true

The sort really is elided, including through the filter() the call sites apply first. That matters beyond the micro-optimisation: it is what makes declaring SORTED load-bearing rather than decorative. If the traversal were ever not ascending, .sorted() would not fix it, ordinalToVectorId would go unsorted, and the Arrays.binarySearch over it would quietly stop finding ordinals - fewer results from every allow-list-filtered search, nothing failing. So the correction prompted a test (ce5fc97f) rather than a doc change; the behaviour is now pinned instead of being re-litigated each round.

The follow-up issue reference was dangling - fixed

Chasing the #5860 reference in the class javadoc found that #5860 is an unrelated, already-merged PR (fix(#5812): make the @props JSON type hint opt-in), not the renumbering follow-up. The issue had never actually been filed; the reference was wrong from the first commit and five review rounds read past it. Now filed as #5870 with the three things that have to move in lockstep with a renumbering (ordinalToVectorId, the persisted tombstone set, nextId), and the javadoc corrected. Thanks - that one was only findable by following the link.

The contract change is now in the release note

Agreed this deserves to be visible to embedding code, not just the javadoc. Added:

VectorLocationIndex.getVectorIdsForRid returns only LIVE ids now, in ascending order. It used to return tombstoned ids as well and require the caller to re-check the location's deleted flag. Nothing in the engine is affected - both callers re-verified anyway - but the contract of a public method inverted, so embedding code that relied on seeing tombstoned ids has to look elsewhere for them (isDeleted(int)).

The other two

  • size() vs getActiveCount() transiently disagreeing during an in-place RID rewrite - correct, and correctly characterised as not-a-bug. Worth adding that the window is unreachable on every engine path, which is what inPlaceRidRewriteCount() == 0 pins, so the disagreement needs a caller that does not exist before it can be observed at all.
  • VectorLocation.deleted vestigial - kept deliberately and documented on the field; it is the definition every loc != null && !loc.deleted page-read caller is written against.

300 vector tests green on ce5fc97f. Java CI - test remains red for the pre-existing main failure (evidence).

@codacy-production

codacy-production Bot commented Aug 7, 2026 •

Copy link
Copy Markdown

Up to standards ✅

🟢 Issues 0 issues

Results:
0 new issues

View in Codacy

🟢 Metrics 104 complexity

Metric Results
Complexity 104

View in Codacy

🟢 Coverage 89.81% diff coverage · -6.34% coverage variation

Metric Results
Coverage variation ✅ -6.34% coverage variation
Diff coverage ✅ 89.81% diff coverage

View coverage diff in Codacy

Coverage variation details
Coverable lines Covered lines Coverage
Common ancestor commit (a759e16) 152340 116884 76.73%
Head commit (3a9826b) 184953 (+32613) 130176 (+13292) 70.38% (-6.34%)

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 (#5861) 432 388 89.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 7, 2026

Copy link
Copy Markdown

Review: primitive-array vector location index (issue 5588)

I read the full rewrite of VectorLocationIndex, every migrated call site in LSMVectorIndex, the ArcadePageVectorValues / GrowableVectorValues / LiveVectorBitsFilter consumers, and the new tests. This is a strong, well-reasoned change. The concurrency model (release/acquire at both directory and element level, packing offset+flag into one word, presence-bit-last publication, chunk-release-on-drain) is internally consistent, and the "written against a specific wrong implementation" test style genuinely exercises the load-bearing invariants rather than the happy path. The getLocation / constructor API change is self-contained: no consumers outside the vector package touch the removed constructors, and estimatedLocationIndexBytes moving to a measured figure is a real improvement over count x constant.

A few things worth a second look, none blocking:

1. Delta-scan comment no longer matches the code (LSMVectorIndex.java ~3536-3543).
The old getLocation(id) != null && loc.deleted check was removed and replaced by a comment block ending with "It stays because it is what the line says it does, at the price of one bit." But nothing stays: there is no isDeleted check on that line now. The phrase "at the price of one bit" reads exactly like the intent was to keep a guard such as if (vectorIndex.isDeleted(delta.vectorId)) continue;. Either the guard was meant to be kept and was dropped by accident, or the removal is intentional (the reasoning that a deleted delta entry is unreachable because remove() purges the delta buffer is sound), in which case the comment should say the check was removed as provably dead, not that "it stays". Functionally I believe the removal is safe, so this is a doc/code consistency nit rather than a bug, but a future reader will trip on it.

2. inPlaceRidRewriteCount() reads a non-volatile int.
inPlaceRidRewrites is a plain int mutated under writeLock and read by the accessor without synchronization. It is a test-only diagnostic, and the tests read it after joining the writer, so it is fine in practice. Worth a one-word note (or a volatile read) that the accessor gives no happens-before guarantee if ever called concurrently with a writer.

3. getVectorIdsForRid single-match allocation.
The common single-match path allocates new int[]{single} per call. It is off the search hot path (delete resolution / reverse lookup, which already allocate), so this is acceptable; just flagging that the "no new search allocation" property in the description applies to the readers, not to this method.

4. Untested release/acquire on the presence word.
Explicitly documented as untestable on x86, which is honest and correct. Not asking for more, but if you ever want it covered, a jcstress harness is the standard tool for the store-visibility ordering. Out of scope for this PR.

Minor.
The javadoc/comment density in VectorLocationIndex is very high. It is excellent as a rationale record, but the ~90 to ~32 / ~21 / APPROX_RETAINED_BYTES_PER_LOCATION figures now live in at least five places (class javadoc, constants, release note, engine/CLAUDE.md, the metadata error). Some of that prose could point at the constant rather than restating the number, to reduce drift.

Nice work overall. The chunk-release-on-drain design correctly preserves the issue 5516 property that residency follows live vectors rather than ids handed out, and the reverse index "store no keys, verify by reading the RID back" approach is a clean way to make tombstoned ids structurally unreachable.

… claims is there

An earlier edit replaced the guard with the comment explaining it and
dropped the statement itself, leaving a comment block that ends 'It
stays because it is what the line says it does, at the price of one bit'
above no line at all. Restored, and the comment now separates the two
independent reasons it cannot fire today - the flag it used to read has
been permanently false since #5516, and remove() purges the delta buffer
for the RID it deletes - from the reason it stays: the buffer and the
tombstone set are maintained by different code paths.

Also from the same review:
- inPlaceRidRewrites is volatile, so the diagnostic accessor is honest
  for a caller that reads it without having joined the writer. A
  counter that silently under-reports is worse than no counter
- getVectorIdsForRid documents that it allocates, so the 'no new search
  allocation' property is not read as covering it
- the per-vector figure is interpolated from
  APPROX_RETAINED_BYTES_PER_LOCATION where javadoc allows it, instead of
  being restated in prose that can drift away from the constant
@lvca

lvca commented Aug 7, 2026

Copy link
Copy Markdown
Member Author

Point 1 was a real defect - thank you. The other three are fixed too.

1. The delta-scan guard really had been dropped

You read it exactly right: an earlier edit replaced the guard with the comment explaining it and deleted the statement, leaving a block that ends "It stays because it is what the line says it does, at the price of one bit" above no line at all. Not a doc nit - the guard was gone. Restored in 3a9826b4.

The comment now separates the two independent reasons it cannot fire from the reason it stays, because they were tangled together and that is what made the block easy to mis-edit in the first place:

  • the flag it used to read (loc.deleted) has been permanently false since LSM_VECTOR index in-memory bloat: VectorLocation objects never removed from ConcurrentHashMap (OOM after weeks of operation) #5516, so the guard did nothing even before this PR;
  • remove() purges the delta buffer of every entry for the RID it deletes, so no delta entry survives its own deletion on any path a test can drive - I tried, twice, and both tests were vacuous: forcing a tombstone in behind the buffer only makes the next rebuild republish the live entry the pages still carry;
  • it stays anyway because the delta buffer and the tombstone set are maintained by different code paths, and one bit is not a price worth negotiating over.

2. inPlaceRidRewrites is now volatile

Agreed, and I took the volatile rather than the note. It is written under writeLock and incremented approximately never, so the read costs nothing, and a diagnostic that silently under-reports is worse than no diagnostic - the whole point of that counter is to be believed when it says zero.

3. getVectorIdsForRid allocation

Fair scoping correction. Its javadoc now says so explicitly - it allocates, it is a resolution step, and its callers (the delete path and the allow-list walk) are already resolving records. The "no new search allocation" property is about the per-ordinal readers and should not be read as covering it.

4. jcstress

Agreed and out of scope. Noted for whoever wants the presence-word ordering covered properly rather than by a green-on-x86 test.

Minor: the figure living in five places

Real drift risk. Where javadoc can interpolate, it now does - {@value VectorLocationIndex#APPROX_RETAINED_BYTES_PER_LOCATION} in LSMVectorIndex and TypeLSMVectorIndexBuilder instead of a literal ~32; LSMVectorIndexMetadata already concatenated the constant. What is left is GlobalConfiguration's runtime description text and engine/CLAUDE.md, neither of which can reference a Java constant, plus the release note, which is a point-in-time record and should keep its number.

300 vector tests green on 3a9826b4.

@claude

claude Bot commented Aug 7, 2026

Copy link
Copy Markdown

Review: primitive-array vector location index (#5588)

I read the full series (7 commits) end to end, focusing on the VectorLocationIndex rewrite and the ~30 call sites migrated off getLocation/VectorLocation. This is an exceptionally well-executed change: the memory-model reasoning is sound, the accessor migration is complete, and the test suite is written against specific wrong implementations rather than the happy path. I could not find a correctness defect. Notes below are mostly confirmation plus a few minor points.

Correctness / concurrency (the load-bearing parts hold up)

  • Packed offset+flag word. The ABSENT == -1L sentinel is provably unambiguous: put() rejects any offset >= OFFSET_MASK - OFFSET_BIAS, so a present entry's word can never be all-ones, and getOffsetAndFlag gates on the presence bit first. Good.
  • Publication ordering. Directory slot and presence word are both setRelease/getAcquire; the presence bit is written last on the way in and read first on the way out, and cleared before a chunk can be dropped. The put ordering (bucketId/position -> offset word -> ridIndex.insert before the presence bit) is internally consistent with rehash() rebuilding from resident bits.
  • Reverse index without keys. Verifying candidates against the resident RID makes the table unable to produce a wrong id, and sizing the rehash from liveCount (not capacity) is what keeps dead-entry pressure from growing it without bound in the LSM_VECTOR index in-memory bloat: VectorLocation objects never removed from ConcurrentHashMap (OOM after weeks of operation) #5516 workload. The dedup in get() traces correctly (the single/found growth path handles the count == found.length grow-before-write case).
  • In-place RID rewrite window. Nicely handled: the branch retires the id, and inPlaceRidRewrites is incremented, exposed, and pinned to zero by a test rather than asserted (an assert would fire on the tests that prove the branch is safe). liveCount/chunk.liveCount are correctly left unchanged on that path.
  • clear() id reuse. Zeroing live chunks' presence bits before nulling the directory closes the one path that reuses id 0.

Points worth a look

  1. Graph-build snapshot granularity in a sparse-but-small live set. snapshotOf(...) / the buildGraphFromScratchExclusively snapshot are now VectorLocationIndex instances at 128-id chunk granularity. For the motivating re-embedding workload this is cheap because the live ids cluster at the top of the id space (monotonic issue). But for a live set that is genuinely scattered across a large id space (e.g. scattered deletes leaving survivors far apart), a live id per chunk costs ~2.7KB/chunk vs ~90B/entry for the old Map. It is bounded by the live index's own residency and is consistent with the documented "partially drained band" tradeoff, so not a regression relative to the live index - just worth confirming the clustering assumption holds for the snapshot too, since the PR frames the snapshot saving as unconditional (~900MB -> ~200MB).

  2. CHUNK_RETAINED_BYTES is a hand-computed layout constant. 40 + 1040 + 528 + 1040 + 32 will silently drift if anyone adds a field to Chunk or changes CHUNK_SIZE. The theRetainedHeapPerLiveVector... test bounds per-vector to [20,40), which catches gross drift, but the absolute estimatedLocationIndexBytes stat could quietly become wrong. A tiny assertion tying the constant to CHUNK_SIZE/CHUNK_WORDS (deriving the array contributions rather than hard-coding 1040/528/32) would make it self-checking.

  3. Minor style (CLAUDE.md): the new test uses fully-qualified java.util.function.IntConsumer and java.util.Comparator in the anonymous Spliterator.OfInt (lines ~274, ~297). Project convention is to import and use the simple name. Trivial.

  4. Comment density. The javadoc/inline commentary is unusually heavy. It is genuinely informative and I would not strip it, but a couple of the multi-paragraph inline blocks in put/addOrUpdate/mergeWithDeltaScan restate the class javadoc; maintainers editing the code have to keep prose and code in sync (the patch-7 fix restoring the delta-scan guard "the comment claims is there" is exactly that failure mode having already happened once).

Tests

Coverage is strong and adversarial: chunk release, offset/flag atomicity under a concurrent rewriter, reverse-index survival across constant rehashing, ascending traversal + SORTED elision (with the nice "lies about being sorted" spliterator pinning the JDK behaviour), offset-range guard, the reference-model property test, and the reopen id-sequence guard in LSMVectorIndexTombstoneMemoryTest. The honesty about what is not tested (release/acquire on the presence word being invisible on x86) is appreciated and correct.

Verdict

Solid, careful, and well-tested. No blocking issues from my read. The two substantive items are (1) confirming the snapshot clustering assumption and (2) making the layout constant self-checking; both are follow-ups, not blockers.

@lvca
lvca merged commit 6042d44 into main Aug 7, 2026
23 of 26 checks passed
@lvca
lvca deleted the issue-5588 branch August 7, 2026 03:34
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.

Vector index: lay the location index out in primitive arrays (~20 bytes/id instead of ~90)

1 participant