Skip to content

fix: strengthen filter pushdown and PK pruning - #25596

Merged
XuPeng-SH merged 8 commits into
matrixorigin:mainfrom
XuPeng-SH:optimize_filter_0711
Jul 12, 2026
Merged

XuPeng-SH merged 8 commits into
matrixorigin:mainfrom
XuPeng-SH:optimize_filter_0711

Conversation

@XuPeng-SH

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:

Fixes #25592
Fixes #25593
Fixes #25594
Fixes #25595

Related to #25588

What this PR does / why we need it:

Makes filter pushdown both safer and more effective across planner, block-filter, primary-key read-filter, partition-state, and iterator paths.

  • Retains compound and constituent block filters through query-statistics recalculation, so composite-key predicates can prune using both the compound zonemap and individual column zonemaps.
  • Preserves non-pushable predicates above function scans instead of dropping them.
  • Uses typed, overflow-safe primary-key comparisons; validates and normalizes IN vectors on owned memory; supports additional primitive PK types; and fails open for malformed/unsupported filter data.
  • Adds partition-state and iterator support for composite-key prefix open ranges, including early upper-bound termination.
  • Reduces hot-path allocation and repeated work by reusing retained block-filter expressions, removing map-based OR union construction, and avoiding unnecessary deep copies.

Validation

  • go test ./pkg/container/types ./pkg/container/vector ./pkg/vm/engine/readutil ./pkg/vm/engine/disttae/logtailreplay ./pkg/sql/plan
  • go test -race ./pkg/container/types ./pkg/container/vector ./pkg/vm/engine/readutil ./pkg/vm/engine/disttae/logtailreplay
  • go vet ./pkg/container/types ./pkg/container/vector ./pkg/vm/engine/readutil ./pkg/vm/engine/disttae/logtailreplay ./pkg/sql/plan
  • make build
  • Distributed BVT: test/distributed/cases/optimizer/blockfilter.test (55/55 passed)

Performance notes

Selective composite-key and prefix-range queries can now prune more blocks and partition-state rows, while iterator upper bounds stop scans early. The implementation avoids per-row maps and unnecessary expression/vector copies in hot paths. Unresolved optimizer limitations that can still cause conservative fallback are tracked in #25588.

@XuPeng-SH
XuPeng-SH requested a review from a user July 11, 2026 02:39
@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 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.

Blocking findings:

  1. High - NaN breaks the new typed range merge and can prune valid rows.

compareBasePKValues now obtains a total order for floats through types.CompareValue/cmp.Compare, but SQL predicates and the block-search functions use IEEE comparisons, where every ordered comparison with NaN is false. For a FLOAT64 PK containing 1 and 2, pk >= CAST('NaN' AS DOUBLE) OR pk >= 1 is semantically pk >= 1; the OR merge treats NaN as the minimum bound and produces pk >= NaN, whose sorted search returns no offsets. I reproduced the exact [0,1] -> nil false-negative locally.

Please reject NaN bounds/IN members from PK pruning and fail open (infinity remains ordered), or introduce comparison/search semantics that preserve SQL's unordered behavior end to end. Add scalar AND/OR and IN regressions for float32/float64, covering sorted block, unsorted block, and workspace/memory paths.

  1. High - malformed IN type mismatch fails open on persisted blocks but filters out workspace rows.

validBlockPKSearchFilter accepts any non-null IN vector without checking filter.Oid == filter.Vec.GetType().Oid. buildBlockPKSearchFuncs later guards the block path by input type, but NewMemPKFilter uses the same weak validation and immediately encodes the mismatched vector. With an INT64 PK and a VARCHAR IN vector containing "1", the block path keeps all rows while MemPKFilter.FilterVector marks the matching INT64 workspace row as skipped. I reproduced skipMask.Count() == 1; malformed/unsupported data therefore still causes false-negative pruning.

Use one shared validation contract before either filter is constructed: IN must match the PK OID; PREFIX_IN must match the explicitly supported compound/varlen domain. A mismatch must make both block and memory filters invalid. Add a regression that executes both paths from the same malformed BasePKFilter.

  1. Blocking CI - static analysis rejects the four new fmt.Errorf calls.

pkg/vm/engine/readutil/pk_filter_base.go:401,428,432,441 violates MatrixOne's moerr rule. The arm64 SCA job already fails with Use moerr instead. Replace all four errors with appropriate moerr constructors and remove the fmt import.

Verified locally on head 09aa3b78f17ce32d3870a7cb6490a23105ffc25c:

  • existing unit tests for vector, readutil, logtailreplay, and sql/plan pass (the standalone types test binary is blocked locally by the external libusearch_c.dylib runtime path);
  • go test -race passes for readutil, logtailreplay, and sql/plan;
  • the two focused negative regressions above both fail exactly as described;
  • no additional leak, hang, or unbounded-growth issue was confirmed in the changed paths.

@XuPeng-SH

Copy link
Copy Markdown
Contributor Author

Addressed all blocking findings in b185f2b7ca:

  1. Float32/Float64 NaN bounds and IN members now disable PK pruning before filter merge or search-function construction. Both operand orders and AND/OR merges are covered; infinities remain ordered and optimizable.
  2. Persisted-block and workspace filters now share one validation contract. Exact IN requires the vector OID to match the PK OID; PREFIX_IN requires a matching explicitly supported prefix domain. Malformed layouts fail open consistently on both paths.
  3. Replaced the four fmt.Errorf calls with moerr constructors. No recover whitelist is needed: serialized-vector headers, field lengths, null bitmaps, physical data, and varlena area bounds are validated before zero-copy unmarshal.

Additional unhappy-path closure:

  • malformed/version-skewed serialized IN filters stay on the residual-expression path instead of failing the query;
  • huge constant IN vectors collapse to one set element, and huge const-NULL vectors collapse to an empty set, preventing logical-length CPU/allocation amplification;
  • common scalar, float-IN, and PREFIX_IN validation paths are covered by a zero-allocation regression.

Validation completed locally:

  • make err-check
  • go vet -vettool=$(which molint) ./pkg/vm/engine/readutil
  • golangci-lint run -c .golangci.yml ./pkg/vm/engine/readutil (0 issues)
  • full readutil tests and affected package tests
  • go test -race ./pkg/vm/engine/readutil
  • go vet for all affected packages
  • make build

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

Blocking findings on 6260242:

  1. High — block-filter dedup can panic on a valid constant LiteralVec. blockFilterConstantSet accepts a vector whenever its logical Length matches LiteralVec.Len, then calls GetConstantValue once per logical row (expr_opt.go:420-428). A CONSTANT vector with logical length > 1 has exactly one physical value: MustFixedColNoTypeCheck intentionally returns a one-element slice for it (vector/tools.go:27-33). Therefore a list-vs-constant-Vec IN comparison indexes row 1 and panics during planning. Do not index a constant vector by its logical row: reduce it to its single value (or simply decline semantic dedup for constants), and add a regression using NewConstFixed(..., length=2) as LiteralVec.

  2. High — the new global dedup pass regresses planner complexity from bounded linear passes to O(B^2 * K) for B block filters containing K-element IN predicates. Every pair first performs structural comparison; Expr_Vec takes the proto-marshalling fallback, then the semantic path unmarshals both vectors and rebuilds value maps (expr_opt.go:377-434, 510-520). This runs after index application for every scan. exprStructuralHash already exists specifically to bucket dedup without this repeated work (expr_hash.go:24-32), but is not used here. Precompute a canonical key once per filter and use hash buckets plus exact collision checking; add a large-IN / many-block-filter regression or benchmark.

  3. P2 — sameGeneratedCompoundFilter treats two compound predicates as equal solely by operation and target column, without comparing RHS (expr_opt.go:475-492). It is used both while rebuilding stats block filters and in final dedup. The stated single-generated-predicate invariant is neither encoded nor checked, so two distinct compound IN/range predicates can silently lose one pruning constraint. Dedup must retain structural/semantic equality, or carry an explicit generation identity; please add a negative test with different compound RHS.

The PK-filter cleanup handoff in the latest commit was checked through reader reset/Close and looks sound. I am requesting changes for the planner panic and the avoidable planner-scale regression.

@XuPeng-SH

Copy link
Copy Markdown
Contributor Author

Addressed in 3a8fc3c.

  • Fixed constant LiteralVec handling: semantic set extraction now reads the single physical value of a constant vector (and handles zero-length vectors), so a logical length greater than one cannot index past physical storage. Added regression coverage with NewConstFixed(..., length=2).
  • Replaced pairwise global dedup with a precomputed semantic hash and hash buckets. Hash collisions still use exact semantic comparison; the same helper is used while rebuilding stats block filters. Added a large-IN (128 x 512) vector benchmark.
  • Removed the operation+compound-column shortcut. Compound predicates are removed only when structurally/semantically equal; added coverage proving distinct RHS values are retained.

Validation: go test ./pkg/sql/plan, targeted tests with -race -count=5, go build ./pkg/sql/plan, go vet ./pkg/sql/plan, and dependent pkg/sql/compile tests all pass.

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 kind/test-ci size/XXL Denotes a PR that changes 2000+ lines

Projects

None yet

4 participants