Repository navigation
fix(engine): apply groupBy cap on score-sorted result set instead of HNSW traversal (fixes #5761) [fj4WqyCCw3C5ShR1RfB7MoBPTpkRrBFYP1uT35g3MvT] - #5786
Conversation
Up to standards ✅🟢 Issues
|
| Metric | Results |
|---|---|
| Complexity | 8 |
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.
|
Tick the box to add this pull request to the merge queue (same as
|
…HNSW traversal (fixes ArcadeData#5761) The previous approach used GroupedRIDBitsFilter as a Bits filter during HNSW traversal, which admitted candidates in traversal order. Entry-point descent pops candidates far from the query first, so the per-group budget was consumed on irrelevant groups before the nearest neighbours were reached. The best group could be locked out entirely. Fix: run the HNSW search with a liveness-only filter (LiveVectorBitsFilter) and 2x search budget, then apply the per-group cap as a post-filter on the score-sorted result set. This ensures the first groupSize candidates per group are the actual highest-scoring members, and the first limit distinct groups encountered are the highest-scoring groups. Fixes ArcadeData#5761
…h still answers with `limit` groups, and pin group choice with tests Moving the cap out of the traversal is right, but reading only `limit * groupSize * 2` candidates out of the search hands the whole candidate pool to the first group dense enough to fill it, and the remaining group slots go unused. That is not a corner case: it is what `groupBy` exists for. `SQLFunctionVectorGroupByTest.denseGroupByReturnsDistinctGroupsAtGroupSize1` went from 10 distinct groups to 8 on this branch, and the reproduction in the issue came back with cluster 1 twice where three groups were asked for. `efSearch` could not buy them back either, because it only widens the beam and the beam was not what was being read. Take the whole beam instead. `topK` never reaches the layer-0 traversal and `rerankK` is unchanged, so every one of those candidates was already scored and reranked: the search does no extra graph work, the group cap decides what survives, and `efSearch` becomes the lever the contract promises. The post-filter still stops as soon as every group is full. Also: unresolvable group keys are counted apart from cap hits instead of being logged as full groups, the two per-query log lines drop from INFO to FINE to match the ungrouped path, and the javadoc says what the candidate pool costs instead of claiming a guarantee the code cannot make. Tests: Issue5761GroupedSearchGroupChoiceTest covers the reported shape at the index and at `vector.neighbors`, the pool/`efSearch` relationship, and group choice at every point on the arc. All four fail on main. Issue5558DeletedRegionSearchTest.theGroupedSearchAnswersADeletedRegionQuery now asserts the cluster rather than liveness, which is what the issue asks for; it fails on main too.
52c9771 to
7bf709d
Compare
|
Reviewed and extended. The diagnosis is right and the approach is the one the issue calls option 1, but the branch as submitted had no test and it broke an existing one, so I pushed a follow-up commit rather than send it back. What I measured on
So the branch fixed the half the issue is about - the nearest group is no longer locked out - and lost the other half. Reading only
Follow-up commit takes the whole beam instead of Tests. Left for a follow-up, not for this PR. Fewer than |
|
Review notes on this one, leaving it open for you or a maintainer to pick up rather than merging as-is: Disclosure: we rebased this branch onto current What review found:
Given the residual gap, whether to merge this as a partial fix (with #5761 left open for the traversal-time fix) or hold for the full fix is a judgment call for the ArcadeDB team. CI on the current head: |
…limit` distinct groups Reading the group cap off a single beam is score-exact but under-answers: a group dense enough to fill the beam on its own leaves no room for the next one, and the issue's own reproduction came back with cluster 1 twice where three groups were asked for. `limit` counts distinct groups, so that is the case groupBy exists for, not a corner of it. The previous revision pinned it as expected behaviour (`containsOnly(1)` at the default beam), which would have blocked the real fix. GraphSearcher.resume continues the same walk - the visited set and the candidate queue survive - so each pass returns strictly new nodes further from the query and the group state accumulates across passes. The search costs one beam in the common case and pays for more ground only when the answer is genuinely short, bounded at 16 beams; a query that exhausts that budget still returns fewer groups and is now counted in groupedSearchesShortOfLimit, which is the cue to raise efSearch. The comment claiming resume() would lose the first pass was wrong: those rows are already in the caller's hands by the time resume is called, and what resume returns is strictly new nodes. Measured on the 1200-vector / 12-cluster fixture, limit=3 groupSize=2: 75 us for the wrong one-group answer, 123 us for the right three-group one, 530 us in the pathological case where the group key has a single value and the whole budget is spent. Plain k=6 on the same index is 32 us. Also: - GroupAdmissionState is promoted out of SQLFunctionVectorAbstract into com.arcadedb.index.vector, so the index-level cap and the SQL-level cap are one rule instead of two copies of it on either side of the same query. - The answer is sorted before returning: a resumed pass can expand a node the previous one left on the frontier and turn up a neighbour that outranks a row already admitted, which would break the declared ascending-by-distance contract. - GroupedRIDBitsFilter is deleted rather than kept as dead code, and LiveVectorBitsFilter's predicate is folded back into get() now that nothing else shares it. Tests: Issue5761GroupedSearchGroupChoiceTest asserts the group count at the index and at vector.neighbors, no duplicate rows across a resumed pass, the RID whitelist across a resumed pass, and that a single-value group key stops instead of walking the whole graph. Issue5558's grouped test now expects the three nearest surviving clusters. Mutation-checked by capping the walk at one pass: three tests go red. 531 tests in com.arcadedb.index.vector + com.arcadedb.function.sql.vector, green.
|
Thanks @waterWang ! |
- 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().
…rays (~90 -> ~32 bytes per live vector) (#5861) * perf(engine) #5588: lay the vector location index out in primitive arrays 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. * chore(engine) #5588: address code review - 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(). * chore(engine) #5588: getBucketId/getPosition are package-private 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. * docs(engine) #5588: quantify the compressed-oops assumption in the retained-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". * docs(engine) #5588: state why the re-add window is benign, and harden 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. * docs(engine) #5588: point the renumbering follow-up at the issue that 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. * fix(engine) #5588: restore the delta-scan tombstone guard the comment 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
Brings the fork up to 26.9.1-SNAPSHOT, which carries the August fixes we filed: ArcadeData#5711 (HTTP row truncation), ArcadeData#5745/ArcadeData#5788 (GAV), ArcadeData#5746 (Cypher through GAVFusedChain), ArcadeData#5747 (close-time HNSW rebuild, our PR ArcadeData#5787), ArcadeData#5796 (Redis port), ArcadeData#5824 (@Rid IN replanned as FETCH FROM RIDs). All verified against the shipped jars before this merge. Conflicts resolved: - 15 .github files kept deleted. Upstream CI the fork does not run; we carry only the five Python workflows. - test-python-examples.yml took upstream's two dependabot SHA bumps (setup-java v5.6.0 -> v5.7.0, cache v4.3.0 -> v6.1.0), staying aligned with the SHA-pinning their review requires. - test_server_wire_protocols.py kept ours. Upstream carries the version from PR ArcadeData#5807, which still has the redis xfail; ArcadeData#5796 is fixed and the marker was retired in a5d82c0. Behaviour changes to watch, none of which renamed or removed a JPype-facing API: ArcadeData#5969 now validates SQL function and method arity, ArcadeData#5908 makes sum/avg reject non-numeric input, ArcadeData#5983 bounds regex backtracking, and ArcadeData#5786 caps vector.neighbors groupBy output per index. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_0173qFfapQBiGxaV7apSZ4X8
Description
Fixes #5761
Problem
GroupedRIDBitsFilteris aBitsfilter that runs during HNSW traversal. It admits candidates in traversal order — the firstgroupSizecandidates per group encountered during the HNSW walk are admitted, regardless of their score. The entry-point descent pops candidates far from the query first, so the per-group budget is consumed on irrelevant groups before the nearest neighbours are reached. The best group (the one closest to the query) can be locked out entirely.Root Cause
The
Bitsinterface is score-blind — JVector callsget()before the score function runs. Group admission based on traversal order works for well-separated clusters where the entry point happens to be near the query, but fails for the general case.Fix
GroupedRIDBitsFilterwithLiveVectorBitsFilter(liveness-only) for the HNSW traversalsearchKtolimit * groupSize * 2to give the post-filter sufficient candidatesgroupSizecandidates per group by their score rankThis ensures:
groupSizecandidates per group are the actual highest-scoring members of that grouplimitdistinct groups encountered are the highest-scoring groupsVerification
The reproduction case from the issue (1200 vectors, 12 clusters, limit=3, groupSize=2) should now return cluster 1 instead of clusters 6, 9, and 10.