Skip to content

fix(function): support DECIMAL arithmetic and comparison with BOOL operands - #31937

Merged
XuPeng-SH merged 3 commits into
matrixorigin:mainfrom
gouhongshen:agent/issue-31181-main-4ce9b6bf
Oct 31, 2026
Merged

XuPeng-SH merged 3 commits into
matrixorigin:mainfrom
gouhongshen:agent/issue-31181-main-4ce9b6bf

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 #31181

What this PR does / why we need it:

Issue #31181: arithmetic, comparison, and assignment mixing a DECIMAL and a BOOL operand failed at plan time with invalid argument operator <op>, bad value [DECIMAL64 BOOL] (and the [DECIMAL128 BOOL] / [BOOL DECIMAL64] variants), while MySQL binds TRUE/FALSE as the exact integers 1/0 next to a DECIMAL.

Root causes:

  • The fixed overload tables for +, -, *, /, %, DIV and the comparisons bind no DECIMAL x BOOL pair in either operand order.
  • The BOOL -> DECIMAL64/128/256 cast rows and the explicit-cast routing are missing, so even CAST(TRUE AS DECIMAL) and the implicit coercions fail.
  • Type derivation is BOOL-blind: the arithmetic domain, the division/modulo result envelope, the comparison aligner, and the safe width/scale derivation handled integers but not a one-digit 0/1 operand, which would strand or mis-derive wide operands once binding existed.
  • The implicit BOOL -> DECIMAL assignment coercion never validated the declared column precision, so TRUE/1.0 could be stored into DECIMAL(1,1) while the integer 1 was rejected under the assignment-range contract of fix(sql): enforce DECIMAL width for integer assignments (#30367) #30639.

Changes:

  • type_check.go: bind the DECIMAL x BOOL pairs for +, -, *, /, %, DIV and the comparisons in both operand orders; treat BOOL as one exact integral digit, scale 0, in the safe width/scale derivation.
  • list_operator.go: same one-digit treatment in the arithmetic domain and the comparison aligner, so maximum-width operands widen to DECIMAL256 exactly as with an integer operand.
  • decimal_division.go / decimal_integer_division.go / decimal_mod.go: BOOL contributes (1,0) to the /, DIV and % result-type envelopes in both operand orders.
  • func_cast.go: add the BOOL -> DECIMAL64/128/256 cast rows and route the explicit cast through the integer parse path, keeping the existing out-of-range clamp semantics; route the implicit assignment coercion through the same declared-precision range validators the integer family uses, so TRUE is admitted exactly when the integer 1 fits the DECIMAL(p,s) column, with identical error text and statement atomicity. Synthesized SELECT-context casts (zero declared width) stay unenforced, matching integers.

Tests (issue-to-proof mapping):

  • pkg/sql/plan/function/decimal_bool_operand_test.go (new UT): operator/cast binding targets for DECIMAL64/128/256, widening at the DECIMAL(38,38) and DECIMAL256 boundaries against the INT64 control, and a 15-case assignment-width matrix proving TRUE/1 equality, FALSE/NULL acceptance, and rejection across DECIMAL64(1,1), DECIMAL128(19,19), and DECIMAL256(40,40). Command: go test ./pkg/sql/plan/function -run 'DecimalBool|BoolToDecimal|_SetSafeDecimalWidthAndScaleFromSource'. Evidence: the new UT fails on the pre-fix parent (RED) and passes after the fix (GREEN); the full package suite passes.
  • test/distributed/cases/operator/decimal_bool_arithmetic.sql (new BVT): the exact issue reproduction, the full operator matrix, NULL propagation, FALSE zero-divisors, transactions, nonliteral BOOL operands (column, comparison result, EXISTS), assignment admission/rejection/atomicity across all three storage carriers and every write path (VALUES, multi-row, INSERT SELECT, UPDATE, ON DUPLICATE KEY UPDATE), explicit-cast clamp, DECIMAL(60,30), and capped division scale. subquery-with-exists.result and view-subquery-with-exists.result are regenerated for the fixed behavior. Evidence: generated results audited line by line against the intended semantics; decimal_bool_arithmetic 90/90, subquery-with-exists 235 passed / 0 failed / 14 skipped, view-subquery-with-exists 340/0/20.

All results equal the corresponding DECIMAL-with-integer-1/0 expressions in value, result class, and scale per MySQL semantics; a BOOL operand contributes exactly one integral digit to the derived precision, where an INT64-typed literal contributes 19.

Residual risks / limits:

  • Protocol Length/precision of +, -, *, % results with a BOOL operand reflects the one-digit contribution and therefore can differ from an INT64-literal expression; result class, scale, and value are identical. Division presentations coincide.
  • BOOL / DECIMAL256 (reversed order) stays unbound, exactly as INT64 / DECIMAL256 already is on main.
  • SUM/AVG over BOOL remain governed by the separate ENABLE_BOOL_SUMAVG sql_mode; the DECIMAL -> BOOL direction shipped separately (fix(sql): support DECIMAL to BOOL cast for boolean contexts #30923).
  • Only the distributed-BVT files listed above were run locally; the broader suite runs in CI.

…erands

Arithmetic, comparison, and assignment mixing a DECIMAL and a BOOL operand
failed at plan time with "bad value [DECIMAL64 BOOL]", while MySQL binds
TRUE/FALSE as the exact integers 1/0 next to DECIMAL.

- bind the DECIMAL x BOOL pairs for +, -, *, /, %, DIV and the comparisons
  and treat a BOOL operand as one exact integral digit with scale 0 in the
  arithmetic domain, the division/modulo result envelope, the comparison
  aligner, and the safe width/scale derivation
- add the missing BOOL -> DECIMAL64/128/256 cast rows and route the explicit
  cast through the integer parse path, keeping the existing out-of-range
  clamp semantics
- route BOOL assignment coercion through the same declared-precision range
  validation the integer family uses, so TRUE is admitted exactly when the
  integer 1 fits the DECIMAL(p,s) column, with identical error text and
  statement atomicity; SELECT-context zero-width casts stay unenforced

Related to matrixorigin#31181
@gouhongshen

Copy link
Copy Markdown
Contributor Author

CI blocker (unrelated to this PR): Matrixone CI execution / UT Test on Ubuntu/x86 of run 41114296492 failed on TestTimestampAddHistoricalDumpRoundtrip/historical_div_signed with Error 20301 (HY000): invalid input: table div_signed contains in-memory rows; flush it before DUMP TABLE 66 ms after the test's mo_ctl('dn','flush',...), despite [FLUSH-END] for the table. This is the known after-flush DUMP visibility race tracked in #31790 (reproduction record added there). This PR's diff only touches plan-time DECIMAL×BOOL function binding and BVT files; it cannot affect TableMetaReader/TN flush/logtail visibility. CI Required failed only as a cascade of that UT job. A one-time failed-jobs rerun of attempt 1 has been requested.

@gouhongshen
gouhongshen marked this pull request as ready for review October 30, 2026 21: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 commented Oct 30, 2026 •

Copy link
Copy Markdown
Contributor

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

Commit: b5b555f88a4d113ccdcc61e4646ecf106e47a36b

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: b5b555f88a4d113ccdcc61e4646ecf106e47a36b

Assessment: approve

Reviewed the complete delta and affected binding, precision, cast and assignment paths. BOOL consistently uses exact 0/1 semantics while preserving NULL handling and assignment bounds. No actionable findings remain.

Model: gpt-6-astra / xhigh

Session: 01a1869d-820c-7212-9788-aecfb86a4141 · slot 0 · generation 2

Validation:

  • Frozen CI reports successful UT, SCA, proxy and pessimistic multi-CN BVT; latest contexts comprise 13 success, 14 skipped and 2 neutral.

  • Local static audit passed: frozen source/delta identity, whitespace, complete discussion coverage and 158 independent numeric/NULL expected-value checks. Receipt: checks/1793400482845162208-3.json; retained logs: review-audit.stdout.log and review-audit.stderr.log.

  • Saved review-plan.md, discussion-assessment.json and validation-ledger.json. The earlier DUMP-after-flush failure remains separately tracked in issue 31790; this PR does not claim to fix it.

Limitations:

  • No local Go or SQL execution was performed; execution evidence relies on supplied CI statuses and author reports, without raw CI logs.

  • Broader PR-body coverage claims absent from the checked-in SQL were not counted as validated scenarios.

@gouhongshen

Copy link
Copy Markdown
Contributor Author

@Mergifyio queue

@mergify

mergify Bot commented Oct 30, 2026 •

Copy link
Copy Markdown
Contributor

🚫 Left the queue

1 min in the queue, with no time running CI.

So far

Reason

The pull request can't be updated

GitHub response: refusing to allow a GitHub App to create or update workflow .github/workflows/python-sdk.yml without workflows permission
GitHub only lets Mergify write to .github/workflows/ with the workflows permission. An organization owner can accept Mergify's pending permissions at https://dashboard.mergify.com/orgs/matrixorigin/repositories.

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

Times in UTC · dashboard · how the merge queue works

@gouhongshen

Copy link
Copy Markdown
Contributor Author

Merge-queue blocker (merge infrastructure, unrelated to this PR's code): Mergify dequeued this PR from the main queue with reason BRANCH_UPDATE_FAILED ("The pull request can't be updated").

GitHub response recorded by Mergify:

refusing to allow a GitHub App to create or update workflow .github/workflows/python-sdk.yml without workflows permission

Verified cause:

  • main advanced from this PR's base 4183159a877e27049a392906ea2c3ae07edcdd42 to 91dfab2132, and that delta includes .github/workflows/python-sdk.yml (+17/−2).
  • This PR's own diff never touches .github/workflows/** (12 files under pkg/sql/plan/function/ and test/distributed/cases/).
  • To run the queue rule, Mergify must push a branch update containing that upstream workflow change, but the Mergify GitHub App lacks the workflows permission, so GitHub rejected the push.

Required action (repository administrator): an org owner accepts Mergify's pending permissions at https://dashboard.mergify.com/orgs/matrixorigin/repositories, then requeue with @mergifyio queue (or the requeue checkbox in Mergify's comment above). Requeueing before the permission is granted will deterministically fail the same way.

Current state: open, approved (mo-bot review on b5b555f, no actionable findings), CI terminally green (CI Required SUCCESS on runs 41114296492 and 41132629442), mergeable=MERGEABLE; mergeStateStatus=BEHIND is ordinary freshness that the merge queue would resolve once it can update the branch. Per repository protection this PR will not edit workflow files or be force-updated to bypass the permission gap; the branch is left in a state that can be retried after the admin fix.

@XuPeng-SH
XuPeng-SH merged commit fe3b559 into matrixorigin:main Oct 31, 2026
@mergify mergify Bot removed the dequeued label Oct 31, 2026
XuPeng-SH pushed a commit that referenced this pull request Nov 4, 2026
…meric branches (#32162)

## What type of PR is this?

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

## Which issue(s) this PR fixes:

Related to #31200

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

### Problem

`CASE`, `IF`, `IFNULL` and `COALESCE` silently folded numeric value
branches to `0`/`1` when another branch was `BOOL`:

```
select coalesce(2, true), ifnull(5, true), if(1, 2.5e0, true), case when 1 then 9 else true end;
-- before: 1 1 1 1     after (MySQL 8): 2 5 2.5 9
```

Root cause: `BOOL` has no implicit numeric cast in
`fixedCanImplicitCastRule`, so the only common type every value branch
could reach in `caseCheck`/`iffCheck`/`coalesceCheck` was `BOOL`, and
the numeric branches were cast to `BOOL`. `IFNULL` is lowered to `CASE`,
so all four constructs shared the defect.

### Change

- `pkg/sql/plan/function/operatorSet.go` (`caseCheck`/`iffCheck` +
shared wrapper): BOOL value branches are normalized to a numeric domain
before common-type resolution — BIGINT, or DECIMAL(1,0) when a DECIMAL
branch participates (TRUE/FALSE need only one integral digit). The
result keeps the numeric type and TRUE/FALSE evaluate as 1/0, matching
MySQL. A mixture the numeric domains cannot resolve (e.g. plan-internal
DECIMAL(76,76) + BOOL) now returns a resolution error instead of
silently folding to BOOL. Non-numeric mixtures (BIT, strings, dates)
keep the original resolution path, and BOOL-only branches keep BOOL
semantics.
- `pkg/sql/plan/function/func_binary.go` (`coalesceCheck`): delegates to
the same wrapper.
- The BOOL→DECIMAL runtime conversion this resolution relies on (value
conversion plus declared-precision validation for assignment casts: TRUE
needs one integral digit, so a target with width ≤ scale, e.g.
DECIMAL(1,1), rejects it with `invalid input: 1 beyond the range, can't
be converted to Decimal64(1,1).`; FALSE/NULL always convert; explicit
`CAST(bool AS DECIMAL(M,N))` keeps its clamp behavior, `CAST(true AS
DECIMAL(1,1))` = 0.9) is already on `main` via #31937 and #30639. This
PR's diff therefore no longer touches
`pkg/sql/plan/function/func_cast.go`; the UT/BVT below keep covering
that contract end to end.

### Tests

- New UT `pkg/sql/plan/function/bool_numeric_branch_test.go`:
common-type resolution for all four constructs (INT/DOUBLE/DECIMAL ×
BOOL, both branch orders, BOOL-only and condition-position controls,
BIT/VARCHAR/DATE non-numeric controls), high-scale DECIMAL
(65,57)/(65,58)/(76,75), unresolvable (76,76) must error, and
BOOL→DECIMAL cast/assignment values and range errors. The new tests fail
on the pre-fix code (13 subtests) and pass after.
- New BVT
`test/distributed/cases/function/func_bool_numeric_branches.{sql,result}`:
literals and nullable columns across all four constructs, both branch
orders, high-scale DECIMAL up to the publicly reachable precision 65,
and assignment/clamp/error coverage (TRUE into DECIMAL(1,1) rejected via
INSERT-SELECT and INSERT-VALUES, FALSE/NULL accepted, explicit CAST
clamps to 0.9, failed inserts leave the table unchanged). mo-tester:
47/47 100%.
- Updated goldens `func_coalesce_1.result` (BOOL+INT columns now resolve
to INT) and `union_and_union_all.result` (int-typed rows under the same
shared resolution); values unchanged where the old result was already
correct. mo-tester: union_and_union_all 234/234 100%; the edited
func_coalesce_1 goldens pass.
- Commands: `.agents/skills/mo-dev/scripts/mo-cgo-test -count=1
-timeout=1800s ./pkg/sql/plan/function ./pkg/sql/plan` → `ok` both
packages; `GOWORK=off go vet -mod=readonly ./pkg/sql/plan/function` →
clean; `golangci-lint run -c .golangci.yml --new-from-rev <merge-base>
./pkg/sql/plan/function` → 0 issues; live-node SQL verification of the
issue's exact queries.
- After the 2026-11-04 rebase onto `main` (52cbba7): semantic
conflict resolution in `operatorSet.go`/`func_binary.go` (the wrapper
now composes with the low-precision-float widening from #29554 and the
ENUM/JSON condition handling from #31492); `func_cast.go` conflicts
resolved by taking `main`'s already-merged BOOL→DECIMAL support, making
the file identical to `main`; the new UT's `TestBoolToDecimalCast`
renamed to `TestBoolToDecimalCastAndClamp` (name already used by
#31937's `decimal_bool_operand_test.go`). Re-validated: `mo-cgo-test
-count=1 -v -run
'TestBoolNumericValueBranchesResolveToNumeric|TestBoolDecimalHighScaleValueBranches|TestBoolDecimalUnresolvableDoesNotFoldToBool|TestBoolNonNumericValueBranchesUnchanged|TestBoolToDecimalCastAndClamp|TestBoolToDecimalAssignmentRangeCheck|TestBoolToDecimalAssignmentValues'
./pkg/sql/plan/function` → 7/7 pass; full `pkg/sql/plan/function`
package suite → `ok` 33s; `go vet` with the repository CGo environment →
clean; `golangci-lint --new-from-rev 52cbba7` → 0 issues.

- After CI on the rebased head, `TestDependentNativeStages` in
`pkg/sql/compile` (from #31275) failed in UT Coverage: its
`range_row_operand_{skipped,selected_one,uncorrelated,deep_guard}`
oracles still assumed `CASE WHEN <bool> THEN <bool row comparison> ELSE
0 END` resolves to BOOL. Under this PR's intended semantics the result
is numeric, so the expected values are now `1`/`0` (matching MySQL).
Only the four expectation strings changed;
`range_row_operand_inner_case`/`range_row_operand_coalesce` stay BOOL
and keep `true`/`false`. Local: `mo-cgo-test -count=1 -run
'TestDependentNativeStages' ./pkg/sql/compile` → `ok`.

### Residual risk / notes

- In one local single-node + JDBC environment, `func_coalesce_1` shows
22 additional failures that are display-width metadata drift only (e.g.
`[12,-1,0]` vs `[12,25,0]`); the identical failure set occurs with the
unmodified base build in that environment, every value row is
byte-identical, and the affected statements include pure `select * from
t1` scans this change cannot influence. CI-generated goldens should not
be affected.
- The unresolvable-mixture error path (needs > 66 total digits) is
unreachable from public SQL because the parser caps `DECIMAL(M)` at M ≤
65; it is covered by UT only. The public boundary (scales 57/58/65) is
covered by BVT.

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

This branch was successfully deployed

No deployments
ci — 3e3cf5eb Deployed Oct 31, 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 size/L Denotes a PR that changes [500,999] lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants