Skip to content

fix(function): preserve mixed integer arithmetic domains - #28704

Merged
XuPeng-SH merged 35 commits into
matrixorigin:mainfrom
aunjgr:fix/mixed-unsigned-arithmetic-domain-28581
Sep 14, 2026
Merged

XuPeng-SH merged 35 commits into
matrixorigin:mainfrom
aunjgr:fix/mixed-unsigned-arithmetic-domain-28581

Conversation

@aunjgr

@aunjgr aunjgr commented Sep 11, 2026 •

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:

issue #28581

What this PR does / why we need it:

Mixed BIGINT UNSIGNED and signed arithmetic previously coerced operands to DECIMAL128 and lost the integer result domain, allowing negative or greater-than-UINT64_MAX values to escape into subsequent expressions and stored columns.

Keep the operands and results integer-typed. Use a widened scalar intermediate to calculate selected non-NULL rows, enforce the UINT64 result bounds for addition, subtraction, and multiplication, and bind NO_UNSIGNED_SUBTRACTION to an INT64 result with both signed bounds enforced. Preserve this decision through constant folding, ordinary plan invalidation, prepared-plan rebuilding, and result metadata.

Version the new arithmetic overloads for remote execution. Check the coordinator rollout gate and probe the actual selected worker versions, validating their pipeline addresses against current worker identity. If a worker is older or cannot be verified, compile the query locally with the checked arithmetic intact. Recheck the destination before serialization, and reject unsupported incoming expressions at the remote protocol boundary.

Cover nested overflow, signed boundaries, NULL and masked rows, reused result vectors, scalar broadcasting, prepared mode/operand changes, CTAS metadata and rollback, older-worker placement, destination changes, and cancellation.

Preserve direct/prepared arithmetic equivalence when a parameter changes type: remove provisional integer operand casts before resolving the new overload, while keeping explicit casts authoritative. Retry planning retains the supplied bind-time mode when no frontend session is present. Cover the BIT-to-UINT64 prepared-peer regression without changing its expected SQL results.

Preserve the original shuffle abort cause when a sibling reaches Prepare after pool retirement. Cancellation from an early-finished consumer must remain distinguishable from a substantive execution error; retain the existing admission and cleanup safeguards.

Keep user-written CAST targets and conversion overloads authoritative when EXECUTE changes a parameter type. Revalidate the new source type, preserve explicit-cast provenance in both rebinding paths, and do not remove the rebuilt boundary as implicit integer widening. Cover nested/reversed casts and successful prepared reuse after an unsigned-domain error.

Require MORPC version 71 for checked integer arithmetic while retaining main's version-70 row-dependent CONV, version-69 RANK boundary ties, and version-67 named-timezone implementations. Older version-70 workers use local fallback; sender and receiver gates enforce the same boundary.

Preserve MySQL's unsigned result domain for mixed BIGINT arithmetic, including NO_UNSIGNED_SUBTRACTION semantics.
@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 →

Prefer the live frontend sql_mode while preserving the serialized remote snapshot, so NO_UNSIGNED_SUBTRACTION takes effect after a session mode change and across CN execution.

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

Reviewed 0631a8c against main 438353c. One concrete compatibility blocker remains.

[P1] Fence the new arithmetic overloads during rolling upgrade. The resolver unconditionally selects overload 2 for BIGINT/BIGINT UNSIGNED +, - and *. The base registry has only overloads 0 and 1. A new coordinator planning a distributed column expression such as SELECT u+s FROM t (u BIGINT UNSIGNED, s BIGINT) can therefore send overload 2 to an old CN; its expression executor calls GetFunctionById and returns function overload id not found. This is a previously valid query failing solely because the cluster is mixed-version. The PR changes neither protocol capability nor RequiredRemoteExpressionFeatures/validateRemoteExpressionPipelineProtocol, so existing sender checks do not fence this new function ID. Append-only IDs protect old plans on new binaries, not new plans on old binaries.

Please add a negotiated oldest-live-version capability and sender-side fence, with a compatible fallback/local placement when the feature is unavailable, and test a new-head expression against a pre-feature capability. Do not simply cast to DECIMAL and send legacy arithmetic while promising unsigned-domain checks, since that drops the new semantics.

Other review results: read all six changed files; traced numeric resolver -> overload binding -> decimal kernel -> selection/null handling and SQL-mode lookup. The added result-domain scan skips masked/NULL rows, leaves smaller/decimal/float operands on their old paths, and adds O(rows) comparisons without an additional value buffer. The source/worktree was not changed and no native suite was run. UT/BVT oracles were inspected; CI was not awaited.

Non-blocking scope limitation to make explicit: NO_UNSIGNED_SUBTRACTION currently disables all result-domain checks, rather than enforcing signed BIGINT bounds. For example with that mode, u=UINT64_MAX and s=-1 permits u-s=18446744073709551616 on this Decimal128 path. This behavior already escaped through the old common-decimal path, so I am not presenting it as a newly introduced runtime regression, but the mode is not full MySQL signed-domain compatibility (https://dev.mysql.com/doc/refman/8.4/en/arithmetic-functions.html).

Exact head/base rechecked before posting.

# Conflicts:
#	pkg/sql/plan/function/list_operator.go
Keep mixed BIGINT UNSIGNED arithmetic integer-typed at both the input and output boundaries. Compute each selected non-NULL row with a widened scalar intermediate and reject results outside the bound UINT64 or INT64 domain before publishing them. This prevents nested operators and prepared rebinding from losing overflow enforcement.

Bind NO_UNSIGNED_SUBTRACTION to the signed-result overload and capture it in ordinary and prepared plan invalidation, including result metadata and retry specialization. Add SQL coverage for nested overflow, prepared mode and operand changes, CTAS metadata, and rollback, plus planner transport and kernel boundary tests.
@aunjgr aunjgr changed the title fix: enforce unsigned domain in mixed bigint arithmetic fix(function): preserve mixed integer arithmetic domains Sep 11, 2026
Revalidate the current CAST source type while retaining its target domain, original overload, and syntax provenance in both prepared rebinding paths. Do not turn a user-written CAST into an implicit widening that enclosing arithmetic can remove. Cover typed plans, reversed and nested casts, binary COM_STMT execution, SQL PREPARE, negative unsigned-domain results, and successful reuse after an error.
@aunjgr

aunjgr commented Sep 12, 2026

Copy link
Copy Markdown
Contributor Author

@XuPeng-SH Fixed in c04bba5, including newest main.

Both prepared-rebind paths now revalidate the current CAST source type while retaining the original target, conversion overload, and explicit-cast provenance. The rebuilt node cannot be mistaken for a planner-inserted integer widening and removed by its parent.

The typed-plan regression reproduced the failure before the fix and now passes for both rebind paths, reversed operands, and nested casts. A real binary COM_STMT test checks positive/error/positive reuse, unsigned-domain error1690, reversed and nested casts, and an outer SIGNED control. The SQL PREPARE regression and existing arithmetic cases pass twice (49/49 statements per run).

Full planner/function/frontend/compile tests and full SCA pass. Local coverage using the unchanged CI parser is79.47%. Fresh CI is running; ready for re-review.

Reuse the injectable listener boundary to force the UDP bind failure after a successful TCP acquisition. Assert that the acquired TCP listener is closed exactly once instead of rebinding a UDP-selected port, which may belong to unrelated TCP traffic on shared CI hosts. Retain real TCP and UDP occupied-socket checks.
@aunjgr

aunjgr commented Sep 12, 2026

Copy link
Copy Markdown
Contributor Author

Fixed the failing CI test in 13d593e, with newest main merged.

The coverage producer failed in TestProbeTestPortRejectsOccupiedSockets/udp: a UDP-assigned ephemeral port was already occupied for TCP, so the test's TCP rebind assertion failed. The downstream coverage job explicitly reported that no coverage verdict was calculated because that producer failed.

The cleanup regression now injects a UDP bind failure and asserts exactly one Close on the acquired TCP listener. Real TCP/UDP occupied-socket checks remain. This reuses the same deterministic helper already present in #28705; no retry, skip, or timeout increase was added.

Validation: focused normal and coverage-instrumented tests, 100 race-detector iterations, owning logservice tests, compile tests after the main merge, and full repository SCA passed. Fresh CI will validate the pushed head.

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

The current head has one verified P1 integration blocker shared with #28705. Please coordinate the MORPC version allocation before these changes are deployed together.

Comment thread pkg/defines/const.go Resolved

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

Reviewed exact head 13d593e against base cbe4daa. No blocking findings remain.

Re-read the complete review/comment/thread history and rechecked the full 28-file diff. The earlier rolling-upgrade and prepared explicit-CAST blockers are closed: checked overloads retain integer result domains and bound SQL-mode semantics, old/unknown workers fall back locally with sender/receiver fences, and both prepared-rebind paths preserve user CAST provenance. I accept the documented main/release-only compatibility boundary: current main ends at v66, so the concurrent unmerged-v67 collision is a merge-order prerequisite rather than a defect in this exact head. If another v67 capability lands first, this PR must merge that main and allocate the next cumulative version before landing.

Validation on the pinned worktree: make thirdparties; make cgo; focused function/planner/compile/frontend/logservice tests; the embedded binary-prepared CAST regression; and additional embedded dead-branch/boundary counterexamples all passed. diff-check and gofmt are clean. Exact head was rechecked immediately before submission.

Retain main's version-67 timezone codec and worker/destination fences alongside this PR's own capability checks. Require version68 for the new capability and exercise version67 fallback, destination downgrade, and receiver rejection where applicable. Preserve both sides of the test and planner merges.
Preserve main's strict-write capability68 and IGNORE_SPACE invalidation alongside checked integer arithmetic and NO_UNSIGNED_SUBTRACTION. Allocate arithmetic capability69 and test version68 fallback. Replace the heartbeat test's fixed sleep with report-completion notification and use its existing harness deadline to verify shutdown.
Register an EXIT trap immediately after opening the test notification FIFO. Stop any background heartbeat and close the descriptor on both success and assertion/timeout exits, retaining the existing harness deadline.
@aunjgr

aunjgr commented Sep 14, 2026

Copy link
Copy Markdown
Contributor Author

Fixed the UT failure and main conflicts in d7c2df4. TestUTHeartbeatStopsCleanly no longer assumes a report appears within a fixed two-second sleep: it waits for an explicit notification containing both expected active cases, checks stopped-process state, and guarantees heartbeat/FIFO cleanup through an EXIT trap. The existing harness deadline remains unchanged. The final test passed24 race-detector repetitions and the full optools package. Main strict-write capability68 and IGNORE_SPACE cache invalidation are retained alongside NO_UNSIGNED_SUBTRACTION; arithmetic capability is now69, with version68 fallback checks. Full frontend/planner/function/compile tests, the real binary-prepared arithmetic regression, and full SCA pass. Fresh CI is running.

Keep main RANK boundary-tie capability at v69. Move checked-arithmetic placement, actual-destination, and receiver gates to v70, retaining v69 local fallback and testing the new boundary.
@aunjgr

aunjgr commented Sep 14, 2026

Copy link
Copy Markdown
Contributor Author

@XuPeng-SH Updated in ae237d1 after merging newest main. Main's RANK boundary-tie implementation remains at MORPC v69; checked integer arithmetic now requires v70 consistently for worker placement, actual-destination validation, and incoming expressions. The focused tests prove v69 local fallback, v70 execution, rejection after destination downgrade, and unchanged legacy-operator handling. Full compile/function/plan-protobuf packages and full repository SCA/pre-push validation pass with zero lint issues. Fresh CI is starting on the pushed revision.

The compatibility contract remains main/release builds only. This PR stays independent: whichever capability lands later must merge the then-current main, preserve its implementation, and allocate the next cumulative version. Mixing arbitrary unmerged PR binaries is not a supported deployment configuration. Ready for your re-review; your request is already active. Already-approved reviewers were not re-requested.

Preserve the landed row-dependent CONV v70 feature detection, worker placement, destination validation and receiver checks. Advance checked arithmetic to v71 at every gate and test combined CONV/arithmetic pipelines against v70 fallback and v71 execution.
@aunjgr

aunjgr commented Sep 14, 2026

Copy link
Copy Markdown
Contributor Author

Resolved the conflicts in edbb436 by merging newest main, including merged #28754. CONV retains v70; checked integer arithmetic now requires v71. Both features' detection, placement, actual-destination, and receiver checks are preserved.

The combined CONV/arithmetic pipeline regression passes for v70 fallback/rejection, v71 execution, and destination downgrade. Full compile/function/plan-protobuf packages and the real two-CN CONV regression pass. Full repository SCA/pre-push validation passes with zero issues. Fresh CI is starting; no rebase or force-push was used.

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

GPT-6 medium deep review at head edbb436. The earlier protocol-version and explicit-cast concerns are addressed: checked arithmetic requires CONV v71, with capability checks/fallback and receiver-side validation, and prepared rebinding preserves explicit CAST semantics. The signed/unsigned bounds and decimal intermediate paths are covered. Exact-head CI is green; no new racing UT exceeds the 45.55s per-test limit. I found no remaining introduced blocker.

@mergify

mergify Bot commented Sep 14, 2026 •

Copy link
Copy Markdown
Contributor

Merge Queue Status

  • ✅ Entered queue — 2026-09-14 18:41 UTC · Rule: main · triggered by rule Automatic queue on approval for main
  • ❌ Checks failed · in-place
  • 🚫 Left the queue — 2026-09-14 20:30 UTC · at ec4bf8f30f0a67ec466dcb2d0f4a30bdae33b948

This pull request spent 1 hour 48 minutes 21 seconds in the queue, with no time running CI.

Waiting for any of
  • check-neutral = CI Required
  • check-skipped = CI Required
  • check-success = CI Required
All conditions

Reason

The merge conditions cannot be satisfied due to failing checks

  • Mergify Merge Protections
  • CI Required

Hint

You may have to fix your CI before adding the pull request to the queue again.
If you update this pull request, to fix the CI, it will automatically be requeued once the queue conditions match again.
If you think this was a flaky issue instead, you can requeue the pull request, without updating it, by posting a @mergifyio queue comment.

Requeued — the merge queue status continues in this comment ↓.

@mergify

mergify Bot commented Sep 14, 2026 •

Copy link
Copy Markdown
Contributor

Merge Queue Status

  • ✅ Entered queue — 2026-09-14 21:51 UTC · Rule: main · triggered by rule Automatic queue on approval for main
  • 🟠 Checks running · in-place
  • 🚫 Left the queue — 2026-09-14 22:11 UTC · at 8b24762a31b8a14e085b9594379ccb73a24dad8a

This pull request spent 20 minutes in the queue, with no time running CI.

Waiting for any of
  • check-neutral = CI Required
  • check-skipped = CI Required
  • check-success = CI Required
All conditions

Reason

Pull request #28704 has been dequeued

Pull request from fork cannot be queued. This pull request comes from a fork, and Mergify needs the author's permission to update its branch.

The author needs to enable "Allow edits from maintainers" on this pull request.

Hint

You should look at the reason for the failure and decide if the pull request needs to be fixed or if you want to requeue it.
If you do update this pull request, it will automatically be requeued once the queue conditions match again.
If you think this was a flaky issue instead, 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

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 size/XL Denotes a PR that changes [1000, 1999] lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants