Skip to content

fix(plan): fold contradictory same-column predicates to near-zero estimates - #32502

Merged
mergify[bot] merged 4 commits into
matrixorigin:mainfrom
gouhongshen:agent/issue-32068-main-beb9d906
Nov 10, 2026
Merged

mergify[bot] merged 4 commits into
matrixorigin:mainfrom
gouhongshen:agent/issue-32068-main-beb9d906

Conversation

@gouhongshen

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:

Related to #32068.

What this PR does / why we need it:

Root cause

A same-column contradictory pair (k2 = 5 AND k2 = 6, zero matching rows by definition) was estimated as the full table - selectivity 1.0, outcnt 1,000,000 on a 1M-row table - so the planner chose full scans and sized every operator above the filter for 1M rows while the true result was empty (#32068). Two defects stacked:

  1. In normalizeColumnDomain (pkg/sql/plan/expr_opt.go) both point-domain falsification verdicts sat behind the hasRange bypass: a surviving same-column range (BETWEEN) kept contradictory equalities unfolded and left them to the selectivity arithmetic.
  2. When a filter list does fold to a constant-false boolean, estimateExprSelectivity's literal case (pkg/sql/plan/stats.go) returned selectivity 1.0, estimating an always-empty filter as a full scan.

Review traced ten further identity defects at the two value-key seams that decide same-column point identity (constLiteralKey, blockFilterLiteralKey): raw signed-zero float bits, raw text bytes instead of the bound collation domain, temporal Width/Scale, decimal declaration width and normalized-spelling provenance, integral Width/Scale, DOUBLE/FLOAT(M,D) declaration metadata (FLOAT32 additionally needs payload normalization by its own declared scale, mirroring runtime comparison), and the retained bind-time fold source (Literal.Src) marshaled into the keys. Each could prove a false contradiction and fold a genuinely satisfiable filter to constant false.

Exact change

  • pkg/sql/plan/expr_opt.go: the point-domain satisfiability verdict now resolves before the hasRange bypass - an empty intersection of same-column point sets (distinct equality literals, disjoint IN lists) or an intersection fully excluded by the column's NOT-IN points folds the filter list to constant false; the range bypass now only skips duplicate-point merging, and satisfiable duplicates still merge into one predicate. Both value-key seams key by runtime SQL value: floating signed zero, text in the bound collation domain (binary payloads keep exact bytes), family-specific declaration-metadata stripping (literalSemanticKeyType), FLOAT32 self-scale normalization (sqlEqualFloat32ScaledLiteral), and fold-source classification (literalDomainValueIdentity: statically evaluable Literal.Src keys by payload; execution-dependent sources decline the domain decision). Low-precision float casts stay declined (unwrapConstLiteral) because the cast rounds the value; the intentional partial float-family coverage in literalSemanticKeyType carries the required // typeswitch:partial annotation.
  • pkg/sql/plan/stats.go: a folded constant FALSE or NULL literal filter takes the near-zero floor (matching the impossible-interval convention) instead of selectivity 1.0.
  • pkg/sql/plan/mock.go: fpts fixture (INT32 primary key, DOUBLE, FLOAT) for cast-shape planner tests.
  • pkg/sql/plan/stats_test.go: eleven focused planner tests including full parse/bind/build companions.
  • test/distributed/cases/optimizer/contradictory_selectivity.sql (+ regenerated .result): public regression over integer, temporal, decimal, string, folded-DIV and double/float fixture blocks.

Issue-to-test proof

  • Contradictory equalities: o_orderkey = 19 AND o_orderkey = 81 (with and without a covering BETWEEN) folds to a constant-false filter with selectivity 0.0000 and returns 0 rows, while the duplicate o_orderkey = 19 AND o_orderkey = 19 keeps one real predicate with a positive point estimate and returns exactly its rows (TestContradictoryPredicateScanEstimate through real parse/bind/build; BVT pins both with EXPLAIN selectivity regexes and COUNT companions; measured live on an isolated single-instance MatrixOne).
  • Folded-boolean bounds and OR/IN lower-bound controls: TestFoldedBooleanLiteralSelectivityBounds, TestConsolidatedOrAndInListSelectivityControls.
  • Every satisfiable spelling class that the falsification could wrongly fold is pinned unfolded with its rows kept in both predicate orders: signed zero, Unicode-collation text, temporal precision, decimal width/provenance, integral and double/float cast metadata, and the same value spelled as a bind-time folded DIV (CAST('19.00' AS DECIMAL(8,2)) DIV 1); genuinely distinct values still fold. Each defect was first reproduced by a focused failing test on the pre-fix tree, then green after the fix.
  • The repository's TestTypeSwitchFamilies gate (./pkg/container/types) passes with the annotated partial switch.

Test commands

# full owning package
.agents/skills/mo-dev/scripts/mo-cgo-test -count=1 -timeout=1500s ./pkg/sql/plan
# -> ok 160.557s, exit=0

# focused proof batch (all ten defect classes)
.agents/skills/mo-dev/scripts/mo-cgo-test -count=1 -timeout=900s \
  -run '^(TestContradictoryPredicateScanEstimate|TestFoldedBooleanLiteralSelectivityBounds|TestConsolidatedOrAndInListSelectivityControls|TestSignedZeroPointDomainSQLValueEquality|TestUnicodeCollationPointDomainSQLValueEquality|TestTemporalPrecisionPointDomainSQLValueEquality|TestDecimalWidthPointDomainSQLValueEquality|TestDecimalProvenancePointDomainSQLValueEquality|TestIntegerCastPointDomainSQLValueEquality|TestDoubleCastPointDomainSQLValueEquality|TestFoldedSourcePointDomainSQLValueEquality)$' \
  ./pkg/sql/plan
# -> 11/11 PASS, exit=0

# typeswitch governance gate
.agents/skills/mo-dev/scripts/mo-cgo-test -count=1 -v -timeout=900s \
  -run '^TestTypeSwitchFamilies$' ./pkg/container/types
# -> PASS, exit=0

# static closure (documented CGo environment)
GOWORK=off go vet -mod=readonly ./pkg/sql/plan            # exit=0
golangci-lint run -c .golangci.yml --new-from-rev "$base" ./pkg/sql/plan  # 0 issues

# BVT (isolated mo-tester runtime; two comparison runs, identical totals)
# test/distributed/cases/optimizer/contradictory_selectivity.sql -> TOTAL :199, SUCCESS RATE :100%
# test/distributed/cases/optimizer/between_selectivity.sql      -> TOTAL :22,  SUCCESS RATE :100%

Residual risk

  • Estimate accuracy only: query results are unchanged - a falsified filter returns the same zero rows it always did, now without planning for a full scan.
  • The near-zero floor reuses the existing impossible-interval convention (1e-8) rather than an exact zero.
  • The separately filed IN-list estimate defect ([Performance]: same-column OR estimates below a single term, 200x off #32059) is out of scope here.
  • Low-precision float columns (bf16/float16/float8/float4) intentionally remain outside point-domain classification; their filters keep the existing evaluation path.
  • The regenerated golden absorbs four per-creation secondary-index UUID rows through the case's existing regex precedent.

…imates

A contradictory same-column predicate pair (k2 = 5 AND k2 = 6), which
matches zero rows by definition, was estimated as the full table
(selectivity 1.0 on a 1M-row table): the falsification verdict sat
behind the same-column-range bypass, so a surviving BETWEEN kept the
contradictory equalities unfolded, and a folded constant-false filter
was itself estimated at full-table rows by estimateExprSelectivity's
literal case. The planner then picked full scans and sized every
operator above the filter for 1M rows while the true result was empty.

- pkg/sql/plan/expr_opt.go: normalizeColumnDomain decides the
  point-domain satisfiability verdict before the hasRange bypass - an
  empty intersection of same-column point sets (distinct equality
  literals, disjoint IN lists) or one fully excluded by the column's
  NOT-IN points folds the filter list to constant false; only the
  duplicate-point merging stays behind the range bypass. The value keys
  that decide point identity now follow runtime SQL equality at both
  constLiteralKey and blockFilterLiteralKey: floating signed zero, text
  keys in the bound collation domain, family-specific declaration
  metadata stripping (string width, temporal Width/Scale, decimal
  width, integral and FLOAT/DOUBLE Width/Scale), FLOAT32 normalization
  by its own scale mirroring runtime comparison, and the retained
  bind-time fold source (Literal.Src) classified by static evaluability
  - statically evaluable sources key by payload while
  execution-dependent sources decline the domain decision instead of
  proving a false contradiction. Low-precision float casts stay
  declined: the cast rounds, so the source literal is not their value.
- pkg/sql/plan/stats.go: a folded constant FALSE or NULL literal filter
  is estimated at the near-zero floor (matching the impossible-interval
  convention) instead of selectivity 1.0, so a falsified filter no
  longer sizes scans and operators for the full table.
- Tests: pkg/sql/plan/stats_test.go adds the focused planner tests for
  the estimate defect and every identity seam (contradictory-equality
  scan estimate through real parse/bind/build, folded-boolean bounds,
  OR/IN consolidated controls, signed zero, Unicode collation,
  temporal precision, decimal widths and provenance, integral cast
  metadata, double/float cast spellings, folded-source point domains);
  pkg/sql/plan/mock.go adds the fpts fixture for float cast-shape
  filters; test/distributed/cases/optimizer/contradictory_selectivity.sql
  and .result add the public regression pinning zero results with
  near-zero estimates for contradictory predicates and kept predicates
  with positive estimates and matching rows for satisfiable duplicates.

Related to matrixorigin#32068
@gouhongshen

gouhongshen commented Nov 10, 2026 •

Copy link
Copy Markdown
Contributor Author

Unrelated CI blockers tracked for this PR:

A single failed-jobs rerun of run 42893155021 (attempt 1) was requested under this loop's CI handling rules; its result has now been inspected:

Rerun outcome (inspected 2026-11-11): run 42893155021 attempt 2 completed success on unchanged head 98ebb0ea — the #31145 recurrence is resolved for this PR. The three previously-failed lanes each passed on attempt 2: UT Coverage on Ubuntu/x86 (success, 22:06:18Z — the recurrence surface itself), the downstream Coverage merge gate (success, 22:07:16Z — the producer published a complete coverage profile this time), and the CI Required aggregate gate (success, 22:07:24Z). No unrelated CI blocker remains tracked for this PR; upstream issue #31145 stays open for the optools watchdog_pids flake itself.

@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 commented Nov 10, 2026 •

Copy link
Copy Markdown
Contributor

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

@XuPeng-SH

XuPeng-SH commented Nov 10, 2026 •

Copy link
Copy Markdown
Contributor

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

Commit: 98ebb0eaaf97959deac1028f2228497b989b77ab

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: 98ebb0eaaf97959deac1028f2228497b989b77ab

Assessment: approve

No actionable correctness or design defects remain. The fix reuses existing domain normalization and runtime comparison helpers, with appropriate safeguards for SQL-equal literal representations.

Model: gpt-6.1-sol / max

Session: 01a1a004-90c3-73b1-acc9-3d4636452003 · slot 0 · generation 0

Validation:

  • Full planner and types suites passed with Go 1.27.1 and the supplied isolated executor, including all 11 added test families. Evidence: owning-suites.log and checks/1794349924116206068-4.json.

  • All 11 additional parser/BuildPlan boundary probes passed, covering decimal scales, FLOAT signed-zero rounding and distinct-value controls. Evidence: value-boundary.log and checks/1794349974888229460-3.json.

  • Isolation preflight, native provenance, source cleanliness and discussion coverage verified. Receipts and retained logs reconciled in review-validation.json; final audit receipt checks/1794350173701637824-3.json.

Limitations:

  • Two preexisting unrelated planner subcases skipped. Distributed BVT was not rerun locally; completed frozen same-head CI evidence was reviewed.

  • Later CI lanes still running in the frozen snapshot were not counted as passes.

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

mergify Bot commented Nov 10, 2026 •

Copy link
Copy Markdown
Contributor

✅ Merged into main as 45917e8 at 23:50 UTC

1 h 13 min in the queue, 1 h 12 min of it CI.

So far

  • ✅ Entered the queue Tue 10 Nov, 22:37 · rule main · triggered by rule Automatic queue on approval for main
  • ✅ Passed · in place
  • ✅ Merged 23:50 · 45917e8 · squash
3 merge conditions met
  • #review-threads-unresolved = 0 · required by GitHub branch protection
  • github-review-approved · required by GitHub branch protection
  • any of · required by GitHub branch protection:
    • check-success = CI Required
    • check-neutral = CI Required
    • check-skipped = CI Required

Times in UTC · dashboard · how the merge queue works

This branch was previously deployed

1 inactive deployment
ci — 483f82ae Deployed Nov 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/XXL Denotes a PR that changes 2000+ lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants