Skip to content

fix(#9692): top up sparse vector searches whose candidates a concurrent commit deleted - #9698

Merged
robfrank merged 4 commits into
mainfrom
fix/9692-sparse-vector-stale-candidate-topup
Oct 10, 2026
Merged

robfrank merged 4 commits into
mainfrom
fix/9692-sparse-vector-stale-candidate-topup

Conversation

@robfrank

@robfrank robfrank commented Oct 10, 2026 •

Copy link
Copy Markdown
Collaborator

Closes #9692

Fixes both consolidated findings (#9634, #9635): a sparse vector search no longer answers short, or empty, when a concurrent commit deletes the records it picked as candidates.

The extra cost is only paid when a candidate was actually dropped. A search with no stale candidates runs exactly one pass, as before.

Finding ledger

# finding status
1 #9634 rescoring drops deleted candidates with no replacement (topK, topKGrouped, committedForGroups/topKForGroups) fixed here
2 #9635 vector.sparseNeighbors emit loop drops stale RIDs with fetchK fixed at k fixed here (non-grouped path); grouped path -> #9697

Coverage

Invariant: a sparse search whose candidates are dropped because their record is gone keeps asking until it has k live rows, or until the index really holds fewer.

entry point state test
topK, unfiltered, rescored fixed topKTopsUpCandidatesWhoseRecordIsGone
topK, allowedRIDs whitelist fixed topKWithAWhitelistTopsUpCandidatesWhoseRecordIsGone
topK with a transaction overlay fixed topKInsideATransactionTopsUpCandidatesWhoseRecordIsGone
topK when the index really holds fewer than k must stop, not loop topKStillAnswersShortWhenTheIndexReallyHoldsFewer
topKGrouped fixed topKGroupedTopsUpCandidatesWhoseRecordIsGone
topKForGroups / committedForGroups (also the top-up inside topKGrouped's overlay branch) fixed topKForGroupsTopsUpCandidatesWhoseRecordIsGone
vector.sparseNeighbors non-grouped, rescoring off (isolates the SQL layer) fixed staleIndexEntriesAreToppedUpWithoutRescoring, aWholeWindowOfStaleEntriesIsToppedUpWithoutRescoring, anIndexHoldingFewerThanKStillAnswersWhatItHas
vector.sparseNeighbors non-grouped, default rescoring fixed staleIndexEntriesAreToppedUpWithTheDefaultRescoring
Reporter's concurrent workload (writer replacing 100 rows per commit, reader on topK + SQL) fixed concurrentDeletesNeverShortenTheAnswer: fails 3/3 without the fix, passes 5/5 with it
VectorLeg (hybrid search), MCP VectorSearchTool / HybridSearchTool covered: they call vector.sparseNeighbors via the SQL tests
VectorFuse / VectorMmr / VectorRerank / VectorRecommend / VectorDiscover out of scope, as stated in #9635: they post-process a list the caller supplies -
Grouped-key resolvers that map a missing record to a null key deliberate and documented, as stated in #9635 -

Known gaps

Test plan

  • Issue9692SparseRescoreStaleCandidateTest (6 tests) and Issue9692SparseNeighborsStaleTopUpTest (5 tests) fail before the fix and pass after it
  • The concurrent repro fails 3/3 on the unfixed code (thousands of probes per run, some answering short) and passes 5/5 with the fix
  • All com.arcadedb.index.sparsevector tests, plus every *Sparse*Test, Issue9368* and Issue9692*: 170 tests, green
  • com.arcadedb.function.sql.vector.*Test, LSMSparseVectorIndex*Test, Issue7966*, Issue8576*, Issue8002*: 392 tests, green

Adversarial pass

Not run: this session had no subagent tool, so the independent follow-up pass could not be spawned. The completeness sweep above was done inline.

Residual risk

Review cycles

cycle head changes bot outcome
1 328216de1b initial fix + tests one real bug: the top-up keep cap max(k, 100_000) could NARROW a first pass with k * oversample above it. Fixed in aa13ca39b5: stop when the wider budget is not greater. Multi-index saturation re-run documented
2 aa13ca39b5 cap fix + saturation comment no blockers; asked to document that rescoreExactly drops for one reason only. Done in 62639746cb
3 62639746cb contract Javadoc no blockers; asked for overflow-safe grouped widening growth and a comment on the unbounded group budget in committedForGroups. Done in d3f5f6b332 (grownWidening)
4 d3f5f6b332 clamp + comment "approving in spirit", minor notes only (see below)

Skipped review suggestions (with rationale)

  • "boolean[] out-params -> result holder" (cycles 1, 4): kept on purpose. This is the exact shape SQLFunctionVectorNeighbors.searchAndEmit uses for vectorNeighbors answers fewer than limit rows while another thread commits deletes: the SQL function skips records the index still returns and does not top up #9368, and the two twins should read alike.
  • "early-return oversample == 0 before the loop" (cycle 1): that branch shares the candidate selection (filter and overlay exclusion) with the rescored branch. Splitting it out would duplicate that code.
  • "per-index saturation" (cycles 2, 4): wasted work only, bounded, and the same trade the dense function makes. Documented inline.
  • "STALE_TOP_UP_GROWTH = 4 alignment" (cycles 2, 3): the column alignment matches the file's existing field-declaration style.
  • "a test pinning rescoreExactly's single drop reason" (cycles 3, 4): there is no other drop reason today, so there is nothing a test could inject. The Javadoc now states the contract at the place where a second reason would be added.
  • "tag the concurrent test slow / require a minimum probe count" (cycle 3): the whole class runs in about 1s, which is not slow-lane material. A minimum probe count is a throughput bound that a GC stall on CI would turn red. The unfixed code fails it 3/3 with more than 5,000 probes per run.
  • "confirm grouped tests fail before the fix" (cycle 3): confirmed. Before the fix, topKGroupedTopsUpCandidatesWhoseRecordIsGone and topKForGroupsTopsUpCandidatesWhoseRecordIsGone returned [].
  • "negative test for an index holding fewer than k" (cycle 4): already present for both layers: topKStillAnswersShortWhenTheIndexReallyHoldsFewer and anIndexHoldingFewerThanKStillAnswersWhatItHas.
  • "metric or log when a top-up fires" (cycle 4): left out. It is not part of the issue, and the dense twin has none either. It can go into a later observability pass.

Final state

clean-approval: the last review found nothing to act on. Merge is up to the maintainer.

🤖 Generated with Claude Code

Summary by CodeRabbit

  • Bug Fixes
    • Sparse-vector searches now retry with a wider candidate pool when deleted records leave too few live results, helping return the requested number of matches when enough indexed records remain.
    • This improvement applies to top-K, grouped, and sparse-neighbor searches. Searches still return fewer than requested when fewer live indexed records are available.

…nt commit deleted

The exact rescoring of LSM_SPARSE_VECTOR (on by default) dropped candidates
whose record was gone and nothing replaced them, so topK / topKGrouped /
topKForGroups could answer short or empty while thousands of matching records
were live (#9634). vector.sparseNeighbors asked each sub-index for exactly k
and skipped stale RIDs at emit time with no retry (#9635).

Both layers now widen and ask again, mirroring the dense #9396 and #9368 fixes.

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

mergify Bot commented Oct 10, 2026 •

Copy link
Copy Markdown
Contributor

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

@codacy-production

codacy-production Bot commented Oct 10, 2026 •

Copy link
Copy Markdown

Not up to standards ⛔

🔴 Issues 1 medium

Alerts:
⚠ 1 issue (≤ 0 issues of at least minor severity)

Results:
1 new issue

Category Results
Complexity 1 medium

View in Codacy

🟢 Metrics 27 complexity

Metric Results
Complexity 27

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.

@claude

claude Bot commented Oct 10, 2026

Copy link
Copy Markdown

Review

The approach is sound. It moves the dense BINARY rerank top-up (#9396) to the sparse side, a clean pass costs exactly one pass as before, and every loop is bounded. The comments are thorough. I read the diff only and did not build it or run the tests.

Possible bug: the widening step can shrink the budget

In LSMSparseVectorIndex.committedTopK:

keep = (int) Math.min((long) keep * STALE_TOP_UP_GROWTH, Math.max(k, MAX_OVERFETCH_ROWS));

The cap is max(k, 100_000), but the first-pass keep is k * oversample. Take k = 60_000 with oversample 2. Then keep = 120_000 and the cap is 100_000, so the "top-up" asks for a narrower candidate set than the first pass. The fetchK == previousFetchK guard only catches an exact repeat, so a smaller value passes it and the retry is wasted. The comments also say the unfiltered branch is deliberately uncapped. Suggest keep = Math.max(keep, min(keep * GROWTH, cap)), or stop when the new keep is not greater than the old one. A test with a large k would pin this.

Smaller points

  • committedTopK handles oversample == 0 inside a loop that cannot repeat in that case. Doing the early return before the loop would read more simply.
  • In SQLFunctionVectorSparseNeighbors, saturated is set when any sub-index returns >= fetchK. In multi-index mode, one saturated index plus a stale skip in another triggers a re-run. That is only wasteful and bounded, but it is worth a comment.
  • In searchAndEmit, the staleSkipped and saturated boolean[] out-params work, but a small result holder would be clearer. This is a style preference, not a blocker.
  • The grouped SQL path is left with a single pass and deferred to [concurrency] vector.neighbors / vector.sparseNeighbors grouped path drops rows whose record a concurrent commit deleted without topping up #9697. That is documented and fine.

Tests

The PR lists tests per entry point, which is good. Please confirm that:

  • None of them assert on wall-clock time (see CLAUDE.md on StallAwareStopwatch).
  • Any concurrency-style test is deterministic, for example by injecting deletes rather than racing a real commit.
  • There is a case where the index really holds fewer than k live records, so the loop exits through indexExhausted.

Otherwise LGTM once the keep cap issue is addressed.

@coderabbitai

coderabbitai Bot commented Oct 10, 2026 •

Copy link
Copy Markdown

Review in Change Stack →

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration
  • Configuration used: defaults
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: cf8c18a1-7373-485d-a9ef-3d00be3d7fdf


📥 Commits

Reviewing files that changed from the base of the PR and between b11c1df and d3f5f6b.



📒 Files selected for processing (4)
  • engine/src/main/java/com/arcadedb/function/sql/vector/SQLFunctionVectorSparseNeighbors.java
  • engine/src/main/java/com/arcadedb/index/sparsevector/LSMSparseVectorIndex.java
  • engine/src/test/java/com/arcadedb/function/sql/vector/Issue9692SparseNeighborsStaleTopUpTest.java
  • engine/src/test/java/com/arcadedb/index/sparsevector/Issue9692SparseRescoreStaleCandidateTest.java


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




📝 Walkthrough
📝 Walkthrough

Walkthrough

Sparse-vector top-K retrieval and non-grouped SQL neighbor searches widen candidate fetches when stale records reduce live results. Grouped index retrieval also retries with wider limits. Tests cover filters, transaction overlays, exhausted results, and concurrent delete-and-replace probes.

Changes

Sparse-vector stale candidate top-up

Layer / File(s) Summary
Rescored top-K retrieval
engine/src/main/java/com/arcadedb/index/sparsevector/LSMSparseVectorIndex.java, engine/src/test/java/com/arcadedb/index/sparsevector/Issue9692SparseRescoreStaleCandidateTest.java
Committed top-K retrieval widens candidate fetches when exact rescoring drops stale records. Filtered fetches retain the 100,000-row cap, and unfiltered fetches can grow up to the integer limit. Tests cover ordinary, whitelisted, transactional, grouped, and selected-group searches, plus searches with fewer live records than requested.
Grouped retrieval top-up
engine/src/main/java/com/arcadedb/index/sparsevector/LSMSparseVectorIndex.java
Grouped and fixed-group retrieval widen group or member fetch limits when rescoring drops stale records. Retries stop when the requested result count is reached, the index is exhausted, limits cannot grow, or the retry limit is reached.
SQL sparse-neighbor top-up
engine/src/main/java/com/arcadedb/function/sql/vector/SQLFunctionVectorSparseNeighbors.java, engine/src/test/java/com/arcadedb/function/sql/vector/Issue9692SparseNeighborsStaleTopUpTest.java
Non-grouped SQL searches double the per-index fetch size when stale records are skipped and a sub-index reaches its fetch budget. Grouped SQL searches retain their distinct-group budget. Tests cover rescored and unrescored results, exhausted searches, and concurrent deletion and replacement.

Priority: ⬇️ Low

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

Change: Bug fix · Severity of issue fixed: Low

Suggested reviewers: lvca



Merge Risk: ⚪ Minimal · up to d3f5f

Sparse vector searches now top up results when concurrent deletes leave stale candidates, with bounded retries and tests for the main cases. No actionable merge-blocking risk remains. Grouped SQL neighbor searches are intentionally left to a follow-up issue.

Pre-merge checks | Passed 4 | Failed 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage Warning Docstring coverage is 29.41% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 34 functions across 4 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check Passed For directly linked issue #9692, the PR implements stale-candidate top-up at the sparse index layer for topK, topKGrouped, and committedForGroups. It also implements bounded fetchK retries for…
Out of Scope Changes check Passed The changed production files implement the #9692 retry behavior or preserve grouped SQL behavior while adding the non-grouped retry loop. The added tests reproduce stale index entries and concurrent d…
Title check Passed The title clearly and concisely identifies the main change: topping up sparse vector searches when concurrent commits delete candidate records.
Description check Passed The description is comprehensive and covers the change, motivation, related issues, test coverage, known gaps, residual risk, and review history. It does not use the repository template headings or in…

  • Fix all pre-merge checks with AI
✨ Finishing Touches 💡 2
📝 Generate docstrings 💡
  • Commit to this branch
  • Create a new PR









🛠️ Fix failing CI checks 💡
  • Commit to this branch
  • Create a new PR


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



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

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

❤️ Share

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

…t; document multi-index saturation

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

claude Bot commented Oct 10, 2026

Copy link
Copy Markdown

Review of #9698

I read the diff and did not build or run the tests. I found no blocking issues.

What looks good

  • Every top-up loop is bounded: 6 attempts at most, plus the "budget can't grow" and "engine exhausted" exits. A search with no dropped candidates still runs exactly one pass.
  • committedTopK keeps the original over-fetch and overlay semantics. It skips a repeat fetch when the cap leaves fetchK unchanged, and it bounds wider so a top-up can never narrow the first pass.
  • groupedExhausted is only evaluated on the short-answer path, so the group-key resolution cost stays off the hot path.
  • The SQL-level loop only retries when a stale candidate was skipped, the answer is short, and a sub-index was saturated. It is capped by MAX_FETCH_CANDIDATES.
  • Moving the dense LSM_VECTOR with BINARY quantization: findNeighborsFromVector returns an empty list while another thread commits deletes and inserts near the query, although 3,000 records are live #9396 pattern to the sparse side keeps the two consistent. The regression test is in the right place and the PR's finding ledger is clear.

Minor suggestions (non-blocking)

  1. In committedTopK, shortBecauseDropped is committed.size() < k && committed.size() < candidates.size(). This relies on rescoreExactly never dropping candidates for any reason other than a missing record. A one-line comment on that contract in rescoreExactly, or a test pinning it, would guard against a future change that adds another drop reason and triggers needless retries.
  2. In the SQL function, saturated is set when any sub-index reaches fetchK. Multi-bucket queries can re-run all sub-indexes when only an unsaturated one had the stale row. The comment already says this is accepted, so it is fine, but per-index saturation would avoid the extra work if it ever shows up in profiles.
  3. The grouped SQL path still has no top-up. The PR points this to [concurrency] vector.neighbors / vector.sparseNeighbors grouped path drops rows whose record a concurrent commit deleted without topping up #9697, which is fine, but keep that issue linked.
  4. Style: the declaration STALE_TOP_UP_GROWTH = 4; has extra alignment spaces. Some of the new comments are also long relative to the surrounding code.
  5. Test coverage: the new test covers the SQL and index entry points. It would be worth confirming there is a case for the allowedRIDs filtered path combined with stale drops, and for the overlay (in-transaction) path, since both change the fetchK arithmetic.

Overall this is a solid, well-reasoned fix.

@claude

claude Bot commented Oct 10, 2026

Copy link
Copy Markdown

Review of #9698 (sparse vector stale-candidate top-up)

I read the diff but did not build it or run the tests.

Overall: the approach is sound. It reuses the dense BINARY rerank pattern from #9396, and extracting committedTopK is a clear improvement. The extra cost only applies when a candidate was actually dropped, so the common path still runs one pass. The termination conditions are well reasoned: full answer, index exhausted, budget cannot grow, or attempt cap.

Points to consider

  1. Concurrent test timing. concurrentDeletesNeverShortenTheAnswer runs 60 rounds of delete and insert against a busy-looping reader thread.
    • It is not tagged. CLAUDE.md asks for @Tag("slow") on multi-second regression tests, so tag it if it runs for a few seconds.
    • It passes only if the reader hits no short answer in any probe, so please confirm it is stable under CI load.
    • probes > 0 would pass with a single probe. A minimum probe count, or a check that probes overlapped the writer, would show the race window was exercised.
  2. Overflow in the grouped top-up. Math.max(widening, 1) * STALE_TOP_UP_GROWTH is int * int in both topKGrouped and committedForGroups. It is probably bounded by groupedWidening/rowWidening, but computing it as long and clamping would make that explicit, as committedTopK already does for keep.
  3. Grouped path cost. groupedExhausted resolves group keys for every candidate, but only on the short path, which is fine. A comment on why Integer.MAX_VALUE is passed as groupsAsked in committedForGroups would help.
  4. rescoreExactly coupling. The top-up relies on "fewer out than in" meaning "record gone". The new Javadoc warns about this. A small test that fails if rescoreExactly ever drops for another reason would enforce it.
  5. Style. STALE_TOP_UP_GROWTH = 4; has extra alignment spaces that do not match the surrounding constants.

Tests: coverage is good. It covers raw and rescored paths, a full window of stale entries, an index holding fewer than k, and an end-to-end race. Please confirm the grouped cases fail before the fix and pass after.

No security concerns. Retries are bounded (6 attempts, plus the MAX_OVERFETCH_ROWS and MAX_FETCH_CANDIDATES caps).

…the unbounded group budget

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

claude Bot commented Oct 10, 2026

Copy link
Copy Markdown

Review of #9698 (sparse vector stale-candidate top-up)

I read the diff but did not build the project or run the tests.

Overall: The approach is sound. It mirrors the dense #9396 and #9368 loops, and the extra cost is only paid when a candidate was actually dropped. The termination conditions are well thought out: full answer, index exhausted, budget unable to grow, and a bounded attempt count.

Code quality

  • committedTopK is much easier to follow than the inlined version. The Javadoc on rescoreExactly warns that a new drop reason would turn into needless retries, which is a useful guard against future breakage.
  • In SQLFunctionVectorSparseNeighbors, staleSkipped and saturated are boolean[1] out-params. They work, but a small result holder, or an AtomicBoolean/field on a per-call context, would read better and avoid the array idiom.
  • The groupBudget = k rename is clear. Passing fetchK into searchAndEmit while the grouped path ignores it is slightly confusing. A one-line note on the parameter would help.

Potential issues

  1. Saturation heuristic across sub-indexes (SQL). saturated is set if any sub-index returned >= fetchK. The comment acknowledges this can cause a wasted re-run. It is bounded and never wrong, so I'm fine with it. Only the sub-index that came back full needs a wider fetch, so you could widen per index, but the added complexity is probably not worth it.
  2. committedTopK with oversample == 0. It returns on the first pass, and the doc explains why (nothing is loaded). Please confirm that the SQL-level loop covers this case, since stale RIDs reach the emit loop there. The Issue9692SparseNeighborsStaleTopUpTest coverage suggests it does.
  3. shortBecauseDropped relies on committed.size() < candidates.size(). This holds only while rescoreExactly drops for exactly one reason. The Javadoc says so, but nothing enforces it. A test that pins this contract would protect it. For example, a candidate with an unrelated skip reason should not trigger retries.
  4. Cap on wider. Math.max(k, MAX_OVERFETCH_ROWS) means a top-up stops growing once keep reaches 100k. That seems intentional given the fix(#9692): top up sparse vector searches whose candidates a concurrent commit deleted #9698 review note. Please confirm that an index with more than 100k deleted-candidate churn degrades to a short answer rather than an error. That is acceptable, but it is worth documenting.
  5. Worst-case cost. Six attempts at x4 growth gives up to 4^5 = 1024x the first-pass candidate count, bounded by the cap. Under heavy concurrent delete churn, each attempt reloads every candidate record. That is fine for a rare path, but a metric or debug log when a top-up fires would help diagnose it in production.

Performance

The no-stale path is a single pass with just two boolean writes, so there is no regression. new ArrayList<>(Math.min(keep, raw.size())) is a good allocation choice.

Tests

Both new test classes cover the entry points in the PR's coverage table (topK, grouped, committedForGroups, SQL non-grouped). Please check against CLAUDE.md that:

  • they use assertThat(...) style assertions,
  • they contain no wall-clock assertions (use StallAwareStopwatch if timing is needed),
  • the deterministic injection of a "deleted between index answer and load" race does not depend on timing or threads.

I also suggest a negative test: an index that really holds fewer than k live rows should stop after one pass with no extra attempts. This guards the indexExhausted branch.

Security

No concerns. The caps keep the work bounded, so a client cannot amplify memory or CPU beyond MAX_FETCH_CANDIDATES or MAX_OVERFETCH_ROWS.

Approving in spirit. The notes above are minor.

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.

[concurrency] Vector search drops candidates whose records a concurrent commit deleted without topping up (sparse

1 participant