You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@pinot.apache.org by "xiangfu0 (via GitHub)" <gi...@apache.org> on 2026/08/19 01:12:57 UTC
[PR] Enforce the upsert doc-ids snapshot in vector candidate generation [pinot]
xiangfu0 opened a new pull request, #19303:
URL: https://github.com/apache/pinot/pull/19303
## Problem
On FULL-upsert tables, `WHERE vectorSimilarity(col, query, K)` planned the ANN search over **all physical rows** and only ANDed the upsert doc-ids snapshot around the result afterwards (`FilterPlanNode.run()`). Obsolete row versions that are physically nearest to the query consume the per-segment top-K candidate budget before the snapshot removes them, so a segment can return fewer than K rows and omit nearer current rows entirely.
Repro shape: entity A's old version sits at the query vector, its new version far away, entities B/C in between. The old A rows win the K candidate slots, get removed by the snapshot AND, and B/C never become candidates — the query returns the wrong entities. The new integration test's `OPTION(skipUpsert=true)` control query demonstrates the obsolete rows are physically nearest.
## What this PR does
The upsert doc-ids snapshot is now a **required candidate filter**, enforced *before* top-K selection on every vector path, and kept strictly separate from the optional metadata prefilter (which retains its adaptive `VectorSearchStrategy` behavior). The outer bitmap AND is retained as defense in depth. This lands as three units (bundled because the integration test exercises them together):
### 1. Required-filter enforcement (pinot-core)
- `FilterPlanNode` captures a defensive copy of the snapshot whenever the filter tree contains a vector predicate (any depth — AND/OR/NOT), clamps it to the planned doc range (under `ConsistencyMode.NONE` the snapshot can reference a row still being written), passes it into the vector operators via the new `VectorSearchSpec` construction context, and uses the same instance for the outer AND.
- `VectorSimilarityFilterOperator`: with a required filter present, candidate generation always uses the filter-aware 3-arg `getDocIds` (intersected with the optional metadata prefilter when both apply, `effectiveAllowed = required ∩ optional`); an empty snapshot/intersection returns empty without invoking the reader; unfiltered ANN is **refused** (`IllegalStateException`) rather than silently run.
- `ExactVectorScanFilterOperator` and `VectorRadiusFilterOperator` scan only the required doc ids when present (top-K and threshold modes) — top-K is selected from the allowed set directly, never computed physically and intersected afterwards. Readers that cannot honor the filter are routed to the exact allowed-doc scan at plan time.
- `VECTOR_SIMILARITY_RADIUS` was already *correct* without this (its candidate-saturation fallback guarantees completeness), but is included so obsolete rows stop wasting its candidate budget and triggering the expensive saturation fallback early.
- Explain/trace output reports `upsertRequiredDocIdsCardinality`, the search mode actually executed (`FILTER_THEN_ANN` / `EXACT_SCAN`), and a clear `upsert_snapshot_*` fallback reason for non-filter-aware readers.
### 2. Filter-aware mutable HNSW (pinot-segment-local)
`MutableVectorIndex` now implements `FilterAwareVectorIndexReader`, so consuming segments use filtered ANN instead of an exact-scan fallback:
- Stores the **supplied** Pinot doc id (StoredField + NumericDocValues) and translates every search hit through it. This also fixes a latent bug on the unfiltered path, which used `ScoreDoc.doc` directly and silently assumed Lucene doc ids equal Pinot doc ids — untrue once Lucene merges renumber across commits.
- Filtered search runs against a `SearcherManager` near-real-time view over the writer (refresh-coalescing, reader reused when nothing changed), so uncommitted rows — typically the *newest* version of a record — are visible. The unfiltered path keeps the cheaper last-committed view, unchanged.
- Bitmap membership is tested per-leaf through doc values (`BasePinotDocIdBitmapFilterQuery`, now shared with the immutable `HnswVectorIndexReader`'s filter query so the correctness-sensitive scaffolding cannot drift).
- `FilterAwareVectorIndexReader` Javadoc now documents the strict contract implementations sign up for: filtered results MUST be a subset of the bitmap, never heuristically degraded — upsert correctness depends on it.
### 3. Vector-column encoding validation (pinot-segment-local)
`VectorIndexType.validate()` now rejects dictionary-encoded vector columns. Every forward-index read path used by vector search (exact-scan fallback, exact rerank, distance-threshold and radius refinement) calls `getFloatMV`, which dictionary-encoded MV readers do not implement — such configs passed validation but failed at query time.
## :warning: Backward incompatible
A table config with a vector index on a column **not** declared `encodingType: RAW` (dictionary encoding is the default) was previously accepted; after this change its next table-config create/update fails validation. Such tables were already broken for the rerank/threshold/exact-scan/radius query paths. **Migration:** declare `encodingType: RAW` (or add the column to `noDictionaryColumns`) and reload segments. All in-tree vector tables already use RAW.
Other behavior changes to be aware of:
- Vector query results on FULL-upsert tables change — previously silently wrong (obsolete rows consumed candidate slots).
- Third-party `VectorIndexReader` plugins that are not filter-aware now take an exact allowed-doc scan on upsert tables (logged at DEBUG with an `upsert_snapshot_*` reason), and fail loudly if no forward index exists where they previously returned upsert-inconsistent unfiltered ANN results. All built-in readers (immutable HNSW/IVF_FLAT/IVF_PQ/IVF_ON_DISK and now mutable HNSW) are filter-aware.
- The exact-scan log for the expected upsert fallback dropped WARN → DEBUG; genuinely-missing-index scans keep the WARN.
- No wire/storage format changes; the mutable index's new doc-values field lives only in the process-local realtime temp index.
## Testing
All deterministic — no reliance on probabilistic ANN recall (fixtures place obsolete rows physically nearest, with distinct distances).
- **pinot-core (110 tests)**: planner/operator tests assert the 3-arg filtered reader is invoked with exactly the snapshot (ArgumentCaptor), the unfiltered overload never runs, required ∩ optional intersection is delivered without mutating either input, empty snapshot/intersection skip the reader, null snapshot preserves existing behavior byte-for-byte, non-filter-aware readers route to the allowed-doc exact scan (or fail loudly with no forward index), the snapshot copy is defensive (post-plan mutation doesn't leak), out-of-range snapshot ids are clamped, mutable segments don't wire the *optional* prefilter, and radius filtered/brute-force/saturation paths behave.
- **pinot-segment-local (26 tests)**: real immutable HNSW filtered search excludes physically-nearest disallowed docs; mutable index filtered search is NRT-visible for uncommitted rows, translates supplied (offset) Pinot doc ids on both filtered and unfiltered paths, and stays correct under a live concurrent writer; RAW-encoding validation accept/reject.
- **Integration (`custom/VectorUpsertTableTest`, shared suite — no dedicated cluster)**: FULL upsert, one Kafka partition, 2-D vectors, stable producer keys, polling-based waits. Covers (1) all records in one consuming segment (NRT filtered mutable HNSW) and (2) obsolete rows sealed into an immutable segment with the new versions in the next consuming segment (filtered immutable HNSW, cross-segment invalidation); both query engines; `skipUpsert=true` control proving obsolete rows are physically nearest; agreement with the exact scalar-distance query. Pre-existing `VectorTest` (19) and `IvfPqVectorRealtimeTest` (6) pass unchanged.
- spotless / checkstyle / license clean on all touched modules.
## Notes / follow-ups
- Filtered ANN with a near-full snapshot pays an O(numDocs) accept-bitset cost per query per segment that unfiltered ANN did not; this is correctness-mandated, but a JMH comparison on a large lightly-upserted segment would quantify it, and a dense-snapshot fast path (over-fetch + intersect + retry) is a possible optimization.
- A public force-prefilter query option (guaranteed tenant/model-scoped top-K over metadata filters) is deliberately out of scope.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org
Re: [PR] Enforce the upsert doc-ids snapshot in vector candidate generation [pinot]
Posted by "codecov-commenter (via GitHub)" <gi...@apache.org>.
codecov-commenter commented on PR #19303:
URL: https://github.com/apache/pinot/pull/19303#issuecomment-5336563986
## [Codecov](https://app.codecov.io/gh/apache/pinot/pull/19303?dropdown=coverage&src=pr&el=h1&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) Report
:x: Patch coverage is `15.70513%` with `263 lines` in your changes missing coverage. Please review.
:white_check_mark: Project coverage is 39.19%. Comparing base ([`1019930`](https://app.codecov.io/gh/apache/pinot/commit/1019930cd7e7e166b00a86400029b678d2b7a67f?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache)) to head ([`66ecb21`](https://app.codecov.io/gh/apache/pinot/commit/66ecb21e5fcd59dc212d2024597734a404e06424?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache)).
:warning: Report is 19 commits behind head on master.
| [Files with missing lines](https://app.codecov.io/gh/apache/pinot/pull/19303?dropdown=coverage&src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | Patch % | Lines |
|---|---|---|
| [...operator/filter/ExactVectorScanFilterOperator.java](https://app.codecov.io/gh/apache/pinot/pull/19303?src=pr&el=tree&filepath=pinot-core%2Fsrc%2Fmain%2Fjava%2Forg%2Fapache%2Fpinot%2Fcore%2Foperator%2Ffilter%2FExactVectorScanFilterOperator.java&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-cGlub3QtY29yZS9zcmMvbWFpbi9qYXZhL29yZy9hcGFjaGUvcGlub3QvY29yZS9vcGVyYXRvci9maWx0ZXIvRXhhY3RWZWN0b3JTY2FuRmlsdGVyT3BlcmF0b3IuamF2YQ==) | 0.00% | [72 Missing :warning: ](https://app.codecov.io/gh/apache/pinot/pull/19303?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) |
| [...re/operator/filter/VectorRadiusFilterOperator.java](https://app.codecov.io/gh/apache/pinot/pull/19303?src=pr&el=tree&filepath=pinot-core%2Fsrc%2Fmain%2Fjava%2Forg%2Fapache%2Fpinot%2Fcore%2Foperator%2Ffilter%2FVectorRadiusFilterOperator.java&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-cGlub3QtY29yZS9zcmMvbWFpbi9qYXZhL29yZy9hcGFjaGUvcGlub3QvY29yZS9vcGVyYXRvci9maWx0ZXIvVmVjdG9yUmFkaXVzRmlsdGVyT3BlcmF0b3IuamF2YQ==) | 0.00% | [63 Missing :warning: ](https://app.codecov.io/gh/apache/pinot/pull/19303?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) |
| [...ava/org/apache/pinot/core/plan/FilterPlanNode.java](https://app.codecov.io/gh/apache/pinot/pull/19303?src=pr&el=tree&filepath=pinot-core%2Fsrc%2Fmain%2Fjava%2Forg%2Fapache%2Fpinot%2Fcore%2Fplan%2FFilterPlanNode.java&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-cGlub3QtY29yZS9zcmMvbWFpbi9qYXZhL29yZy9hcGFjaGUvcGlub3QvY29yZS9wbGFuL0ZpbHRlclBsYW5Ob2RlLmphdmE=) | 0.00% | [44 Missing and 1 partial :warning: ](https://app.codecov.io/gh/apache/pinot/pull/19303?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) |
| [...perator/filter/VectorSimilarityFilterOperator.java](https://app.codecov.io/gh/apache/pinot/pull/19303?src=pr&el=tree&filepath=pinot-core%2Fsrc%2Fmain%2Fjava%2Forg%2Fapache%2Fpinot%2Fcore%2Foperator%2Ffilter%2FVectorSimilarityFilterOperator.java&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-cGlub3QtY29yZS9zcmMvbWFpbi9qYXZhL29yZy9hcGFjaGUvcGlub3QvY29yZS9vcGVyYXRvci9maWx0ZXIvVmVjdG9yU2ltaWxhcml0eUZpbHRlck9wZXJhdG9yLmphdmE=) | 0.00% | [44 Missing :warning: ](https://app.codecov.io/gh/apache/pinot/pull/19303?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) |
| [...e/pinot/core/operator/filter/VectorSearchSpec.java](https://app.codecov.io/gh/apache/pinot/pull/19303?src=pr&el=tree&filepath=pinot-core%2Fsrc%2Fmain%2Fjava%2Forg%2Fapache%2Fpinot%2Fcore%2Foperator%2Ffilter%2FVectorSearchSpec.java&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-cGlub3QtY29yZS9zcmMvbWFpbi9qYXZhL29yZy9hcGFjaGUvcGlub3QvY29yZS9vcGVyYXRvci9maWx0ZXIvVmVjdG9yU2VhcmNoU3BlYy5qYXZh) | 0.00% | [22 Missing :warning: ](https://app.codecov.io/gh/apache/pinot/pull/19303?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) |
| [...eaders/vector/BasePinotDocIdBitmapFilterQuery.java](https://app.codecov.io/gh/apache/pinot/pull/19303?src=pr&el=tree&filepath=pinot-segment-local%2Fsrc%2Fmain%2Fjava%2Forg%2Fapache%2Fpinot%2Fsegment%2Flocal%2Fsegment%2Findex%2Freaders%2Fvector%2FBasePinotDocIdBitmapFilterQuery.java&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-cGlub3Qtc2VnbWVudC1sb2NhbC9zcmMvbWFpbi9qYXZhL29yZy9hcGFjaGUvcGlub3Qvc2VnbWVudC9sb2NhbC9zZWdtZW50L2luZGV4L3JlYWRlcnMvdmVjdG9yL0Jhc2VQaW5vdERvY0lkQml0bWFwRmlsdGVyUXVlcnkuamF2YQ==) | 57.14% | [8 Missing and 1 partial :warning: ](https://app.codecov.io/gh/apache/pinot/pull/19303?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) |
| [...local/realtime/impl/vector/MutableVectorIndex.java](https://app.codecov.io/gh/apache/pinot/pull/19303?src=pr&el=tree&filepath=pinot-segment-local%2Fsrc%2Fmain%2Fjava%2Forg%2Fapache%2Fpinot%2Fsegment%2Flocal%2Frealtime%2Fimpl%2Fvector%2FMutableVectorIndex.java&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-cGlub3Qtc2VnbWVudC1sb2NhbC9zcmMvbWFpbi9qYXZhL29yZy9hcGFjaGUvcGlub3Qvc2VnbWVudC9sb2NhbC9yZWFsdGltZS9pbXBsL3ZlY3Rvci9NdXRhYmxlVmVjdG9ySW5kZXguamF2YQ==) | 80.95% | [6 Missing and 2 partials :warning: ](https://app.codecov.io/gh/apache/pinot/pull/19303?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) |
> :exclamation: There is a different number of reports uploaded between BASE (1019930) and HEAD (66ecb21). Click for more details.
>
> <details><summary>HEAD has 24 uploads less than BASE</summary>
>
>| Flag | BASE (1019930) | HEAD (66ecb21) |
>|------|------|------|
>|lane-a|2|0|
>|integration|4|0|
>|java-25|6|1|
>|integration2|2|0|
>|temurin|6|1|
>|lane-b|2|0|
>|unittests1|1|0|
>|unittests|2|1|
>|integration1|2|0|
></details>
<details><summary>Additional details and impacted files</summary>
```diff
@@ Coverage Diff @@
## master #19303 +/- ##
=============================================
- Coverage 67.10% 39.19% -27.92%
+ Complexity 1424 1417 -7
=============================================
Files 3459 3464 +5
Lines 219697 220567 +870
Branches 34985 35191 +206
=============================================
- Hits 147432 86453 -60979
- Misses 60488 126234 +65746
+ Partials 11777 7880 -3897
```
| [Flag](https://app.codecov.io/gh/apache/pinot/pull/19303/flags?src=pr&el=flags&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | Coverage Δ | |
|---|---|---|
| [integration](https://app.codecov.io/gh/apache/pinot/pull/19303/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `?` | |
| [integration1](https://app.codecov.io/gh/apache/pinot/pull/19303/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `?` | |
| [integration2](https://app.codecov.io/gh/apache/pinot/pull/19303/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `?` | |
| [java-25](https://app.codecov.io/gh/apache/pinot/pull/19303/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `39.19% <15.70%> (-27.92%)` | :arrow_down: |
| [lane-a](https://app.codecov.io/gh/apache/pinot/pull/19303/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `?` | |
| [lane-b](https://app.codecov.io/gh/apache/pinot/pull/19303/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `?` | |
| [temurin](https://app.codecov.io/gh/apache/pinot/pull/19303/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `39.19% <15.70%> (-27.92%)` | :arrow_down: |
| [unittests](https://app.codecov.io/gh/apache/pinot/pull/19303/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `39.19% <15.70%> (-27.91%)` | :arrow_down: |
| [unittests1](https://app.codecov.io/gh/apache/pinot/pull/19303/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `?` | |
| [unittests2](https://app.codecov.io/gh/apache/pinot/pull/19303/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `39.19% <15.70%> (-0.04%)` | :arrow_down: |
Flags with carried forward coverage won't be shown. [Click here](https://docs.codecov.io/docs/carryforward-flags?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#carryforward-flags-in-the-pull-request-comment) to find out more.
</details>
[:umbrella: View full report in Codecov by Harness](https://app.codecov.io/gh/apache/pinot/pull/19303?dropdown=coverage&src=pr&el=continue&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache).
:loudspeaker: Have feedback on the report? [Share it here](https://about.codecov.io/codecov-pr-comment-feedback/?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache).
<details><summary> :rocket: New features to boost your workflow: </summary>
- :package: [JS Bundle Analysis](https://docs.codecov.com/docs/javascript-bundle-analysis): Save yourself from yourself by tracking and limiting bundle sizes in JS merges.
</details>
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org
Re: [PR] Enable filtered vector search on mutable HNSW and share the doc-id filter query [pinot]
Posted by "xiangfu0 (via GitHub)" <gi...@apache.org>.
xiangfu0 commented on PR #19303:
URL: https://github.com/apache/pinot/pull/19303#issuecomment-5485829066
Addressed the seven items from the latest review on head `ea22c5d4d416987d4ec7bf3704edd168337b8d6c`:
1. Replaced `maybeRefreshBlocking()` with generation-aware coalescing. One caller refreshes the captured writer sequence while same-generation callers wait; a caller targeting a genuinely newer sequence performs the next refresh. The test now deterministically holds the winner after it publishes the in-progress state, proves another caller entered the production wait branch, then verifies all eight calls complete with exactly one refresh. I also added an 8-reader/1-writer workload and compared the original and updated heads below.
2. Empty bitmaps return before NRT refresh and before search-executor submission. The test occupies the only search worker, requires the empty-filter call to finish within one second, and asserts zero refreshes.
3. Added mutable HNSW selectivity coverage at 100%, 10%, 1%, and 0.1% over 25,000 vectors. Updated-head recall/p50/p95 were: `0.3550/486.5/900.1 µs`, `0.8600/798.0/1170.3 µs`, `1.0000/338.3/431.4 µs`, and `1.0000/207.0/242.5 µs`.
4. Reworked the live-writer test into phased, deterministic overlap inside Lucene filter evaluation. Cleanup force-terminates synchronization and interrupts/joins the writer with a bound.
5. Made the IVF-PQ case non-vacuous: the query document and nearest unfiltered neighbor are excluded, and the test requires the exact farther allowed documents.
6. Renamed the shared class to `BasePinotDocIdBitmapFilterQuery` and added direct scorer/cache/identity/visitor tests.
7. Rewrote the single commit message and PR body to match the actual implementation; the stale per-instance-directory claim and stored-field wording are gone.
Concurrent workload, same revised harness and settings (`4k` initial + `4k` adds, 8 readers, 1% filter):
| Head | Ingest docs/s | Recall@10 | p50 (µs) | p95 (µs) | Wall QPS |
| --- | ---: | ---: | ---: | ---: | ---: |
| Original `322c2bd1f6` | 12,512.2 | 1.0000 | 7,800.6 | 287,008.0 | 123.4 |
| Updated `ea22c5d4d4` | 13,445.1 | 1.0000 | 9,050.8 | 260,266.0 | 134.0 |
Validation: 77 targeted vector tests pass, `VectorUpsertTableTest` passes under both query engines, `pinot-perf` compiles, and Spotless/Checkstyle/license format/license check pass on all five affected modules.
@Jackie-Jiang please take another look when convenient.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org
Re: [PR] Enable filtered vector search on mutable HNSW and share the doc-id filter query [pinot]
Posted by "xiangfu0 (via GitHub)" <gi...@apache.org>.
xiangfu0 commented on PR #19303:
URL: https://github.com/apache/pinot/pull/19303#issuecomment-5503267962
Addressed the follow-up scope review in `265c9da852` and rebased the PR onto current `master` (`9fd510fe81`).
- Removed both benchmark implementations while retaining their measurements in the PR description.
- Reverted the unrelated immutable-HNSW and IVF changes/tests, SPI/comment-only churn, and redundant mutable-index edge tests.
- Added a mode-only strategy path so `FilterPlanNode` does not eagerly format explanations.
- Removed the shared-worker re-interrupt while preserving the interruption as the `IOException` cause.
- Kept the sparse exact-scan strategy, generation-based refresh coalescing, shared `BaseFilterQuery`, realtime integration coverage, and FULL-upsert coverage.
- Applied the three inline requests: `BaseFilterQuery` naming, `DataType` import, and static TestNG assertions.
Validation on the rebased patch: 69 focused unit tests and 8 integration tests pass; both integration commands completed the full 63-module reactor successfully. Spotless, Checkstyle, license format, and license check pass on all three affected modules.
The dense FULL-upsert-plus-filtered-ANN fixture and newer-generation-behind-in-flight-refresh test remain intentionally out of scope as the review marked both coverage gaps non-blocking.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org
Re: [PR] Enable filtered vector search on mutable HNSW and share the doc-id filter query [pinot]
Posted by "Jackie-Jiang (via GitHub)" <gi...@apache.org>.
Jackie-Jiang commented on code in PR #19303:
URL: https://github.com/apache/pinot/pull/19303#discussion_r3890217425
##########
pinot-segment-local/src/main/java/org/apache/pinot/segment/local/realtime/impl/vector/MutableVectorIndex.java:
##########
@@ -90,13 +127,11 @@ public MutableVectorIndex(String segmentName, String vectorColumn, VectorIndexCo
_commitDocs = Long.parseLong(
vectorIndexConfig.getProperties().getOrDefault("commitDocs", String.valueOf(DEFAULT_COMMIT_DOCS)));
_vectorSimilarityFunction = VectorIndexUtils.toSimilarityFunction(vectorIndexConfig.getVectorDistanceFunction());
- // Each column of a segment gets its own directory, so that cleaning up one column does not remove the index of
- // another column of the same segment.
- _indexDir = new File(new File(FileUtils.getTempDirectory(), segmentName),
- _vectorColumn + V1Constants.Indexes.VECTOR_V912_HNSW_INDEX_FILE_EXTENSION);
+ _indexDir = createIndexDir(segmentName, _vectorColumn);
Review Comment:
The per-instance directory isolation change fixes an independent write-lock/lifecycle problem and has its own dedicated test. This PR is already a large correctness-sensitive filtered-ANN change; please move directory isolation into a focused follow-up PR unless it is required for the mutable pre-filter capability.
##########
pinot-segment-local/src/main/java/org/apache/pinot/segment/local/realtime/impl/vector/MutableVectorIndex.java:
##########
@@ -279,18 +450,35 @@ public void close() {
try {
_indexWriter.commit();
// IndexWriter does not close the Directory passed to it, so both need to be closed.
- IOUtils.close(_indexWriter, _indexDirectory);
+ IOUtils.close(_searcherManager, _indexWriter, _indexDirectory);
} catch (IOException e) {
- // Both close() implementations are idempotent, so this is a no-op for whatever was already closed above.
- IOUtils.closeWhileHandlingException(_indexWriter, _indexDirectory);
+ // All close() implementations are idempotent, so this is a no-op for whatever was already closed above.
+ IOUtils.closeWhileHandlingException(_searcherManager, _indexWriter, _indexDirectory);
throw new RuntimeException(e);
} finally {
deleteIndexDir();
}
}
- /// Deletes the temporary index directory of this column, then the segment directory holding it if this was the last
- /// column with an index under it.
+ /// Creates a private directory for this index instance, under a directory named for the segment.
+ ///
+ /// The directory is unique per instance rather than per segment and column, so two replicas of the same segment
+ /// hosted in one JVM cannot collide on the Lucene write lock. Segment and column stay in the path so a leaked
+ /// directory can still be attributed to its owner.
+ private static File createIndexDir(String segmentName, String column) {
+ File segmentDir = new File(FileUtils.getTempDirectory(), segmentName);
+ try {
+ Files.createDirectories(segmentDir.toPath());
+ return Files.createTempDirectory(segmentDir.toPath(),
+ column + V1Constants.Indexes.VECTOR_V912_HNSW_INDEX_FILE_EXTENSION + '_').toFile();
+ } catch (IOException e) {
+ throw new RuntimeException(
+ "Failed to create mutable vector index directory for column: " + column + ", segment: " + segmentName, e);
+ }
+ }
+
+ /// Deletes the temporary index directory of this instance, then the segment directory holding it if this was the
Review Comment:
Deleting the shared segment parent races with construction of another index for the same segment. T2 can create/observe the parent, T1 can delete it after removing its private child, and then T2's `createTempDirectory(segmentDir, ...)` fails with `NoSuchFileException`. Please delete only this instance's private `_indexDir`, or coordinate parent creation/deletion atomically.
##########
pinot-segment-local/src/main/java/org/apache/pinot/segment/local/segment/index/readers/vector/IvfPqVectorIndexReader.java:
##########
@@ -217,6 +217,13 @@ public MutableRoaringBitmap getDocIds(float[] searchQuery, int topK) {
return result;
}
+ @Override
+ public boolean supportsPreFilter() {
Review Comment:
This explicit pre-filter opt-in is behaviorally significant now that the interface default is `false`, but IVF_PQ has no test covering the override or filtered path. Please add coverage asserting `supportsPreFilter()` and verifying that filtered search excludes nearer disallowed documents, or an integration query whose EXPLAIN reports `FILTER_THEN_ANN`.
##########
pinot-segment-local/src/test/java/org/apache/pinot/segment/local/realtime/impl/vector/MutableVectorIndexTest.java:
##########
@@ -80,12 +84,180 @@ public void testRuntimeControlDebugInfoReflectsOverrides() {
Assert.assertEquals(debugInfo.get("effectiveEfSearch"), 6);
Assert.assertEquals(debugInfo.get("effectiveHnswUseRelativeDistance"), Boolean.FALSE);
Assert.assertEquals(debugInfo.get("effectiveHnswUseBoundedQueue"), Boolean.FALSE);
- Assert.assertEquals(debugInfo.get("supportsPreFilter"), Boolean.FALSE);
+ Assert.assertEquals(debugInfo.get("supportsPreFilter"), Boolean.TRUE);
+ Assert.assertTrue(index.supportsPreFilter(),
+ "The reader must advertise filtered search: that is what makes the planner choose it over an exact scan");
} finally {
index.close();
}
}
+ // -----------------------------------------------------------------------
+ // Filtered search (upsert doc-ids snapshot enforcement)
+ // -----------------------------------------------------------------------
+
+ /// 2-D corpus with distinct distances from the query vector {1, 0}:
+ /// docs 0 and 1 are nearest (the "upsert-obsoleted" rows), docs 2 and 3 are the valid rows.
+ private static MutableVectorIndex create2DIndex(long commitDocs, int docIdOffset) {
+ Map<String, String> properties = new HashMap<>();
+ properties.put("commitDocs", String.valueOf(commitDocs));
+ properties.put("vectorIndexType", "HNSW");
+ properties.put("vectorDimension", "2");
+ VectorIndexConfig config = new VectorIndexConfig(false, "HNSW", 2, 1,
+ VectorIndexConfig.VectorDistanceFunction.EUCLIDEAN, properties);
+ MutableVectorIndex index =
+ new MutableVectorIndex("mutableVectorIndexFilterTest_" + System.nanoTime(), COLUMN_NAME, config);
+ addVector(index, new float[]{1.0F, 0.0F}, docIdOffset);
+ addVector(index, new float[]{0.99F, 0.01F}, docIdOffset + 1);
+ addVector(index, new float[]{0.0F, 1.0F}, docIdOffset + 2);
+ addVector(index, new float[]{0.0F, -1.0F}, docIdOffset + 3);
+ return index;
+ }
+
+ @Test
+ public void testFilteredSearchExcludesNearestDisallowedDocs() {
+ // commitDocs=4 commits on the 4th add, so the unfiltered committed-view sanity check below sees all rows
+ MutableVectorIndex index = create2DIndex(4, 0);
+ try {
+ // Sanity: unfiltered top-2 returns the physically nearest ("obsolete") docs 0 and 1
+ ImmutableRoaringBitmap unfiltered = index.getDocIds(new float[]{1.0F, 0.0F}, 2);
+ Assert.assertEquals(unfiltered, ImmutableRoaringBitmap.bitmapOf(0, 1));
+
+ // Filtered top-2 restricted to docs 2 and 3 must return exactly those docs. A post-intersection
+ // implementation would return empty here (the unfiltered top-2 has no overlap with the allowed set),
+ // so this assertion genuinely discriminates filtered candidate generation.
+ ImmutableRoaringBitmap filtered =
+ index.getDocIds(new float[]{1.0F, 0.0F}, 2, ImmutableRoaringBitmap.bitmapOf(2, 3));
+ Assert.assertEquals(filtered, ImmutableRoaringBitmap.bitmapOf(2, 3),
+ "Filtered search must return the allowed docs, not the nearest disallowed ones");
+ } finally {
+ index.close();
+ }
+ }
+
+ @Test
+ public void testConcurrentFilteredSearchWithLiveWriter()
+ throws Exception {
+ // Single writer, concurrent reader: filtered searches must stay correct (results always a subset of
+ // the filter bitmap) while rows are being added and commits fire mid-run
+ Map<String, String> properties = new HashMap<>();
+ properties.put("commitDocs", "7");
+ properties.put("vectorIndexType", "HNSW");
+ properties.put("vectorDimension", "2");
+ VectorIndexConfig config = new VectorIndexConfig(false, "HNSW", 2, 1,
+ VectorIndexConfig.VectorDistanceFunction.EUCLIDEAN, properties);
+ MutableVectorIndex index =
+ new MutableVectorIndex("mutableVectorIndexConcurrentTest_" + System.nanoTime(), COLUMN_NAME, config);
+ int numDocs = 200;
+ ImmutableRoaringBitmap allowed = ImmutableRoaringBitmap.bitmapOf(2, 3);
+ AtomicReference<Throwable> failure =
+ new AtomicReference<>();
+ try {
+ addVector(index, new float[]{0.0F, 1.0F}, 0);
+ addVector(index, new float[]{0.0F, -1.0F}, 1);
+ addVector(index, new float[]{1.0F, 0.0F}, 2);
+ addVector(index, new float[]{0.99F, 0.01F}, 3);
+
+ Thread writer = new Thread(() -> {
+ try {
+ for (int docId = 4; docId < numDocs; docId++) {
+ addVector(index, new float[]{-1.0F, 0.0F}, docId);
+ }
+ } catch (Throwable t) {
+ failure.compareAndSet(null, t);
+ }
+ });
+ writer.start();
+ while (writer.isAlive() && failure.get() == null) {
Review Comment:
This test does not guarantee concurrent reader/writer execution: the writer can finish all additions before the main thread evaluates `writer.isAlive()`, leaving only the post-join assertion. Please use latches or a `Phaser` to force at least one interleaved add/search phase and assert that a filtered read occurred before allowing the writer to finish.
##########
pinot-segment-local/src/main/java/org/apache/pinot/segment/local/segment/index/readers/vector/BaseDocIdBitmapFilterQuery.java:
##########
@@ -0,0 +1,136 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.pinot.segment.local.segment.index.readers.vector;
+
+import java.io.IOException;
+import javax.annotation.Nullable;
+import org.apache.lucene.index.LeafReaderContext;
+import org.apache.lucene.search.ConstantScoreWeight;
+import org.apache.lucene.search.DocIdSetIterator;
+import org.apache.lucene.search.IndexSearcher;
+import org.apache.lucene.search.Query;
+import org.apache.lucene.search.QueryVisitor;
+import org.apache.lucene.search.ScoreMode;
+import org.apache.lucene.search.Scorer;
+import org.apache.lucene.search.Weight;
+import org.roaringbitmap.buffer.ImmutableRoaringBitmap;
+
+
+/// Base class for Lucene [Query] implementations that accept only documents whose Pinot doc id is present
+/// in a [ImmutableRoaringBitmap]. Used to implement pre-filter ANN search by restricting HNSW graph
+/// traversal to the filtered document set.
+///
+/// Because Lucene uses its own internal doc ids (which differ from Pinot doc ids), subclasses supply the
+/// per-leaf iterator that maps Lucene doc ids to Pinot doc ids before testing membership in the bitmap
+/// (via a doc-id translator, doc values, etc.). This class owns the constant-score weight/scorer
+/// scaffolding, identity-based equality, and cache opt-out, so filter-correctness fixes apply to every
+/// implementation at once.
+///
+/// Instances are single-use per search and must never be cached by Lucene ([Weight#isCacheable] returns
+/// false), since the accepted docs depend on the bitmap instance.
+public abstract class BaseDocIdBitmapFilterQuery extends Query {
Review Comment:
Please document bitmap ownership and thread safety on this new public base class. `MutableRoaringBitmap` is an `ImmutableRoaringBitmap` subtype, so a caller can mutate the retained instance during search and change matching behavior. State that the bitmap must remain unchanged for the query lifetime and whether query instances may be shared across threads (or snapshot defensively if mutation is allowed).
##########
pinot-segment-local/src/main/java/org/apache/pinot/segment/local/realtime/impl/vector/MutableVectorIndex.java:
##########
@@ -230,33 +294,140 @@ public Map<String, Object> getIndexDebugInfo() {
info.put("effectiveEfSearch", getEffectiveEfSearch());
info.put("effectiveHnswUseRelativeDistance", getEffectiveUseRelativeDistance());
info.put("effectiveHnswUseBoundedQueue", getEffectiveUseBoundedQueue());
- info.put("supportsPreFilter", false);
+ info.put("supportsPreFilter", true);
try (DirectoryReader directoryReader = DirectoryReader.open(_indexDirectory)) {
info.put("numDocs", directoryReader.numDocs());
info.put("numDeletedDocs", directoryReader.numDeletedDocs());
info.put("luceneSegments", directoryReader.leaves().size());
} catch (IOException e) {
LOGGER.warn("Failed to load mutable HNSW debug stats for segment: {}, column: {}", _segmentName, _vectorColumn,
e);
- info.put("numDocs", _nextDocId);
+ info.put("numDocs", _numDocsAdded);
info.put("numDeletedDocs", 0);
info.put("luceneSegments", 0);
}
return info;
}
private MutableRoaringBitmap executeVectorSearch(float[] vector, int topK, int efSearch,
- boolean useRelativeDistance, boolean useBoundedQueue) throws IOException {
+ boolean useRelativeDistance, boolean useBoundedQueue, @Nullable ImmutableRoaringBitmap preFilterBitmap)
+ throws IOException {
+ if (preFilterBitmap != null) {
+ // Filtered search enforces the query's visible-document set, so it must see every row that set names --
+ // including rows still in the writer's RAM buffer. Refreshing is expensive: maybeRefreshBlocking takes an
+ // exclusive lock (it does not coalesce; that is maybeRefresh), and on an actively consuming segment the
+ // reopen always flushes the writer, which stalls indexing. So only refresh when this query can actually
+ // see past the last refresh. The added-doc watermark is read BEFORE refreshing so rows arriving during
+ // the refresh are not wrongly claimed as visible.
+ if (!preFilterBitmap.isEmpty() && preFilterBitmap.last() > _searcherRefreshedThroughDocId) {
Review Comment:
**Blocking correctness issue:** this freshness check assumes Pinot doc IDs arrive monotonically, but `MutableIndex` explicitly allows additions in arbitrary doc-ID order. For example, after refreshing through doc 10, adding uncommitted doc 5 and searching with bitmap `{5}` skips refresh because `5 <= _searcherRefreshedThroughDocId`; the stale searcher silently omits doc 5. Please track an insertion/writer generation rather than the maximum doc ID, and add an out-of-order regression test.
This path can also call `maybeRefreshBlocking()` once per interleaved ingested row, forcing tiny Lucene flushes and serializing query callers. Please coalesce generation-aware refreshes (or merge a stable ANN generation with an exact-scanned unrefreshed tail) and validate concurrent ingest/query performance.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org
Re: [PR] Enable filtered vector search on mutable HNSW and share the doc-id filter query [pinot]
Posted by "xiangfu0 (via GitHub)" <gi...@apache.org>.
xiangfu0 commented on code in PR #19303:
URL: https://github.com/apache/pinot/pull/19303#discussion_r3890418560
##########
pinot-segment-local/src/main/java/org/apache/pinot/segment/local/realtime/impl/vector/MutableVectorIndex.java:
##########
@@ -152,16 +193,39 @@ public void add(Object[] values, @Nullable int[] dictIds, int docId) {
@Override
public MutableRoaringBitmap getDocIds(float[] vector, int topK) {
+ return submitSearch(vector, topK, null);
+ }
+
+ @Override
+ public boolean supportsPreFilter() {
+ // Every filtered call restricts its candidates to the supplied bitmap; it never degrades to an unfiltered
+ // search, so the engine can rely on filtered search instead of an exact scan.
+ return true;
Review Comment:
Done -- default is back to `true` and all five overrides are gone.
You are right that implementing an interface named `FilterAwareVectorIndexReader` is itself the declaration that the reader does filtered search, so the permissive default matches the intent and the overrides only restated it. The Javadoc now says that explicitly: override to `false` only when the filter can be honored conditionally, in which case the engine falls back to an exact scan.
The tightened contract stays, since that is the part this PR needs -- a reader answering `true` commits to returning a subset of the supplied bitmap on every filtered call and must never heuristically degrade to unfiltered search, because the engine relies on filtered search to keep obsolete row versions out of candidate generation.
_🤖 Addressed by [Claude Code](https://claude.com/claude-code)_
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org
Re: [PR] Enable filtered vector search on mutable HNSW and share the doc-id filter query [pinot]
Posted by "Jackie-Jiang (via GitHub)" <gi...@apache.org>.
Jackie-Jiang commented on code in PR #19303:
URL: https://github.com/apache/pinot/pull/19303#discussion_r3873584082
##########
pinot-segment-local/src/main/java/org/apache/pinot/segment/local/segment/index/readers/vector/BasePinotDocIdBitmapFilterQuery.java:
##########
@@ -0,0 +1,124 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.pinot.segment.local.segment.index.readers.vector;
+
+import java.io.IOException;
+import org.apache.lucene.index.LeafReaderContext;
+import org.apache.lucene.search.ConstantScoreWeight;
+import org.apache.lucene.search.DocIdSetIterator;
+import org.apache.lucene.search.IndexSearcher;
+import org.apache.lucene.search.Query;
+import org.apache.lucene.search.QueryVisitor;
+import org.apache.lucene.search.ScoreMode;
+import org.apache.lucene.search.Scorer;
+import org.apache.lucene.search.Weight;
+import org.roaringbitmap.buffer.ImmutableRoaringBitmap;
+
+
+/// Base class for Lucene [Query] implementations that accept only documents whose PINOT doc id is present
+/// in a [ImmutableRoaringBitmap]. Used to implement pre-filter ANN search by restricting HNSW graph
+/// traversal to the filtered document set.
+///
+/// Because Lucene uses its own internal doc ids (which differ from Pinot doc ids), subclasses supply the
+/// per-leaf iterator that maps Lucene doc ids to Pinot doc ids before testing membership in the bitmap
+/// (via a doc-id translator, doc values, etc.). This class owns the constant-score weight/scorer
+/// scaffolding, identity-based equality, and cache opt-out, so filter-correctness fixes apply to every
+/// implementation at once.
+///
+/// Instances are single-use per search and must never be cached by Lucene ([Weight#isCacheable] returns
+/// false), since the accepted docs depend on the bitmap instance.
+public abstract class BasePinotDocIdBitmapFilterQuery extends Query {
+ protected final ImmutableRoaringBitmap _bitmap;
Review Comment:
Name it properly
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org
Re: [PR] Enable filtered vector search on mutable HNSW and share the doc-id filter query [pinot]
Posted by "xiangfu0 (via GitHub)" <gi...@apache.org>.
xiangfu0 commented on code in PR #19303:
URL: https://github.com/apache/pinot/pull/19303#discussion_r3890384694
##########
pinot-segment-local/src/main/java/org/apache/pinot/segment/local/realtime/impl/vector/MutableVectorIndex.java:
##########
@@ -90,13 +127,11 @@ public MutableVectorIndex(String segmentName, String vectorColumn, VectorIndexCo
_commitDocs = Long.parseLong(
vectorIndexConfig.getProperties().getOrDefault("commitDocs", String.valueOf(DEFAULT_COMMIT_DOCS)));
_vectorSimilarityFunction = VectorIndexUtils.toSimilarityFunction(vectorIndexConfig.getVectorDistanceFunction());
- // Each column of a segment gets its own directory, so that cleaning up one column does not remove the index of
- // another column of the same segment.
- _indexDir = new File(new File(FileUtils.getTempDirectory(), segmentName),
- _vectorColumn + V1Constants.Indexes.VECTOR_V912_HNSW_INDEX_FILE_EXTENSION);
+ _indexDir = createIndexDir(segmentName, _vectorColumn);
Review Comment:
Agreed, removed. The directory handling is back to master's per-segment/per-column layout, and the isolation test is gone with it. I will send the write-lock fix as its own PR.
_🤖 Addressed by [Claude Code](https://claude.com/claude-code)_
##########
pinot-segment-local/src/main/java/org/apache/pinot/segment/local/realtime/impl/vector/MutableVectorIndex.java:
##########
@@ -279,18 +450,35 @@ public void close() {
try {
_indexWriter.commit();
// IndexWriter does not close the Directory passed to it, so both need to be closed.
- IOUtils.close(_indexWriter, _indexDirectory);
+ IOUtils.close(_searcherManager, _indexWriter, _indexDirectory);
} catch (IOException e) {
- // Both close() implementations are idempotent, so this is a no-op for whatever was already closed above.
- IOUtils.closeWhileHandlingException(_indexWriter, _indexDirectory);
+ // All close() implementations are idempotent, so this is a no-op for whatever was already closed above.
+ IOUtils.closeWhileHandlingException(_searcherManager, _indexWriter, _indexDirectory);
throw new RuntimeException(e);
} finally {
deleteIndexDir();
}
}
- /// Deletes the temporary index directory of this column, then the segment directory holding it if this was the last
- /// column with an index under it.
+ /// Creates a private directory for this index instance, under a directory named for the segment.
+ ///
+ /// The directory is unique per instance rather than per segment and column, so two replicas of the same segment
+ /// hosted in one JVM cannot collide on the Lucene write lock. Segment and column stay in the path so a leaked
+ /// directory can still be attributed to its owner.
+ private static File createIndexDir(String segmentName, String column) {
+ File segmentDir = new File(FileUtils.getTempDirectory(), segmentName);
+ try {
+ Files.createDirectories(segmentDir.toPath());
+ return Files.createTempDirectory(segmentDir.toPath(),
+ column + V1Constants.Indexes.VECTOR_V912_HNSW_INDEX_FILE_EXTENSION + '_').toFile();
+ } catch (IOException e) {
+ throw new RuntimeException(
+ "Failed to create mutable vector index directory for column: " + column + ", segment: " + segmentName, e);
+ }
+ }
+
+ /// Deletes the temporary index directory of this instance, then the segment directory holding it if this was the
Review Comment:
Moot now: the per-instance directory change is out of this PR, so `deleteIndexDir` is back to master's behaviour. The parent-deletion race you describe is real though, and I will carry it into the separate directory-isolation PR rather than lose it.
_🤖 Addressed by [Claude Code](https://claude.com/claude-code)_
##########
pinot-segment-local/src/main/java/org/apache/pinot/segment/local/segment/index/readers/vector/BaseDocIdBitmapFilterQuery.java:
##########
@@ -0,0 +1,136 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.pinot.segment.local.segment.index.readers.vector;
+
+import java.io.IOException;
+import javax.annotation.Nullable;
+import org.apache.lucene.index.LeafReaderContext;
+import org.apache.lucene.search.ConstantScoreWeight;
+import org.apache.lucene.search.DocIdSetIterator;
+import org.apache.lucene.search.IndexSearcher;
+import org.apache.lucene.search.Query;
+import org.apache.lucene.search.QueryVisitor;
+import org.apache.lucene.search.ScoreMode;
+import org.apache.lucene.search.Scorer;
+import org.apache.lucene.search.Weight;
+import org.roaringbitmap.buffer.ImmutableRoaringBitmap;
+
+
+/// Base class for Lucene [Query] implementations that accept only documents whose Pinot doc id is present
+/// in a [ImmutableRoaringBitmap]. Used to implement pre-filter ANN search by restricting HNSW graph
+/// traversal to the filtered document set.
+///
+/// Because Lucene uses its own internal doc ids (which differ from Pinot doc ids), subclasses supply the
+/// per-leaf iterator that maps Lucene doc ids to Pinot doc ids before testing membership in the bitmap
+/// (via a doc-id translator, doc values, etc.). This class owns the constant-score weight/scorer
+/// scaffolding, identity-based equality, and cache opt-out, so filter-correctness fixes apply to every
+/// implementation at once.
+///
+/// Instances are single-use per search and must never be cached by Lucene ([Weight#isCacheable] returns
+/// false), since the accepted docs depend on the bitmap instance.
+public abstract class BaseDocIdBitmapFilterQuery extends Query {
Review Comment:
Documented on `BaseFilterQuery`. It now states that the bitmap is retained by reference and not copied, that `ImmutableRoaringBitmap` only promises this type exposes no mutators (a caller may pass a `MutableRoaringBitmap` subtype), that mutating it mid-search changes which documents are accepted partway through traversal and yields results matching neither set, and that callers who cannot honour that must pass a detached copy. Also notes instances are safe to share across a single search's threads, since the bitmap is only read and each leaf gets its own iterator.
_🤖 Addressed by [Claude Code](https://claude.com/claude-code)_
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org
Re: [PR] Enable filtered vector search on mutable HNSW and share the doc-id filter query [pinot]
Posted by "xiangfu0 (via GitHub)" <gi...@apache.org>.
xiangfu0 commented on PR #19303:
URL: https://github.com/apache/pinot/pull/19303#issuecomment-5491033665
Thanks — follow-ups addressed on `a4e24efb01`. Status per item:
**1. Blocking refresh under concurrent ingestion — benchmarked.** Added `BenchmarkVectorFilterWorkloads`, which
runs filtered queries against a consuming segment while it ingests. 1 writer + 8 reader threads, 2000 initial +
2000 streamed docs, 1% selectivity:
| ingest docs/s | Recall@10 | p50 | p95 | QPS |
|---|---|---|---|---|
| 4600 | 1.000 | 156 us | 369 us | 38.6k |
So the refresh cost is real but bounded at this scale, and ingestion keeps up alongside it. I also changed the
path to try the non-blocking `maybeRefresh()` first and only fall back to `maybeRefreshBlocking()` when another
thread already holds the refresh lock. Proper coalescing via a background reopen thread
(`ControlledRealTimeReopenThread`, as `RealtimeLuceneIndexRefreshManager` does for text indexes) is the right
fix but is a larger change; I've recorded the trade-off in the class Javadoc and will send it as a follow-up
rather than grow this PR.
**2. Empty filter short-circuit — done.** `getDocIds(vector, topK, preFilterBitmap)` returns an empty bitmap
before `submitSearch`, so an empty filter takes neither the refresh nor the searcher acquire.
**3. Doc-values walk is O(index size) — benchmarked, kept.** The selectivity sweep is in the same benchmark.
Worth noting the iterator reports `cost()` as the filter cardinality, so Lucene's own planning sees the
selective filter, and at 0.1%–10% selectivity filtered mutable HNSW measures **recall 1.000** (vs 0.29–0.39 for
the IVF backends) because a small accepted set makes Lucene short-circuit to an exact search. A reverse
Pinot-doc-ID mapping would bound the scan but costs memory per consuming segment; I'd rather land that with its
own numbers than fold it in here.
**4. Live-writer test overlap — done.** The test now uses a `Phaser` plus a filter bitmap that blocks the search
inside its first membership check until that phase's concurrent writes complete, so the overlap is deterministic
rather than timing-dependent. The `finally` force-terminates the phaser, interrupts and joins the writer with a
timeout, and asserts it actually died.
**5. IvfPq test strengthened — done.** Renamed to `testPreFilterExcludesNearestDocsFromCandidateGeneration`. It
now asserts up front that the allowed docs lie *outside* the unfiltered top-K, then asserts the filtered search
returns exactly those docs — so an unfiltered-top-K-then-intersect implementation would return empty and fail.
**6. `BaseFilterQuery` name.** Leaving as-is: the previous round asked to shorten it away from
`BasePinotDocIdBitmapFilterQuery`, and the bitmap/doc-id contract is now stated in the class Javadoc along with
ownership and thread-safety. Happy to rename if you'd prefer to settle it the other way.
**Minor.** Commit description updated — the private-per-index-directory text was already dropped with that
change, and the stale `BasePinotDocIdBitmapFilterQuery` reference is now fixed.
Validation on `a4e24efb01`: 76 `pinot-segment-local` + 608 `pinot-core` vector/filter tests, `VectorUpsertTableTest`
(2/2), and spotless/checkstyle/license/test-compile all pass.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org
Re: [PR] Enable filtered vector search on mutable HNSW and share the doc-id filter query [pinot]
Posted by "xiangfu0 (via GitHub)" <gi...@apache.org>.
xiangfu0 commented on code in PR #19303:
URL: https://github.com/apache/pinot/pull/19303#discussion_r3886135236
##########
pinot-segment-local/src/main/java/org/apache/pinot/segment/local/segment/index/readers/vector/BaseDocIdBitmapFilterQuery.java:
##########
@@ -0,0 +1,124 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.pinot.segment.local.segment.index.readers.vector;
+
+import java.io.IOException;
+import org.apache.lucene.index.LeafReaderContext;
+import org.apache.lucene.search.ConstantScoreWeight;
+import org.apache.lucene.search.DocIdSetIterator;
+import org.apache.lucene.search.IndexSearcher;
+import org.apache.lucene.search.Query;
+import org.apache.lucene.search.QueryVisitor;
+import org.apache.lucene.search.ScoreMode;
+import org.apache.lucene.search.Scorer;
+import org.apache.lucene.search.Weight;
+import org.roaringbitmap.buffer.ImmutableRoaringBitmap;
+
+
+/// Base class for Lucene [Query] implementations that accept only documents whose PINOT doc id is present
+/// in a [ImmutableRoaringBitmap]. Used to implement pre-filter ANN search by restricting HNSW graph
+/// traversal to the filtered document set.
+///
+/// Because Lucene uses its own internal doc ids (which differ from Pinot doc ids), subclasses supply the
+/// per-leaf iterator that maps Lucene doc ids to Pinot doc ids before testing membership in the bitmap
+/// (via a doc-id translator, doc values, etc.). This class owns the constant-score weight/scorer
+/// scaffolding, identity-based equality, and cache opt-out, so filter-correctness fixes apply to every
+/// implementation at once.
+///
+/// Instances are single-use per search and must never be cached by Lucene ([Weight#isCacheable] returns
+/// false), since the accepted docs depend on the bitmap instance.
+public abstract class BasePinotDocIdBitmapFilterQuery extends Query {
+ protected final ImmutableRoaringBitmap _bitmap;
Review Comment:
Renamed to `BaseDocIdBitmapFilterQuery`. The `Pinot` prefix was redundant inside the repo, and the neighbouring `DocIdTranslator` in `HnswVectorIndexReader` already uses unprefixed `DocId` for the Pinot side, so this matches what is there. The Lucene-vs-Pinot doc id distinction that motivated the prefix is stated in the class Javadoc instead, which is where it actually needs explaining.
The subclasses keep their existing names, so the family now reads `BaseDocIdBitmapFilterQuery` -> `RoaringBitmapFilterQuery` / `NumericDocValuesBitmapFilterQuery`. Happy to use a different name if you had one in mind.
_🤖 Addressed by [Claude Code](https://claude.com/claude-code)_
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org
Re: [PR] Enable filtered vector search on mutable HNSW and share the doc-id filter query [pinot]
Posted by "Jackie-Jiang (via GitHub)" <gi...@apache.org>.
Jackie-Jiang commented on code in PR #19303:
URL: https://github.com/apache/pinot/pull/19303#discussion_r3906948715
##########
pinot-segment-local/src/test/java/org/apache/pinot/segment/local/segment/index/readers/vector/BasePinotDocIdBitmapFilterQueryTest.java:
##########
@@ -0,0 +1,124 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.pinot.segment.local.segment.index.readers.vector;
+
+import java.util.concurrent.atomic.AtomicReference;
+import org.apache.lucene.index.LeafReaderContext;
+import org.apache.lucene.search.DocIdSetIterator;
+import org.apache.lucene.search.Query;
+import org.apache.lucene.search.QueryVisitor;
+import org.apache.lucene.search.ScoreMode;
+import org.apache.lucene.search.Scorer;
+import org.apache.lucene.search.Weight;
+import org.roaringbitmap.buffer.ImmutableRoaringBitmap;
+import org.roaringbitmap.buffer.MutableRoaringBitmap;
+import org.testng.Assert;
+import org.testng.annotations.Test;
+
+
+/// Tests the shared Lucene constant-score scaffolding and identity contract for Pinot doc-id bitmap filters.
+public class BasePinotDocIdBitmapFilterQueryTest {
+
+ @Test
+ public void testConstantScoreScaffoldingAndCacheOptOut()
+ throws Exception {
+ TestQuery query = new TestQuery(MutableRoaringBitmap.bitmapOf(2, 4), new Object(),
+ DocIdSetIterator.range(1, 3));
+ Weight weight = query.createWeight(null, ScoreMode.COMPLETE, 2.5F);
+
+ Assert.assertFalse(weight.isCacheable(null));
Review Comment:
(minor) Use static import for Assert methods, same for other places
##########
pinot-integration-tests/src/test/java/org/apache/pinot/integration/tests/custom/HnswVectorRealtimeTest.java:
##########
@@ -0,0 +1,236 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.pinot.integration.tests.custom;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import java.io.File;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.List;
+import java.util.Map;
+import java.util.Random;
+import org.apache.avro.file.DataFileWriter;
+import org.apache.avro.generic.GenericData;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.pinot.spi.config.table.FieldConfig;
+import org.apache.pinot.spi.config.table.TableConfig;
+import org.apache.pinot.spi.config.table.TableType;
+import org.apache.pinot.spi.data.FieldSpec;
+import org.apache.pinot.spi.data.Schema;
+import org.testng.annotations.Test;
+
+import static org.testng.Assert.assertEquals;
+import static org.testng.Assert.assertTrue;
+
+
+/// Realtime integration coverage for filtered HNSW search on a **consuming** segment, where the vector index is
+/// `MutableVectorIndex` rather than the offline reader.
+///
+/// This pins a behavior change that reaches plain realtime tables, not only upsert ones: because the consuming
+/// segment now advertises `supportsPreFilter()`, a `vectorSimilarity` predicate combined with a metadata filter
+/// plans as `FILTER_THEN_ANN` instead of running an unfiltered ANN and intersecting afterwards. Nothing else
+/// covers this -- the other HNSW integration tests are offline-only, and [IvfPqVectorRealtimeTest] asserts the
+/// IVF_PQ exact-scan fallback.
+///
+/// ## Why the fixture is sized the way it is
+///
+/// `VectorSearchStrategy.decide` only wires the optional pre-filter when the filter matches at least
+/// `EXACT_SCAN_THRESHOLD` (1000) documents *and* selectivity falls below the mid-range cutoff of 0.105; anything
+/// more selective is cheaper as an exact scan, anything less selective is left to post-filtering. A single
+/// consuming segment of [#getCountStarResult] rows over [#NUM_CATEGORIES] categories yields 1250 matches at
+/// selectivity 0.083, which clears both bounds with margin. One Kafka partition and a flush size above the row
+/// count keep every row in one consuming segment, so the per-segment counts the planner sees are the ones
+/// computed here. The category column carries an inverted index because the wiring additionally requires every
+/// non-vector filter to produce a bitmap -- a scan-based predicate silently leaves the vector operator
+/// post-filtering.
+@Test(suiteName = "CustomClusterIntegrationTest")
+public class HnswVectorRealtimeTest extends CustomDataQueryClusterIntegrationTest {
+ private static final String DEFAULT_TABLE_NAME = "HnswVectorRealtimeTest";
+ private static final String VECTOR_COL = "embedding";
+ private static final String CATEGORY = "category";
+ private static final int VECTOR_DIM_SIZE = 32;
+ private static final int NUM_CATEGORIES = 12;
+ private static final int NUM_ROWS = 15000;
+ private static final String TARGET_CATEGORY = "cat_3";
+
+ @Override
+ protected long getCountStarResult() {
+ return NUM_ROWS;
+ }
+
+ @Override
+ public String getTableName() {
+ return DEFAULT_TABLE_NAME;
+ }
+
+ @Override
+ public boolean isRealtimeTable() {
+ return true;
+ }
+
+ /// Keep every row in a single consuming segment: the planner reasons about per-segment counts, so a mid-stream
+ /// commit would shrink them below the pre-filter thresholds this test depends on.
+ @Override
+ protected int getRealtimeSegmentFlushSize() {
+ return NUM_ROWS * 10;
+ }
+
+ @Override
+ protected int getNumKafkaPartitions() {
+ return 1;
+ }
+
+ @Override
+ public Schema createSchema() {
+ return new Schema.SchemaBuilder().setSchemaName(getTableName())
+ .addMultiValueDimension(VECTOR_COL, FieldSpec.DataType.FLOAT)
Review Comment:
(minor) Import `FieldSpec.DataType`
##########
pinot-segment-local/src/main/java/org/apache/pinot/segment/local/segment/index/readers/vector/BasePinotDocIdBitmapFilterQuery.java:
##########
@@ -0,0 +1,148 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.pinot.segment.local.segment.index.readers.vector;
+
+import java.io.IOException;
+import javax.annotation.Nullable;
+import org.apache.lucene.index.LeafReaderContext;
+import org.apache.lucene.search.ConstantScoreWeight;
+import org.apache.lucene.search.DocIdSetIterator;
+import org.apache.lucene.search.IndexSearcher;
+import org.apache.lucene.search.Query;
+import org.apache.lucene.search.QueryVisitor;
+import org.apache.lucene.search.ScoreMode;
+import org.apache.lucene.search.Scorer;
+import org.apache.lucene.search.Weight;
+import org.roaringbitmap.buffer.ImmutableRoaringBitmap;
+
+
+/// Base class for Lucene [Query] implementations that accept only documents whose Pinot doc id is present
+/// in a [ImmutableRoaringBitmap]. Used to implement pre-filter ANN search by restricting HNSW graph
+/// traversal to the filtered document set.
+///
+/// Because Lucene uses its own internal doc ids (which differ from Pinot doc ids), subclasses supply the
+/// per-leaf iterator that maps Lucene doc ids to Pinot doc ids before testing membership in the bitmap
+/// (via a doc-id translator, doc values, etc.). This class owns the constant-score weight/scorer
+/// scaffolding, identity-based equality, and cache opt-out, so filter-correctness fixes apply to every
+/// implementation at once.
+///
+/// Instances are single-use per search and must never be cached by Lucene ([Weight#isCacheable] returns
+/// false), since the accepted docs depend on the bitmap instance.
+///
+/// **Bitmap ownership.** The bitmap is retained by reference, not copied. [ImmutableRoaringBitmap] only
+/// promises that *this* type exposes no mutators -- a caller may pass a `MutableRoaringBitmap`, which is a
+/// subtype -- so the caller must not modify it once it has been handed over. Mutating it during a search
+/// changes which documents are accepted midway through traversal and yields results matching neither the old
+/// nor the new set. Callers that cannot promise that must pass a detached copy.
+///
+/// Given that, instances are safe to share across the threads of a single search: the bitmap is only read,
+/// and each leaf gets its own iterator.
+public abstract class BasePinotDocIdBitmapFilterQuery extends Query {
Review Comment:
Let's keep it `BaseFilterQuery`, seems AI is going back and forth for this
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org
Re: [PR] Enable filtered vector search on mutable HNSW and share the doc-id filter query [pinot]
Posted by "xiangfu0 (via GitHub)" <gi...@apache.org>.
xiangfu0 commented on code in PR #19303:
URL: https://github.com/apache/pinot/pull/19303#discussion_r3890385352
##########
pinot-segment-local/src/test/java/org/apache/pinot/segment/local/realtime/impl/vector/MutableVectorIndexTest.java:
##########
@@ -80,12 +84,180 @@ public void testRuntimeControlDebugInfoReflectsOverrides() {
Assert.assertEquals(debugInfo.get("effectiveEfSearch"), 6);
Assert.assertEquals(debugInfo.get("effectiveHnswUseRelativeDistance"), Boolean.FALSE);
Assert.assertEquals(debugInfo.get("effectiveHnswUseBoundedQueue"), Boolean.FALSE);
- Assert.assertEquals(debugInfo.get("supportsPreFilter"), Boolean.FALSE);
+ Assert.assertEquals(debugInfo.get("supportsPreFilter"), Boolean.TRUE);
+ Assert.assertTrue(index.supportsPreFilter(),
+ "The reader must advertise filtered search: that is what makes the planner choose it over an exact scan");
} finally {
index.close();
}
}
+ // -----------------------------------------------------------------------
+ // Filtered search (upsert doc-ids snapshot enforcement)
+ // -----------------------------------------------------------------------
+
+ /// 2-D corpus with distinct distances from the query vector {1, 0}:
+ /// docs 0 and 1 are nearest (the "upsert-obsoleted" rows), docs 2 and 3 are the valid rows.
+ private static MutableVectorIndex create2DIndex(long commitDocs, int docIdOffset) {
+ Map<String, String> properties = new HashMap<>();
+ properties.put("commitDocs", String.valueOf(commitDocs));
+ properties.put("vectorIndexType", "HNSW");
+ properties.put("vectorDimension", "2");
+ VectorIndexConfig config = new VectorIndexConfig(false, "HNSW", 2, 1,
+ VectorIndexConfig.VectorDistanceFunction.EUCLIDEAN, properties);
+ MutableVectorIndex index =
+ new MutableVectorIndex("mutableVectorIndexFilterTest_" + System.nanoTime(), COLUMN_NAME, config);
+ addVector(index, new float[]{1.0F, 0.0F}, docIdOffset);
+ addVector(index, new float[]{0.99F, 0.01F}, docIdOffset + 1);
+ addVector(index, new float[]{0.0F, 1.0F}, docIdOffset + 2);
+ addVector(index, new float[]{0.0F, -1.0F}, docIdOffset + 3);
+ return index;
+ }
+
+ @Test
+ public void testFilteredSearchExcludesNearestDisallowedDocs() {
+ // commitDocs=4 commits on the 4th add, so the unfiltered committed-view sanity check below sees all rows
+ MutableVectorIndex index = create2DIndex(4, 0);
+ try {
+ // Sanity: unfiltered top-2 returns the physically nearest ("obsolete") docs 0 and 1
+ ImmutableRoaringBitmap unfiltered = index.getDocIds(new float[]{1.0F, 0.0F}, 2);
+ Assert.assertEquals(unfiltered, ImmutableRoaringBitmap.bitmapOf(0, 1));
+
+ // Filtered top-2 restricted to docs 2 and 3 must return exactly those docs. A post-intersection
+ // implementation would return empty here (the unfiltered top-2 has no overlap with the allowed set),
+ // so this assertion genuinely discriminates filtered candidate generation.
+ ImmutableRoaringBitmap filtered =
+ index.getDocIds(new float[]{1.0F, 0.0F}, 2, ImmutableRoaringBitmap.bitmapOf(2, 3));
+ Assert.assertEquals(filtered, ImmutableRoaringBitmap.bitmapOf(2, 3),
+ "Filtered search must return the allowed docs, not the nearest disallowed ones");
+ } finally {
+ index.close();
+ }
+ }
+
+ @Test
+ public void testConcurrentFilteredSearchWithLiveWriter()
+ throws Exception {
+ // Single writer, concurrent reader: filtered searches must stay correct (results always a subset of
+ // the filter bitmap) while rows are being added and commits fire mid-run
+ Map<String, String> properties = new HashMap<>();
+ properties.put("commitDocs", "7");
+ properties.put("vectorIndexType", "HNSW");
+ properties.put("vectorDimension", "2");
+ VectorIndexConfig config = new VectorIndexConfig(false, "HNSW", 2, 1,
+ VectorIndexConfig.VectorDistanceFunction.EUCLIDEAN, properties);
+ MutableVectorIndex index =
+ new MutableVectorIndex("mutableVectorIndexConcurrentTest_" + System.nanoTime(), COLUMN_NAME, config);
+ int numDocs = 200;
+ ImmutableRoaringBitmap allowed = ImmutableRoaringBitmap.bitmapOf(2, 3);
+ AtomicReference<Throwable> failure =
+ new AtomicReference<>();
+ try {
+ addVector(index, new float[]{0.0F, 1.0F}, 0);
+ addVector(index, new float[]{0.0F, -1.0F}, 1);
+ addVector(index, new float[]{1.0F, 0.0F}, 2);
+ addVector(index, new float[]{0.99F, 0.01F}, 3);
+
+ Thread writer = new Thread(() -> {
+ try {
+ for (int docId = 4; docId < numDocs; docId++) {
+ addVector(index, new float[]{-1.0F, 0.0F}, docId);
+ }
+ } catch (Throwable t) {
+ failure.compareAndSet(null, t);
+ }
+ });
+ writer.start();
+ while (writer.isAlive() && failure.get() == null) {
Review Comment:
Fixed. The writer now waits on a latch for the reader to start and holds each row until the reader has completed a minimum number of searches, so the two genuinely overlap instead of the writer racing to completion. The loop asserts that minimum was met, and the test has `timeOut = 60_000` so a writer/refresh deadlock -- the bug class it exists to catch -- fails it instead of hanging the suite.
_🤖 Addressed by [Claude Code](https://claude.com/claude-code)_
##########
pinot-segment-local/src/main/java/org/apache/pinot/segment/local/segment/index/readers/vector/IvfPqVectorIndexReader.java:
##########
@@ -217,6 +217,13 @@ public MutableRoaringBitmap getDocIds(float[] searchQuery, int topK) {
return result;
}
+ @Override
+ public boolean supportsPreFilter() {
Review Comment:
Added `IvfPqVectorIndexTest#testSupportsPreFilterAndRestrictsResultsToTheFilter`. It asserts `supportsPreFilter()` is true (so removing the override fails rather than silently downgrading every IVF_PQ query to an exact scan), that filtered results are a subset of the supplied bitmap, and that an empty filter yields nothing. IVF_FLAT and IVF_ON_DISK already had filter-aware coverage; IVF_PQ was the gap.
_🤖 Addressed by [Claude Code](https://claude.com/claude-code)_
##########
pinot-segment-local/src/main/java/org/apache/pinot/segment/local/realtime/impl/vector/MutableVectorIndex.java:
##########
@@ -152,16 +193,39 @@ public void add(Object[] values, @Nullable int[] dictIds, int docId) {
@Override
public MutableRoaringBitmap getDocIds(float[] vector, int topK) {
+ return submitSearch(vector, topK, null);
+ }
+
+ @Override
+ public boolean supportsPreFilter() {
+ // Every filtered call restricts its candidates to the supplied bitmap; it never degrades to an unfiltered
+ // search, so the engine can rely on filtered search instead of an exact scan.
+ return true;
Review Comment:
Worth checking the diff here: this PR changes the default to `false`, so the overrides are what keep the in-tree readers doing filtered search.
The reasoning is that `supportsPreFilter()` became a correctness contract in this PR -- the planner uses it to choose filtered ANN over an exact scan, and a reader that answers yes without honouring the filter silently drops rows. The previous Javadoc explicitly allowed conditional filtering, so an out-of-tree reader written against it would now be asserting a guarantee it never made. Defaulting to `false` makes that degrade to a slower-but-correct exact scan instead.
If you would rather keep the default `true` and drop the five overrides, that is a smaller diff and I am happy to switch -- it just trades out-of-tree safety for brevity.
_🤖 Addressed by [Claude Code](https://claude.com/claude-code)_
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org
Re: [PR] Enable filtered vector search on mutable HNSW and share the doc-id filter query [pinot]
Posted by "xiangfu0 (via GitHub)" <gi...@apache.org>.
xiangfu0 commented on code in PR #19303:
URL: https://github.com/apache/pinot/pull/19303#discussion_r3890384215
##########
pinot-segment-local/src/main/java/org/apache/pinot/segment/local/segment/index/readers/vector/BaseDocIdBitmapFilterQuery.java:
##########
@@ -0,0 +1,124 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.pinot.segment.local.segment.index.readers.vector;
+
+import java.io.IOException;
+import org.apache.lucene.index.LeafReaderContext;
+import org.apache.lucene.search.ConstantScoreWeight;
+import org.apache.lucene.search.DocIdSetIterator;
+import org.apache.lucene.search.IndexSearcher;
+import org.apache.lucene.search.Query;
+import org.apache.lucene.search.QueryVisitor;
+import org.apache.lucene.search.ScoreMode;
+import org.apache.lucene.search.Scorer;
+import org.apache.lucene.search.Weight;
+import org.roaringbitmap.buffer.ImmutableRoaringBitmap;
+
+
+/// Base class for Lucene [Query] implementations that accept only documents whose PINOT doc id is present
+/// in a [ImmutableRoaringBitmap]. Used to implement pre-filter ANN search by restricting HNSW graph
+/// traversal to the filtered document set.
+///
+/// Because Lucene uses its own internal doc ids (which differ from Pinot doc ids), subclasses supply the
+/// per-leaf iterator that maps Lucene doc ids to Pinot doc ids before testing membership in the bitmap
+/// (via a doc-id translator, doc values, etc.). This class owns the constant-score weight/scorer
+/// scaffolding, identity-based equality, and cache opt-out, so filter-correctness fixes apply to every
+/// implementation at once.
+///
+/// Instances are single-use per search and must never be cached by Lucene ([Weight#isCacheable] returns
+/// false), since the accepted docs depend on the bitmap instance.
+public abstract class BasePinotDocIdBitmapFilterQuery extends Query {
+ protected final ImmutableRoaringBitmap _bitmap;
Review Comment:
Sorry, I misread the first time. Done as suggested: the class is `BaseFilterQuery` and the field is `_docIds`.
_🤖 Addressed by [Claude Code](https://claude.com/claude-code)_
##########
pinot-segment-local/src/main/java/org/apache/pinot/segment/local/realtime/impl/vector/MutableVectorIndex.java:
##########
@@ -230,33 +294,140 @@ public Map<String, Object> getIndexDebugInfo() {
info.put("effectiveEfSearch", getEffectiveEfSearch());
info.put("effectiveHnswUseRelativeDistance", getEffectiveUseRelativeDistance());
info.put("effectiveHnswUseBoundedQueue", getEffectiveUseBoundedQueue());
- info.put("supportsPreFilter", false);
+ info.put("supportsPreFilter", true);
try (DirectoryReader directoryReader = DirectoryReader.open(_indexDirectory)) {
info.put("numDocs", directoryReader.numDocs());
info.put("numDeletedDocs", directoryReader.numDeletedDocs());
info.put("luceneSegments", directoryReader.leaves().size());
} catch (IOException e) {
LOGGER.warn("Failed to load mutable HNSW debug stats for segment: {}, column: {}", _segmentName, _vectorColumn,
e);
- info.put("numDocs", _nextDocId);
+ info.put("numDocs", _numDocsAdded);
info.put("numDeletedDocs", 0);
info.put("luceneSegments", 0);
}
return info;
}
private MutableRoaringBitmap executeVectorSearch(float[] vector, int topK, int efSearch,
- boolean useRelativeDistance, boolean useBoundedQueue) throws IOException {
+ boolean useRelativeDistance, boolean useBoundedQueue, @Nullable ImmutableRoaringBitmap preFilterBitmap)
+ throws IOException {
+ if (preFilterBitmap != null) {
+ // Filtered search enforces the query's visible-document set, so it must see every row that set names --
+ // including rows still in the writer's RAM buffer. Refreshing is expensive: maybeRefreshBlocking takes an
+ // exclusive lock (it does not coalesce; that is maybeRefresh), and on an actively consuming segment the
+ // reopen always flushes the writer, which stalls indexing. So only refresh when this query can actually
+ // see past the last refresh. The added-doc watermark is read BEFORE refreshing so rows arriving during
+ // the refresh are not wrongly claimed as visible.
+ if (!preFilterBitmap.isEmpty() && preFilterBitmap.last() > _searcherRefreshedThroughDocId) {
Review Comment:
You are right, and thank you for catching it -- I had quoted the `MutableIndex#add` contract about arbitrary doc-id order earlier in this change and then built a watermark that assumed the opposite.
Now tracking the writer sequence number returned by `IndexWriter#addDocument` instead of the maximum doc id, which is monotonic by construction regardless of doc-id order. Added `testFilteredSearchSeesOutOfOrderUncommittedDoc`, which reproduces your exact scenario (refresh through doc 10, add doc 5, search bitmap {5}); I confirmed it fails against a doc-id watermark and passes with the sequence number.
On coalescing: the refresh is now skipped entirely whenever nothing has been added since the last one, but you are right that an actively ingesting segment still refreshes per query. `ControlledRealTimeReopenThread#waitForGeneration` is the proper fix and I did not take it here because it adds a thread per index instance, which is significant at Pinot's consuming-segment counts. Happy to do it in this PR if you prefer, otherwise I would rather size it as follow-up work with a concurrent ingest/query benchmark.
_🤖 Addressed by [Claude Code](https://claude.com/claude-code)_
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org
Re: [PR] Enable filtered vector search on mutable HNSW and share the doc-id filter query [pinot]
Posted by "Jackie-Jiang (via GitHub)" <gi...@apache.org>.
Jackie-Jiang commented on code in PR #19303:
URL: https://github.com/apache/pinot/pull/19303#discussion_r3890210686
##########
pinot-segment-local/src/main/java/org/apache/pinot/segment/local/realtime/impl/vector/MutableVectorIndex.java:
##########
@@ -152,16 +193,39 @@ public void add(Object[] values, @Nullable int[] dictIds, int docId) {
@Override
public MutableRoaringBitmap getDocIds(float[] vector, int topK) {
+ return submitSearch(vector, topK, null);
+ }
+
+ @Override
+ public boolean supportsPreFilter() {
+ // Every filtered call restricts its candidates to the supplied bitmap; it never degrades to an unfiltered
+ // search, so the engine can rely on filtered search instead of an exact scan.
+ return true;
Review Comment:
Default is already true, can we remove all override?
##########
pinot-segment-local/src/main/java/org/apache/pinot/segment/local/segment/index/readers/vector/BaseDocIdBitmapFilterQuery.java:
##########
@@ -0,0 +1,124 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.pinot.segment.local.segment.index.readers.vector;
+
+import java.io.IOException;
+import org.apache.lucene.index.LeafReaderContext;
+import org.apache.lucene.search.ConstantScoreWeight;
+import org.apache.lucene.search.DocIdSetIterator;
+import org.apache.lucene.search.IndexSearcher;
+import org.apache.lucene.search.Query;
+import org.apache.lucene.search.QueryVisitor;
+import org.apache.lucene.search.ScoreMode;
+import org.apache.lucene.search.Scorer;
+import org.apache.lucene.search.Weight;
+import org.roaringbitmap.buffer.ImmutableRoaringBitmap;
+
+
+/// Base class for Lucene [Query] implementations that accept only documents whose PINOT doc id is present
+/// in a [ImmutableRoaringBitmap]. Used to implement pre-filter ANN search by restricting HNSW graph
+/// traversal to the filtered document set.
+///
+/// Because Lucene uses its own internal doc ids (which differ from Pinot doc ids), subclasses supply the
+/// per-leaf iterator that maps Lucene doc ids to Pinot doc ids before testing membership in the bitmap
+/// (via a doc-id translator, doc values, etc.). This class owns the constant-score weight/scorer
+/// scaffolding, identity-based equality, and cache opt-out, so filter-correctness fixes apply to every
+/// implementation at once.
+///
+/// Instances are single-use per search and must never be cached by Lucene ([Weight#isCacheable] returns
+/// false), since the accepted docs depend on the bitmap instance.
+public abstract class BasePinotDocIdBitmapFilterQuery extends Query {
+ protected final ImmutableRoaringBitmap _bitmap;
Review Comment:
I meant the name of `_bitmap`...
Consider naming the class `BaseFilterQuery`, and name the ImmutableRoaringBitmap `_docIds`
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org
Re: [PR] Enable filtered vector search on mutable HNSW and share the doc-id filter query [pinot]
Posted by "xiangfu0 (via GitHub)" <gi...@apache.org>.
xiangfu0 merged PR #19303:
URL: https://github.com/apache/pinot/pull/19303
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org
Re: [PR] Enforce the upsert doc-ids snapshot in vector candidate generation [pinot]
Posted by "xiangfu0 (via GitHub)" <gi...@apache.org>.
xiangfu0 commented on PR #19303:
URL: https://github.com/apache/pinot/pull/19303#issuecomment-5433295004
## Review — enforce the upsert doc-ids snapshot in vector candidate generation
Reviewed at `aebbdae5f6` (18 files, +2221/−239) against current `master`.
### Context first: half of this PR has already landed
#19297–#19300 merged the base fix, so `ExactVectorScanFilterOperator`, `VectorSimilarityFilterOperator`, `FilterPlanNode` and their tests are now duplicated by (and will conflict with) `master`. That part of this PR is done.
What is **not** in `master`, and not in #19336 either, is the rest — and it is the most valuable part:
| Piece | Status elsewhere |
| --- | --- |
| `FilterAwareVectorIndexReader` contract hardening | nowhere else |
| `BasePinotDocIdBitmapFilterQuery` | nowhere else |
| `HnswVectorIndexReader` (−72 lines of duplication) | nowhere else |
| `VectorIndexType` | nowhere else |
| `VectorRadiusFilterOperator` | nowhere else |
| `MutableVectorIndex` | overlaps #19336 |
The recommendation is to reduce this PR to those rows and let it be the mutable-index/SPI PR, rather than close it — closing it as superseded would silently drop the items above.
### What is genuinely good
- **The SPI hardening is the standout.** Turning `supportsPreFilter()` into an unconditional commitment — with the class-level note that the filter is a correctness contract and an implementation must never heuristically degrade to unfiltered search — closes a real hazard. Under the old "may support it only for certain selectivities" wording, a reader could legally answer `true` at plan time and degrade at execution time, which is precisely the case where obsolete row versions would silently re-enter top-K. Making it binary, with exact scan as the honest fallback, is the right contract.
- **`BasePinotDocIdBitmapFilterQuery` is the correct factoring.** One constant-score weight/scorer, a `createLeafIterator` hook per reader, `isCacheable=false`, identity-based `equals`/`hashCode` including `getClass()`. It removes 72 lines from `HnswVectorIndexReader` instead of adding a second copy — the opposite of what #19336 currently does.
- Stores the **supplied** Pinot doc id rather than an internal counter, fixing the same latent out-of-order-ingestion bug.
- Keeps `DirectoryReader.open(_indexDirectory)`, so it does **not** have the unpublished-document exposure that NRT reading introduces in #19336.
- Extending the required-doc-ids restriction to `VectorRadiusFilterOperator` is unique to this PR, and the Javadoc is commendably honest that radius results were already correct and this is about not burning the candidate budget (and the saturation latency cliff) on obsolete rows.
### 1. (Blocking, process) Drop the already-merged half
Rebase onto current `master` and remove the base-fix files. Without that this PR cannot merge, and its diff hides the parts that still need review.
### 2. (Major) `VectorSearchSpec` reverses a merged review decision
`master` deliberately passes the required doc-id bitmap directly. The wrapper type that used to hold it was removed during review of #19297 — the reviewer's point was that a single-field wrapper adds a layer without adding meaning, and a type should be introduced when a second field actually exists. Reintroducing `VectorSearchSpec` would undo that. If it carries more than one field, that changes the argument — but then the extra state should be the justification, called out explicitly.
### 3. (Minor) Translate through doc values, not stored fields
`translateTopDocs` resolves each hit with `storedFields.document(scoreDoc.doc)`, which decompresses a stored-field block per hit, while the numeric doc values needed for filtering are already maintained on the same documents. Reading the doc id from doc values instead is cheaper on the hot path and would let the `StoredField` be dropped entirely, halving the per-document id storage. (#19336 does the translation this way, and additionally sorts hits by Lucene doc id first, which is required for forward-only `advanceExact`.)
### 4. Freshness trade-off worth stating
Committed-only reading means rows added since the last commit are invisible to vector search, so a FULL-upsert query can return fewer than K rows until the next commit fires. That is `master`'s existing behavior and not a regression — but since #19336 takes the opposite approach (NRT, fresher, and needing a publication bound), whichever lands should say which trade-off it is choosing and why.
---
_🤖 Automated review by [Claude Code](https://claude.com/claude-code)_
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org
Re: [PR] Enable filtered vector search on mutable HNSW and share the doc-id filter query [pinot]
Posted by "xiangfu0 (via GitHub)" <gi...@apache.org>.
xiangfu0 commented on PR #19303:
URL: https://github.com/apache/pinot/pull/19303#issuecomment-5491260890
Rebased and updated on `7c3954f8b75808fc17faa6d09fa184aea3a34ca3`, a single commit directly on current `master` (`88ea694bae5f98760fb8c61f737fe6d3bc713427`). I re-audited all eight review threads plus the non-threaded follow-ups; all threads are resolved and no newer human feedback was left unaddressed.
The final patch now:
- coalesces mutable-HNSW refreshes by exact writer generation, short-circuits empty scopes, and keeps uncommitted rows visible;
- uses sparse exact scan when the required scope and forward index make that cheaper, while dense/no-forward cases retain filtered ANN and never degrade to a post-filter;
- shares `BasePinotDocIdBitmapFilterQuery`, resets crash-left temp indexes with `OpenMode.CREATE`, fails fast on missing doc-ID values, and cleans up after checked or unchecked close failures;
- warms benchmark readers before timing, defaults to 200 aggregate samples, proves a measured add/query overlap, observes a real refresh waiter, and verifies exactly one refresh for a frozen reader generation.
Validation on the published tree:
- 80 targeted vector tests: 64 `pinot-segment-local` + 16 `pinot-core`;
- 62 planner/strategy/operator tests;
- `MutableVectorIndexTest`: 18/18;
- `VectorUpsertTableTest`: 2/2 across both query engines (full 63-module reactor);
- reduced and 25,000-vector performance workloads, including `timedIngestQueryOverlaps=1`, a real waiter, and refresh delta `1`;
- Spotless, license format, Checkstyle, and license check across all five affected modules.
Fresh CI has been triggered for this exact head. @Jackie-Jiang, please re-review when convenient; the earlier change request remains the outstanding review gate until then.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org
Re: [PR] Enable filtered vector search on mutable HNSW and share the doc-id filter query [pinot]
Posted by "xiangfu0 (via GitHub)" <gi...@apache.org>.
xiangfu0 commented on PR #19303:
URL: https://github.com/apache/pinot/pull/19303#issuecomment-5539268249
Documentation follow-up: https://github.com/pinot-contrib/pinot-docs/pull/1031 (merged). It documents filter-aware mutable HNSW search on consuming segments, including sparse exact scan versus filtered ANN selection and FULL-upsert visible-doc candidate generation.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org
Re: [PR] Enable filtered vector search on mutable HNSW and share the doc-id filter query [pinot]
Posted by "xiangfu0 (via GitHub)" <gi...@apache.org>.
xiangfu0 commented on code in PR #19303:
URL: https://github.com/apache/pinot/pull/19303#discussion_r3910090660
##########
pinot-segment-local/src/main/java/org/apache/pinot/segment/local/segment/index/readers/vector/BasePinotDocIdBitmapFilterQuery.java:
##########
@@ -0,0 +1,148 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.pinot.segment.local.segment.index.readers.vector;
+
+import java.io.IOException;
+import javax.annotation.Nullable;
+import org.apache.lucene.index.LeafReaderContext;
+import org.apache.lucene.search.ConstantScoreWeight;
+import org.apache.lucene.search.DocIdSetIterator;
+import org.apache.lucene.search.IndexSearcher;
+import org.apache.lucene.search.Query;
+import org.apache.lucene.search.QueryVisitor;
+import org.apache.lucene.search.ScoreMode;
+import org.apache.lucene.search.Scorer;
+import org.apache.lucene.search.Weight;
+import org.roaringbitmap.buffer.ImmutableRoaringBitmap;
+
+
+/// Base class for Lucene [Query] implementations that accept only documents whose Pinot doc id is present
+/// in a [ImmutableRoaringBitmap]. Used to implement pre-filter ANN search by restricting HNSW graph
+/// traversal to the filtered document set.
+///
+/// Because Lucene uses its own internal doc ids (which differ from Pinot doc ids), subclasses supply the
+/// per-leaf iterator that maps Lucene doc ids to Pinot doc ids before testing membership in the bitmap
+/// (via a doc-id translator, doc values, etc.). This class owns the constant-score weight/scorer
+/// scaffolding, identity-based equality, and cache opt-out, so filter-correctness fixes apply to every
+/// implementation at once.
+///
+/// Instances are single-use per search and must never be cached by Lucene ([Weight#isCacheable] returns
+/// false), since the accepted docs depend on the bitmap instance.
+///
+/// **Bitmap ownership.** The bitmap is retained by reference, not copied. [ImmutableRoaringBitmap] only
+/// promises that *this* type exposes no mutators -- a caller may pass a `MutableRoaringBitmap`, which is a
+/// subtype -- so the caller must not modify it once it has been handed over. Mutating it during a search
+/// changes which documents are accepted midway through traversal and yields results matching neither the old
+/// nor the new set. Callers that cannot promise that must pass a detached copy.
+///
+/// Given that, instances are safe to share across the threads of a single search: the bitmap is only read,
+/// and each leaf gets its own iterator.
+public abstract class BasePinotDocIdBitmapFilterQuery extends Query {
Review Comment:
Renamed the shared query and its test back to `BaseFilterQuery`.
##########
pinot-integration-tests/src/test/java/org/apache/pinot/integration/tests/custom/HnswVectorRealtimeTest.java:
##########
@@ -0,0 +1,236 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.pinot.integration.tests.custom;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import java.io.File;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.List;
+import java.util.Map;
+import java.util.Random;
+import org.apache.avro.file.DataFileWriter;
+import org.apache.avro.generic.GenericData;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.pinot.spi.config.table.FieldConfig;
+import org.apache.pinot.spi.config.table.TableConfig;
+import org.apache.pinot.spi.config.table.TableType;
+import org.apache.pinot.spi.data.FieldSpec;
+import org.apache.pinot.spi.data.Schema;
+import org.testng.annotations.Test;
+
+import static org.testng.Assert.assertEquals;
+import static org.testng.Assert.assertTrue;
+
+
+/// Realtime integration coverage for filtered HNSW search on a **consuming** segment, where the vector index is
+/// `MutableVectorIndex` rather than the offline reader.
+///
+/// This pins a behavior change that reaches plain realtime tables, not only upsert ones: because the consuming
+/// segment now advertises `supportsPreFilter()`, a `vectorSimilarity` predicate combined with a metadata filter
+/// plans as `FILTER_THEN_ANN` instead of running an unfiltered ANN and intersecting afterwards. Nothing else
+/// covers this -- the other HNSW integration tests are offline-only, and [IvfPqVectorRealtimeTest] asserts the
+/// IVF_PQ exact-scan fallback.
+///
+/// ## Why the fixture is sized the way it is
+///
+/// `VectorSearchStrategy.decide` only wires the optional pre-filter when the filter matches at least
+/// `EXACT_SCAN_THRESHOLD` (1000) documents *and* selectivity falls below the mid-range cutoff of 0.105; anything
+/// more selective is cheaper as an exact scan, anything less selective is left to post-filtering. A single
+/// consuming segment of [#getCountStarResult] rows over [#NUM_CATEGORIES] categories yields 1250 matches at
+/// selectivity 0.083, which clears both bounds with margin. One Kafka partition and a flush size above the row
+/// count keep every row in one consuming segment, so the per-segment counts the planner sees are the ones
+/// computed here. The category column carries an inverted index because the wiring additionally requires every
+/// non-vector filter to produce a bitmap -- a scan-based predicate silently leaves the vector operator
+/// post-filtering.
+@Test(suiteName = "CustomClusterIntegrationTest")
+public class HnswVectorRealtimeTest extends CustomDataQueryClusterIntegrationTest {
+ private static final String DEFAULT_TABLE_NAME = "HnswVectorRealtimeTest";
+ private static final String VECTOR_COL = "embedding";
+ private static final String CATEGORY = "category";
+ private static final int VECTOR_DIM_SIZE = 32;
+ private static final int NUM_CATEGORIES = 12;
+ private static final int NUM_ROWS = 15000;
+ private static final String TARGET_CATEGORY = "cat_3";
+
+ @Override
+ protected long getCountStarResult() {
+ return NUM_ROWS;
+ }
+
+ @Override
+ public String getTableName() {
+ return DEFAULT_TABLE_NAME;
+ }
+
+ @Override
+ public boolean isRealtimeTable() {
+ return true;
+ }
+
+ /// Keep every row in a single consuming segment: the planner reasons about per-segment counts, so a mid-stream
+ /// commit would shrink them below the pre-filter thresholds this test depends on.
+ @Override
+ protected int getRealtimeSegmentFlushSize() {
+ return NUM_ROWS * 10;
+ }
+
+ @Override
+ protected int getNumKafkaPartitions() {
+ return 1;
+ }
+
+ @Override
+ public Schema createSchema() {
+ return new Schema.SchemaBuilder().setSchemaName(getTableName())
+ .addMultiValueDimension(VECTOR_COL, FieldSpec.DataType.FLOAT)
Review Comment:
Imported `FieldSpec.DataType` and now use the `DataType` constants directly.
##########
pinot-segment-local/src/test/java/org/apache/pinot/segment/local/segment/index/readers/vector/BasePinotDocIdBitmapFilterQueryTest.java:
##########
@@ -0,0 +1,124 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.pinot.segment.local.segment.index.readers.vector;
+
+import java.util.concurrent.atomic.AtomicReference;
+import org.apache.lucene.index.LeafReaderContext;
+import org.apache.lucene.search.DocIdSetIterator;
+import org.apache.lucene.search.Query;
+import org.apache.lucene.search.QueryVisitor;
+import org.apache.lucene.search.ScoreMode;
+import org.apache.lucene.search.Scorer;
+import org.apache.lucene.search.Weight;
+import org.roaringbitmap.buffer.ImmutableRoaringBitmap;
+import org.roaringbitmap.buffer.MutableRoaringBitmap;
+import org.testng.Assert;
+import org.testng.annotations.Test;
+
+
+/// Tests the shared Lucene constant-score scaffolding and identity contract for Pinot doc-id bitmap filters.
+public class BasePinotDocIdBitmapFilterQueryTest {
+
+ @Test
+ public void testConstantScoreScaffoldingAndCacheOptOut()
+ throws Exception {
+ TestQuery query = new TestQuery(MutableRoaringBitmap.bitmapOf(2, 4), new Object(),
+ DocIdSetIterator.range(1, 3));
+ Weight weight = query.createWeight(null, ScoreMode.COMPLETE, 2.5F);
+
+ Assert.assertFalse(weight.isCacheable(null));
Review Comment:
Converted the new query test to static TestNG assertion imports.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org
Re: [PR] Enable filtered vector search on mutable HNSW and share the doc-id filter query [pinot]
Posted by "xiangfu0 (via GitHub)" <gi...@apache.org>.
xiangfu0 commented on PR #19303:
URL: https://github.com/apache/pinot/pull/19303#issuecomment-5491613686
Added the missing realtime HNSW integration coverage, plus one guard, on `e63a090a59`.
**`HnswVectorRealtimeTest`** — filtered HNSW search against a *consuming* segment, where the index is
`MutableVectorIndex`. Nothing covered this before: the other HNSW integration tests are offline-only, and
`IvfPqVectorRealtimeTest` asserts the IVF_PQ exact-scan fallback.
Two things worth recording, because both were surprises found while making the test actually exercise the path:
1. **The optional metadata pre-filter is wired far more narrowly than it looks.** It requires *all* of: the filter
matching at least `EXACT_SCAN_THRESHOLD` (1000) rows, selectivity below the mid-range cutoff of 0.105, and
every non-vector filter being able to produce a bitmap. My first attempt used a 1000-row table with a plain
(unindexed) category column and quietly planned as `POST_FILTER_ANN` — it would have passed as a green test
that proved nothing. The fixture is now sized deliberately (15000 rows, 12 categories -> 1250 matches at
selectivity 0.083) with an inverted index on the filter column, and the reasoning is in the class Javadoc so
the next person does not have to rediscover it.
2. **`searchMode` is not assertable from `EXPLAIN`.** It is initialized to `POST_FILTER_ANN` and only reassigned
to `FILTER_THEN_ANN` while the search executes; `EXPLAIN` plans without executing, so it always reports the
initial value. The test asserts `filterSelectivity` instead, which is derived from the bitmap the operator
actually received and so genuinely distinguishes a wired pre-filter from an unwired one.
The tests discriminate — verified, not assumed. Against the unwired plan the same assertions returned **1 row
instead of 10** and **5 instead of 50**; they pass 6/6 once the bitmap reaches the operator.
**`HnswVectorIndexReader`** now rejects a null pre-filter bitmap and short-circuits an empty one. It was the only
one of the five filter-aware readers with neither guard, so a null there NPE'd deep inside Lucene traversal
rather than failing with the contract message.
Validation on `e63a090a59`: 76 `pinot-segment-local` vector tests, `HnswVectorRealtimeTest` 6/6, and
spotless/checkstyle/license all clean.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org