Skip to content

fix: decimal comparison precision handling and add range validation for type casting and div operator improvement - #23440

Merged
mergify[bot] merged 54 commits into
matrixorigin:mainfrom
XuPeng-SH:fix-divide-by-zero
Jan 7, 2026
Merged

mergify[bot] merged 54 commits into
matrixorigin:mainfrom
XuPeng-SH:fix-divide-by-zero

Conversation

@XuPeng-SH

@XuPeng-SH XuPeng-SH commented Jan 4, 2026 •

Copy link
Copy Markdown
Contributor

User description

What type of PR is this?

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

Which issue(s) this PR fixes:

issue #23439 #23404

What this PR does / why we need it:

1. Fix Decimal128 High-Bit Handling (Critical)

  • Issue: hasTrailingZeros() only checked low 64 bits of Decimal128, ignoring high bits
  • Fix: Added decimal128HasTrailingZeros() using proper 128-bit modulo arithmetic
  • Impact: Fixes incorrect trailing zeros detection for large decimal values (>18 digits)

2. Add Integer Range Validation (Critical)

  • Issue: canUse() function allowed unsafe type casting without range checks
    • uint8 column vs 20000 constant → overflow error
    • uint32 column vs -1 constant → negative value error
  • Fix: Added checkNoNeedCast() validation for integer and float types
  • Impact: Prevents "data out of range" errors in row_constructor tests

3. Fix Float Precision Limits (Medium)

  • Issue: Float32 precision check used incorrect limit (100000 instead of 2^24)
  • Fix: Updated to correct IEEE 754 safe ranges:
    • Float32: ±2^24 (16777216) for exact integer representation
    • Float64: ±2^53 (conservative limit: MaxInt32)
  • Impact: Prevents precision loss in float comparisons

4. Add Early Detection for Decimal Comparisons (Medium)

  • Feature: Detect when decimal comparisons are always false/true
    • price = 99.991234567 (column scale=2) → always false
    • price <> 99.991234567 → always true
  • Optimization: Returns constant boolean instead of executing comparison
  • Impact: Eliminates unnecessary table scans

5. Skip Constant Folding for Division by Zero (Medium)

  • Feature: Added check to skip constant folding for division/modulo by zero
  • Reason: Allows runtime to check sql_mode and statement type for proper error handling
  • Impact: Correct error handling for division operations

6. Smart Type Selection for Decimal Literals (Low)

  • Feature: Choose decimal64 for small values, decimal128 for large values
  • Impact: Avoids unnecessary type promotion, preserves index usage

Performance Impact

  • Compilation: Negligible (<0.1%) - all checks are O(1)
  • Execution: No impact - optimizations reduce unnecessary operations
  • Memory: No additional allocations

@qodo-code-review

qodo-code-review Bot commented Jan 4, 2026 •

Copy link
Copy Markdown

PR Compliance Guide 🔍

Below is a summary of compliance checks for this PR:

Security Compliance
🟢
No security concerns identified No security vulnerabilities detected by AI analysis. Human verification advised for critical code.
Ticket Compliance
⚪
🎫 No ticket provided
  • Create ticket/issue
Codebase Duplication Compliance
⚪
Codebase context is not defined

Follow the guide to enable codebase context checks.

Custom Compliance
🟢
Generic: Comprehensive Audit Trails

Objective: To create a detailed and reliable record of critical system actions for security analysis
and compliance.

Status: Passed

Learn more about managing compliance generic rules or creating your own custom rules

Generic: Meaningful Naming and Self-Documenting Code

Objective: Ensure all identifiers clearly express their purpose and intent, making code
self-documenting

Status: Passed

Learn more about managing compliance generic rules or creating your own custom rules

Generic: Secure Error Handling

Objective: To prevent the leakage of sensitive system information through error messages while
providing sufficient detail for internal debugging.

Status: Passed

Learn more about managing compliance generic rules or creating your own custom rules

Generic: Secure Logging Practices

Objective: To ensure logs are useful for debugging and auditing without exposing sensitive
information like PII, PHI, or cardholder data.

Status: Passed

Learn more about managing compliance generic rules or creating your own custom rules

Generic: Security-First Input Validation and Data Handling

Objective: Ensure all data inputs are validated, sanitized, and handled securely to prevent
vulnerabilities

Status: Passed

Learn more about managing compliance generic rules or creating your own custom rules

🔴
Generic: Robust Error Handling and Edge Case Management

Objective: Ensure comprehensive error handling that provides meaningful context and graceful
degradation

Status:
Overflow edge cases: New integer DIV implementations use direct int64 division/casts without guarding overflow
cases (e.g., MIN_INT64 / -1 panic and uint64→int64 conversion overflow), violating robust
edge-case handling.

Referred Code
// integerDivSigned handles DIV for signed integer types
func integerDivSigned(parameters []*vector.Vector, result vector.FunctionResultWrapper, proc *process.Process, length int, selectList *FunctionSelectList) error {
	if length == 0 {
		return nil
	}

	paramType := parameters[0].GetType()
	rs := vector.MustFunctionResult[int64](result)
	rsVec := rs.GetResultVector()
	rss := vector.MustFixedColNoTypeCheck[int64](rsVec)
	rsNull := rsVec.GetNulls()
	shouldError := checkDivisionByZeroBehavior(proc, selectList)

	switch paramType.Oid {
	case types.T_int8:
		p1 := vector.GenerateFunctionFixedTypeParameter[int8](parameters[0])
		p2 := vector.GenerateFunctionFixedTypeParameter[int8](parameters[1])
		for i := uint64(0); i < uint64(length); i++ {
			v1, null1 := p1.GetValue(i)
			v2, null2 := p2.GetValue(i)
			if null1 || null2 || v2 == 0 {


 ... (clipped 132 lines)

Learn more about managing compliance generic rules or creating your own custom rules

  • Update
Compliance status legend 🟢 - Fully Compliant
🟡 - Partial Compliant
🔴 - Not Compliant
⚪ - Requires Further Human Verification
🏷️ - Compliance label

@qodo-code-review

qodo-code-review Bot commented Jan 4, 2026 •

Copy link
Copy Markdown

PR Code Suggestions ✨

Explore these optional code suggestions:

CategorySuggestion                                                                                                                                    Impact
Possible issue
Fix incorrect negative decimal conversion

Correct the logic for converting a negative Decimal128 to int64 by directly
casting the lower 64 bits, as it is already in two's complement form.

pkg/sql/plan/function/arithmetic.go [1538-1549]

 		// Extract integer value
-		// Decimal128 stores value as 128-bit two's complement
-		// Check sign bit (bit 127)
-		if divResult.Sign() {
-			// Negative - convert from two's complement
-			// Negate the 128-bit value first, then extract lower 64 bits
-			negated := divResult.Minus()
-			rss[i] = -int64(negated.B0_63)
-		} else {
-			// Positive or zero
-			rss[i] = int64(divResult.B0_63)
-		}
+		// Decimal128 stores value as 128-bit two's complement.
+		// The value has been scaled and checked for int64 range.
+		// We can now safely cast the lower 64 bits.
+		rss[i] = int64(divResult.B0_63)
  • Apply / Chat
Suggestion importance[1-10]: 9

__

Why: The suggestion correctly identifies a bug in the two's complement conversion from Decimal128 to int64, which would lead to incorrect results for negative numbers.

High
✅ Fix unsigned integer overflow bug
Suggestion Impact:The commit adjusts an expected test output for a BIGINT UNSIGNED DIV case from -1 to the correct positive value (9223372036854775807 for (MAX_UINT64-1)/2), addressing the same kind of unsigned DIV overflow/incorrect signed result highlighted by the suggestion, though for a different input than max unsigned DIV 1.

code diff:

 SELECT CAST(18446744073709551614 AS BIGINT UNSIGNED) DIV CAST(2 AS BIGINT UNSIGNED);  -- (MAX_UINT64-1)/2 = MAX_INT64
 ➤ cast(18446744073709551614 as bigint unsigned) div cast(2 as bigint unsigned)[-5,64,0]  𝄀
--1
+9223372036854775807

Correct the expected result for BIGINT UNSIGNED DIV 1 from -1 to
18446744073709551615 to fix an apparent overflow bug.

test/distributed/cases/function/func_div_by_zero.result [242-244]

 SELECT CAST(18446744073709551615 AS BIGINT UNSIGNED) DIV CAST(1 AS BIGINT UNSIGNED);
 ➤ cast(18446744073709551615 as bigint unsigned) div cast(1 as bigint unsigned)[-5,64,0]  𝄀
--1
+18446744073709551615

[Suggestion processed]

Suggestion importance[1-10]: 9

__

Why: The suggestion correctly identifies a critical bug where a DIV operation on the maximum BIGINT UNSIGNED value results in an overflow, returning -1 instead of the correct large unsigned value, indicating a flaw in the operator's implementation.

High
Fix incorrect test result data

Fix the test result for INSERT IGNORE to show unique ids 1, 2, and 3 instead of
incorrect duplicates, and add a TRUNCATE TABLE statement for test isolation.

test/distributed/cases/function/func_div_by_zero_strict_mode.result [35-45]

+TRUNCATE TABLE t_strict_div;
 INSERT IGNORE INTO t_strict_div VALUES (1, 10/0);
 INSERT IGNORE INTO t_strict_div VALUES (2, 10 DIV 0);
 INSERT IGNORE INTO t_strict_div VALUES (3, 10 % 0);
 SELECT * FROM t_strict_div ORDER BY id;
 ➤ id[4,32,0]  ¦  val[4,32,0]  𝄀
 1  ¦  null  𝄀
-1  ¦  null  𝄀
 2  ¦  null  𝄀
-2  ¦  null  𝄀
-3  ¦  null  𝄀
 3  ¦  null
  • Apply / Chat
Suggestion importance[1-10]: 8

__

Why: The suggestion correctly identifies that the test result file shows duplicate ids, which contradicts the test logic of inserting unique ids (1, 2, 3), and points out a likely copy-paste error, which is a critical issue for test validity.

Medium
General
Treat INSERT IGNORE as non-error

Explicitly handle INSERT IGNORE statements in the checkDivisionByZeroBehavior
function to ensure division by zero always returns NULL and never raises an
error for this case.

pkg/sql/plan/function/baseTemplate.go [1829-1840]

-// In INSERT/UPDATE: check sql_mode
-resolveFunc := proc.GetResolveVariableFunc()
-if resolveFunc == nil {
+// In INSERT/UPDATE: check for IGNORE first
+stmtTypeUpper := strings.ToUpper(strings.TrimSpace(stmtType))
+// Treat INSERT IGNORE as always return NULL
+if strings.HasPrefix(stmtTypeUpper, "INSERT") && strings.Contains(stmtTypeUpper, "IGNORE") {
     atomic.StoreInt32(&proc.Base.DivByZeroErrorMode, 0)
     return false
 }
-mode, err := resolveFunc("sql_mode", true, false)
-...
 isInsertOrUpdate := stmtTypeUpper == "INSERT" || stmtTypeUpper == "UPDATE" || queryTypeUpper == "DML"
 if !isInsertOrUpdate {
     atomic.StoreInt32(&proc.Base.DivByZeroErrorMode, 0)
     return false
 }

[To ensure code accuracy, apply this suggestion manually]

Suggestion importance[1-10]: 8

__

Why: The suggestion correctly points out that INSERT IGNORE is a special case for division-by-zero handling that was missed in the PR, preventing a potential bug.

Medium
✅ Avoid code duplication across packages
Suggestion Impact:The commit partially followed the refactoring intent by exporting the helper and updating the call site: isDivisionByZeroConstant was renamed to IsDivisionByZeroConstant and the constant-folding check now calls IsDivisionByZeroConstant(fn). However, the helper still remains in constant_fold.go (and no utils.go consolidation is shown), so the duplication-removal portion of the suggestion was not implemented.

code diff:

 	// Skip constant folding for division/modulo by zero.
 	// This allows runtime to check sql_mode and statement type for proper error handling.
-	if isDivisionByZeroConstant(fn) {
+	if IsDivisionByZeroConstant(fn) {
 		return expr
 	}
 
@@ -659,6 +687,11 @@
 	case *plan.Expr_Lit, *plan.Expr_T, *plan.Expr_Vec:
 		return true
 	case *plan.Expr_F:
+		// CASE expressions should always be evaluated at runtime to preserve
+		// branch semantics; treat them as non-constant.
+		if fid, _ := function.DecodeOverloadID(ef.F.Func.GetObj()); fid == function.CASE {
+			return false
+		}
 		overloadID := ef.F.Func.GetObj()
 		f, exists := function.GetFunctionByIdWithoutError(overloadID)
 		if !exists {
@@ -692,10 +725,10 @@
 	}
 }
 
-// isDivisionByZeroConstant checks if the expression is a division/modulo operation
+// IsDivisionByZeroConstant checks if the expression is a division/modulo operation
 // where the divisor is a constant zero or either operand is NULL.
 // We skip constant folding for such cases to allow runtime to properly handle them.
-func isDivisionByZeroConstant(fn *plan.Function) bool {
+func IsDivisionByZeroConstant(fn *plan.Function) bool {
 	fid, _ := function.DecodeOverloadID(fn.Func.GetObj())

Remove the duplicated isDivisionByZeroConstant and isZeroLiteral functions from
constant_fold.go and use a single, exported version from utils.go to avoid code
duplication.

pkg/sql/plan/rule/constant_fold.go [695-752]

-// isDivisionByZeroConstant checks if the expression is a division/modulo operation
-// where the divisor is a constant zero or either operand is NULL.
-// We skip constant folding for such cases to allow runtime to properly handle them.
-func isDivisionByZeroConstant(fn *plan.Function) bool {
-	fid, _ := function.DecodeOverloadID(fn.Func.GetObj())
-	if fid != function.DIV && fid != function.INTEGER_DIV && fid != function.MOD {
-		return false
-	}
-	if len(fn.Args) < 2 {
-		return false
-	}
+// NOTE: The following functions should be removed from this file.
+// They should be exported from 'pkg/sql/plan/utils.go' and used from there.
+//
+// In 'pkg/sql/plan/utils.go':
+// func IsDivisionByZeroConstant(fn *plan.Function) bool { ... }
+// func IsZeroLiteral(lit *plan.Literal) bool { ... }
+//
+// In 'pkg/sql/plan/rule/constant_fold.go', update the call site:
+// if plan.IsDivisionByZeroConstant(fn) { ... }
 
-	// Check if either operand is NULL
-	for _, arg := range fn.Args {
-		lit := arg.GetLit()
-		if lit != nil && lit.GetIsnull() {
-			return true
-		}
-	}
-
-	divisor := fn.Args[1]
-	lit := divisor.GetLit()
-	if lit == nil {
-		return false
-	}
-	return isZeroLiteral(lit)
-}
-
-// isZeroLiteral checks if a literal value is zero
-func isZeroLiteral(lit *plan.Literal) bool {
-	switch v := lit.Value.(type) {
-	case *plan.Literal_I8Val:
-		return v.I8Val == 0
-	case *plan.Literal_I16Val:
-		return v.I16Val == 0
-	case *plan.Literal_I32Val:
-		return v.I32Val == 0
-	case *plan.Literal_I64Val:
-		return v.I64Val == 0
-	case *plan.Literal_U8Val:
-		return v.U8Val == 0
-	case *plan.Literal_U16Val:
-		return v.U16Val == 0
-	case *plan.Literal_U32Val:
-		return v.U32Val == 0
-	case *plan.Literal_U64Val:
-		return v.U64Val == 0
-	case *plan.Literal_Fval:
-		return v.Fval == 0
-	case *plan.Literal_Dval:
-		return v.Dval == 0
-	case *plan.Literal_Decimal64Val:
-		return v.Decimal64Val.A == 0
-	case *plan.Literal_Decimal128Val:
-		return v.Decimal128Val.A == 0 && v.Decimal128Val.B == 0
-	}
-	return false
-}
-

[Suggestion processed]

Suggestion importance[1-10]: 7

__

Why: The suggestion correctly identifies significant code duplication between constant_fold.go and utils.go, and proposes a sound refactoring to improve maintainability.

Medium
  • Update

@mergify

mergify Bot commented Jan 7, 2026 •

Copy link
Copy Markdown
Contributor

Merge Queue Status

✅ The pull request has been merged at 47c0a11

This pull request spent 55 minutes 12 seconds in the queue, including 55 minutes running CI.
The checks were run in-place.

Required conditions to merge
  • #approved-reviews-by >= 1 [🛡 GitHub branch protection]
  • #changes-requested-reviews-by = 0 [🛡 GitHub branch protection]
  • #review-threads-unresolved = 0 [🛡 GitHub branch protection]
  • branch-protection-review-decision = APPROVED [🛡 GitHub branch protection]
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone Compose CI / multi cn e2e bvt test docker compose(PESSIMISTIC)
    • check-neutral = Matrixone Compose CI / multi cn e2e bvt test docker compose(PESSIMISTIC)
    • check-skipped = Matrixone Compose CI / multi cn e2e bvt test docker compose(PESSIMISTIC)
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone Standlone CI / Multi-CN e2e BVT Test on Linux/x64(LAUNCH, PROXY)
    • check-neutral = Matrixone Standlone CI / Multi-CN e2e BVT Test on Linux/x64(LAUNCH, PROXY)
    • check-skipped = Matrixone Standlone CI / Multi-CN e2e BVT Test on Linux/x64(LAUNCH, PROXY)
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone Standlone CI / e2e BVT Test on Linux/x64(LAUNCH, PESSIMISTIC)
    • check-neutral = Matrixone Standlone CI / e2e BVT Test on Linux/x64(LAUNCH, PESSIMISTIC)
    • check-skipped = Matrixone Standlone CI / e2e BVT Test on Linux/x64(LAUNCH, PESSIMISTIC)
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone CI / SCA Test on Ubuntu/x86
    • check-neutral = Matrixone CI / SCA Test on Ubuntu/x86
    • check-skipped = Matrixone CI / SCA Test on Ubuntu/x86
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone CI / UT Test on Ubuntu/x86
    • check-neutral = Matrixone CI / UT Test on Ubuntu/x86
    • check-skipped = Matrixone CI / UT Test on Ubuntu/x86
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone Compose CI / multi cn e2e bvt test docker compose(Optimistic/PUSH)
    • check-neutral = Matrixone Compose CI / multi cn e2e bvt test docker compose(Optimistic/PUSH)
    • check-skipped = Matrixone Compose CI / multi cn e2e bvt test docker compose(Optimistic/PUSH)
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone Standlone CI / e2e BVT Test on Linux/x64(LAUNCH,Optimistic)
    • check-neutral = Matrixone Standlone CI / e2e BVT Test on Linux/x64(LAUNCH,Optimistic)
    • check-skipped = Matrixone Standlone CI / e2e BVT Test on Linux/x64(LAUNCH,Optimistic)
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone Upgrade CI / Compatibility Test With Target on Linux/x64(LAUNCH)
    • check-neutral = Matrixone Upgrade CI / Compatibility Test With Target on Linux/x64(LAUNCH)
    • check-skipped = Matrixone Upgrade CI / Compatibility Test With Target on Linux/x64(LAUNCH)
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone Utils CI / Coverage
    • check-neutral = Matrixone Utils CI / Coverage
    • check-skipped = Matrixone Utils CI / Coverage

This branch was previously deployed

1 inactive deployment
ci — 47c0a111 Deployed Jan 7, 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 Review effort 4/5 size/XXL Denotes a PR that changes 2000+ lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants