Skip to content

fix(plan): guard IVFFLAT residual distance predicates - #29792

Merged
XuPeng-SH merged 4 commits into
matrixorigin:mainfrom
iamlinjunhong:fix/29077-ivfflat-distance-range
Oct 10, 2026
Merged

XuPeng-SH merged 4 commits into
matrixorigin:mainfrom
iamlinjunhong:fix/29077-ivfflat-distance-range

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:

#29047 was already addressed by merged upstream PR #29282 and is included here only as related context.

What this PR does / why we need it:

IVFFLAT can leave an unrecognized distance predicate, such as BETWEEN, on the base scan while truncating the vector-index candidate stream to Top-K. Qualifying rows outside that prefix are then lost. This change detects residual predicates on the indexed distance expression before building PRE, POST, INCLUDE, or AUTO rewrites and falls back to the exact plan. The check covers exact and lossy entries, preserves SQL three-valued logic, validates the scan relation binding, and keeps canonical range pushdown unchanged.

The regression case covers literal and prepared BETWEEN queries across force, PRE, POST, and AUTO modes. The issue should be verified by the reporter after the PR is merged.

Validation

  • GOWORK=off .agents/skills/mo-dev/scripts/mo-cgo-test -count=1 -timeout=300s ./pkg/sql/plan
  • GOWORK=off go vet -mod=readonly ./pkg/sql/plan
  • Go 1.27.1-built golangci-lint v2.14.0 --new-from-rev origin/main ./pkg/sql/plan (0 issues)
  • Task-owned mo-service with vector_ivf_prepare_dist_range.sql: normal comparison passed 84/84 twice on the same instance after reviewing generated result output.

Performance and compatibility

Canonical recognized distance ranges retain the existing vector-index pushdown. Queries with residual distance predicates now use the exact scan to preserve correctness; this is a deliberate conservative tradeoff for unsupported predicate shapes and lossy scores.

@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 →

@matrix-meow matrix-meow added the size/M Denotes a PR that changes [100,499] lines label Oct 9, 2026
@mergify mergify Bot added the kind/bug Something isn't working label Oct 9, 2026
@iamlinjunhong
iamlinjunhong force-pushed the fix/29077-ivfflat-distance-range branch from 72d62f8 to 58afe5f Compare October 9, 2026 18:37

@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.

Deep review of 58afe5f against merge-base 8f48d6f. REQUEST_CHANGES for one verified P1 incomplete correctness fix. Reviewed directly, without subagents.

[P1] Track indexed-column dependencies inside distance arguments, not only direct column arguments.

The recursive guard descends through wrappers around a distance expression, but indexedDistanceExprMatches accepts only arg.GetCol(). With l2_distance(CAST(v AS vecf32(3)), '[1,1,1]') over indexed vecf64 v, the distance argument is a CAST. The outer walk subsequently reaches a plain column, where it no longer knows it was inside a distance call. The predicate is left residual and the bounded IVFFLAT POST path is still selected.

Verified through real MySQL SQL execution on the exact head, using a fresh database, a one-list IVFFLAT index and 20 rows id=i, v=[i,i,i], i=1..20:

SET experimental_ivf_index=1;
-- t(id INT PRIMARY KEY, v VECF64(3)); index: lists=1, vector_l2_ops
SELECT id FROM t
WHERE l2_distance(CAST(v AS vecf32(3)), '[1,1,1]') BETWEEN 32 AND 34
ORDER BY l2_distance(v,'[1,1,1]')
LIMIT 1 BY RANK WITH OPTION 'mode=post';

Expected [20], actual empty. Changing only mode to FORCE returns [20]; changing only the WHERE vector argument back to v also returns [20] in POST. PRE, INCLUDE and AUTO happen to return [20] for this small fixture, so I am not claiming that all modes return the wrong result. Literal POST fails on two runs, and binary prepared POST with BETWEEN ? AND ? bound to 32/34 fails identically. A separate public BuildPlan probe confirms CAST and normalize_l2 vector arguments bypass the guard; direct-column controls preserve the exact plan. The runtime loss is verified for CAST, not merely inferred from the planner shape.

The only qualifying distance is sqrt(3*19^2), about 32.909. The candidate budget for LIMIT 1 with a residual filter is 11, so the qualifying row is outside the prefix. One centroid excludes approximate list recall as the explanation. Extend the distance-dependency predicate through bound argument expressions while retaining relation/column binding and the canonical range control. Keep dependency detection distinct from direct-column score substitution: the existing isVectorDistanceExpr owner also intentionally tests direct arguments, and indiscriminately broadening score substitution would be unsafe.

Design/closure review: read every hunk in all six files and traced issue #29077's public contract, the range extractor and its in-place compaction, IVFFLAT admission, PRE/POST/INCLUDE membership/coverage splitting, adaptive FORCE fallback, lossy-entry handling, candidate-budget ownership and prepared binding. The intended fail-closed decision belongs before adaptive branch construction; preserving the original predicate tree and SQL three-valued semantics is appropriate. Recognized exact ranges retain their existing pushdown; lossy distance predicates intentionally fall back to exact evaluation. No new storage/wire/plugin registration, executor state machine or asynchronous resource owner is introduced. The new work is bounded planner expression traversal/copying; unsupported distance shapes can become substantially slower exact scans, which is an explicit correctness tradeoff rather than a TP throughput claim.

Test quality: the focused author tests for residual shapes, scan-binding mismatch, mode fallback and exact/lossy ownership all PASS locally (package 1.850s). They construct distance calls with direct column arguments and therefore miss the actual dependency boundary. The public SQL regression has only four rows; that is below the existing k+10 overfetch floor for LIMIT 1, so it cannot establish that a qualifying row outside the real candidate budget survives. A reviewer-only negative-control overlay that disables the new guard still passes the equivalent four-row literal SQL matrix (10/10, package 9.630s), confirming that this fixture can hide the missing protection. Add a discriminating public literal/prepared counterexample beyond the budget and retain direct-column/canonical-range controls. Reusing the existing SQL case and planner fixtures is preferable to another broad test framework.

Validation: native macOS arm64/Apple M4, Go1.27.1, matching freshly built native prerequisites and mo-cgo-test. Reviewer-only overlays run the actual public planner and MySQL/binary-prepared execution; no tracked source was edited. Current Required CI run 37974608832 succeeds and the author's existing 84/84 same-instance BVT evidence remains valid for its selected cases; neither includes the failing wrapped-argument boundary. There were no substantive prior review comments on this PR to close.

Increment assessed separately: implementation 2 files +106/-3; tests/fixtures 4 files +153/-28; docs 0. The removed lossy-index expectations are legitimately superseded by exact fallback checks. Two unused matcher parameters and optional scanTags retained mainly for old test call sites are small cleanup opportunities, not additional blockers. The key remaining issue is the concrete incomplete dependency analysis above, not code size.

Comment thread pkg/sql/plan/apply_indices_vector.go Resolved

@aunjgr aunjgr 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.

APPROVE at 58afe5f against declared base/merge-base 8f48d6f. No blocking finding confirmed in the residual indexed-distance guard.

Reviewed the complete six-file change and surrounding rewrite flow. The guard runs before AUTO/adaptive or PRE/POST/INCLUDE branches are built, probes range extraction on a private expression copy, and declines candidate truncation if an unsupported distance predicate remains. Exact entries retain canonical range extraction; lossy entries cannot use encoded scores to prove exact SQL distance predicates safe. Scan relation tags prevent same-position columns from another binding from being consumed as this scan's range. AUTO fallback clears its adaptive advertisement; original residual filters remain intact.

The recursive function/list walk covers BETWEEN, reversed comparisons, NOT/OR wrappers and direct indexed-column distances using another metric/query vector, with different-column and extracted-canonical-range controls. Tests additionally verify unchanged filter ownership, exact fallback plan shape across modes, lossy-entry rejection and the qualifying-row-outside-nearest-prefix public regression in literal and prepared forms. Changes to prior lossy rewrite assertions follow the newly enforced exact-fallback contract rather than suppressing an error. No new per-algorithm dispatch, storage/wire format, resource owner or runtime state machine is added.

Evidence reused: exact-head required CI, UT/SCA/coverage and proxy/pessimistic BVT are green. The author reports the full planner suite and two84/84 normal comparisons of vector_ivf_prepare_dist_range.sql. This pass independently inspected implementation and retained/new test oracles and passed git diff --check; those local package/public SQL runs were not rerun. The conservative exact-path cost for unsupported residual shapes is explicit and is appropriate for the stated correctness repair.

@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.

Reviewed head 39594be against base/merge-base e5dd472. APPROVE: the previous P1 is fixed and no remaining blocking finding was found in the complete six-file range.

The residual predicate guard now follows dependencies inside both vector arguments, including CAST/nested functions, and preserves relation/column identity. It remains at the existing IVFFLAT rewrite owner, before AUTO branches are constructed. Canonical safe distance ranges still use the existing extractor; direct-column score substitution is correctly left narrower. This is a focused correctness fix, with no new execution state machine, storage, protocol, resource owner or retry path.

Previous review closure: the CAST(vecf64 -> vecf32) distance predicate no longer escapes the guard. The regression now has 20 rows, beyond LIMIT 1's 11-candidate budget, and its persisted-entry readiness assertion makes the public test discriminating. The original P1 thread is substantively addressed. No other substantive review comments remain.

Validation on this exact head:

  • Focused residual-shape, distance-range, ownership and all-mode fallback planner tests: PASS (pkg/sql/plan, 3.524s).
  • Reviewer external-overlay public MySQL test: PASS (9.751s). Direct-column and CAST controls across FORCE/PRE/POST/INCLUDE/AUTO, binary prepared BETWEEN bounds, and a neighboring second-vector-argument CAST case all return id=20. Two rounds on the same embedded instance with database teardown/recreation passed. The old head failed the original CAST POST/binary-prepared witness.
  • Exact-head CI run 38033595927: SUCCESS. Inspected compose execution artifact 11663452102: vector_ivf_prepare_dist_range.sql selected and completed 101/101, failed/ignored/abnormal all zero (1.628s). This includes retained prepared NULL/rebinding and optimized-plan-shape controls.

Performance: the extra filter copy and dependency walk are confined to IVFFLAT planning. Unsafe residual-distance queries intentionally fall back to exact scanning and can cost materially more on large tables; bounded candidates cannot preserve their SQL result contract. Ordinary non-vector TP execution does not enter this branch. No throughput benchmark claim is made.

Increment assessed separately: implementation +132/-3 in 2 files; tests/SQL/results +227/-28 in 4 files; docs 0. Tests reuse existing fixtures and add data needed to exceed the actual truncation budget. No production edits were made during review.

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

mergify Bot commented Oct 10, 2026 •

Copy link
Copy Markdown
Contributor

Merge Queue Status

  • ✅ Entered queue — 2026-10-10 09:17 UTC · Rule: main · triggered by rule Automatic queue on approval for main
  • 🟠 Checks running · in-place
  • 🚫 Left the queue — 2026-10-10 09:22 UTC · at 9a1a68d01db20b58f4b87bf4c67c5ad2ab0ee958

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

Reason

The pull request can't be updated

This pull request seems to come 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, or update the branch manually.

Hint

You should update or rebase your pull request manually. If you do, this pull request will automatically be requeued once the queue conditions match again.
If you think this was a flaky issue, you can requeue the pull request, without updating it, by posting a @mergifyio queue comment.

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

  • Requeue this pull request

This branch was previously deployed

1 inactive deployment
ci — 9a1a68d0 Deployed Oct 10, 2026 by mergify[bot]
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 size/M Denotes a PR that changes [100,499] lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants