Skip to content

Vector search: empty filter matches nothing, compaction clears the search cache (#8959, #8957) - #8971

Merged
lvca merged 4 commits into
mainfrom
fix/8959-8957-vector-filter-compact
Oct 3, 2026
Merged

lvca merged 4 commits into
mainfrom
fix/8959-8957-vector-filter-compact

Conversation

@lvca

@lvca lvca commented Oct 2, 2026 •

Copy link
Copy Markdown
Member

Fixes #8959
Fixes #8957

  • vector.neighbors / vector.sparseNeighbors: a filter that resolves to no RIDs now returns an empty result instead of an unfiltered search (absent filter is unchanged).
  • LSMVectorIndex: the id-keyed search vector cache is cleared when the location index is published, so a renumbering compaction no longer serves other records' vectors.

Tests: Issue8959EmptyVectorFilterTest, Issue8957CompactionSearchCacheTest (both fail without the fix); 467 related vector tests pass.

Summary by CodeRabbit

  • Bug Fixes
    • Vector-neighbor searches now return no results when a supplied filter matches no records, including empty filters.
    • Vector searches now return consistent results after index compaction.
    • Invalid vector index specifications continue to report errors, even when the filter matches no records.

… the search vector cache (#8959, #8957)

vector.neighbors and vector.sparseNeighbors treated a filter option that resolved to no RIDs as no filter, returning records outside it. The SQL layer now answers with an empty result.

COMPACT INDEX renumbers vector ids but left the id-keyed search vector cache populated, so searches scored nodes against other records' vectors. The cache is now cleared when the location index is published.

Fixes #8959
Fixes #8957
@lvca lvca added this to the 26.10.1 milestone Oct 2, 2026
@lvca lvca self-assigned this Oct 2, 2026
@coderabbitai

coderabbitai Bot commented Oct 2, 2026 •

Copy link
Copy Markdown

Review in Change Stack →

Navigate logical layers of code changes, visualize relationships, and explore their blast radius.

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration
  • Configuration used: defaults
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: d52cfee5-2ef4-4c3f-b206-0d3f1b63a50b
📥 Commits

Reviewing files that changed from the base of the PR and between 94cf342 and 2bb18f2.

📒 Files selected for processing (7)
  • engine/src/main/java/com/arcadedb/function/sql/vector/SQLFunctionVectorAbstract.java
  • engine/src/main/java/com/arcadedb/function/sql/vector/SQLFunctionVectorNeighbors.java
  • engine/src/main/java/com/arcadedb/function/sql/vector/SQLFunctionVectorSparseNeighbors.java
  • engine/src/main/java/com/arcadedb/index/vector/LSMVectorIndex.java
  • engine/src/test/java/com/arcadedb/function/sql/vector/Issue8959EmptySparseFilterTest.java
  • engine/src/test/java/com/arcadedb/function/sql/vector/Issue8959EmptyVectorFilterTest.java
  • engine/src/test/java/com/arcadedb/index/vector/Issue8957CompactionSearchCacheTest.java

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


📝 Walkthrough

Walkthrough

Vector neighbor functions now return no results when a supplied RID filter resolves to an empty set. Location-index publication also clears the vector search cache. Regression tests cover both changes.

Changes

Empty RID filters

Layer / File(s) Summary
Parse and apply RID filters
engine/src/main/java/com/arcadedb/function/sql/vector/SQLFunctionVectorAbstract.java, engine/src/main/java/com/arcadedb/function/sql/vector/SQLFunctionVectorNeighbors.java, engine/src/main/java/com/arcadedb/function/sql/vector/SQLFunctionVectorSparseNeighbors.java
An absent filter remains distinct from an empty RID set. Both vector neighbor functions return no results for an empty set after resolving the index.
Test RID filter behavior
engine/src/test/java/com/arcadedb/function/sql/vector/Issue8959EmptyVectorFilterTest.java, engine/src/test/java/com/arcadedb/function/sql/vector/Issue8959EmptySparseFilterTest.java
Regression tests cover empty and matching filters, null and absent filters, and index-resolution errors.

Compaction search cache

Layer / File(s) Summary
Clear cache on location-index publication
engine/src/main/java/com/arcadedb/index/vector/LSMVectorIndex.java
Publishing a rebuilt location index now clears the search vector cache.
Test search results after compaction
engine/src/test/java/com/arcadedb/index/vector/Issue8957CompactionSearchCacheTest.java
The regression test checks nearest-neighbor ranking and cosine distances before and after compaction.

Priority: ➖ Normal

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

Change: Bug fix · Severity of issue fixed: Medium

Suggested reviewers: robfrank

Merge Risk: ⚪ Minimal · up to 2bb18

The filter and compaction changes are mergeable after normal checks.

Security Architecture Review

Security architecture risk: 🔵 Low · up to 2bb18

The changes tighten search filtering and keep cached vectors aligned with records during compaction. No introduced security concern was identified in the inspected paths, but broader access-control and crash-recovery behavior was not fully verified.

Retained concerns
No architecture-level concerns identified.

Security review details

Security Blast Radius

  • inferred — In the inspected paths, the filter change narrows returned candidates and the cache change acts on an individual index's search-vector cache. Neither change introduces a new caller or identity authority. This does not establish tenant-wide authorization guarantees.

Trust Boundaries and Controls

  • observed — Caller-supplied filter values remain query-selection inputs, not a newly introduced authorization control. String RIDs are validated and materialized through the command-context database; malformed values remain parsing errors, and nonempty sets continue through RID membership checks.

Resilience and Maintainability Implications

  • inferred — The inspected transition preserves record/vector identity across repeated publication and concurrent searches: replacement locations are built before assignment, cache entries use immutable ID/vector pairs with atomic publication, and recovery can discard and recreate the cache. The cache-clear addition does not widen the pre-existing file-swap crash window; that window lacks fault-injection evidence.
🚥 Pre-merge checks | ✅ 4 | ❓ 1

❌ Failed checks (1 inconclusive)

Check name Status Explanation Resolution
Docstring Coverage ❓ Inconclusive Docstring coverage is 4.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 25 functions across 6 files. (1 skipped: 1… Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes both primary changes: empty vector filters return no results, and compaction clears the search cache.
Description check ✅ Passed The description clearly explains the two changes, links them to issues #8959 and #8957, and identifies the regression tests and test results. It omits the template headings and checklist, but the esse…
Linked Issues check ✅ Passed The PR meets the coding requirements for [#8959] and [#8957]. For [#8959], parseRidFilter preserves null for an absent filter and returns an empty RID set for an explicit empty filter. Both `vecto…
Out of Scope Changes check ✅ Passed The changed production code directly implements [#8959] filter semantics and [#8957] cache invalidation. The added tests verify both fixes and related error and filter cases. The available PR summary …
Full details: Docstring Coverage

Explanation

Docstring coverage is 4.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 25 functions across 6 files. (1 skipped: 1 too large.)

✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Commit to this branch
  • Create a new PR
🧪 Generate unit tests (beta)
  • Commit to this branch
  • Create a new PR
  • Autopilot · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Autopilot is currently an internal CodeRabbit preview.


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.

@mergify

mergify Bot commented Oct 2, 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 2, 2026 •

Copy link
Copy Markdown

Up to standards ✅

🟢 Issues 0 issues

Results:
0 new issues

View in Codacy

🟢 Metrics 0 complexity

Metric Results
Complexity 0

View in Codacy

🟢 Coverage 100.00% diff coverage · -5.87% coverage variation

Metric Results
Coverage variation ✅ -5.87% coverage variation
Diff coverage ✅ 100.00% diff coverage

View coverage diff in Codacy

Coverage variation details
Coverable lines Covered lines Coverage
Common ancestor commit (94cf342) 207763 176046 84.73%
Head commit (2bb18f2) 240420 (+32657) 189596 (+13550) 78.86% (-5.87%)

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 (#8971) 8 8 100.00%

Diff coverage is the percentage of lines that are covered by tests out of the coverable lines that the pull request added or modified: <covered lines added or modified>/<coverable lines added or modified> * 100%

NEW Get contextual insights on your PRs based on Codacy's metrics, along with PR and Jira context, without leaving GitHub. Enable AI reviewer
TIP This summary will be updated as you push new changes.

@claude

claude Bot commented Oct 2, 2026

Copy link
Copy Markdown

Review

Both fixes are correct in intent and small. I read the diff and the surrounding code, but did not run the tests.

#8959 (empty filter returns nothing)

  • Splitting "absent" (null) from "present but empty" in parseRidFilter is the right fix, and the early return in both vector.neighbors and vector.sparseNeighbors fails closed, which matters for the tenant-isolation case in the issue. parseRidFilter has only these two callers, so nothing else is affected.
  • Early return happens before the index is resolved. With an empty filter, a typo in the index spec (or a missing index) now returns [] instead of throwing. Moving the check after the index/typeIndex resolution (and the collectSparseIndexes call for sparse) keeps bad specs loud. This is minor but cheap.
  • Fail-open on a null filter value. filter: null (for example a bound parameter that is null) still goes through opts.getList("filter") as null and is treated as "no filter". That is the pre-existing "absent" contract, but for a tenant-scoping use it is the same class of hazard as vector.neighbors: a filter that matches no records is treated as no filter, so the search returns records outside it (a tenant subquery with no rows returns other tenants' records) #8959. Worth a conscious decision, or at least a note in the docs.
  • Test gap: Issue8959EmptyVectorFilterTest only covers vectorNeighbors. The sparse function got the same change but has no regression test. Please add one for vectorSparseNeighbors.

#8957 (clear search cache on publish)

  • Clearing in publishLocationIndex after the residentLocations swap, under the write lock, is the right place and ordering for the renumbering compaction.
  • Clears on every publish, not just renumbering. publishLocationIndex is also called from the graph rebuild path (LSMVectorIndex.java:3259) where ids do not change, so those rebuilds now also drop a warm cache and the next searches pay cold reads. Probably acceptable (rebuilds are rare and heavy), but you could clear only on the renumbering path (the compactDataFile branch, line ~774) if you want to avoid the extra cost. A comment saying the broader clear is intentional would help either way.
  • Residual race. The write lock does not stop a search that started before the swap and is still running: it can put an old-id to old-vector entry into the cache after clear(). The window is narrow, but the invariant "no stale entry survives the publish" is not strictly guaranteed. If you want it airtight, key the cache by a generation or have the cache be replaced (new VectorCache instance referenced by the searchers) instead of cleared in place. Fine to leave and note if you judge it too rare.
  • The test is good: it exercises update-then-compact on 2000 vectors and checks both the top hit and the distances before and after compaction. It is single-threaded, so it does not cover the race above.

Style

Follows CLAUDE.md conventions (final params, AssertJ style, no new deps, no debug output). Nothing to flag.

Overall: LGTM modulo adding the sparse test, and consider moving the empty-filter return after index resolution.

@claude

claude Bot commented Oct 2, 2026

Copy link
Copy Markdown

Review of #8971

Both fixes look correct and are tightly scoped. The empty-filter change closes a real tenant-isolation hole (an empty subquery silently turning into an unfiltered search), and the cache clear matches how the id-keyed cache is already invalidated elsewhere. No blocking issues. Notes below.

#8959 - empty filter

  • parseRidFilter now distinguishes "absent" (null) from "present but empty" (empty set), and both functions short-circuit after the index spec is resolved, so a bad spec still fails loudly. Good ordering, covered by badIndexSpecStaysLoudWithAnEmptyFilter.
  • The root cause still lives in the engine layer. LSMVectorIndex treats an empty allow-list as "no filter" in several places (allowedRIDs != null && !allowedRIDs.isEmpty() around lines 6413, 6682, 6761, 6795), and the sparse engine has the same shape. The SQL functions are now safe, but any other caller that passes an empty set to findNeighborsFromVector(..., allowedRIDs) or topK(...) (Java API, other query languages, future call sites) still gets an unfiltered result. Not blocking, but consider documenting on those public methods that empty means unrestricted, or a follow-up issue to make the index treat an empty non-null set as "match nothing".
  • Minor: List.of() would avoid the new ArrayList<>(0) allocation.

#8957 - cache clear on publish

  • Clearing inside publishLocationIndex (under the write lock, after residentLocations is swapped) is the right place. Both the compaction path (rewriteDataFileWithLiveEntries) and the rebuild path (~line 3260) go through it, so one rule covers both. A search that repopulates the cache afterwards loads via the new location index, so entries are consistent with the new numbering.
  • Cost: every rebuild now drops a warm cache, not only renumbering ones. The comment justifies this and I agree; a brief latency blip after a rebuild is expected.
  • VectorCache.clear() is O(capacity) while holding the write lock. Small next to the rebuild itself, but worth knowing for very large caches.

Tests

  • All three follow project style (assertThat(...), no System.out, no hardcoded ports); the compaction test uses a fixed seed. It verifies behaviour (distances recomputed from source vectors) rather than cache internals, which is good.
  • Issue8959EmptySparseFilterTest is not mentioned in the PR description (only two tests are listed). Please confirm it also fails without the fix.
  • badIndexSpecStaysLoudWithAnEmptyFilter (sparse) only asserts isInstanceOf(Exception.class), which any failure satisfies. Asserting CommandSQLParsingException or a message fragment would actually prove the ordering claim. The dense test class has no equivalent; adding one would be symmetric.
  • Consider pinning filter: [[]] and a list of only nulls: both now resolve to an empty set and so to an empty result. That is the intended behaviour but a visible change.

Behaviour change to flag

Anyone relying on filter: [] meaning "no restriction" now gets an empty result. That is the safe direction and matches the issue, but it deserves a changelog line.

Overall: LGTM, with the optional follow-ups above.

@claude

claude Bot commented Oct 2, 2026

Copy link
Copy Markdown

Review

Overall: both fixes are small, targeted and correct as far as I can tell. No blockers.

#8959 (empty filter)

  • Dropping items.isEmpty() from parseRidFilter and short-circuiting on allowedRIDs.isEmpty() after the index is resolved is the right shape, and keeping the bad-index-spec error loud (with tests for it) is a nice touch. Only two callers of parseRidFilter exist, and both are covered.
  • One fail-open edge worth a conscious decision: filter: null (for example a bound parameter that is null, or a subquery that yields a null list) still means "no filter" and searches everything. That is the same class of bug for a tenant-isolation use case. If the option key is present but the value is null, returning empty may be the safer reading. If you keep the current behaviour, a test pinning it down would document the choice.
  • The same early-return could live once in the abstract class instead of being duplicated in both functions, but with two call sites this is fine as is.

#8957 (search cache)

  • Clearing under the write lock inside publishLocationIndex matches the invariant (searches hold the read lock when filling the cache), and clearing on every publish is a sensible simplification.
  • VectorCache.clear() is O(capacity) (nulls every slot) and runs inside the write-locked section. Capacity is bounded by computeSearchCacheCapacity(), so this is probably negligible next to the rebuild, but if capacity can reach millions it extends the write-lock hold time. Swapping in a fresh cache (or a generation counter) would avoid that; not required.
  • Line 3260 is the second publishLocationIndex caller. Worth a one-line confirmation that it also runs under the write lock, since the new clear relies on that.

Tests

  • Good coverage: empty subquery, empty list, nested empty, list of nulls, still-restricts, absent filter, bad index spec, and a compaction regression that checks distances against the true vectors (so a stale cache is caught even when the top hit is right).
  • Issue8957CompactionSearchCacheTest only verifies the end result after COMPACT INDEX. It does not assert that the cache was populated before compaction, so it could pass vacuously if the warm-up stopped populating the cache. The PR says it fails without the fix, so it is fine today.
  • Nits: in Issue8959EmptySparseFilterTest the count helper passes unused ids/tenant params in some calls, and the imports are slightly out of order (ResultSet before SchemaException). The long LSMVectorIndex cast line in the compaction test exceeds the usual line width.
  • Per CLAUDE.md, none of these need @Tag("slow") (2000 small docs), and no wall-clock assertions are used. Good.

LGTM modulo the filter: null question.

@claude

claude Bot commented Oct 2, 2026

Copy link
Copy Markdown

Review

Overall this is a clean, well-scoped fix for both issues. Both regression tests are described as failing without the fix, and the guard sits at the right point.

#8959 (empty filter)

  • parseRidFilter now returns null only for an absent option and an empty set otherwise. The two call sites short-circuit after the index is resolved, so a bad index spec still throws. Both are covered by tests.
  • filter: [] used to mean "no filter" and now means "match nothing". That is a deliberate and correct change (it was a tenant-isolation leak), but it is user visible. Please mention it in the release notes and check that the vector function docs don't describe the old behavior.
  • The root cause remains one layer down: LSMVectorIndex.findNeighborsFromVector(..., Set<RID> allowedRIDs) and the sparse topK(...) still treat an empty set as "no filter". Any other caller that passes an empty set (Java API, other modules) has the same leak. Consider making the index-level contract explicit (return empty for an empty non-null set, or document/assert it) so the hazard doesn't recur.
  • The null-filter test pins "null means absent", which is good.

#8957 (search cache after compaction)

  • Clearing searchVectorCache inside publishLocationIndex is the right place, under the same write lock as the new ids.
  • Performance: the comment says every publish clears, not only renumbering ones. The rebuild path in LSMVectorIndex (around line 10410) deliberately feeds the shared search cache while serializing the graph so the index comes out of a rebuild with its working set resident (issue 5412). If that serialization runs before the publish, this clear throws that warm-up away on every rebuild. Please confirm the ordering, and if so consider clearing only when ids were actually renumbered (the compaction path already knows it reset nextId), or accept the cold start explicitly.
  • Residual race: a search that started before the publish and still holds the old location snapshot/ordinal map could repopulate the cache with old-id to old-vector entries after the clear(). VectorCache.clear() only nulls slots and entries are not versioned. If searches hold the read lock for their full duration, including cache population, the write lock excludes them and this is safe; if not, a generation counter checked on put would close it. A short comment stating which holds would help future readers.

Tests

  • Good coverage on the SQL side: subquery matching nothing, empty list, nested empty list, list of nulls, null filter, non-empty filter still restricting, absent filter, and bad index spec.
  • Issue8957CompactionSearchCacheTest is a solid end-to-end check (updates first so ids are non-trivial, then compaction, then verifies scores against recomputed cosine distance). It only exercises findNeighborsFromVector on the bucket index; there is no case for a non-renumbering publish or a search concurrent with compaction. Not blocking.
  • Cosmetic: the all-caps PINNED CONTRACT comment is shouty compared with the rest of the file, and imports in the sparse test are slightly out of order.
  • Please confirm the 2000-vector + compaction test runs fast enough not to need @tag("slow").

Style / CLAUDE.md

  • Final variables, imports, and AssertJ style follow the guidelines. No new dependencies, no stray System.out.

Nothing blocking from my side; the main thing worth a reply is the cache-clear vs. rebuild warm-up and the in-flight search question.

@codecov

codecov Bot commented Oct 2, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 76.52%. Comparing base (94cf342) to head (2bb18f2).
⚠️ Report is 7 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff            @@
##               main    #8971   +/-   ##
=========================================
  Coverage     76.51%   76.52%           
+ Complexity     3851     3849    -2     
=========================================
  Files          2109     2109           
  Lines        207763   207820   +57     
  Branches      43824    43845   +21     
=========================================
+ Hits         158974   159035   +61     
  Misses        31756    31756           
+ Partials      17033    17029    -4     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@lvca
lvca merged commit 66541f5 into main Oct 3, 2026
@lvca
lvca deleted the fix/8959-8957-vector-filter-compact branch October 3, 2026 01:30
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment