Skip to content

perf(plan): avoid duplicate MATCH searches in IVFFLAT PRE - #30178

Merged
XuPeng-SH merged 3 commits into
matrixorigin:mainfrom
iamlinjunhong:perf/ivfflat-pre-single-match-30165
Oct 14, 2026
Merged

XuPeng-SH merged 3 commits into
matrixorigin:mainfrom
iamlinjunhong:perf/ivfflat-pre-single-match-30165

Conversation

@iamlinjunhong

Copy link
Copy Markdown
Contributor

What type of PR is this?

  • API-change
  • BUG
  • Improvement
  • Documentation
  • Feature
  • Test and CI
  • Code Refactoring

Which issue(s) this PR fixes:

What this PR does / why we need it:

IVFFLAT PRE copies its filtered scan into a membership producer. Late fulltext rewriting then executes a filter-only MATCH twice, on both the producer and the final row-fetch scan.

Use the existing exact primary-key SEMI join and outer primary-key join to prove that deterministic MATCH predicates already hold. Remove whole redundant row-fetch conjuncts only after both joins are successfully constructed, and update column-reference counts. Publish the current query root before the early vector rewrite so score-consumer checks inspect reachable ancestors. Projected scores and unsafe MATCH groups retain their existing searches.

Validation on macOS arm64, Go 1.27.1, CPU-only:

  • 21 focused planner test selections pass, covering fulltext/fulltext2, thresholds, supported OR, multiple terms, scalar/NULL filters, score projections, volatile predicates, exact SEMI membership, binding counts, fallback, pagination and prepared plans.
  • The owning planner package passes (3,711 top-level tests); incremental go vet, configured golangci-lint and formatting/diff checks pass.
  • The final service builds with the repository Makefile.
  • Actual EXPLAIN ANALYZE on the issue's 1,026-row, single-list/single-probe fixture reduces fulltext producers from two to one for rare/common/no-hit terms. The remaining producer outputs 16/1,009/0 hits respectively; IDs and distance order match the baseline.
  • Public SQL comparisons against fulltext-only reference tables pass for scores, scalar/NULL predicates, thresholds, Boolean/multiple-term queries, pagination, prepared term changes, prepared reuse after DML and fulltext2.

Design and overall review use gpt-6-astra with medium reasoning effort. CI and the existing distributed hybrid BVT remain pending. Projected-score sharing is outside this bounded optimization.

@qodo-code-review

Copy link
Copy Markdown

Qodo reviews are paused for this user.

Troubleshooting steps vary by plan Learn more →

On a Teams plan?
Reviews resume once this user has a paid seat and their Git account is linked in Qodo.
Link Git account →

Using GitHub Enterprise Server, GitLab Self-Managed, or Bitbucket Data Center?
These require an Enterprise plan - Contact us
Contact us →

@XuPeng-SH

XuPeng-SH commented Oct 14, 2026 •

Copy link
Copy Markdown
Contributor

mo-bot review · mo-bot-local · done

Commit: df676166a762c342ac314506c1c81da1f9d7423d

Review completed. Read the assessment.

@XuPeng-SH XuPeng-SH left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

mo-bot review · mo-bot-local · review

Commit: df676166a762c342ac314506c1c81da1f9d7423d

Assessment: approve

Reviewed the complete delta and affected planner/fulltext callers. The design appropriately reuses exact-PK membership joins, preserves score consumers and unsafe predicates, and commits filter removal only after successful construction. No actionable defects remain.

Model: gpt-6-astra / xhigh

Session: 01a12d8f-8e48-7622-ad17-b605f08450ce · slot 1 · generation 0

Validation:

  • Preflight passed; reconciled 192 native inputs and 46 artifacts with the repository-owned build. Source remained unchanged.

  • 22 focused planner tests and 52 subtests passed: focused-tests.log, receipt checks/1791985853460491349-2.json.

  • 24 public SQL scenarios passed through an embedded cluster, covering fulltext/fulltext2, thresholds, NULL/scalar predicates, multiple terms, pagination, projected scores, and prepared reuse after DML: sql-tests.log, receipt checks/1791985916137508839-2.json.

  • Base-production overlay executed two fulltext producers versus one at HEAD, with identical result IDs. Its expected negative-control failure is retained in base-sql-tests.log and checks/1791985972690932212-2.json.

  • Commands, source fingerprints, outcomes, logs and diagnostic hashes reconciled in /home/xupeng/.local/state/mo-bot/jobs/5a63e6b5931a7bc2893a37b5/attempt-1/validation-ledger.json. Frozen exact-head CI also reports successful build, UT, SCA and BVT.

Limitations:

  • Measured producer reduction and result equivalence, not large-scale latency or throughput. Added planning work is confined to IVF membership analysis; no new runtime state or execution path.

  • The linked issue's full body and author validation artifacts were absent. Core behavior was independently validated from the frozen PR contract.

@mergify mergify Bot added the queued label Oct 14, 2026
@mergify

mergify Bot commented Oct 14, 2026 •

Copy link
Copy Markdown
Contributor

Merge Queue Status

  • ✅ Entered queue — 2026-10-14 13:55 UTC · Rule: main · triggered by rule Automatic queue on approval for main
  • 🟠 Checks running · in-place
  • 🚫 Left the queue — 2026-10-14 14:45 UTC · at ab79005e319836779a5ba4599a107cb441476a47

This pull request spent 50 minutes 3 seconds in the queue, with no time running CI.

Reason

Pull request #30178 has been dequeued

Pull request from fork cannot be queued. This pull request comes from a fork, and Mergify needs the author's permission to update its branch.

The author needs to enable "Allow edits from maintainers" on this pull request.

Hint

You should look at the reason for the failure and decide if the pull request needs to be fixed or if you want to requeue it.
If you do update this pull request, it will automatically be requeued once the queue conditions match again.
If you think this was a flaky issue instead, you can requeue the pull request, without updating it, by posting a @mergifyio queue comment.

Waiting for any of
  • check-neutral = CI Required
  • check-skipped = CI Required
  • check-success = CI Required
All conditions

Tick the box to put this pull request back in the merge queue (same as @mergifyio queue).

  • Requeue this pull request

@XuPeng-SH
XuPeng-SH merged commit 43ae1ed into matrixorigin:main Oct 14, 2026
@mergify mergify Bot added dequeued and removed queued labels Oct 14, 2026
cpegeric added a commit to cpegeric/matrixone that referenced this pull request Oct 14, 2026
Resolve apply_indices_ivfflat.go against matrixorigin#30178 (avoid duplicate MATCH searches
in IVFFLAT PRE): ivfflat PRE is built by the shared buildVectorPreFilterJoin on
this branch, so the row-fetch MATCH removal moves there and applies to hnsw,
cagra and ivfpq as well. TestVectorPreFulltextMembershipSearchesOnce covers
them; the hybrid BVTs check one fulltext scan in EXPLAIN.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
mergify Bot pushed a commit that referenced this pull request Oct 21, 2026
…agra, ivfpq and ivfflat (#28988) (#30127)

A filtered vector top-k could return a short or empty page while qualifying rows exist (issue fixture: hnsw 0 of 10; recall@10 0.18 hnsw / 0.33 ivfflat vs 0.998 pgvector iterative scan). `mode=pre|post|auto` was honored by ivfflat only. Design: `docs/design/20261012-filtered-vector-search.md`; every claim there names its BVT.

- **Pre-filtering.** The index search filters inside the search in two ways:
- INCLUDE columns and the primary key, evaluated on the index entries (no JOIN): ivfflat entries scan, cagra/ivfpq GPU bitset.
- membership: the primary keys of the filtered rows, from a SEMI JOIN, as a runtime filter (all four indexes; on cagra/ivfpq ANDed into the GPU filter mask).

A filter neither covers runs after the search (post-filtering).
- **Modes on all four vector indexes.**
- `post`: one index search; only primary-key filters run inside it.
- default (no option): as `post`, plus INCLUDE-column filters inside the search (unchanged).
- `pre`: one search with every filter it can pre-filter. INCLUDE-column and primary-key filters run in the search on ivfflat, cagra and ivfpq; other filters go through membership on all four indexes. A distance range predicate (`l2_distance(v, q) < K`) runs on the search output and never builds the PRE shape. An ivfflat `pre` whose filters are all on INCLUDE columns or the primary key builds no JOIN.
- `iterative`: `pre` that widens while the page is short, up to `max_itopk` / `max_nprobe` (pgvector's iterative scan).
- `auto`: `ADAPTIVE_TOP [post, pre, force]` on every index, pre omitted when it equals post.
- `include` (ivfflat's earlier name for `iterative`, #24168) is accepted as an alias of `iterative` on every index, so existing queries keep running.
- **Membership key set.** The membership producer scan also applies the filters the index search evaluates, so the key set holds only rows that pass every filter (fewer keys; on ivfflat a set of 100 keys or fewer is searched exactly in every list).
- **Membership in C memory (hnsw, cagra, ivfpq).** `docfilter.NewForC` builds a cbitmap when eligible, otherwise whichever of CRoaring and C sorted64 is estimated smaller; the estimate is reserved with the CN memory admission before the build and released on the last `Free`. One `mo_membership_t` (`cgo/membership.h`) is shared by usearch and cuVS. cuVS probes it per row against `host_ids` inside the existing CPU mask pass (cbitmap read in place, CRoaring/sorted64 `contains`, no extra allocation), ANDed with the INCLUDE/pk predicates and the deletes, then one upload. A membership needs int64 `host_ids`; a Go-memory filter is an error. The filter mask and its delete copy are reserved with the admission when together they are 1 MiB or more. `iterative` stops at `min(LIMIT, members)`.
- **Filter mask built once per iterative search (cagra, ivfpq).** `prepare_bitset` builds the host filter mask (membership AND INCLUDE/pk predicates AND deletes; one per index, shard and CDC overflow) once; every round of a `mode=iterative` search uses it through `search_quantize_with_bitset`, instead of rebuilding and re-uploading it per round. Go: `Bitset` / `MultiBitset`, `PrepareBitset`, `SearchQuantizeWithBitset`. The deletes are those at prepare time. `upload_host_mask` now clears bits past the mask (raft's bitset defaulted to all set, so rows appended after a mask was built passed the filter) and clamps the copy to the shard.
- **Knobs.** `BY RANK WITH OPTION 'itopk=…', 'max_itopk=…', 'nprobe=…', 'max_nprobe=…'` by index family, session variables `vector_itopk`, `vector_max_itopk`, `vector_max_nprobe` resolved per execution (a `SET` after `PREPARE` applies). `nprobe` is 1..80000 (the `probe_limit` range); an unknown option key is an error. On cagra `itopk` and `max_itopk` are at most 1024, the most keys one cuVS CAGRA search returns: a larger BY RANK value is an error, a larger session value is lowered to 1024 (the session variables are shared with hnsw); the `iterative` default cap is 1024 (20000 on hnsw). EXPLAIN shows the knobs and the filter the index search applies (`Index Filter`).
- **Iterative search.** One Go policy per algorithm (`pkg/vectorindex/<algo>/iterative.go`, `searchplugin.IterativeSearchHooks`) over the unchanged regular search, run only for `mode=iterative`; hnsw/cagra/ivfpq restart with doubled knobs, ivfflat continues its centroid cursor. Every policy has a terminal round: ivfpq caps at the list count of the built index (`MultiGpuIvfPq.NLists`; an overflow-only generation stops after its first round, which searches every row) and at the indexed rows; doubling saturates; cagra/hnsw/ivfpq stop on a canceled statement between rounds.
- **Capabilities.** `MembershipHooks` / `IndexFilterHooks` / `InternalTopKLimitHooks` replace algorithm-name checks; the mode check runs only for the index that serves the query.
- **Hybrid fulltext.** hnsw, cagra and ivfpq serve a `MATCH` + vector top-k through the PRE shape (both indexes, exact matching rows). On every index the PRE shape runs a filter-only `MATCH` once, in the membership producer: main's #30178 row-fetch removal (ivfflat) lives in the shared `buildVectorPreFilterJoin` on this branch and covers hnsw, cagra and ivfpq too.
- **Single evaluation under PRE.** The PRE shape runs the scan's filters in the membership producer and on the row-fetch scan. When those filters or the membership join read a sequence or volatile expression (`nextval`, `rand()`, ...), every index leaves the query to the exact sort, which evaluates them once per row, as `auto` already runs `force` (`vectorPreFilterReplaySafe`).
- **Wire.** `IndexSearchScan.internal_topk`, `max_internal_topk`, `max_nprobe` with a dedicated MORPC version, `vectorscan.SearchKnobsProtocolVersion` (the single reference to the number; shared with no other feature); required only when a knob is set, and stamped only for algorithms that use it. `RankOption` carries `nprobe` at field 2, as on main.
- **Fixes found on the way.**
- ivfpq: an inline `INDEX i USING ivfpq(v)` without options took the `DefaultOptions` hook, which has no `lists`, bypassing `ParamsFromTree`'s `lists > 0` rule; `mode=iterative` on such an index with a short page never terminated (reproduced on GPU SQL). An index declared without options now takes the plugin's `ParamsFromTree` of an empty option list, as `CREATE INDEX` does; `DefaultOptions` is removed (ivfflat/hnsw/cagra params unchanged).
- cagra: `mode=iterative` widened `itopk` past 1024 when fewer than `LIMIT` rows qualified on a table over 1024 rows, and cuVS failed with "topk must be lower than or equal to 1024"; `itopk` above 1024 is now an error.
- ivfpq: the host post-filter always runs under a filter; before, a filter the probed lists did not hold returned excluded rows and failed with "vector magnitude is too large" (C++ test `FilterEmptyInProbedListsPadsWithSentinels`).
- ivfflat: centroid ranking is a permutation, so a zero query vector under cosine no longer scans lists twice (duplicate rows).
- ivfflat: an exact primary-key search reads every list; EXPLAIN now reports that window (`bucket_windows=0:n`) instead of the `nprobe` lists.
- `mo_sorted64_build_fixed` rejects an element size other than 1/2/4/8 and skips a truncated item.
- cagra/ivfpq create: an async REINDEX runs `cagra_create` / `ivfpq_create` in parallel pipelines; an instance that received no rows called `DeviceDemand` on a nil builder in `end()`, and the panic failed the ISCP build iteration. It now returns early (`TestCreateEndWithoutRows`).
- ivfflat: an `itopk` above the indexed rows (up to the largest uint64) panicked an INCLUDE search (`makeslice: cap out of range`) and, in the default mode, lost the storage Top-K distance column. The result buffers are preallocated with a bound, and the storage Top-K limit is at most the largest int (every row). hnsw and ivfpq already bound the search by the index rows; cagra rejects an `itopk` above 1024.
- Removed the unused statement-level auto retry (`rewriteAutoModeToPre`).

Behavior changes against main:
- ivfflat `pre` runs INCLUDE-column filters in the index search instead of through membership: more qualifying rows per round, but no exact membership set, so a filter that only a few rows (100 or fewer) pass can return a short page where `iterative` fills it (short-page matrix).
- cagra/ivfpq `pre` and `iterative` (and a membership join or `MATCH` filter) run filters outside the INCLUDE columns through membership, in the GPU search, instead of after it.
- `mode=include` runs as `mode=iterative` on every index (on main it changed behaviour only on ivfflat).
- A zero query vector under cosine on ivfflat returns no duplicate rows.
- An inline ivfpq index without `lists` is refused, as `CREATE INDEX` already refuses it.

`mode=force` stays the exact CPU sort: it bypasses the index, so it is not a GPU search. A GPU `vector_matmul` force was measured and rejected: one query on 1M × 768 vecf32 took 1.07 s on the GPU and 0.19 s on the CPU (the GPU is 5.6× slower).

### Tests

- `prepare_bitset`: C++ `PreparedBitsetSearch` (cagra, ivf_pq, brute force), `PreparedBitsetSearchSharded`, `PreparedBitsetExcludesRowsAddedAfterPrepare` (fails with the all-set upload); Go `TestGpu{Cagra,IvfPq,BruteForce}PreparedBitset`, `TestMultiGpu{Cagra,IvfPq}PreparedBitset` (race `-count` 55–100). 1M × 768 bench, `mode=iterative`: ivfpq with a 99% filter 61.0 → 57.5 ms mean (A/B/A), ivfpq with a 0.1% filter 18.4 → 16.7 ms; single-round searches unchanged. The per-round saving is the mask pass over the index rows (~3 ms at 1M rows with a 990k-key membership), so it grows with table size × rounds.

- BVT: `cases/vector/vector_filtered_search_{hnsw,ivfflat,modes,knobs}.sql`, `vector_hybrid_fulltext.sql`; `gpu_cases/vector/vector_filtered_search_gpu.sql`, `vector_filtered_search_knobs_gpu.sql`, `vector_hybrid_fulltext_gpu.sql`, `vector_cagra_itopk_limit.sql`. Full `cases/vector`, `gpu_cases/vector`, `cases/fulltext`, `cases/optimizer/explain_format_json.sql`, `pessimistic_transaction/vector` pass at 100% (156 files).
- Unit tests across the touched packages (GPU build; membership tests also 100× under `-race`); C++ cuVS tests (223/223) for the ivfpq post-filter and the membership mask (`EvalFilterMembershipTest`, `Gpu{Cagra,IvfPq}Test::FilteredSearchAppliesMembership`); C test `cgo/test/test_sorted64.c`.
- Iterative termination: `TestIterativeSearchTerminates` (omitted lists / overflow only, filter below LIMIT, known lists, `max_nprobe`, all indexed rows, full page, members, saturation; fails on the previous policy), `TestInlineVectorIndexWithoutOptionsUsesParamsFromTree` (inline DDL equals `ParamsFromTree`, ivfpq refused), `TestMultiGpuIvfPqPreparedBitset` (`NLists`).
- GPU BVT added: `gpu_cases/pessimistic_transaction/vector/vector_filtered_search_overflow_gpu.sql` (built index + CDC overflow under membership, primary-key and subquery filters, pre and iterative, cagra and ivfpq), `vector_ivfpq_iterative_overflow.sql` (inline ivfpq without lists refused; overflow-only iterative below LIMIT), `gpu_cases/vector/vector_sharded_filtered.sql` (sharded pre/iterative membership across shards).
- Protocol fence: `TestSearchKnobScopeRefusesPriorEpochDestination` — a knob scope whose frozen destination reports the prior version is refused at the send-time re-probe, on the execution-stream handshake and on receiver decode; a no-knob scope still runs there.
- 1M × 768 (cagra / ivfpq, median ms): no filter 5.9 / 3.5; cbitmap 500k keys 41.8 / 36.4; cbitmap 1k 22.9 / 6.7; CRoaring 10k 26.1 / 24.5; C sorted64 150 keys 33.3 / 20.3; no returned row fails the filter.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Approved by: @XuPeng-SH, @aunjgr, @fengttt

This branch was previously deployed

1 inactive deployment
ci — ab79005e Deployed Oct 14, 2026 by mergify[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

dequeued kind/enhancement size/M Denotes a PR that changes [100,499] lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants