Skip to content

fix: preserve DECIMAL comparison domains on 4.2 - #32767

Merged
XuPeng-SH merged 3 commits into
matrixorigin:4.2-devfrom
XuPeng-SH:codex/42-decimal-domain-20261115
Nov 15, 2026
Merged

XuPeng-SH merged 3 commits into
matrixorigin:4.2-devfrom
XuPeng-SH:codex/42-decimal-domain-20261115

Conversation

@XuPeng-SH

@XuPeng-SH XuPeng-SH commented Nov 15, 2026 •

Copy link
Copy Markdown
Contributor

Problem

On 4.2-dev, comparisons between DECIMAL operands with different scales can discard matching rows after flush. Serialized index bounds can also use the wrong comparison domain. The failure exposed by #32675 exists independently on 4.2-dev. The original query works on main, which includes #26815 and #31624.

Changes

  • Compare storage pruning bounds in a compatible decimal domain and fail open when a bound is not proven safe.
  • Admit serialized index predicates only when their bound can preserve the stored comparison domain; keep decoded SQL residuals when a prefix lookup can admit extra candidates.
  • Preserve SQL NULL and outer-join semantics, remove the unsafe early constant fold, and use checked common decimal domains and overflow-aware vector comparisons.
  • Rebuild fixed-type parameter wrappers when a source type changes or requires conversion.
  • Preserve CHAR static index access and same-type CHAR JOIN runtime filters, which use byte comparisons and the same string serialization. Mixed CHAR/VARCHAR JOIN filters remain conservative.

CI follow-up and validation

The first CI run exposed four EXPLAIN changes: a necessary composite VARCHAR prefix residual, an unintended CHAR index fallback, and two common DECIMAL type widths. The CHAR fallback is fixed; the other expectations now reflect the proven plans. On the old baseline, a composite VARCHAR IN query actually returned an extra embedded-NUL peer before and after flush; the residual removes it.

  • Two-CN BVT for the three previously failing files and DECIMAL coverage: 1,027/1,027 passed, with no failures or skips. Added real persisted CHAR index/JOIN, NUL-prefix and signed INT32 boundary cases.
  • Actual SQL on one and two CNs, before and after flush, covered FORCE/AUTO/IGNORE, composite DECIMAL bounds, NULL and outer joins, and overflow. CHAR FORCE/IGNORE comparisons covered trailing spaces, NUL, NULL, IN, ranges, prepared parameters, covering and backfill. The CHAR JOIN probe verified the runtime filter was actually present before and after flush.
  • Full normal and race tests for pkg/sql/plan and pkg/sql/plan/function passed after this follow-up. The earlier six affected package suites also passed normal and race before the latest unrelated 4.2 base updates.
  • Incremental go vet, golangci-lint and molint passed.

Before this CI follow-up, ABBA microbenchmarks on host 57 against 4.2-dev 296402f measured valid DECIMAL64/128 comparisons and INT64 controls; their vector kernels are unchanged by this follow-up. INT64 one-row batches increased by about 3.5 ns, while larger batches were essentially unchanged.

A separate pre-existing 4.2 prepared-statement issue remains: reusing an untyped parameter with different DECIMAL scales can produce an incorrect comparison even without an index. Explicitly casting the parameter to a fixed DECIMAL type avoids it; it is outside this change.

@XuPeng-SH
XuPeng-SH requested a review from aunjgr as a code owner November 15, 2026 12:50
@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 15, 2026 •

Copy link
Copy Markdown
Contributor

This pull request is merged.

@XuPeng-SH

XuPeng-SH commented Nov 15, 2026 •

Copy link
Copy Markdown
Contributor Author

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

Commit: 28543f1fef751de5ef75ed070b66fa11d331568e

Review completed. Read the assessment.

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

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

Commit: 28543f1fef751de5ef75ed070b66fa11d331568e

Assessment: approve

The DECIMAL fix preserves comparison and NULL semantics while centralizing index-domain checks through existing numeric, keycodec and zonemap owners. Conservative fallback and residual paths are justified; no actionable PR regression remains.

Model: gpt-6.1-sol / max

Session: 01a1a004-9884-72c0-ad39-f096c4209c4a · slot 1 · generation 0

Validation:

  • Full normal suites passed for types, vector, function, plan, readutil and colexec; see types-vector-tests.log and owner-tests.log. All test binaries used the assigned test-exec.

  • Independent arithmetic probe passed 63,681 DECIMAL64 comparisons and 10,000 DECIMAL128/256 scale checks against math/big. The identical baseline comparison control failed 1,034 cases; numeric source transformations/provenance are retained.

  • Binder/executor control passed a 1,024-row NULL-to-ordinary decimal transition (bound-comparison.log).

  • Preflight, frozen-input CPU native build, formatting, diff checks, clean-source verification and discussion coverage passed. validation-inventory.json and final-audit.log reconcile retained logs with receipts.

Limitations:

  • Live distributed SQL/BVT, race and performance checks were not rerun; author-reported results lack supplied raw artifacts. Substantive CI jobs were pending in the frozen evidence.

  • A direct converted-wrapper NULL-transition probe also fails with the baseline helper. The bound-expression control passes; this preexisting internal edge is not reported as a PR regression.

  • Initial proxy timeouts and missing native headers were recovered using the same assigned caches; those setup attempts are not counted as test passes.

@XuPeng-SH

XuPeng-SH commented Nov 15, 2026 •

Copy link
Copy Markdown
Contributor Author

mo-bot review · mo-bot-local · superseded

Commit: c85e3b540baacedb32cc5ea3ccd35a22c4b4fd58

Review belongs to an older commit; it is not a review of the current head.

@XuPeng-SH

Copy link
Copy Markdown
Contributor Author

Independent QA challenge (base cc056261a8fb, head c85e3b540baa)

I ran an independent correctness/performance pass on macOS/arm64 (Apple M4) using the repository CGo wrapper. Custom QA tests were kept in temporary worktrees and are not part of this PR.

Result: no confirmed correctness blocker in the tested scope.

Correctness

  • Added an independent math/big.Int oracle covering 96 deterministic operand pairs (negative/zero/extreme/random int64 values), scales 0/1/6/18, DECIMAL64/128, six comparison operators, and vector/left-const/right-const/both-const shapes.
  • Head passed all oracle checks.
  • The same test fails on the base, e.g. DECIMAL64 -10 at scale 0 compared with 0 at scale 18 under <: expected true, base returned false. This confirms the oracle distinguishes the bug from the fix.
  • Full unit tests passed for all six directly affected packages:
    pkg/container/types, pkg/container/vector, pkg/sql/colexec, pkg/sql/plan, pkg/sql/plan/function, and pkg/vm/engine/readutil.
  • Focused race tests for the new DECIMAL comparison/reuse paths and DECIMAL pruning paths passed.
  • Focused serialized-index, composite-residual, CHAR/VARCHAR-domain, fail-open pruning, NULL, and mixed-physical-frame tests passed.

Supplemental local microbenchmarks

ABBA order (base/head/head/base), 8 scenarios × 4 runs × 5 samples, 500 ms per sample. The custom harness includes result PreExtendAndReset, so these are supplemental end-to-end kernel-call measurements rather than official benchmark results.

Scenario Base Head Delta
DECIMAL64 same scale, 1 row 70.69 ns 47.37 ns -33.0%
DECIMAL64 same scale, 1024 rows 3,940 ns 2,252 ns -42.8%
DECIMAL64 scale-up, 1024 rows 5,339.5 ns 3,956 ns -25.9%
DECIMAL64 scale-up overflow, 1024 rows 4,802,617.5 ns 3,766 ns ~-99.9%
DECIMAL128 same scale, 1024 rows 4,603 ns 3,205 ns -30.4%
DECIMAL128 scale-up, 1024 rows 7,049 ns 8,551 ns +21.3%
INT64 control, 1 row 38.62 ns 45.18 ns +17.0% (~+6.6 ns)
INT64 control, 1024 rows 2,202 ns 2,255 ns +2.4%

The DECIMAL64 overflow case drops from approximately 1.85 MB / 73,730 allocations per call to zero allocations; the other measured DECIMAL cases drop from 192 B / 2 allocations to zero. Overall performance improves substantially, but the DECIMAL128 scale-up and small-batch INT64 regressions are worth acknowledging rather than claiming that every path is neutral.

Remaining validation boundary

I did not locally rerun persisted LOAD/flush SQL with FORCE/IGNORE INDEX, outer-join runtime-filter cases, or a two-CN deployment. Those remain covered by the PR validation/CI rather than by my local run. At the time of this comment, the compose PROXY BVT has passed; Ubuntu UT, SCA, and the pessimistic multi-CN BVT are still pending.

Compatibility assessment from the tested scope: no confirmed wrong-result regression. Intentional changes include corrected DECIMAL/NUL-prefix results and some EXPLAIN/access-path changes; the measured small-batch and DECIMAL128 scale-up costs are the main performance-compatibility considerations.

@XuPeng-SH
XuPeng-SH merged commit 6dd9f9d into matrixorigin:4.2-dev Nov 15, 2026
XuPeng-SH added a commit that referenced this pull request Nov 16, 2026
)

## What type of PR is this?

- [ ] API-change
- [x] BUG
- [x] Improvement
- [ ] Documentation
- [ ] Feature
- [x] Test and CI
- [ ] Code Refactoring

## Which issue(s) this PR fixes:

Fixes #32665
Fixes #32690 on 4.2-dev

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

Preserve a useful forced regular-index access when ORDER BY still needs
a separate sort. A bounded index-side Top is admitted only when the
access is private, all required predicates and sort keys can be
evaluated safely, the order includes the primary key, and known
statistics justify it. The base SQL predicates and final Top remain
authoritative; an unproven residual prevents a static reader limit.

Keep nullable TopValue pruning fail-open when nullability, physical
type, scale or block metadata cannot prove exclusion. Reuse existing
scan-reader and shuffle ownership, exact IN membership, vector and Top
execution paths while avoiding redundant reader, decoding and sorting
work.

Publish complete index predicates before deriving scan statistics. A
synthesized prefix range and its decoded SQL residual must not count the
same condition twice. Scan statistics derive an estimation-only view
from the actual encoded access and decoded rechecks, recognizing every
proven static integer prefix component or exact IN set. The executable
expressions keep their own selectivities for filter ordering and block
estimates. Unproven cases remain conservative.

The pre-existing 4.2 DECIMAL comparison and pruning defect exposed by
this PR's CI was fixed independently by #32767, now merged into 4.2-dev
as 6dd9f9d. This branch is rebased on that merge. The original
reported DECIMAL query has also been verified on main.

The logtail CI failure is addressed by backporting the test-only
read-barrier synchronization already merged on main in #30998. Receiving
the response can precede the publisher's deferred release; the test now
waits to reacquire the sole admission slot and still detects a leak.

The CI follow-up updates the expected block-filter plan and fixes the
test comparator's tie key for two IVF JOIN queries. Their original SQL
is unchanged; actual plans confirm that the default query still uses IVF
and the forced exact query retains its exact path.

## Validation

- Current fix on 57: full `pkg/sql/plan` normal tests, the focused
selectivity suite under `-race`, and `static-check-selected` for
`pkg/sql/plan` exited successfully. Golangci-lint reported zero issues;
molint also printed five `checkrecover` diagnostics in code unchanged
from the previous PR head. On the previous PR head, the new multi-prefix
regression failed with 18,939.39 estimated rows; after the fix the index
scan and inner Top input cost both estimate 75,757.58. The test also
covers open ranges, a residual, low selectivity, repeated refresh, and
mismatching/NULL/sourced bounds.
- Executed FORCE-versus-IGNORE SQL on one- and two-CN embedded
instances, before and after flushing both the table and its index.
Range, offset, descending order, residual, NULL, empty, IN and
composite-primary-key cases matched; after flush `EXPLAIN` confirmed the
index-side Top and both rechecks. The two-CN instance selected
`ForceOneCN`, so this does not claim multi-CN parallel execution.

- Logtail test-only follow-up before the current selectivity fix: the
exact failing logtail test passed 100 race-detector repetitions; its
full owning package passed normal and race tests, go list/build/vet, and
static-check-selected.
- On the clean 4.2-dev baseline, controlled publisher scheduling
demonstrated that the response can arrive before the deferred slot
release. A temporary leak-injection overlay made the corrected test fail
as expected; no production mutation was retained.
- Against 4.2-dev at 296402f and #32767: actual SQL on one and two
CNs, before and after flush, including FORCE/AUTO/IGNORE, composite
DECIMAL bounds, NULL, outer joins and overflow. The original FORCE query
was verified to use its index.
- A DECIMAL composite-index query with a non-exact range was verified to
apply its decoded residual below the internal Top; both FORCE and IGNORE
returned the same expected rows. After rebasing, actual CHAR index and
JOIN runtime-filter probes and the one/two-CN DECIMAL and Top/vector
plan probes all passed.
- Before the current selectivity fix, relevant two-CN BVT: 1,451/1,451
statements passed, with no failures or skips. This includes all three
previously failing #32767 files as well as force_index_order,
explain_index and vector_ivf_equi_join.
- Before the current selectivity fix, the complete pkg/sql/plan and
pkg/sql/plan/function suites passed both normally and with race
detection. Earlier focused tests for the affected packages and
selectivity proof boundaries also passed.
- Before the current selectivity fix, vet and the project
static-check-selected target (molint and golangci-lint) passed for all
12 Go packages then changed relative to 4.2-dev.
- BuildPlan tests with explicit 1M-row statistical fixtures verify the
range and IN estimates are counted once and remain correct after a leaf
statistics refresh. Tests also cover NULL, parameter sources,
malformed/different vectors, changed bindings and truncated keys.

## Performance

For this selectivity fix, an ABBA planner microbenchmark on 57 compared
the previous PR head and the fix using the same four FORCE query/fixture
shapes. The two-run mean changed from -3.2% to +2.8% across cases; the
multi-prefix Top case changed from 289.4 to 290.5 microseconds per
planning iteration. This includes fixture construction and parsing and
is not a SQL execution latency benchmark.

On host 57, a direct ABBA comparison used the prior #32675 head
baefd9b and the then-candidate d4671cf (before the later
prerequisite CI follow-up), one million flushed/analyzed rows in
concentrated and scattered layouts, eight SQL cases, 100 warmups and 300
measured executions per case per process. All 16 comparisons used
identical plans and result digests; mean process medians changed between
-4.6% and +5.1%.

A separate comparison made before the prerequisite CI follow-up against
the then-#32767 baseline showed that some FORCE queries are 14%–47%
slower because the old code ignored FORCE and used a table scan, while
the candidate performs the requested index scan and backfill. Other
workloads improved; for example the concentrated IN/Top case improved
about 75%. The identical-plan AUTO case was faster in the concentrated
layout and essentially unchanged in the scattered layout. These numbers
describe the tested workloads, not every possible query.

A separate pre-existing 4.2 issue remains for reused untyped prepared
parameters whose DECIMAL scale changes; it also reproduces without an
index and is outside this PR.

This branch was previously deployed

1 inactive deployment
ci — c85e3b54 Deployed Nov 15, 2026 by XuPeng-SH
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

size/XXL Denotes a PR that changes 2000+ lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants