Skip to content

fix(sql): preserve DECIMAL pruning for prepared integer comparisons - #29667

Merged
XuPeng-SH merged 4 commits into
matrixorigin:mainfrom
LeftHandCold:fix/prepared-decimal-pruning-20261007
Oct 8, 2026
Merged

XuPeng-SH merged 4 commits into
matrixorigin:mainfrom
LeftHandCold:fix/prepared-decimal-pruning-20261007

Conversation

@LeftHandCold

@LeftHandCold LeftHandCold commented Oct 7, 2026 •

Copy link
Copy Markdown
Collaborator

What type of PR is this?

  • API-change
  • BUG
  • Improvement
  • Documentation
  • Feature
  • Test and CI
  • Code Refactoring

Which issue(s) this PR fixes:

Part of issue #29661: direct integer bindings compared with a native DECIMAL column. This PR does not close the direct TEXT or explicit DOUBLE/INT64 pruning gaps recorded there.

What this PR does / why we need it:

A prepared INT64 comparison against DECIMAL(18,2) widens the stored column to DECIMAL(21,2), losing native ZoneMap pruning even when the actual binding fits exactly. Clean current Main reads four blocks for the existing 32,768-row probe where the equivalent literal reads one block; results are correct.

Before generic comparison binding, admit only direct SELECT integer-parameter/native-DECIMAL-column comparisons whose current value fits the unchanged column domain. Reuse the existing exact-domain algorithm and existing per-EXECUTE diagnostic/cache guards. Keep executable parameter references and wider-domain fallback; no new cache, worker, state owner, storage or protocol change.

Guard the exact transport spelling before cached reuse: integer-to-DECIMAL conversion alone does not enforce declared precision. This prevents a later out-of-range value from reusing the narrowed plan. Safe plans remain cacheable; wide fallbacks cannot replace them. Literal, TEXT, explicit DOUBLE, DML and column-to-column paths are unchanged.

Reuse the existing DECIMAL BVT fixture rather than adding a new fixture, load, sleep or retry. Add typed admission/guard checks for DECIMAL64/128/256 and public execution checks for changed values, out-of-range bindings, NULL and recovery. Retain a DOUBLE collision control above 2^53.

Tested with:

  • Fresh native build, Go 1.27.0, Shanghai50 isolated containers with verified clean/patched binary entrypoints, base 281ca809d688f7ff727e813a48436aff1cfbea36.
  • .agents/skills/mo-dev/scripts/mo-cgo-test -v -count=1 -timeout=120s -run 'TestPreparedDecimalComparison(Pruning|AdmissionOwnership)' ./pkg/sql/plan.
  • .agents/skills/mo-dev/scripts/mo-cgo-test -count=1 -timeout=180s ./pkg/sql/plan.
  • Standard mo-tester on test/distributed/cases/prepare/issue_29514_decimal_expression_filter.sql: clean baseline 238/239 (new pruning assertion fails), patched 239/239 twice, about 2.8 seconds per run.
  • Actual binary-protocol prepared SELECT and EXPLAIN ANALYZE: direct integer 4 blocks before / 1 after; changed values, INT64_MAX, NULL and re-execution return correct rows. TEXT and explicit DOUBLE/INT64 remain unchanged.
  • Scoped latency/cache control: the four-block direct integer query improves from approximately 0.63 ms to 0.30 ms; the submitted guarded plan retains prepared cache reuse. A broader non-cacheable prototype was rejected, not included.
  • Final reversed-order 5,000-query two-row controls measured approximately 0.217 ms before / 0.228 ms after (about 11 microseconds / 5% additional precision-guard cost; an earlier repeat showed about 13 microseconds / 6%). The unchanged explicit-DOUBLE control stayed approximately 0.214-0.220 ms. This patch does not claim zero overhead for tiny queries. A separate transport-shortcut prototype did not remove this cost and was also rejected.

No claim is made that this fixes the full MOTR pruning matrix, the Daily HNSW QPS decline, or any 4.2 incident.

The comparative baseline is 281ca80. Main subsequently advanced to 15cc623 (#29649, Dragonboat constructor cleanup), which Mergify merged into this branch as 46df957. All four patch files match c3cbefb byte-for-byte. The final published head was independently built on Shanghai50 with its updated dependency pin: full pkg/sql/plan PASS (9.683s), actual binary-protocol query controls PASS, and standard BVT 239/239 PASS (2.790s). Executable build metadata records vcs.revision=46df957b58da1922526507e6101f7fe6a89dbf11, vcs.modified=false. The latency A/B above is on the original 281ca80 comparative base; it was not relabelled as a new latency experiment after the unrelated dependency merge. Hosted CI remains separate and is not claimed green.

@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

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Deep review of head bbf096866c2c60cc13c20e2e0f11c06fc1626017 against merge-base ea011906d61dfe2b023993dbbbe2e778459776f8. Independently reviewed without subagents.

Decision: REQUEST_CHANGES for the mandatory validation gate below. I did not find a confirmed new production correctness defect in the reviewed implementation.

Blocking validation finding

[P2] Resolve the incremental Coverage failure before approval. Exact-head Coverage job fails on real measured coverage, not missing BVT artifacts or infrastructure: the downloaded coverage-summary.json reports 8/11 covered modified entries, 72.73%, below the required >75%. CI Required consequently fails. pr_coverage.out identifies the uncovered entries as the three error returns in prepared_binding.go at lines 492, 500 and 508.

This is a gate failure, not evidence that overflow/NULL/precision behavior is untested: those behavioral paths do have coverage and passed the additional challenges below. Please close the gate with meaningful reachable coverage or an appropriate simplification using the existing domain owner; do not add production fault-injection machinery, delete error handling, or exempt the file merely to manufacture a green percentage. If these are defensively unreachable failures, any coverage-policy exception needs an explicit decision by the policy owner, not an implicit waiver by this review.

One non-blocking simplification opportunity is that the new admission only consumes witness.Typ from makePlan2ExactDecimalStringExprWithType; the existing decimal-domain helper already owns that analysis. Reusing the domain result directly could avoid constructing a throwaway literal/cast expression. This is not a separate correctness finding or a requirement to introduce another validator.

Design / correctness conclusions

  • The responsibility remains in the existing prepared-consumer binder, exact DECIMAL domain merger, and per-execution diagnostic/cache owner. No second cache, state machine, precision algorithm or execution path is introduced. The +36 production lines are proportionate to restoring native-column pruning.
  • Admission is restricted to direct integer markers versus a native DECIMAL column in SELECT. Wide values retain the wider comparison and their value dependency; explicit DOUBLE/text semantics are not silently generalized. This is a bounded contribution to #29661, not proof that all of that issue's performance cases are fixed.
  • The TEXT-to-DECIMAL diagnostic candidate is necessary: the integer-to-DECIMAL executable cast does not itself enforce declared precision. The guard runs on each cache reuse; the binary integer fast-proof does not bypass this DECIMAL guard.
  • The original executable parameter is retained. Existing dependencies of other consumers are preserved. The frontend's non-cacheable fallback cannot replace the reusable native plan. Checked NULL, range changes, signed boundaries, mixed consumers, and recovery.
  • No persistent format/schema change or data-compatibility requirement is introduced. No new goroutine/wait/lock/resource lifecycle or unbounded cache is added; a separate blanket race rerun would not target a new concurrency mechanism here.

Validation and test quality

  • Rebuilt native CGo dependencies for the isolated exact-head worktree, then ran TestPreparedDecimalComparisonPruning and TestPreparedDecimalComparisonAdmissionOwnership: PASS, package time 1.788s, Go 1.27.0 darwin/arm64.
  • Added temporary review-only challenges, without changing the PR: real optimized scan expressions evaluated by the expression executor, checked against an independent big.Rat oracle for all eight comparison spellings. Covered neighboring integers around 2^53, fractional neighbors, INT64 min/max, NULL, changed parameters and recovery; also checked AND/OR combinations of safe and wide consumers. PASS, package time 0.889s. These are local white-box/executor checks, not a claim of a fresh binary-protocol end-to-end run.
  • Reused exact-head Ubuntu UT, SCA, and both BVT jobs, all successful. Downloaded the Compose BVT execution log and confirmed the changed issue_29514_decimal_expression_filter.sql actually ran: 239/239, 0 ignored, 2.679s.
  • Implementation/test/documentation deltas were reviewed separately: +36 production, +133 unit-test, +30 BVT SQL and +47 expected-result lines; no documentation delta. The BVT extends the existing persisted-data fixture rather than creating another heavy setup. The type/guard unit tests and persisted-scan assertions exercise different contracts.

Performance / scope

Author measurements document the intended four-block case improving from 4 blocks to 1 and approximately 0.63ms to 0.30ms, with a small two-row case increasing from approximately 0.217ms to 0.228ms due to the guard. This is a disclosed tradeoff, not a universal speedup. I verified the patch files are unchanged from the measured intermediate revision; I did not rerun latency benchmarks on this final head. Current-head BVT independently confirms the selective-scan behavior.

There are no earlier human review comments or inline review threads on this PR to reconcile; the only existing discussion comment is the Qodo-paused notice. Rechecked head and CI immediately before submitting this review.

@XuPeng-SH
XuPeng-SH merged commit 8929ab4 into matrixorigin:main Oct 8, 2026
XuPeng-SH pushed a commit that referenced this pull request Oct 11, 2026
## What type of PR is this?

- [x] BUG
- [x] Test and CI

## Which issue(s) this PR fixes:

Part of #29661; follow-up to #29667. **Does not close #29661.**

## What this PR does / why we need it:

Two independent boundaries prevent meaningful prepared-DECIMAL pruning
coverage:

1. The existing exact integer admission covers a direct binary
comparison, but not integer lists/ranges or a value-preserving explicit
SIGNED peer. Overload resolution can widen the DECIMAL column and lose
block pruning or secondary-index access.
2. `OperatorStats.InputBlocks` has `json:"-"`. Remote terminal analysis
preserves input rows but drops the actual block count, so aggregation
can report `Rows=32768, Blocks=0`. That diagnostic failure blocks the
nightly fixture before its prepared comparisons are exercised; it is not
proof that a storage scan read zero blocks.

This patch shares the existing exact-domain admission across SELECT
comparisons, IN/NOT IN and BETWEEN. It admits only a native DECIMAL
column and integer literals/parameters, including injective integer cast
chains. All peers must fit before any conversion guard is published.
Original executable parameter/cast expressions, wide-value fallback,
earlier value dependencies, and existing cache ownership are retained. A
declared-precision conversion guard protects subsequent EXECUTEs; an
unsafe binding cannot replace the reusable safe plan.

The diagnostic fix is one optional JSON field. Real remote-terminal
producer/consumer tests cover round-trip, idempotent terminal delivery,
mixed local/remote aggregation, and legacy missing-field inputs. Missing
data stays zero; counts are never invented from row counts. No storage
format, RPC protocol version, reader implementation, global
type-coercion policy, or DML behavior changes.

### Validation scope

Base: freshly verified Main `f42af4dfcba210fd91b6f1fc5d7b5a72704502ee`.

Actual SQL is tested on server 50 in task-owned single-CN instances (4
CPU / 8 GiB), using identical persisted data and independent fixed-row
expected results, with both binary Prepared Statements and SQL EXECUTE.
Existing user services and nightly clusters are untouched.

The existing DECIMAL BVT is extended in place, reusing its dataset and
normal result comparison. On the unmodified base the original 239
statements pass; the final extended 274-statement case has exactly four
new scan/index assertion failures and 270 passes. No existing
expectation is weakened.

Local candidate results:

- 312/312 independent SQL result assertions pass on both versions,
including safe → wide → safe → NULL → TEXT/DOUBLE → integer rebinding in
both protocols.
- 40 scoped pruning/index capability failures on the base become zero on
the candidate. Non-index integer IN/BETWEEN read one block / 8,192 rows
instead of four / 32,768. Indexed integer IN/BETWEEN and identity SIGNED
peers retain the native secondary-index path.
- The original untyped DECIMAL18 BETWEEN literal was itself
non-selective. It was replaced **only in the diagnostic harness** with
an explicit same-domain DECIMAL literal, independently verified
selective on both binaries. The original invalid-control logs are
retained; they are not used as regression evidence.
- Extended BVT: **274/274 twice**, normal `run` mode, 2.830s / 2.839s.
Explicit before/after database checks are zero. No generated-result
acceptance.
- Complete `pkg/sql/plan` tests pass; focused frontend real-cache tests
pass, including safe cache identity, wide/NULL fallback and recovery,
plus existing signed-narrowing/assignment/float controls.
- Complete `pkg/vm/process`, `pkg/sql/models`, `pkg/sql/compile` tests
pass. The real remote-terminal regression test fails on the base (rows
preserved, expected four blocks become zero) and passes after the
optional-field change.
- Focused planner race checks pass (1.926s), and frontend
cache/rebinding plus existing narrowing/assignment/float race checks
pass (1.312s).
- Scoped `go vet` passes for the five affected packages; formatting and
whitespace checks pass. Pinned `golangci-lint v2.14.0`, repository
config, all five packages, `--new-from-rev=f42af4df...`: **exit 0, zero
reported issues** (1m 2.787s). The initially selected host Go launcher
could not recognize SIMD inside lint's package loader; fixing only
PATH/GOROOT to the verified Go 1.27.1 toolchain resolved it. SIMD/v3 and
native provenance checks were retained.

Bounded actual-query timing (median of five 200-operation batches per
protocol/scenario; 8,000 correctness-checked operations per binary):
persisted IN takes 43.3% / 45.2% of base time (binary / SQL EXECUTE);
indexed SIGNED takes 53.1% / 55.5%. On two-row tables, the added guarded
paths cost **15–37 microseconds per execution (5.3–14.0%)** in this
shared-host sample. This cost is disclosed, not called zero regression
or a production guarantee. The existing cache is retained, rather than
replacing the access-path issue with repeated planning or a new cache
mechanism.

Both isolated test services have been stopped; test databases were
removed. All evidence is retained under
`/tmp/mo-29661-completion-20261011.O28F1p` on server 50.

### Explicit remaining limits

- Direct TEXT on physical DECIMAL128(18,2), and explicit DOUBLE
comparison with an INT binding, remain outside this patch. A
conversion-only guard does not establish float injectivity; forcing
per-execution replanning is not an acceptable substitute for a sound
cache proof.
- The remote block-count defect is reproduced through the actual
terminal serialization/receiver/aggregation code, not a claim that a
full TKE topology was rerun locally.
- Local timing comparisons are informational measurements on a shared
host, not a production performance guarantee. Full GitHub CI is reported
separately from local evidence.

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>

This branch had an error being deployed

1 failed deployment
ci — 297de445 Deployed Oct 8, 2026 by XuPeng-SH
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/test-ci size/M Denotes a PR that changes [100,499] lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants