Skip to content

fix(engine): apply groupBy cap on score-sorted result set instead of HNSW traversal (fixes #5761) [fj4WqyCCw3C5ShR1RfB7MoBPTpkRrBFYP1uT35g3MvT] - #5786

Merged
lvca merged 3 commits into
ArcadeData:mainfrom
waterWang:fix/issue-5761-grouped-search-traversal-order
Aug 6, 2026
Merged

lvca merged 3 commits into
ArcadeData:mainfrom
waterWang:fix/issue-5761-grouped-search-traversal-order

Conversation

@waterWang

Copy link
Copy Markdown
Contributor

Description

Fixes #5761

Problem

GroupedRIDBitsFilter is a Bits filter that runs during HNSW traversal. It admits candidates in traversal order — the first groupSize candidates 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 Bits interface is score-blind — JVector calls get() 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

  1. Replace GroupedRIDBitsFilter with LiveVectorBitsFilter (liveness-only) for the HNSW traversal
  2. Expand searchK to limit * groupSize * 2 to give the post-filter sufficient candidates
  3. Apply the per-group cap as a post-filter on the score-sorted result set — walk the JVector output (which is already in score order), track per-group counts, and admit the first groupSize candidates per group by their score rank

This ensures:

  • The first groupSize candidates per group are the actual highest-scoring members of that group
  • The first limit distinct groups encountered are the highest-scoring groups
  • The fix is score-exact, not approximate

Verification

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.

@codacy-production

codacy-production Bot commented Aug 3, 2026 •

Copy link
Copy Markdown

Up to standards ✅

🟢 Issues 0 issues

Results:
0 new issues

View in Codacy

🟢 Metrics 8 complexity

Metric Results
Complexity 8

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.

@mergify

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

waterWang and others added 2 commits August 5, 2026 20:02
…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.
@robfrank
robfrank force-pushed the fix/issue-5761-grouped-search-traversal-order branch from 52c9771 to 7bf709d Compare August 5, 2026 18:03
@robfrank

robfrank commented Aug 5, 2026

Copy link
Copy Markdown
Collaborator

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 main, with the 1200-vector / 12-cluster fixture from the issue, limit=3, groupSize=2, query at the centre of cluster 1:

groups returned
main, index level 4, 5, 8 (and 3, 4, 8 through vector.neighbors)
main, ungrouped search, same index, same query cluster 1, five out of five
this branch as submitted cluster 1 twice, and nothing else
this branch after the follow-up cluster 1 twice at the default beam, clusters 0/1/2 at efSearch=400

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 limit * groupSize * 2 nodes 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 the case groupBy exists for, and it showed up as a red test: SQLFunctionVectorGroupByTest.denseGroupByReturnsDistinctGroupsAtGroupSize1 went from 10 distinct groups to 8 on this branch.

efSearch could not buy the groups back either. The comment added in this PR says JVector's resume() re-runs the search when the returned count is short, but there is no resume() call on this path; efSearch only widens the beam, and the beam was not what was being read. efSearch=300 returned the same two rows as the default.

Follow-up commit takes the whole beam instead of limit * groupSize * 2. topK never reaches the layer-0 traversal (searchLayer0 passes only rerankK to searchOneLayer; topK just sizes the pop) and rerankK is unchanged, so every one of those candidates was already scored and reranked - no extra graph work, and efSearch becomes the lever the contract promises. 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, GroupedRIDBitsFilter gets a note saying it is no longer wired into anything and why it is kept, and the javadoc states the candidate-pool cost 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, and fails on main too. Full com.arcadedb.index.vector + com.arcadedb.function.sql.vector sweep: 566 tests, the only red one was LSMVectorIndexIncrementalIngestScalingTest.graphShouldKeepAbsorbingPendingVectorsWithoutFurtherSearches, a 2-minute awaitility that timed out under CPU contention and passes in 1.6 s in isolation.

Left for a follow-up, not for this PR. Fewer than limit groups still come back when one group is denser than the beam, which is the documented cost of moving the cap out of the traversal. Closing that needs option 2 from the issue - admitting into a per-group min-heap so a better candidate can evict a worse one, with the traversal still pruning full groups - so #5761 may be worth keeping open against that.

@robfrank

robfrank commented Aug 5, 2026

Copy link
Copy Markdown
Collaborator

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 main and pushed a follow-up commit (fix(engine) #5761: read the whole beam so the grouped search still an...) to fix issues found in review (see below). This was a force-push (--force-with-lease) to your branch fix/issue-5761-grouped-search-traversal-order - your original commit's authorship is preserved, but if you have local work on this branch you will need to git fetch and reset to the new remote head before pushing again, or you'll get a non-fast-forward rejection.

What review found:

  • The diagnosis and approach (option 1 from LSM_VECTOR: groupBy spends its distinct-group budget in traversal order, so a grouped search returns the wrong groups #5761: choose groupBy groups by score instead of by HNSW traversal order) are correct.
  • As originally submitted, the branch had no regression test, and reading only limit*groupSize*2 nodes from the search handed the whole candidate pool to the densest group - this broke an existing test (SQLFunctionVectorGroupByTest.denseGroupByReturnsDistinctGroupsAtGroupSize1, which regressed from 10 groups to 8) and didn't fully fix the issue's own reproduction (cluster 1 was still missing from the answer).
  • The follow-up commit reads the whole search beam instead of a fixed multiple, which fixes both of those, plus adds a dedicated regression test (Issue5761GroupedSearchGroupChoiceTest) confirmed to fail without the fix and pass with it.
  • Residual gap, not fixed by either commit: if one group is denser than the search beam, fewer than limit distinct groups can still come back, because nothing prunes by group during the graph traversal itself. Widening efSearch works around it (verified: default beam of 100 on a 100-members-per-cluster fixture returns 1 group, efSearch=400 returns the correct 3), but the real fix is option 2 from the issue - a score-aware per-group min-heap that prunes during traversal, not after. That's a separate, larger change.

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: unit-tests and integration-tests are red at the "Check test results" step - worth confirming whether that's pre-existing on main or caused by this diff before merging either way.

…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.
@lvca
lvca merged commit c67740b into ArcadeData:main Aug 6, 2026
3 checks passed
@lvca
lvca requested review from lvca and robfrank August 6, 2026 23:07
@lvca lvca added this to the 26.9.1 milestone Aug 6, 2026
@lvca

lvca commented Aug 6, 2026

Copy link
Copy Markdown
Member

Thanks @waterWang !

lvca added a commit that referenced this pull request Aug 6, 2026
- 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().
lvca added a commit that referenced this pull request Aug 7, 2026
…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
tae898 added a commit to humemai/arcadedb-embedded-python that referenced this pull request Aug 11, 2026
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

LSM_VECTOR: groupBy spends its distinct-group budget in traversal order, so a grouped search returns the wrong groups

3 participants