Skip to content

[4.2-dev] Avoid SQL literal expansion for exact IVF PRE - #33551

Merged
XuPeng-SH merged 1 commit into
matrixorigin:4.2-devfrom
XuPeng-SH:fix/ivf-exact-pre-33549
Dec 1, 2026
Merged

XuPeng-SH merged 1 commit into
matrixorigin:4.2-devfrom
XuPeng-SH:fix/ivf-exact-pre-33549

Conversation

@XuPeng-SH

Copy link
Copy Markdown
Contributor

What type of PR is this?

  • BUG
  • Improvement

Which issue(s) this PR fixes:

issue #33549

What this PR does / why we need it:

#33514 established exact IVF PRE membership before ranking. On wide VARCHAR primary keys, it also expanded complete typed key vectors into SQL literals and ran the optimizer and entries scan for every list of literals. The optimizer accounted for 54% of sampled CPU in the 8,193-key reproduction. The inner executor also returned all matching entries before the Go merge took the Top-K.

  • Send bounded primary-key vectors through prepared parameters. Evaluate exact membership before the SQL Top-K, then merge up to LIMIT + OFFSET candidates per chunk across all lists.
  • Bind compact, sorted key sets through the existing typed IN expression when the column's equality and ZoneMap ordering support it. Preserve pruning on selective queries.
  • Keep the caller's statement snapshot and observe pipeline cancellation. Publish the merged keys and aligned INCLUDE values after all chunks succeed. Remove the superseded literal conversion and predicate batching.

Validation

Local Linux amd64 measurements against 34b63d7261, two runs per side, eight timed samples per mode and key count per run. Each query returned the expected Top-10. Values are ranges of the run medians in milliseconds.

Eligible 1,021-byte keys Base PRE PR PRE
8,192 231–260 30–32
8,193 242–276 22.8–23.2

FORCE remained in the 1.4–2.0 ms range. With persisted 48,000-row controls, the 2-key BIGINT median was 1.58–2.07 vs 1.59–1.61 ms. The 2-key VARCHAR median was 1.57–1.72 vs 1.73–1.92 ms, with overlapping sample ranges. The 100-key BIGINT and VARCHAR controls retained block pruning and the 5,000-key integer control retained docfilter.

  • 507 assertions passed across 11 IVF BVT cases, including a binary-key page spanning chunks with OFFSET, excluded nearer rows and an empty domain.
  • A two-CN native run crossed the byte budget with 17 MiB of binary keys and matched an independent order and page oracle. Transactional visibility and rollback checks passed.
  • Local UT race across eight packages, gofmt, go vet and diff-scoped golangci passed. The pinned molint diagnostics match the base.

@qodo-code-review

qodo-code-review Bot commented Dec 1, 2026 •

Copy link
Copy Markdown

PR Summary by Qodo

Pass exact IVF PRE keys as typed parameters, not SQL literals

🐞 Bug fix ✨ Enhancement 🧪 Tests 🕐 40+ Minutes

Grey Divider

AI Description

• Sends exact IVF pre-filter keys as binary prepared parameters, removing SQL literal expansion and
 its optimizer cost.
• Evaluates exact membership in the entries scan and merges per-chunk Top-K (LIMIT + OFFSET) before
 publishing results.
• Replaces the optional and required literal paths with one bounded, chunked exact search. Keeps
 typed IN for small sorted key sets.
Merge Risk 🟡 Medium

Blast radius 🟢 Low 💥 1 capability

  • 1 affected end-to-end capability after fault-specific containment; implementation boundaries do not widen its functional scope.
  • The table function, runtime-key producer, planner residual predicate, internal SQL executor, and entries consumer jointly implement one bounded IVF search behavior.
  • They affect the same vector-search outcome rather than independent technical capabilities.
  • The exact residual predicate is a mode of the same end-to-end IVF search integration: runtime keys originate in the build side, are transported as chunks, bound into internal SQL, and constrain entries consumed by the vector search.
Behavioral complexity 🟡 Medium 🧩 Multiple interactions

  • Before, IVF membership was converted into SQL literals or one membership payload.
  • After, the implementation selects exact versus approximate modes, binds encoded chunks through internal SQL, suppresses incompatible pushdown, and merges chunk results.
  • New correctness conditions are that every chunk is applied exactly once, the residual predicate remains below Top-K, parameter type and scale match the probe key, include columns stay aligned during global Top-K merging, and ordinary callers remain compatible with the new payload requirement.
  • The planner also preserves older supported key domains by falling back when small-list conversion is not safe.
Potential damage 🟡 Medium 🩹 Temporary loss

  • If the nil-payload fault is reachable, the affected IVF query can fail before returning vector results.
  • Reverting restores the prior ordinary-search behavior; no persistent state or external effect requires repair.
  • A code rollback restores the prior search path.
  • A failed query can be retried after deployment rollback or correction; no stored data repair is required.
Assessed commit f1cdc4b
Diagram

sequenceDiagram
  participant S as ivfflat Search
  participant E as RunIvfExactSearch
  participant X as SQL Executor
  participant F as ivf_exact_pk_in
  S->>E: key chunk as binary param
  E->>X: entries SELECT with ? param
  X->>F: membership per row
  F-->>X: bool per row
  X-->>E: Top-K candidates
  E-->>S: chunk rows
  S->>S: merge Top-K across chunks
Loading
High-Level Assessment

The following are alternative approaches to this PR:

1. Temp table or semi-join for key domain
  • ➕ Scales to very large key domains without per-chunk scans
  • ➕ Lets the optimizer choose the join strategy
  • ➖ Requires temp table DDL and cleanup inside the caller's transaction
  • ➖ Harder to keep snapshot and rollback semantics identical to the entries scan

Recommendation: Keep the PR's approach for the current scale. Binary parameters avoid parser and optimizer cost, and typed IN preserves ZoneMap pruning on small sorted sets. A larger-scale alternative would be a temp table or semi-join for very large key domains, but that adds DDL and transaction complexity that this change does not need.

Files changed (24) +1125 / -565

Enhancement (11) +282 / -19
key_payload.goAdd membership chunk byte cap and small-key crossover constants +8/-0

Add membership chunk byte cap and small-key crossover constants

• Adds MembershipKeyChunkBytes (16 MiB) to bound each membership frame, since row count alone does not bound variable-width keys. Adds SmallMembershipKeyRows (100) as the crossover for using a typed IN predicate.

pkg/common/hashmap/keycodec/key_payload.go

type.goAdd exact-search context marker and PK-in function name +6/-0

Add exact-search context marker and PK-in function name

• Adds the IvfExactSearch context key so the planner keeps Top-K above the membership residual. Adds IvfExactPkInName as the internal function name used by the entries query.

pkg/defines/type.go

build.goEnable chunked key collection for membership filters +1/-0

Enable chunked key collection for membership filters

• Sets membershipKeyChunks when the runtime filter uses a membership filter that must apply. This makes the hash build collect keys in bounded chunks.

pkg/sql/colexec/hashbuild/build.go

hashmap.goTrack and reset membershipKeyChunks flag +3/-0

Track and reset membershipKeyChunks flag

• Adds the membershipKeyChunks field to HashmapBuilder and clears it in both Reset and Free.

pkg/sql/colexec/hashbuild/hashmap.go

key_batches.goCap unique-key append size when membership chunking is on +5/-1

Cap unique-key append size when membership chunking is on

• Caps the per-append byte budget at MembershipKeyChunkBytes when membership chunking is enabled. Otherwise the existing MaxAllocationSize limit applies.

pkg/sql/colexec/hashbuild/key_batches.go

base_binder.goRoute ivf_exact_pk_in calls to the exact PK binder +3/-0

Route ivf_exact_pk_in calls to the exact PK binder

• Dispatches calls to the ivf_exact_pk_in function name to bindIvfExactPkIn before normal function binding.

pkg/sql/plan/base_binder.go

function_id.goRegister IVF_EXACT_PK_IN function id +6/-1

Register IVF_EXACT_PK_IN function id

• Adds the IVF_EXACT_PK_IN function id (638), bumps FUNCTION_END_NUMBER to 639, and registers the name in functionIdRegister.

pkg/sql/plan/function/function_id.go

ivf_exact_pk.goImplement exact membership evaluation over a bound key vector +124/-0

Implement exact membership evaluation over a bound key vector

• Implements ivf_exact_pk_in as a boolean function that decodes a constant key vector once and tests each probe row. Supports binary, scaled float, double, and rowid keys, and rejects malformed or wrong-domain vectors. Nulls never match.

pkg/sql/plan/function/ivf_exact_pk.go

list_builtIn.goRegister ivf_exact_pk_in as internal overload +16/-0

Register ivf_exact_pk_in as internal overload

• Adds the internal boolean overload for ivf_exact_pk_in with checkFn and an newOpWithFree constructor.

pkg/sql/plan/function/list_builtIn.go

ivf_exact_pk.goBind small sorted key sets to typed IN predicates +89/-0

Bind small sorted key sets to typed IN predicates

• Binds the PK-in call to a typed IN expression only when the key set is small (at most 100 rows), non-null, and sorted, and the column's equality and ZoneMap ordering support it. Larger or wider domains keep the executor predicate. Caps plan-side key bytes at 128 KiB.

pkg/sql/plan/ivf_exact_pk.go

sqlexec.goAdd RunIvfExactSearch with binary params and pipeline context +21/-17

Add RunIvfExactSearch with binary params and pipeline context

• Removes IvfRuntimeFilterData and ExactPkFilter from SqlProcess. Adds RunIvfExactSearch, which passes a key chunk as a binary parameter, marks the context with IvfExactSearch, and observes the pipeline context. Refactors RunSql to share a runSQL helper.

pkg/vectorindex/sqlexec/sqlexec.go

Bug fix (2) +148 / -227
pushdown.goSkip IVF reader pushdown for exact membership searches +4/-0

Skip IVF reader pushdown for exact membership searches

• Stops pushing Top-K into the IVF index reader when the query is marked as exact. The reader cannot enforce the exact membership residual, so Top-K must stay above the scan.

pkg/sql/plan/pushdown.go

search.goReplace literal PRE with chunked exact Top-K search +144/-227

Replace literal PRE with chunked exact Top-K search

• Removes getBloomFilter and the literal IN predicate path. Small or required non-integer key sets now run searchExact, which sends each chunk as a bound parameter and merges Top-K to LIMIT + OFFSET. Large integer or optional sets use docfilter membership.

pkg/vectorindex/ivfflat/search.go

Refactor (1) +84 / -0
runtime_keys.goMove WaitUniqueJoinKeys into runtime_keys.go +84/-0

Move WaitUniqueJoinKeys into runtime_keys.go

• Moves WaitUniqueJoinKeys out of the deleted bloomfilter.go into its own file. Adds a nil guard on the spec.

pkg/vectorindex/sqlexec/runtime_keys.go

Tests (9) +609 / -318
ivf_exact_pk_test.goTest exact membership across binary, float, and null cases +91/-0

Test exact membership across binary, float, and null cases

• Covers binary keys with NULL, scaled float32 with signed zero and NaN, and float64 edge values. Also checks that malformed bytes and mismatched types or scales are rejected.

pkg/sql/plan/function/ivf_exact_pk_test.go

getbloomfilter_test.goRemove bloom filter tests superseded by exact search +0/-190

Remove bloom filter tests superseded by exact search

• Deletes tests for the removed getBloomFilter path, including approximate and literal-based exact PK cases.

pkg/vectorindex/ivfflat/getbloomfilter_test.go

search_membership_test.goTest docfilter routing and empty required domain +99/-0

Test docfilter routing and empty required domain

• Verifies that large integer or optional domains use docfilter with one SQL call. Also checks that a required empty domain returns an exhausted, empty result without SQL.

pkg/vectorindex/ivfflat/search_membership_test.go

search_quantize_test.goUpdate quantize test to the bound-parameter exact path +6/-11

Update quantize test to the bound-parameter exact path

• Switches the exact-search quantize test to runIvfExactSearch and checks for the bound parameter and LIMIT. Removes the literal-based exact SQL assertions.

pkg/vectorindex/ivfflat/search_quantize_test.go

search_test.goAssert bound-parameter exact SQL and chunked Top-K merge +46/-117

Assert bound-parameter exact SQL and chunked Top-K merge

• Replaces literal IN assertions with checks on ivf_exact_pk_in(..., ?) and ORDER BY ... LIMIT. Tests that chunked exact batches publish only the global Top-K, and that cancellation leaves the cursor and include data unchanged.

pkg/vectorindex/ivfflat/search_test.go

runtime_keys_test.goMove WaitUniqueJoinKeys tests into runtime_keys_test.go +282/-0

Move WaitUniqueJoinKeys tests into runtime_keys_test.go

• Moves the WaitUniqueJoinKeys tests from the deleted bloomfilter_test.go into their own file. Test logic is unchanged.

pkg/vectorindex/sqlexec/runtime_keys_test.go

sqlexec_test.goTest RunIvfExactSearch context and parameter binding +55/-0

Test RunIvfExactSearch context and parameter binding

• Checks that RunIvfExactSearch sets the exact-search marker, drops the old membership filter, passes binary keys as params, and returns cancellation from the pipeline context.

pkg/vectorindex/sqlexec/sqlexec_test.go

vector_ivf_pre_exact_domain.resultAdd expected results for multi-chunk binary-key PRE page +18/-0

Add expected results for multi-chunk binary-key PRE page

• Records expected output for a binary-PK IVF query with OFFSET across chunks. Also records that a required empty domain returns zero rows.

test/distributed/cases/vector/vector_ivf_pre_exact_domain.result

vector_ivf_pre_exact_domain.sqlAdd BVT case for multi-chunk binary-key PRE with OFFSET +12/-0

Add BVT case for multi-chunk binary-key PRE with OFFSET

• Adds an 8,300-row binary-PK table with an IVF index, where the closest keys are excluded and one row has no vector. Runs a paged query with OFFSET and an empty-domain query.

test/distributed/cases/vector/vector_ivf_pre_exact_domain.sql

Other (1) +2 / -1
function_id_test.goUpdate predefined function id table for IVF_EXACT_PK_IN +2/-1

Update predefined function id table for IVF_EXACT_PK_IN

• Adds the IVF_EXACT_PK_IN entry and moves FUNCTION_END_NUMBER to 639 in the predefined id test table.

pkg/sql/plan/function/function_id_test.go

@mergify

mergify Bot commented Dec 1, 2026 •

Copy link
Copy Markdown
Contributor

This pull request is merged.

@qodo-code-review

Copy link
Copy Markdown

Code Review by Qodo

🐞 Bugs (0) 📘 Rule violations (0) 📎 Requirement gaps (0)

Grey Divider

Great, no issues found!

Qodo reviewed your code and found no material issues that require review

Grey Divider

Tip of the day
💡 Did you know, you can pick a display mode instead of tweaking every Display option by hand

More tips ↗ | Customize Qodo ↗ | Qodo docs ↗

Grey Divider

Qodo Logo

@XuPeng-SH

XuPeng-SH commented Dec 1, 2026 •

Copy link
Copy Markdown
Contributor Author

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

Commit: f1cdc4b552378fd679ed0720674ce7d0fdea9548

Review completed. Read the assessment.

@XuPeng-SH XuPeng-SH left a comment

Copy link
Copy Markdown
Contributor Author

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: f1cdc4b552378fd679ed0720674ce7d0fdea9548

Assessment: approve

The change preserves exact membership before Top-K while replacing wide-key SQL literal expansion with bounded, typed key payloads. It reuses the existing executor and filtering paths; the added per-chunk matcher and scans carry a cost, but the tested wide-key workload improved substantially. The automated review’s possible nil-payload concern is not supported: Rows is nil-safe and the required-filter path distinguishes an empty domain from an unavailable payload.

Model: gpt-6.1-terra / max

Session: 01a22b07-00b6-7e32-b0a1-3099d0b867c7 · slot 1 · generation 39

Validation:

  • Preflight and native-input provenance audit passed; receipts 1796090409350465087-3.json and 1796090435532280299-4.json.

  • Focused planner, matcher, hashbuild, IVF search and SQL executor tests passed; targeted race tests also passed. Receipts 1796090691685460882-3.json and 1796091578421982011-3.json.

  • Public SQL probes passed for multiple primary-key types and a two-CN wide-key domain crossing the byte budget. A separate SQL probe verified the added binary-key, INCLUDE, OFFSET and empty-domain results against a relational control. Receipts 1796090888841004253-3.json and 1796091652092611898-3.json.

  • Equal-fixture performance probes against the target base reconstructed with a Go overlay and the candidate passed. Median PRE times for 8,192 and 8,193 wide keys fell from approximately 242 and 247 ms to 37 and 39 ms, respectively. Receipts 1796091122107008325-3.json and 1796091169501837309-3.json.

Limitations:

  • The supplied evidence had no completed CI result or normal mo-tester comparison for the entire changed BVT case. The added SQL results were independently exercised through the SQL frontend.

  • The performance comparison used one run per revision with four timed samples per case; it supports the observed improvement for that fixture, not a precise general performance estimate.

This branch was previously deployed

1 inactive deployment
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

kind/bug Something isn't working kind/enhancement size/XXL Denotes a PR that changes 2000+ lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants