Skip to content

[4.2-dev] Require exact membership before scalar IVF PRE Top-K - #33514

Merged
XuPeng-SH merged 4 commits into
matrixorigin:4.2-devfrom
LeftHandCold:fix/42-scalar-ivf-pre-topk
Nov 30, 2026
Merged

XuPeng-SH merged 4 commits into
matrixorigin:4.2-devfrom
LeftHandCold:fix/42-scalar-ivf-pre-topk

Conversation

@LeftHandCold

@LeftHandCold LeftHandCold commented Nov 30, 2026 •

Copy link
Copy Markdown
Collaborator

What type of PR is this?

  • BUG

Which issue(s) this PR fixes

Fixes #33504 on 4.2-dev. Separate from the flush/replay problem in #33149.

What this PR does / why we need it

Scalar PRE membership is a correctness condition, not an optional optimization: a Bloom false positive can take the place of an eligible row before Top-K. Keep exact membership for this domain. In particular, preserve the original scalar and vector predicates when producing eligible keys. A sync IVF candidate implies the direct vector IS NOT NULL test, not arbitrary predicates mentioning that vector.

The follow-up fixes the review findings on cb68ff3:

  • Preserve TIMESTAMP instants via the existing typed tuple codec (including DST folds), rather than interpreting a UTC wall-clock string in the session zone. Compare DECIMAL64/128/256 at their declared precision/scale rather than coercing to DOUBLE; support typed YEAR keys.
  • Required non-integer domains use disjoint, bounded internal predicates (8 MiB encoded key list and 8,192 keys per batch). Merge ranked candidates across batches before returning, retaining OFFSET and associated INCLUDE/NULL values. A failed batch fails the statement; there is no fallback to a weaker membership test. A single key which cannot fit still fails explicitly.
  • No wire, catalog, or index format change, no new service, and no change to POST's contract.

Verification

  • On two isolated local single-CN servers, the review's 200-row SQL returned only the full-scan controls on cb68ff3; the fix returned exactly IDs 41–50 for all four queries. Tested plain session-default PRE and INSERT … SELECT with readback, 100/101/160 qualifying keys, +08:00 and -05:00, and both distinct instants displayed as the same local 01:30:00.000001 in New York.
  • Added vector_ivf_pre_exact_domain.sql with independent expected outputs. Same SQL/expectations: 30/37 on the previous PR head (seven failing assertions), 37/37 on the fix. Whole selected IVF BVT: 480/480 across 11 scripts, no skips including membership/collision, quantization, include, adaptive rounds and joins. No existing golden output was rewritten.
  • Final build: 35/35 additional SQL comparisons, including DECIMAL(65,0), YEAR, cross-batch nearest keys with OFFSET on 8,193 wide keys and 45,000 × 197-byte keys, and combined distance + scalar filters; verified IVF plans vs same-transaction exact reference. Additional unit tests check a better winner/NULL include from the second batch, cancellation returns no key page, escaping and byte boundaries.
  • Complete sqlexec, ivfflat and planner Go tests; repeated focused tests; go vet; incremental golangci-lint (0 issues); CPU mo-service build, gofmt and diff checks.

Floating PK review follow-up (cfacc1a)

The previous revision could turn a tiny DOUBLE into zero or overflow Decimal256 for a large DOUBLE when parsing bare fixed-point PK literals. Encode the shortest round-trip text for the source width as a quoted string explicitly cast to FLOAT/DOUBLE. No change to batching, ranking, or storage.

Same SQL on 1944c90 vs the fix: 171 eligible out of 340 distinct keys, all four lists probed. Small DOUBLE: unhinted PRE returned zero rows in 5/5 trials, now IDs 1–10 in 5/5; large negative DOUBLE: error 20301 in 5/5, now IDs 1–10 in 5/5. On a new connection after COMMIT, the small-DOUBLE insert-select changed from an empty destination to exactly IDs 1–10. A seven-table differential run covering FLOAT, DOUBLE, adjacent representable keys, and 100/101/171/340 candidates passed all 36 query and 7 committed-readback checks. The updated repository SQL regression failed 2 assertions on the old revision and passed 46/46 twice on the fix; full sqlexec/ivfflat/plan tests, incremental lint, vet and binary build passed. The independent, pre-existing volatile-predicate short page is tracked in #33531.

Release trade-off

Exact string PRE is still not performance-neutral. On the fixed build, a small in-memory-like test with almost every row eligible and 1,021-byte keys gave median 289 / 302 ms for 8,192 / 8,193 keys vs 9.9 / 9.8 ms for the same query on the exact relational path (single CN, 3 vCPU limit, six alternating timed trials after warm-up, identical ordered results). This is a path comparison, not a before/after throughput claim. For very broad domains, a per-query BY RANK WITH OPTION 'mode=force' selects the exact relational alternative. No assertion of multi-CN or production performance certification.

@XuPeng-SH
XuPeng-SH marked this pull request as ready for review November 30, 2026 09:07
@XuPeng-SH
XuPeng-SH self-requested a review as a code owner November 30, 2026 09:07
@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 →

@mergify mergify Bot added the kind/bug Something isn't working label Nov 30, 2026
@mergify

mergify Bot commented Nov 30, 2026 •

Copy link
Copy Markdown
Contributor

Queue requested — the merge queue status continues in this comment ↓.

@XuPeng-SH

XuPeng-SH commented Nov 30, 2026 •

Copy link
Copy Markdown
Contributor

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

Commit: cb68ff3d2eb4bb614725fb26ab25151088e665fd

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

Assessment: request_changes

The required-domain approach fixes the demonstrated scalar PRE Bloom collision by reusing the existing membership pipeline. Expanding that pipeline to scalar predicates also exposes two primary-key type defects and an 8 MiB limit that rejects previously successful queries. The exactness fix needs to preserve those cases.

Model: gpt-6.1-terra / max

Session: 01a22aff-bb68-7e31-ae71-ee4ab48ad9d0 · slot 0 · generation 45

  • P2 pkg/sql/plan/apply_indices_ivfflat.go:1703: A scalar IVF PRE query has more than 100 qualifying TIMESTAMP primary keys and runs in a non-UTC session time zone.
    Impact: The exact membership predicate can identify different timestamps, silently omitting qualifying rows or returning an empty Top-K result.
    Evidence: The newly required non-integer path formats timestamps in UTC in pkg/vectorindex/sqlexec/bloomfilter.go:292, but the internal SQL executor uses the session time zone at pkg/vectorindex/sqlexec/sqlexec.go:192. In an indexed SQL test with 101 qualifying keys, the candidate returned no rows at +08:00 while the unindexed reference and the original planner returned row 1; the UTC control also returned row 1. Generate literals in the executor's time zone or use a time-zone-independent exact representation.

  • P2 pkg/sql/plan/apply_indices_ivfflat.go:1687: A scalar IVF PRE query has more than 100 qualifying DECIMAL(65,0) primary keys.
    Impact: A valid query that previously completed now fails with "ivf_search: unsupported pk type 34".
    Evidence: The mandatory non-integer path calls AppendVectorSQLLiteral, whose decimal cases cover Decimal64 and Decimal128 but not Decimal256. An indexed SQL test with 101 DECIMAL(65,0) keys failed on the candidate and returned the expected row with the original planner. Add Decimal256 support or use another exact membership representation for this supported key type.

  • P2 pkg/sql/plan/apply_indices_ivfflat.go:1703: A scalar IVF PRE predicate produces non-integer primary keys whose encoded exact predicate exceeds 8 MiB.
    Impact: Previously valid queries fail even when their former results were correct; the failure depends on the size of the eligible domain, not the requested Top-K.
    Evidence: The PR discloses the existing exact-predicate limit, but this change applies it to scalar PRE queries that previously used the optional path. In an indexed SQL test with 45,000 qualifying VARCHAR keys of 197 bytes each and all rows eligible, the original planner and an unindexed reference returned row 1; the candidate failed with "exact primary-key filter exceeds 8388608 bytes". Preserve exact PRE semantics for broad domains, for example through an exact membership representation or a correct scan fallback.

Validation:

  • Private execution preflight passed: checks/1796038852598415064-3.json.

  • Focused planner, IVF membership, and exact-filter Go tests passed: checks/1796039167973089171-3.json and focused-recovered.log.

  • The indexed Bloom-collision SQL control passed on the candidate and reproduced the missing row with the original planner: checks/1796039934108922731-3.json, checks/1796039963293920985-3.json, and the corresponding ivf-sql-collision logs.

  • Indexed TIMESTAMP and DECIMAL SQL probes failed on the candidate and passed with the original planner overlaid on the same checkout: checks/1796039379626380184-3.json, checks/1796039531411409844-3.json, and the corresponding ivf-sql logs.

  • The 45,000-key SQL probe failed on the candidate and passed with the original planner: checks/1796039664634820636-3.json, checks/1796039696282510798-3.json, and the corresponding ivf-sql-large logs.

  • Receipt, log, source-fingerprint, baseline-file, and discussion-key checks are recorded in review-evidence-audit.json.

Limitations:

  • The SQL probes used an embedded single-CN cluster with one IVF list; this review did not run a multi-CN test.

  • The full changed BVT suite and the PR-reported full package suites were not independently rerun; their raw local-validation logs were not supplied.

  • The first focused test attempt failed during offline dependency setup. It passed after the assigned module cache was populated.

@XuPeng-SH

XuPeng-SH commented Nov 30, 2026 •

Copy link
Copy Markdown
Contributor

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

Commit: cfacc1a37a3b14a75376823c295c73398b9219ef

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

Assessment: approve

The fix uses the existing PRE membership and join path, with bounded exact-key batches and global ranking across batches. The earlier timestamp, Decimal256 and oversized-predicate findings are resolved. Broad string-key PRE queries have a substantial measured latency cost; the author disclosed that trade-off and the available mode=force alternative. POST remains the default unless PRE is selected or enabled for the session.

Model: gpt-6.1-terra / max

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

Validation:

  • Isolation preflight and native-input provenance checks passed: checks/1796056276209520461-3.json and checks/1796056355253226794-3.json.

  • Focused planner tests and the full ivfflat and sqlexec package tests passed: checks/1796057500675596033-3.json and checks/1796057437146452041-3.json.

  • Public SQL probes passed for the original Bloom collision, timestamp and decimal keys, a 45,000-key domain, BIT, binary, escaped string, UUID, composite and subnormal floating-point keys: checks/1796056838736568501-3.json, checks/1796057405570237404-3.json and checks/1796057586011458475-3.json.

  • An 8,200-key query with OFFSET returned the expected page through both CN entry points: checks/1796057227678003734-3.json.

  • git diff --check passed: checks/1796057449950484401-3.json.

Limitations:

  • In a single-CN, 45,000-row all-qualifying string-key fixture, median PRE latency was 32 ms with merge-base production-file overlays and 588 ms on the candidate; each median used five timed runs after warm-up. This is a workload-scoped regression, not a production latency estimate.

  • The two-CN probe did not establish that the internal entries scan used a remote route.

  • The author-reported mo-tester logs were not supplied, and the exact mo-tester fixtures were not independently rerun. The separate volatile-predicate short-page issue is pre-existing and tracked in #33531.

@mergify mergify Bot added the queued label Nov 30, 2026
@mergify

mergify Bot commented Nov 30, 2026 •

Copy link
Copy Markdown
Contributor

🚫 Left the queue · pull request dequeued

17 min in the queue, with no time running CI.

So far

  • ✅ Entered the queue Mon 30 Nov, 16:55 · rule release-4.2 · triggered by rule Automatic queue on approval for release-4.2
  • ⏹️ Testing stopped · in place
  • 🚫 Left the queue 17:12 · 71b209f

Reason

Pull request #33514 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.

To get back in the queue

  • Push a change if one is needed: the pull request is queued again once its queue conditions match.
  • If no change is needed, tick the box below to queue it again as it is.

Merge conditions not met when it left the queue

  • any of · required by GitHub branch protection:
    • check-neutral = CI Required
    • check-skipped = CI Required
    • check-success = CI Required

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

  • Requeue this pull request
2 merge conditions met
  • #review-threads-unresolved = 0 · required by GitHub branch protection
  • github-review-approved · required by GitHub branch protection

Times in UTC · dashboard · how the merge queue works

@XuPeng-SH
XuPeng-SH merged commit cc55300 into matrixorigin:4.2-dev Nov 30, 2026
24 of 30 checks passed
@mergify mergify Bot added dequeued and removed queued labels Nov 30, 2026
XuPeng-SH added a commit that referenced this pull request Dec 1, 2026
## What type of PR is this?

- [x] BUG
- [x] 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.

This branch was successfully deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

dequeued kind/bug Something isn't working size/L Denotes a PR that changes [500,999] lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants