Repository navigation
perf(engine) #5588: lay the vector location index out in primitive arrays (~90 -> ~32 bytes per live vector) - #5861
Conversation
…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.
|
Tick the box to add this pull request to the merge queue (same as
|
# Conflicts: # docs/release-26.9.1.md
Up to standards ✅🟢 Issues
|
| Metric | Results |
|---|---|
| Complexity | 104 |
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 please review this |
|
Claude finished @lvca's task in 4m 55s —— View job Review of #5861Tasks
SummaryThis is a careful, well-scoped rewrite. I read
I did not find any correctness bugs in this diff. One minor nit (non-blocking)
Verification noteI was not able to run |
|
Review: primitive-array vector location index (issue 5588) I read Strengths
Things worth a second look (non-blocking)
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 Verification Reviewed statically; confirmed no stale references to the removed six-constructor API or the old Nice work: the memory reduction is real and the reasoning is unusually well documented. Reviewed by Claude Code |
# 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().
Review: #5588 primitive-array vector location indexReviewed 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
Caller compatibility - checked
Minor / non-blocking
TestsStrong coverage: chunk release, packed-word atomicity under a concurrent rewriter, reverse-index survival across constant rehashing, ascending traversal + One ask before mergeI 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 ( 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 Report❌ Patch coverage is 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. 🚀 New features to boost your workflow:
|
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.
Confirmed, with one caveat that matters: The three failing jobs on run 31131778011 are
Everything else on this PR is green: Locally on the merged branch: 1162 tests in Note the branch also carries a merge of The two review points, addressed
Also from the earlier review pass: |
Review: primitive-array vector location index (#5588)I reviewed the core rewrite ( What holds up well
Things worth a second look
Test coverageExcellent. The 11-test Verification noteI 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 + 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".
|
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 2. 3. 4. Non-hot-path rescans. Documented on both, pointing at On the slow-runner concernWorth being concrete rather than hopeful, so I measured every test in the new class:
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, On CI
|
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 ( Note: I was unable to run Things I like / verified by reasoning
Questions / minor observations (none blocking)
CoverageExcellent. 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 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.
Review: primitive-array vector location index (#5588)I read the full Correctness / concurrency (verified, no blockers found)
Behavioral change worth calling out explicitly
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)
Test coverageExcellent. 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 One thing I could not verifyI did not run the reactor build in this environment (no dependency-resolution network). Static review found no compile concerns: 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.
|
Two of the four observations produced changes, and one of them found something real that none of the earlier rounds caught. The
|
Up to standards ✅🟢 Issues
|
| Metric | Results |
|---|---|
| Complexity | 104 |
🟢 Coverage 89.81% diff coverage · -6.34% coverage variation
Metric Results Coverage variation ✅ -6.34% coverage variation Diff coverage ✅ 89.81% diff coverage 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.
|
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). 2. inPlaceRidRewriteCount() reads a non-volatile int. 3. getVectorIdsForRid single-match allocation. 4. Untested release/acquire on the presence word. Minor. 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
|
Point 1 was a real defect - thank you. The other three are fixed too. 1. The delta-scan guard really had been droppedYou 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 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:
2.
|
Review: primitive-array vector location index (#5588)I read the full series (7 commits) end to end, focusing on the Correctness / concurrency (the load-bearing parts hold up)
Points worth a look
TestsCoverage is strong and adversarial: chunk release, offset/flag atomicity under a concurrent rewriter, reverse-index survival across constant rehashing, ascending traversal + VerdictSolid, 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. |
Closes #5588.
What
VectorLocationIndexheld one boxed entry per live vector in aConcurrentHashMap<Integer, VectorLocation>plus aConcurrentHashMap<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,VectorLocationat 24 B andRIDat 24 B, both exactly 1:1 with the vector count, and read that as the ~90 B figure being high.jdk.ObjectCountreports per class, and those are two of the five contributors the constant enumerates - the other three (ConcurrentHashMap$Node, the boxedjava.lang.Integerkey, and theridToVectorIdsnode with itsint[]) 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 --livecannot answer a retained-heap question, and JFR needs no JDK.This PR stops the number being arguable:
estimatedLocationIndexBytesis now summed off the arrays the index has actually allocated instead oflive 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.
aDrainedIdSpaceIsHandedBackfails 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
nullfor a chunk that exists, i.e. dropping a just-inserted vector out of every search.Three orderings are documented where they are implemented:
applyReplicatedPageUpdatere-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.theOffsetAndItsCompactedFlagCannotBeReadFromDifferentGenerationsfails within milliseconds on the split layout;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 packedgetOffsetAndFlag,isLocationOf- so the liveness filter each search applies per traversed graph ordinal still costs one presence bit.getLocationstays 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.ArcadePageVectorValuesis built throughforSearch(...)/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
longwould 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 moveordinalToVectorIdand the persisted tombstone set in lockstep, so it is its own PR; aTODOin 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 theSORTEDcharacteristic (load-bearing -ordinalToVectorIdis read withArrays.binarySearch), the offset range and its no-page-entry sentinel, tombstoning a non-resident id, a model-based property test over random operation sequences includingclear()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
LSMVectorIndexTombstoneMemoryTestthat 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 incom.arcadedb.schema/com.arcadedb.engine/LowRamProfileTest, the serverIssue5559LocationCacheSizeHttpIT, and a full reactor build.🤖 Generated with Claude Code
https://claude.ai/code/session_0131GDFM4QGFC5URdReusH4A