Skip to content

fix: align explicit integer string casts with MySQL - #25431

Closed
ck89119 wants to merge 46 commits into
matrixorigin:mainfrom
ck89119:issue-25216-main
Closed

ck89119 wants to merge 46 commits into
matrixorigin:mainfrom
ck89119:issue-25216-main

Conversation

@ck89119

@ck89119 ck89119 commented Jul 3, 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 #25216

What this PR does / why we need it:

This PR aligns explicit string-to-integer casts with MySQL integer-prefix
semantics.

For example:

SELECT CAST('7e0' AS SIGNED),
       CAST('7e+2' AS SIGNED),
       CAST('1.5e0' AS SIGNED),
       CAST('7e2' AS UNSIGNED);

now returns 7, 7, 1, 7. Explicit integer casts consume only the leading
decimal integer prefix; they do not consume the exponent or fractional suffix.

The change is restricted to the explicit CAST path. Assignment casts,
implicit comparison/arithmetic conversion, prepared statements, joins,
indices, temporal arithmetic, and warning behavior are unchanged. Existing
MatrixOne binary/octal/hexadecimal string extensions continue to use their
strict radix parser.

Validation:

  • make build
  • full pkg/sql/plan/function CGo unit tests
  • focused race test repeated 100 times
  • full pkg/sql/plan/function race test
  • focused golangci-lint: 0 issues
  • make static-check reached the full lint stage but is currently blocked by
    two pre-existing unused methods on main in
    pkg/common/malloc/sane_allocator_cache.go

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

I think this still needs changes before merge.

The direct numeric-string comparison fix looks materially better at this head, but one remaining blocker is that the index rewrites still serialize exact numeric-vs-string predicates with the raw numeric RHS type.

That is not semantics-preserving for indexed VARCHAR keys.

Evidence chain:

  • comparisonTypeCastRule no longer forces every numeric-vs-MySQL-string comparison through DOUBLE, so the comparison kernel can now distinguish exact numeric/string cases again.
  • but master-index and composite/prefix index rewrites still build lookup keys by serializing the raw constant directly:
    • apply_indices_master.go builds serial_full(colSeq, args[1]) for equality / range probes;
    • apply_indices.go builds prefix_eq / prefix_between / prefix_in_range keys from the raw literal side the same way.
  • SerialHelper encodes numeric and string values differently: int64 goes through EncodeInt64, while varchar/text goes through EncodeStringType.

So a predicate like WHERE s = 1 on an indexed VARCHAR column is still unsafe to rewrite as an index probe on serialized numeric 1. The stored index key was built from the string payload, not from the numeric encoding. Rows such as s='1' are already enough to show the encoding mismatch; rows like '01' or '1abc' make the semantic gap even wider under MySQL-style leading-integer comparison.

This means the optimizer can still underfetch exact numeric-vs-string predicates when it chooses the index path, even though the non-indexed comparison semantics were fixed.

Suggested fix: block master/composite/prefix index rewrites for exact numeric <-> MySQL string predicates (same idea as the mixed exact numeric/string guard in expr_opt), or normalize the lookup key through the same string-comparison semantics before serializing. As long as the index path serializes the raw numeric RHS, it does not match the repaired comparison semantics.

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

Requesting changes on d0edc8dbbc6f1d2c639164dac1568e299cd57b76.

There are two correctness blockers, and the current red e2e jobs reproduce their blast radius.

  1. The cast modes encode the wrong MySQL contracts. integerStringForCast currently groups castImplicit and castExplicit and evaluates the full decimal/exponent, while castAssignment truncates the parsed decimal. MySQL 8.0.44 does the opposite at these boundaries:
SELECT CAST('7e2' AS SIGNED), CAST('1.5' AS SIGNED),
       CAST('9.007199254740993e15' AS SIGNED);
-- 7, 1, 9

CREATE TABLE t(i BIGINT);
INSERT INTO t VALUES ('7e2'), ('1.5'), ('-1.5'),
                     ('9.007199254740993e15');
SELECT i FROM t;
-- 700, 2, -2, 9007199254740993

The new tests instead require explicit '7e2' -> 700 and assignment '1.5' -> 1, so they are passing against an incorrect oracle. This also means the original issue is not closed systemically: '7e0' happens to mask whether exponent syntax was consumed.

  1. Mixed numeric/string comparisons have been changed from MySQL DOUBLE semantics to exact-decimal semantics. The binder folds numeric string literals to exact integer/decimal values, and the runtime path uses math/big for every remaining VARCHAR/TEXT-vs-integer/decimal comparison. MySQL explicitly specifies that string/numeric comparison is floating-point in this case: https://dev.mysql.com/doc/refman/8.0/en/type-conversion.html. MySQL 8.0.44 confirms:
SELECT '9007199254740992' = 9007199254740993;
-- 1

CREATE TABLE t(s VARCHAR(64), i BIGINT);
INSERT INTO t VALUES ('9007199254740992', 9007199254740993);
SELECT s=i FROM t;
-- 1

This head returns exact inequality instead. Besides compatibility, mixedNumericStringCompare now allocates/parses big.Int values and formats the numeric operand for every row; that is a serious hot-path regression for scans and nested-loop fallback joins. The index/join guards then disable optimizations to preserve this non-MySQL behavior, compounding the cost.

The latest CI is consistent with these problems, not an unrelated flaky failure: all three e2e jobs fail, repeatedly including func_cast, CHAR/VARCHAR predicates, BETWEEN, JOIN and in_domain cases. For example, func_cast.test expects 3223093.0 for 1.0 * (X'312E35' | X'312E35') but the head returns 1.0; the same mismatch occurs in all three jobs.

Please establish one conversion matrix first (explicit CAST, assignment, implicit arithmetic, comparison; exact/approximate; prefix/suffix/exponent/overflow), validate each cell against MySQL, and then route binder, constant folding, vector kernels, index rewrites and join planning through those contracts. In particular, do not repair comparison precision beyond MySQL by changing its documented coercion rule; it creates both semantic drift and optimizer/performance fallout.

@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 previous raw numeric-key serialization issue is addressed by the new index/composite/join guards at this head. I still cannot approve because the broader comparison rewrite has multiple confirmed correctness regressions.

  1. [High][correctness] Mixed exact numeric/string predicates remain marked zonemappable while storage pushdown assumes homogeneous encodings. list_operator.go:27-32 keeps = globally Function_ZONEMAPPABLE and returns success without casting mixed operands. The function kernel understands this pair, but readutil consumes the original RHS bytes as the column key (expr_filter.go:985-999). This is not semantics-preserving. The current CI reproduces both forms in three independent BVT jobs: VARCHAR BETWEEN 1 AND 3 returns no rows (and the corresponding DELETE under-deletes), while INT = empty-string reaches ZoneMap.ContainsKey and panics in DecodeInt32 on a zero-length key. The same run also has lockop.fetchVarlenaRows type panics after affected DELETE/join plans. Please make mixed comparison forms non-zonemappable/non-fast-filterable unless storage receives a key encoded in the column domain, and add post-flush BVT coverage for sorted and unsorted =, ranges/BETWEEN, IN, and DELETE/UPDATE. Function-only tests cannot cover this boundary. Failing jobs: compose pessimistic, proxy multi-CN, standalone pessimistic.

  2. [High][correctness/availability] Decimal128 is the wrong intermediate for integer truncation. integerStringForCast parses the full token with types.Parse128 before truncating (func_cast.go:5127-5174). That parser stores the exponent in int32 and rounds inputs beyond Decimal128 precision, so the intermediate can already differ from the source value. Two deterministic current-head repros are:

    • integerStringForCast("1e4294967295", castExplicit) returns "0" instead of an out-of-range error because the exponent wraps. Nearby wrapped exponents can also amplify a tiny input into tens of millions of ScaleTruncate iterations.
    • integerStringForCast("0.999999999999999999999999999999999999999", castExplicit) returns "1", although the documented toward-zero conversion must return "0"; Parse128 rounds across the integer boundary before truncation.
      Both paths also feed SIGNED/UNSIGNED and assignment modes. Please parse sign/digits/exponent with explicit bounds and derive the truncated integer without first rounding to 38 decimal digits. Add exponent-overflow and >38-fraction regressions across all modes; the existing 7e2/1.5 shapes are not sufficient.
  3. [Compatibility/design blocker] The new exact comparison kernel does not implement the MySQL contract claimed by this PR. mixedNumericStringCompare performs arbitrary-precision decimal comparison (func_compare.go:33-207). The MySQL manual explicitly says string-vs-number comparisons use DOUBLE and even documents that 9223372036854775807 compares equal to 9223372036854775806 through this approximation: https://dev.mysql.com/doc/refman/8.0/en/type-conversion.html. The current kernel deliberately returns false for that equality. My earlier precision review was too broad: blocking raw numeric index-key rewrites was necessary, but replacing the SQL comparison semantics with exact arithmetic is a separate behavioral decision. Bug #101806 concerns prepared-parameter type reprepare, not a general mandate to make all literal/column comparisons exact: https://bugs.mysql.com/107811. Please either scope this PR back to issue #25216 (CAST scientific notation) and the required safe coercion changes, or get an explicit decision for this intentional divergence and update the PR contract/tests accordingly.

  4. [Test hygiene/CI] The result fixtures are not merge-ready. Many unrelated result files were mechanically converted to a different table format. For example, the changed dtype/enum.result expectations produce an extra trailing field for DESCRIBE/SHOW rows, while runtime output does not; this accounts for many deterministic BVT failures. Other failures are real underfetch/panics and must not be accepted by regenerating results. Please revert unrelated fixture churn and regenerate only semantic changes with the same mo-tester/parser configuration used by CI. Coverage and three BVT checks are currently red.

Local validation on d0edc8dbbc6f1d2c639164dac1568e299cd57b76: go test ./pkg/sql/plan/function ./pkg/sql/plan and git diff --check pass. I also ran deterministic temporary repro tests for item 2 and removed them afterward; the review worktree is clean. A focused helper benchmark did not show a latency blocker (exact compare ~191 ns vs ParseFloat ~829 ns), although the exact path allocates 16 B/row, so performance is not the basis of this request.

@aunjgr aunjgr 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 cast refactor still has correctness blockers: explicit casts and assignments disagree on fractional and exponent forms; mixed numeric/string comparisons diverge from the intended DOUBLE semantics; zone-map rewrite can underfetch for mixed values; and Decimal128 intermediate handling can wrap huge exponents or over-round long fractions. Please separate assignment coercion from explicit CAST and comparison planning, then cover execution and zone-map equivalence for the same corpus.

aunjgr
aunjgr previously requested changes Jul 20, 2026

@aunjgr aunjgr 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 cast refactor still has correctness blockers: explicit casts and assignments disagree on fractional and exponent forms; mixed numeric/string comparisons diverge from the intended DOUBLE semantics; zone-map rewrite can underfetch for mixed values; and Decimal128 intermediate handling can wrap huge exponents or over-round long fractions. Please separate assignment coercion from explicit CAST and comparison planning, then cover execution and zone-map equivalence for the same corpus.

ck89119 added 9 commits July 23, 2026 15:27
# Conflicts:
#	pkg/sql/plan/base_binder.go
#	pkg/sql/plan/function/func_cast.go
#	pkg/sql/plan/function/func_cast_test.go
#	pkg/sql/plan/function/function_id.go
#	pkg/sql/plan/function/function_id_test.go
#	test/distributed/cases/dtype/date.result
#	test/distributed/cases/dtype/text_1.result
#	test/distributed/cases/function/func_cast.result
#	test/distributed/cases/function/func_coalesce.result
#	test/distributed/cases/optimizer/in_domain.result

This branch had an error being deployed

1 failed deployment
ci — 80f2aa71 Deployed Jul 26, 2026 by ck89119 via Matrixone Utils CI / Coverage #42595
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