Skip to content

[4.2-dev] fix(sql): preserve complete strings and serialized JSON in omitted-length CAST AS CHAR - #32438

Closed
gouhongshen wants to merge 26 commits into
matrixorigin:4.2-devfrom
gouhongshen:agent/issue-32336-4.2-dev-0690474a
Closed

gouhongshen wants to merge 26 commits into
matrixorigin:4.2-devfrom
gouhongshen:agent/issue-32336-4.2-dev-0690474a

Conversation

@gouhongshen

@gouhongshen gouhongshen commented Nov 10, 2026 •

Copy link
Copy Markdown
Contributor

What type of PR is this?

  • BUG

Which issue(s) this PR fixes:

Related to #32336, Related to #32374

What this PR does / why we need it:

Root cause

CAST(expr AS CHAR) and CONVERT(expr, CHAR) without an explicit length materialized the cast target as VARCHAR(65535) in the grammar, and the cast executor width-enforced that target, silently truncating every result over 64 KiB (#32336: strings and stored LONGTEXT reads; #32374: serialized JSON documents and scalar strings, which also invalidated JSON_VALID).

A second gap affected the JSON path only: an explicit CAST/CONVERT(<json scalar string> AS/TO CHAR) returned the unquoted payload because character-target casts never bound the dedicated explicit-cast overload, and jsonToStr unconditionally unquoted scalar strings. MySQL's JSON conversion rules require the serialized form (enclosing quotes and escaping) for explicit casts; the issue itself notes JSON_UNQUOTE is not a replacement when the original representation of scalar strings is needed.

Changes

  • pkg/sql/parsers/dialect/mysql/mysql_sql.y: both omitted-length CHAR branches (CAST/:: and CONVERT) map the Oid to the unbounded TEXT type (MYSQL_TYPE_TEXT) while keeping the re-parseable omitted-length char signature (FamilyString char, DisplayWith=-1) — see the Review follow-up #4 section for why the earlier text textual signature was reverted. This removes the truncating width and keeps the canonical rendering a re-parseable bare char: CREATE TABLE ... AS SELECT rebuilds its INSERT ... SELECT by re-rendering and re-parsing the source select (pkg/sql/plan/build_ddl.go), and char re-enters the same omitted-length action instead of binding an explicit TEXT cast. mysql_sql.go regenerated with the committed goyacc; the regeneration is verified byte-identical.
  • pkg/sql/plan/base_binder.go: explicit character and binary CAST/CONVERT targets now bind the dedicated explicit-cast overload (the 4.2-dev-applicable subset of fix: preserve prepared ROUND and TRUNCATE value domains #29508); the existing DECIMAL and LONGLONG rules are unchanged.
  • pkg/sql/plan/function/func_cast.go: in explicit cast mode a JSON scalar string serializes with its enclosing quotes and escaping (MySQL JSON conversion rules); implicit string coercion keeps returning the unquoted payload.
  • Tests:
    • pkg/sql/parsers/dialect/mysql/cast_omitted_length_test.go (new): omitted-length target and render-parity assertions for every spelling (CAST, ::, CONVERT), re-parsing back to the unbounded TEXT target; explicit-length and omitted-VARCHAR controls unchanged.
    • pkg/sql/plan/base_binder_cast_omitted_length_test.go (new): binder-level target construction (TEXT family/Oid, unbounded width), canonical hex-literal cast whitelist with the TEXT target.
    • pkg/sql/plan/function/func_cast_omitted_char_length_test.go (new) + func_cast_width_test.go: executor-level large-string/JSON preservation, explicit scalar serialization (quoted/escaped forms, round-trip), explicit-mode width behavior, implicit unquoted control, explicit CHAR(N) truncation control.
    • test/distributed/cases/function/func_cast_omitted_char_length.test/.result (new BVT): the issue reproductions for strings and JSON, stored-column reads, 65535/65536-byte boundaries, a 262,140-byte/87,380-character multibyte value, NULL/empty, oversized-REPEAT NULL control ([Bug]: SHA2 truncates LONGTEXT input to 65,535 bytes #28103), explicit CHAR(10) control, JSON documents and escaped scalars with complete-serialization/round-trip assertions, and both CREATE TABLE ... AS SELECT compositions (string and JSON) with information_schema/SHOW CREATE TABLE metadata checks.
    • Aligned recorded expectations of existing BVT files that pinned the old VARCHAR rendering/metadata for these casts: func_datetime_addtime/subtime/timediff, func_cast (the two convert(..., char) rows), func_coalesce (the two CAST(COALESCE(a,a) AS CHAR) headings), func_bit_count (three CAST(... AS CHAR) labels), func_avg_numeric_contract. Unrelated stale rows in these files are proven pre-existing on the base commit (byte-identical red on the pristine base binary) and intentionally untouched.
    • pkg/sql/plan/build_util_test.go, pkg/sql/plan/mysql_special_order_provenance_test.go: aligned the pre-existing plan-level UTs that still pinned the legacy VARCHAR mapping for omitted-length casts — CONVERT(x, CHAR) resolution (was VARCHAR(65535), now the unbounded T_text target with width 0) and the ENUM/SET special-order provenance cases keyed through CAST(... AS CHAR) (plain-union, derived, window and GROUP_CONCAT order keys now read the TEXT target). Only the asserted result types moved from VARCHAR to TEXT; the provenance contracts ("stays lexical"/"clears provenance") and the explicit CHAR(N)/BINARY controls are unchanged, and the recursive-CTE cast case keeps its VARCHAR sort key because it flows through the provenance-clearing path rather than the cast target. Surfaced by the merge-head CI UT run; the complete ./pkg/sql/plan package suite is green after the alignment commit.

Issue-to-test proof

  • [Bug]: CAST AS CHAR without a length silently truncates large strings #32336: on the base commit SELECT LENGTH(CAST(CONCAT(REPEAT('a',50000),REPEAT('b',50000)) AS CHAR)) returned 65535; on this PR it returns 100000 with the final bytes 6262 (BVT + independent blind-challenge reproduction: 100000/100000/61/6262). Stored LONGTEXT and operator expr::char paths preserve the same value; CAST ... AS CHAR(10) still truncates to 10 characters; CTAS of the cast now succeeds and derives a text/text(0) column carrying the complete 100,000-byte value (previously a syntax error via the un-reparseable rendering).
  • JSON cast to CHAR silently truncates values beyond 65535 bytes #32374: on the base commit LENGTH(CAST(JSON_OBJECT('s', @payload) AS CHAR)) returned 65535 with JSON_VALID(...)=0; on this PR the same query returns 100009, valid, ending a"}. Stored JSON columns keep the complete valid serialization pre- and post-commit; explicit casts of a 100,000-byte JSON scalar string return the 100,002-byte quoted serialization (opening/closing byte 22, JSON round-trip recovers all 100,000 bytes), an escaped scalar a"b serializes as hex 22615C226222; the JSON-derived CTAS column keeps the complete valid document (100,009 bytes, text/text(0)).

Test commands

# focused parser/binder/executor UT (69 top-level tests; also proven red on the base tree for the new tests)
.agents/skills/mo-dev/scripts/mo-cgo-test -count=1 -run 'TestCast|TestJSONToStr|TestExplicitCast|TestCanonicalStringLiteralCast' -v ./pkg/sql/plan/function/ ./pkg/sql/plan/
.agents/skills/mo-dev/scripts/mo-cgo-test -count=1 -run 'TestCast|TestValid' -v ./pkg/sql/parsers/dialect/mysql/
# pre-existing plan UTs aligned to the unbounded TEXT target (proven red on the unaligned head) plus the full owning-package suite
.agents/skills/mo-dev/scripts/mo-cgo-test -count=1 -run '^(TestConvertCharBinaryTypeResolution|TestMySQLSpecialOrderProvenanceThroughQueryBoundaries|TestMySQLSpecialOrderProvenanceInGroupConcat)$' -v ./pkg/sql/plan/
.agents/skills/mo-dev/scripts/mo-cgo-test -count=1 -v ./pkg/sql/plan/
# grammar regeneration gate
cd pkg/sql/parsers/dialect/mysql && make
# BVT (mo-tester run with metadata comparison; func_cast_omitted_char_length 39/39 and the updated files 100%)
# full focused set: func_datetime_addtime/subtime/timediff, func_avg_numeric_contract, func_bit_count,
# func_cast_omitted_char_length, func_cast, func_coalesce, dtype/varchar, zz_dml/select/select

Independent black-box verification (16 cases across both issues) passed all dimension checks in this PR's venue: exact reproductions, stored/transactional reads, protocol metadata, operator spelling, both CTAS compositions, NULL/explicit-length controls, 65535/65536 boundaries, multibyte and JSON serialized-size boundaries, and quoted/escaped scalar serialization; make build and go vet clean.

Residual risks

  • Result-set and CTAS metadata for omitted-length CHAR casts is now the unbounded TEXT family (BLOB, length 0 / information_schema text/text(0)) instead of VARCHAR(65535) — intentional, MySQL-aligned, and pinned by metadata-annotated BVT rows.
  • Explicit CHAR(N) still silently truncates; for JSON it now truncates the serialized form (MySQL-consistent; asserted as a control).
  • Functions with varchar/char-only signatures (LEFT/RIGHT) still pre-truncate TEXT results through an implicit convert — pre-existing divergence, documented in tests.
  • Pre-existing BVT mismatches unrelated to this PR remain and are deliberately untouched (proven byte-identically pre-existing on the pristine base binary): dtype/char.test 6 rows, func_cast.test row 772, func_coalesce.test 4 temporal datetime(6, 6)/time(6, 6)-rendering rows.
  • Oversized REPEAT (>65535) still returns NULL ([Bug]: SHA2 truncates LONGTEXT input to 65,535 bytes #28103) and single-argument CONCAT is still rejected — controls retained.

Review follow-up (2026-11-10): two reviewer-found regressions fixed

Review of the initial head found two downstream regressions of the omitted-length target widening; both were reproduced on the PR head before the fix and are green after.

  • REVERSE truncated omitted-length cast results well below 64 KiB. REVERSE's overloads are ordered CHAR, VARCHAR, BLOB; a TEXT input matches all three by implicit cast at equal cost, and fixedTypeMatch keeps the first match, inserting a CHAR(255) cast that silently truncated before reversal: LENGTH(REVERSE(CAST(REPEAT('a', 300) AS CHAR))) fell from 300 on the base to 255. Fixed by adding a T_text overload to REVERSE (returns TEXT) so CAST/CONVERT-to-CHAR results bind directly with no narrowing cast. Covered by TestReverseTextKeepsOmittedLengthCastValue (binding + executor) and new BVT rows (300-byte probe, 100000-byte probe, multibyte, NULL, both CAST and CONVERT spellings).
  • LEAST/GREATEST stopped binding JSON+temporal compositions of omitted-length casts. leastGreatestJSONDateTemporalType whitelisted CHAR/VARCHAR and rejected TEXT, so LEAST(CONVERT('2024-01-01', CHAR), CAST('2024-01-02' AS DATE), CAST('"2024-01-03"' AS JSON)) failed to bind (the base returned 2024-01-01). Fixed by accepting TEXT in that whitelist: resolution now mirrors the CHAR/VARCHAR peer path exactly (VARCHAR result, temporal inputs kept, other peers cast to VARCHAR; blob/binary peers stay rejected). Covered by the updated TestLeastGreatestTemporalResolution, the new TestLeastGreatestJSONTemporalTextComposition binding+executor UT, and new BVT rows for LEAST and GREATEST in both spellings plus the NULL-peer edge.

A full audit of the fixedTypeMatch overload registry confirmed REVERSE was the only function where a previously direct VARCHAR match fell into a width-narrowing CHAR cast under TEXT input (LTRIM/RTRIM/EMPTY truncated VARCHAR inputs identically before this PR; LEFT/RIGHT/HEX/LOCATE and similar first-listed-VARCHAR functions route TEXT to VARCHAR(65535) exactly as before, bounded only at the 64 KiB cap), and binary operators bind text/text directly through the comparison cast rules.

Validation for this round: pre-fix tree reproduced both defects (REVERSE resolving with a CHAR(255) implicit-cast target from TEXT; the LEAST/GREATEST composition failing to bind); post-fix the full pkg/sql/plan/function package suite, the focused pkg/sql/plan and parser suites, and the regenerated func_cast_omitted_char_length BVT (pure append to the result file, all pre-existing rows byte-identical) passed 43/43 in compare mode against a local build of this branch.

CI follow-up (2026-11-10): stale greatest JSON+date TEXT expectation updated

The multi-CN PROXY compose BVT run on a24c7455a8 failed (multi cn e2e bvt test docker compose(PROXY), run 42764601295: 70947 statements, 1 failure) and, in turn, blocked the Coverage merge job (prerequisites_ready: false — a required producer never published its coverage profile). Root cause: one stale recorded expectation in greatest_least_numeric.result still asserted the pre-mapping bind failure

invalid argument function greatest, bad value [JSON DATE TEXT]

for SELECT GREATEST(json_extract('"2020-01-02"', '$'), CAST('2020-01-01' AS DATE), CAST('x' AS TEXT));. With TEXT accepted in the packed-date JSON+temporal branch (review follow-up above), this composition resolves exactly like its VARCHAR peer and now fails at the parse step — invalid argument parsedate, bad value x, byte-identical to the VARCHAR-spelled peer (... , 'x')) and to the LEAST spelling on this branch's binary. fff1622110 updates that expectation and pins the unchanged VARCHAR-peer behavior beside it; the blob/binary rejections in the same section stay recorded.

Local verification for this round: both spellings produce byte-identical errors on a locally launched build of this branch; greatest_least_numeric.sql matches every value/error row (161 statements — the only diffs are the two known local-only RSMetaData-annotation rows, value rows byte-identical; CI's mo-tester build does not compare those annotations); func_cast_omitted_char_length passes 43/43; the focused least/greatest + REVERSE UT selection is green (124 invocations, TestLeastGreatestTemporalResolution, TestLeastGreatestJSONTemporalTextComposition, TestReverseTextKeepsOmittedLengthCastValue all pass).


Review follow-up 2 (2026-11-10): operator rewrites and date-extraction string paths restored for TEXT

A second review round found two more downstream regressions of the omitted-length target widening (both P1 by iamlinjunhong, both verified real on this branch):

  • +/- operator rewrites stopped firing for TEXT operands. The binder's date-arithmetic rewrite for VARCHAR/INTERVAL pairs and the VARCHAR-only string-pair concatenation rewrite gated on T_varchar, so the widened cast results failed to bind: CAST('2024-01-01' AS CHAR) + INTERVAL 1 DAY errored with invalid argument operator +, bad value [TEXT INTERVAL] (the base returned 2024-01-02), and CAST('a' AS CHAR) + 'b' did not concatenate. Fixed in pkg/sql/plan/base_binder.go by accepting the TEXT target wherever the rewrites accepted VARCHAR (forward/reversed INTERVAL additions to date_add, subtraction to date_sub, which then bind their executing TEXT overloads directly, and TEXT/TEXT + TEXT/VARCHAR + VARCHAR/TEXT pairs to concat, which accepts MySQL strings natively). CHAR literals stay on their previous path.
  • DAYOFMONTH/QUARTER/DAYNAME/MONTHNAME/WEEKOFYEAR lost their component-preserving string paths. Each of these has a DATE overload listed before its VARCHAR overload; TEXT casts to DATE and VARCHAR at the same preferLevel, so the tie selected the DATE overload and the inserted strToDate NULLed year-zero/incomplete dates: DAYOFMONTH(CAST('0000-01-01' AS CHAR)) fell from 1 to NULL and DAYOFMONTH(CONVERT('2024-00-15', CHAR)) fell from 15 to NULL; MONTHNAME(CAST('0000-01-01' AS CHAR)) lost January. Fixed by adding direct T_text overloads in pkg/sql/plan/function/list_builtIn.go bound to the same DateString* executors as their VARCHAR peers. MONTH needs no change: its string path already NULLs unparseable strings exactly like the inserted cast (verified live on both builds). YEAR deliberately keeps its overload set: a direct T_text entry rewrites how prepared statements type year's parameter, moving select ? + year(?) from the pinned [double, date] inference (ut TestNumericContextDoesNotCrossComparisonOrTemporalBoundary) to raw TEXT parameters; the remaining composed-spelling consequence is that YEAR(CAST('0000-01-01' AS CHAR)) returns NULL for unparseable strings where the pre-widening spelling raised the parsedate error (YEAR('0000-01-01') -> ERROR 20203 unchanged; valid dates identical in every spelling) — accepted boundary, documented in the review thread.

Covered by TestOmittedLengthTextKeepsOperatorRewrites and TestOmittedLengthTextKeepsDateExtractionStringPaths (planner-level binding: the TEXT operand reaches date_add/date_sub/concat/each extractor directly, no narrowing cast) plus TestDateStringExtractorsBindTextDirectly (function-level direct binding and year-zero/incomplete-date values on TEXT inputs for all five extractors, mirroring the pinned VARCHAR expectations). New BVT rows in func_cast_omitted_char_length.test cover both spellings: the date-arithmetic compositions return 2024-01-02/2024-03-30/2024-01-02 12:34:56, all concatenation mixes return ab, and the extractor rows return 1/15/1/Sunday/January/52 with valid-date YEAR/MONTH controls (2024/6). The appended rows were also probed live against the pre-change base binary and return identical values there, while the full file runs 62/62 on this branch's build; on the base binary only the established 14 pre-fix truncation/JSON rows fail and every appended row passes, so the new rows pin the preserved semantics rather than the widening itself.


Review follow-up 3 (2026-11-11)

Both P1 findings from the third review are fixed at commit 61bcce0e6346ff1e1f0bbf131994641f234c31ae.

  • Signed and full-width numeric coercion for widened CHAR results — T_text's implicit-cast rule now prefers INT64 exactly like the CHAR/VARCHAR rows (pkg/sql/plan/function/type_check.go). BIN(CAST('256' AS CHAR)) returns 100000000 again for both spellings; ROUND/TRUNCATE/SPACE and two-argument CEIL/FLOOR keep accepting negative inputs through the signed INT64 cast; unary minus/plus recover the negative domain; shift and bitwise operators and INET_NTOA keep the INT64 route. Verified live against the pre-change base binary, including out-of-range parity (BIN(CAST('18446744073709551615' AS CHAR)) errors on both builds, and ROUND(CAST('2.5' AS CHAR)) keeps its pre-existing error).
  • The post-fix registry-wide audit caught one further interaction: HEX, the single function with both string and integer overloads, would let the now-cheaper INT64 route capture the widened TEXT operand (HEX(CAST('256' AS CHAR)) → 100). HEX therefore received the same direct TEXT overload pattern this PR already uses for its string consumers, keeping the VARCHAR peer's string encoding (323536) and passing the complete untruncated value to the encoder for over-65,535-byte results (LENGTH(HEX(CAST(...))) → 200000, the MySQL-composed result).
  • DATE's string parser for compact datetimes — an explicit TEXT overload bound to DateStringToDate keeps DATE(CAST/CONVERT('20240102123456', CHAR)) returning 2024-01-02 like the pre-widening composition; the 8-digit and full-datetime spellings return the same dates on every build.
  • MONTH was verified result-identical on both builds (NULL on unparseable strings either way) and stays unchanged.
  • Tests — new regression rows in test/distributed/cases/function/func_cast_omitted_char_length.test (BIN/ROUND/TRUNCATE/SPACE/CEIL/FLOOR/unary/shift compositions with VARCHAR controls, date spelling cases, and the HEX string-encoding rows; the domain-restoration rows pass on the pre-change base binary too) and new focused UTs TestNumericTextCompositionsKeepSignedInt64Peer, TestHexTextKeepsStringEncoding, TestDateTextKeepsStringParser in pkg/sql/plan/function/func_omitted_length_consumers_test.go.

CI follow-up (2026-11-11)

The first full post-61bcce0 CI pass surfaced one pre-existing expectation in the shared corpus that the unified signed-INT64 coercion legitimately supersedes, at commit a72970d8fb89626283eb092afa724b80506e90f1:

  • test/distributed/cases/dtype/text_blob.sql rows 48–49 (select bin(t3)/select space(t3) from text_01) failed the multi-CN compose BVT (PROXY group, run 42866418416). The committed .result recorded two stored-TEXT quirks of the old argument binding: BIN bound its first-listed UINT8 overload, so the '983' row errored with Data truncation: data out of range: data type uint8, value '983' (pre-4.2-dev, the composed spelling BIN(CAST('983' AS CHAR)) already returned 1111010111 via the VARCHAR→INT64 route); SPACE bound its UINT64 overload (invalid argument cast to uint64). Both rows now pin the unified underlying contract this PR already established for the widened target: the same signed INT64 route as the VARCHAR peer and MySQL's BIN('983') = 1111010111, so the 983 row parses instead of range-failing and each statement fails at the first non-numeric value with the standard string-to-INT64 message invalid argument cast to int, bad value 中文. This is the behaviour-preserving direction for the composition contract; the old uint8/uint64 expectations pinned which overload list position a stored TEXT column happened to bind, not a supported semantic. The Coverage merge job of the same run failed only as a consequence (prerequisites_ready: false: this BVT job did not publish a complete coverage profile), so both failures share this single root cause and fix.

Verified on the local head/base validation pair: text_blob.sql runs 143/143 at the PR head with the aligned expectations, and exactly rows 48–49 fail on the pre-change base binary with the old uint8/uint64 messages while the other 141 statements stay byte-identical on both builds. No production code changed in this round; corpus scan found no other expectations pinning the old TEXT→uint8/uint64 function-argument routes (dtype/text_1 and dtype/tinyint record explicit CAST(col AS tinyint unsigned) target errors, unchanged by this PR; the other bin/space corpus users are bigint/varchar-typed or ran green in CI group 0).


Review follow-up 4 (2026-11-11)

The fourth review's single P1 finding — the restored TEXT→INT64 preference rejected the upper unsigned range that explicit AS TEXT casts and existing TEXT columns used to accept through ROUND/TRUNCATE and the two-argument CEIL/FLOOR's UINT64 overloads (SELECT ROUND(CAST('9223372036854775808' AS TEXT)); fell from 9223372036854775808 to data out of range: int64, ..., same for TRUNCATE/CEIL/FLOOR and stored TEXT columns in [2^63, 2^64)) — is fixed at commit 77dbc963b6a6f56d5df85b00e9c69c81973c4d39 with direct dual-domain TEXT overloads, leaving the global T_text implicit-cast rule (and with it every BIN/SPACE/unary and CHAR-composition result from follow-up 3) untouched.

  • What changed: ROUND (one- and two-argument), TRUNCATE (one- and two-argument) and two-argument CEIL/FLOOR gain direct T_text overloads in pkg/sql/plan/function/list_builtIn.go bound to the new RoundText/TruncateText/CeilText/FloorText executors in func_binary.go; the TEXT argument stays TEXT (the widening's actual subject) and the digits argument stays INT64. One-argument CEIL/FLOOR keep their existing TEXT entries (CeilStr/FloorStr from the accepted rounds).
  • Per-row semantics (dualDomainMathText): parseSignedCastString first, so every input the INT64 route accepted keeps its result and diagnostics byte-identically; then parseUnsignedCastString as the fallback that restores the previously accepted domain [2^63, 2^64) (plus its oversized 0x… tokens), executing the very same roundUint64/truncateUint64/ceilUint64/floorUint64 cores the base binary selected — so the base's values and its quirks survive (ROUND(..., -1) → 9223372036854775810; TRUNCATE(..., -2) → 9223372036854775800; CEIL(18446744073709551615, -1) → the uint64-digit-arithmetic wrap 0; FLOOR(18446744073709551615, -1) → 18446744073709551610). Rows both parsers reject keep the INT64 cast error (ROUND(CAST('2.5' AS TEXT), 0) → invalid argument cast to int, bad value 2.5, unchanged).
  • The signed round-up corridor: the two-argument set also takes the largest signed values across int64's ceiling when digits < 0. The base binary returned 9223372036854775810 for ROUND/CEIL('9223372036854775807', -1) and 9223372036854775900 for CEIL(..., -2), while the INT64 kernels panic (data out of range: data type int64, ROUND) or silently wrap (CEIL → -9223372036854775800). roundTextCrossesInt64Limit/ceilTextCrossesInt64Limit mirror the kernels' own overflow conditions and route exactly those crossing rows through the UINT64 core; FLOOR and TRUNCATE only move positive values toward zero, so they never cross (both binaries keep 9223372036854775800). The same predicates cover the UINT64 kernels' one-digit-wider scale tables at digits -19 (ROUND('9000000000000000000', -19) → the base's 10000000000000000000; below half a unit and at digits ≤ -20 both kernels already agree on 0). At the uint64 maximum the preserved behavior is deliberately the base core's own failure: SELECT ROUND(CAST('18446744073709551615' AS TEXT), -1) still fails with the base's data out of range: data type uint64, ROUND (the pre-fix head had failed earlier with the int64 cast error instead).
  • Result container: a single static binding cannot hold both -1 and 9223372036854775808 in an INT64 or UINT64 result, so the direct overloads return scale-0 DECIMAL(38,0) — exact for both domains and display-identical to the previous UINT64/INT64 outputs; composed chains keep their values on either input domain (measured: ROUND(CAST('9223372036854775808' AS TEXT)) + 1 → 9223372036854775809, BIN/HEX/SPACE/ABS/MOD/SUM/AVG over these rows behave numerically).
  • Tests: new focused UT TestRoundTruncateCeilFloorTextKeepUnsignedUpperRange (direct-binding asserts for all six overload entries plus executor rows for the upper-unsigned boundary, INT64 max/min, negatives, NULLs, hex tokens and trimming, digit arithmetic including the UINT64 wrap quirk, the -1/-2 corridor with below-half controls, the -19 digit-table boundary with its below-half and ≤ -20 controls, and the unchanged error classes), TestNumericTextCompositionsKeepSignedInt64Peer updated to pin the new direct-TEXT route while BIN/SPACE/unary keep the INT64-peer asserts, and kernel reruns TestRound/TestTruncate/TestCeil/TestFloor stay green. New BVT rows in func_cast_omitted_char_length.test cover the explicit AS-TEXT spelling, the widened omitted-length AS-CHAR composition (CONVERT(expr, TEXT) has never parsed in MatrixOne — on either build, including before this PR — so the text spelling uses CAST(... AS TEXT)), the corridor, the -19 boundary, the preserved uint64-ROUND error, and a stored TEXT column with signed controls and INT64-diagnostics error rows; the regenerated .result was reviewed row by row against live base/PR-head probes (every unsigned, corridor and boundary row equals the base binary's measured output; every signed row equals the INT64 route's) and the full BVT file was re-run end to end with method=run passing on the fixed build.

CI follow-up 2 (2026-11-11)

The first CI execution at 77dbc963 (PROXY compose BVT, run 42899048729) failed exactly two func_coalesce.test rows with a regression introduced by the direct TEXT overloads themselves; fixed at commit 26c5432b385538ef9fc2bacb7b37220db57906cb.

  • The failed rows — SELECT ROUND(COALESCE(a,a)) FROM t1 over the DATE and DATETIME blocks (job rows 133/144): the corpus pins the bind-time errors invalid argument function round, bad value [DATE]/[DATETIME]; the run returned the runtime invalid argument cast to int, bad value 2000-01-01(00:00:00) instead. DATE, DATETIME, TIME, TIMESTAMP and UUID reach T_text only through an implicit cast (prefer level 2) and have no numeric route, so the dual-domain TEXT overloads captured those inputs and moved their failure from binding into the TEXT executors.
  • The fix — pkg/sql/plan/function/type_check.go gains fixedTypeMatchWithExactText: a T_text overload position matches only an input that is already exactly T_text; ROUND, TRUNCATE, CEIL and FLOOR use it for their tables (list_builtIn.go, 4 entries). Selection otherwise keeps fixedTypeMatch's cost order and direct-match short-circuit, so bare TEXT inputs keep the direct dual-domain overload and its restored unsigned upper range, CHAR/VARCHAR keep the INT64 route, and the one-argument CEIL/FLOOR string parsers stay reachable for TEXT and VARCHAR.
  • Tests — new TestRoundFamilyTemporalInputsKeepBindTimeRejection (proven red at 77dbc963: round([DATE]) binds with a nil error there) pins both corpus messages, the TIME/TIMESTAMP/UUID forms, the digits forms, and the counterexamples (bare-TEXT direct binding without implicit cast, the string-parser and INT64 routes). The whole pkg/sql/plan/function suite passes (-count=1, 37.6s), the focused pkg/sql/plan set passes, and go vet is clean.
  • BVT re-verified locally at the fixed build — the two CI-failed rows pass again; func_cast_omitted_char_length 96/96, dtype/text_blob 143/143, and func_bit_count, func_avg_numeric_contract, func_datetime_addtime/subtime/timediff all 100%. func_cast and greatest_least_numeric showed only the pre-existing local-vs-CI column-meta rendering differences this machine has produced since before this PR's first commit (observed identically on the pre-change base binary; both files were 243/243 and 161/161 green in the very CI run that failed the two rows above).
  • The unrelated part of the same run — func_convert_json.test row 317 hit a 300s hang, then the compose CN restarted (no route to host to the backend, later files reporting lock table bind changed), cascading to about 15 later files, and the Coverage job of the same run failed downstream (prerequisites_ready: false). The two round rows failed two seconds before that hang began, on an otherwise-healthy corpus segment (neighboring files green), with no matching existing issue for the compose collapse; the head refresh re-runs the composition CI with the fix.

CI follow-up 3 (2026-11-11)

The second CI execution at head 26c5432b (run 42914442656) produced three terminal failures; two are environmental, one was this PR's own and is fixed at commit ebd8cb597a433b12f99f3ee9a70e5de0e227d797 (formatted branch).

  • PR-side (fix pushed) — the SCA-on-arm64 gate failed with exactly one processed finding repo-wide: pkg/sql/plan/function/list_builtIn.go:7581: File is not properly formatted (gofmt). The explanatory comments inside the four ROUND/TRUNCATE/CEIL/FLOOR TEXT entries split gofmt's field-alignment group, so the manually padded checkFn: fixedTypeMatchWithExactText, lines are not canonical. ebd8cb597a re-aligns those four lines to gofmt's canonical single-space form — a whitespace-only change inside struct literals with no behavior difference; the PR's test evidence for the binding and executor semantics carried to this commit unchanged. Locally verified after the fix: gofmt -l is clean on the file and every PR-touched Go file, and go build ./pkg/sql/plan/function/ exits 0 (fast CGo env build).
  • Not this PR — PESSIMISTIC compose multi-CN BVT — mid-corpus the compose cluster lost its CN backend: drop database IF EXISTS \func_coalesce`hitLock wait timeout exceededat 22:46:45 and from 22:46:57 every statement againstcn-0:18102(172.18.0.7) failed withconnect: no route to host. All 68 expectation mismatches of the run are cascade effects after that point (show databasesdrift in the snapshot/clone restore family, missing publications and tables after failed creates,find 0 snapshot records …`), in git4data, snapshot, tenant, temporary and the pub-sub function files. The verdict: not caused by this PR — environmental compose-cluster collapse, re-evaluated by the fresh CI run at the pushed head.
  • The PR's own rows are green in exactly that failed run — func_coalesce.test now runs 143 rows with 0 failed (the one abnormal row is the trailing drop database statement hit by the lock wait during the collapse; the two rows that failed the previous run, SELECT ROUND(COALESCE(a,a)) over DATE/DATETIME, pass). Also green in the same job: func_cast_omitted_char_length 96/96, func_cast 243/243, greatest_least_numeric 161/161, func_bit_count 62/62, func_avg_numeric_contract 2/2, func_datetime_addtime/subtime/timediff, and the PROXY compose BVT (the same run) passed 100% including dtype/text_blob 143/143.
  • Not this PR — Coverage job — failed 4 seconds after the BVT job with PREREQUISITES_READY: false ("a required producer did not publish a complete coverage profile"); no coverage verdict was calculated. Pure downstream consequence of the BVT corridor above.
  • Bookkeeping — no rerun was issued for run 42914442656: its SCA failure was PR-caused, so re-running the old head would deterministically re-fail; the fix-and-push supersedes it with a complete fresh run at ebd8cb597a. Issue tracking for the compose-corridor collapse was again left untouched after searching (repeated around 14 query variants across this and the previous round): no open issue in matrixorigin/matrixone matches this mid-corpus CN connectivity-loss root cause (the closest hits — compose MinIO download 504 preflight [Bug]: Compose PROXY CI fails before BVT when pinned MinIO client download returns HTTP 504 #32416, fulltext2 pessimistic deadlock [Bug]: Fulltext2 DROP DATABASE deadlocks with ISCP watermark flush in pessimistic BVT #31063, coverage-budget [Bug]: coverage-enabled pessimistic BVT exceeds its 75-minute CI job budget #27071 — are different root causes).

CI follow-up (2026-11-11, run 42982316351 attempt 2): PR-caused borrowed-executor leak in constant folding — fixed at 9923c2b21c

The mid-corpus CN loss behind the compose PROXY BVT failure of run 42982316351 attempt 2 was caused by this PR, superseding the earlier environmental reading of that event. The uploaded cn-0 runtime log shows the process was killed by a Go-finalizer panic raised from the reuse-pool checker (mo_reuse_enable_checker=true, as compose CI configures):

panic: missing free for type: *colexec.FunctionExpressionExecutor, &{... resultType:{Oid:33 ... Width:38 Scale:0}
      functionInformationForEval:{fid:167 overloadID:717259538445 ...}}
    reuse.(*checker[...]).gc                  checker.go:133
    reuse.newSyncPoolBased[...].func1.1()    sync_pool_based.go:48
    runtime.runFinalizers()

fid:167 / overloadID:717259538445 is the round(TEXT, INT64) → DECIMAL128(38,0) overload this PR added (list_builtIn.go; the panic dump's Oid:33 Width:38 Scale:0 result type matches). The corridor timeline in the same job shows the full sequence: func_bit.sql (66 ok, 1 ignored), func_cast.test (243/243) and func_cast_omitted_char_length.test (96/96) all completed green by 09:08:56.24Z; the script's select round(cast('18446744073709551615' as text), -1); row evaluates through the plan-time constant folder, which borrows a FunctionExpressionExecutor from the reuse pool — the round core reports the uint64 overflow the recorded way (data out of range: data type uint64, ROUND from func_binary.go:572, recovered into the expected SQL error), but the panic unwound past every Free call, leaking the executor tree. The finalizer detected the un-freed executor ~1.4 s later (09:08:57.64Z) and its fatal missing free panic killed CN0; every subsequent corpus statement then hit the dead backend (the 300s DDL stall and no route to host cascade previously read as environmental cluster collapse).

Compose parity was reproduced locally before the fix: a fresh single-binary launch with the checker enabled ran a 14-script BVT window on the pre-fix head binary and CN0 died with the byte-identical panic (fid:167 overloadID:717259538445, verbose allocation stack recorded), truncating the window from 1,173 rows to 691 success / 2 failed / 480 abnormal with the same dead-backend cascade behind it.

Runtime pipelines already recover such panics (Scope.Run recover, pipeline.catchPanic); the borrow seam in pkg/sql/colexec/evalExpressionOpt.go did not. Commit 9923c2b21c adds evalBorrowedExecutor, which closes the borrowing at the seam on every non-success exit: a returned error frees the borrowed executor, a panicking evaluation frees it and re-raises the original panic value unchanged, and success keeps the previous ownership contract (readonly hands executor.Free to the caller; writable transfers the result out with the existing Dup fallback). The SQL error path is byte-identical, so no recorded expectation moves — the BVT row still records Data truncation: data out of range: data type uint64, ROUND.

Regression coverage in the new pkg/sql/colexec/evalExpressionOpt_test.go:

  • TestEvalBorrowedExecutorClosesBorrowOnNonSuccessExits pins the seam contract with stub executors: no free on success (the caller owns the executor), exactly one free on a returned error, exactly one free plus the original value re-raised on panic (both error and non-error panic values).
  • TestBorrowedExecutorIsFreedWhenEvaluationPanics drives the real panicking round(TEXT, INT64) overload through both public seams (GetReadonlyResultFromExpression and GetWritableResultFromNoColumnExpression), asserting the out-of-range moerr still propagates unchanged, and proves the borrow stays usable after a panicking evaluation. The committed test deliberately avoids reuse.RunReuseTests: with pool objects created before the checker is enabled, warmed pools carry stale checker state, so the definitive missing-free proof is the service-level compose-parity rerun with the checker enabled.

Local validation: on the parent commit the focused selection crashes the test process with the identical missing-free checker panic (recorded log); on 9923c2b21c it is green, the complete ./pkg/sql/colexec package suite is green, and go vet/gofmt are clean. The compose-parity rerun of the identical 14-script window against a checker-enabled build of 9923c2b21c (CommitID verified in the build log) completed with no CN panic: the panicking fold executed four times (data out of range: data type uint64, ROUND recovered to the expected SQL error each time), func_cast_omitted_char_length.test ran 96/96, and the whole window executed 1,173 rows with 1,165 success, 0 abnormal and 8 failed — every one of the 8 a pre-existing metadata-annotation-only mismatch with byte-identical values (recorded upstream annotations like datetime(6, 6) vs the local protocol's datetime(6)), on rows this PR does not touch (including func_bit.sql's ignored-marker row and func_cast.test row 772, which this same CI job itself shows passing). The pre-fix run of the same window on the same corpus crashed CN0 mid-corpus instead.

Review follow-up (iamlinjunhong round of 2026-11-11): single-argument CEIL/FLOOR exact integers and NULL rows — fixed at 8dacb3f

The latest review flagged two regressions in the one-argument CEIL/FLOOR on TEXT that this PR had registered:

[P1] Exact integers. The first registration rebound overload 13 to CeilStr/FloorStr with a FLOAT64 return: strconv.ParseFloat rounded 9007199254740993 to 9007199254740992 before ceiling/flooring, silently changing values the pre-widening UINT64 tie returned exactly (including 18446744073709551615 → 18446744073709552000), and shrank the accepted unsigned domain. Commit 8dacb3faa7 binds the one-argument spellings to their own dual-domain executors (CeilTextUnary/FloorTextUnary in pkg/sql/plan/function/func_binary.go), mirroring the already-reviewed two-argument design: integer strings parse through parseSignedCastString first and parseUnsignedCastString second and keep their exact INT64/UINT64 values; integer tokens beyond the uint64 domain keep the UINT64 cast argument's out-of-range error instead of a silently rounded float; everything the integer parsers reject at syntax falls back to strconv.ParseFloat, keeping the decimal/negative/exponent-string support the widening restored. The result type moves FLOAT64 → scale-0 DECIMAL128(38,0), the same return the two-argument TEXT overloads already use: FLOAT64 could not carry the exact integer the review asked to preserve, while DECIMAL128(38,0) is exact for both integer domains and renders like the base's UINT64 route. Values are unchanged on every decimal row (ceil('1.2') is still 2, floor('-1.2') still -2); the only visible difference is those integral results no longer display FLOAT64's trailing .0.

Measured against the isolated services (evidence logs under this PR's loop artifacts):

  • exact base 42aac8161c: 9007199254740993 for both spellings, 18446744073709551615 exact, data out of range: data type uint64, value '...' for out-of-domain integer tokens;
  • pre-fix head 9923c2b: 9007199254740992, 18446744073709552000, 100000000000000000000000 for the 23-digit control (red probes + the mo-tester red run of the same script);
  • fixed 8dacb3faa7: the base values again, byte-identical error strings for the out-of-domain rows.

[P1] NULL rows. SELECT FLOOR(v) FROM t over a mixed nullable TEXT batch ('1', NULL) failed the whole query on the pre-fix head (strconv.ParseFloat: parsing "": invalid syntax): FloorStr's hand-rolled row loop appended the NULL result but fell through to GetStrValue/strconv.ParseFloat on the same row. The fixed commit evaluates FloorStr through the shared opUnaryStrToFixedWithErrorCheck template — the exact shape CeilStr already uses — whose row loop skips NULL rows, so mixed nullable batches keep the 1/NULL results the base's null-preserving UINT64 route returned. This also closes the pre-existing VARCHAR exposure of the same defect. The fixed binary returns 1/NULL for the review's batch, matching the exact base.

Regression coverage added at 8dacb3faa7:

  • BVT (func_cast_omitted_char_length.test): large-integer controls for both single-argument spellings and both composition forms (9007199254740993 as TEXT and as CHAR/CONVERT, int64 min/max, 2^63, uint64 max, 0x10, ' 42 '), a mixed nullable TEXT-column table (ceil(v)/floor(v) over ('9007199254740993'), (NULL), ('1'), ('-1.2')), and the out-of-domain integer/non-numeric error rows. The updated script is 108 rows; mo-tester compares 108/108 green against the fixed binary, while the same script on the pre-fix head binary fails exactly the 9 defect rows (2 rendering blocks, 2 exact-integer statements, the 3 NULL-table selects, 2 out-of-domain rows).
  • UT (func_omitted_length_consumers_test.go): TestCeilFloorTextKeepStringNumericParsing now drives the registered one-argument TEXT executors with exact large-integer controls, mixed-NULL batches, out-of-range and non-numeric reject rows, and the VARCHAR CeilStr/FloorStr rows including the mixed-nulls cases; TestRoundFamilyTemporalInputsKeepBindTimeRejection and the binder-level TestOmittedLengthConsumersKeepStringOverloads pin the DECIMAL128 return and direct binding, with ceil/floor(cast('9007199254740993' as text)) binder probes.
  • Red/green: on the parent commit the focused NULL-batch executor test fails with the exact strconv.ParseFloat: parsing "" error while the CeilStr control passes; at 8dacb3faa7 the whole focused selection (72 tests/subtests across pkg/sql/plan/function, pkg/sql/plan, pkg/sql/parsers/dialect/mysql) is green, go vet and gofmt clean. The neighbor compare window (func_math_ceil 86/86, func_math_floor 95/95, func_cast 242/243, func_coalesce 139/143, greatest_least_numeric 159/161, dtype/text_blob 143/143, func_bit_count 62/62, func_avg_numeric_contract 2/2) shows only the 7 previously documented local-only metadata-annotation mismatches with byte-identical values on rows this PR does not touch — the same rows CI passed green at the previous head.

Review follow-up at 7943d72fb6: widened CEIL/FLOOR composed-CHAR numeric domain

The mo-bot review of 8dacb3faa7 (PRR_kwDOFEPiGM8AAAABXXGEoA, P2) found that the one-argument TEXT CEIL/FLOOR executors' DECIMAL128(38,0) intermediate rejected numeric CHAR compositions the pre-widening FLOAT64 route always accepted: CEIL(CAST('1e40' AS CHAR)) raised a decimal conversion error and FLOOR(CONVERT('18446744073709551616', CHAR)) raised a uint64 range error, where the frozen-base production binary displayed 10000000000000000000000000000000000000000 and 18446744073709552000.

The follow-up keeps the exact INT64/UINT64 integer tokens 8dacb3faa7 introduced and restores the composed domain by widening the one-argument result to scale-0 DECIMAL256(76,0), the widest integral numeric the type system provides:

  • Integer tokens in the int64/uint64 ranges keep exact values (9007199254740993, 18446744073709551615 unchanged).
  • Every other numeric token — including integer tokens beyond uint64 and all decimal/exponent strings — falls back to the pre-widening string parser, and the conversion through the shortest round-trip float digits reproduces the prior FLOAT64 displays digit for digit for every magnitude within 76 integral digits (±1e40, 1.5e40, 23-nines, 41-digit, 2^64 → 18446744073709552000, up to 1e75).
  • Magnitudes whose display needs more than 76 integral digits (1e76 and above) exceed any scale-0 numeric type and keep an explicit decimal conversion error; a TEXT-typed return was rejected because it breaks arithmetic compositions through the implicit TEXT-to-INT cast. Superseded at bb387d87e7: the next round removed this ceiling — the one-argument TEXT CEIL/FLOOR overloads now return the FLOAT64 digit-rendering VARCHAR, every finite FLOAT64 magnitude (1e76 and above) succeeds again with the base display, and the 1e76/1e300 error rows in the BVT were re-pinned to those restored values.
  • The two-argument TEXT overloads keep DECIMAL128: their pre-existing argument errors are identical to the composition's prior behavior.
  • Regression controls: TestCeilFloorTextKeepStringNumericParsing now carries the restored wide corpus, wide mixed-NULL batches and the ±DECIMAL256 boundary rows (red at 8dacb3faa7: the binding pins fail with decimal128 vs decimal256); the binder probes pin the widened return; the omitted-length CHAR BVT adds the review's two cited queries in both spellings, the wide mixed-NULL table and the documented >76-digit error rows (114 statements, 100% on the local metadata-enabled run).

Base sync with advanced 4.2-dev (8c77e14665): one helper unified

4.2-dev advanced 44 commits past this branch's previous merge point, and the upstream ENUM/SET work (#32841, #32823, #32808, #32723) refactored the '+' → CONCAT rewrite condition in pkg/sql/plan/base_binder.go into a shared helper stringPlusConcatenates(args), reusing it for the ENUM/SET numeric-contract recovery in pkg/sql/plan/mysql_special_types.go. The advancing base made the branch conflicting (mergeable_state: dirty); it is merged now.

The single content conflict was resolved semantically:

Behavior after the merge: the CONCAT rewrite still binds TEXT + TEXT composed casting (e.g. CAST(x, ... ) + CAST(y AS CHAR) never regresses to a numeric overload), and the ENUM/SET numeric-contract recovery now treats TEXT operands exactly like their VARCHAR peers, so enum_col + CAST(literal AS CHAR) keeps MySQL's numeric operator contract just as enum_col + literal does. VARCHAR-only behavior is byte-identical to upstream: the widened domain is a superset.

The two other overlapping files (pkg/sql/plan/build_util_test.go, pkg/sql/plan/function/list_builtIn.go) auto-merged in disjoint regions: this PR's test realignment and TEXT-target overloads (EXTRACT, REVERSE, CEIL/FLOOR, LEAST/GREATEST) combine with upstream's new ENUM ordinal overloads and decimalComparisonTarget registry refactor.

Validation on the merged tree: complete ./pkg/sql/plan, ./pkg/sql/plan/function, ./pkg/sql/parsers/dialect/mysql and ./pkg/sql/colexec package suites are green, covering both this PR's regressions and upstream's new ENUM/SET tests that exercise the shared helper.

Review follow-up at bb387d87e7: restored full FLOAT64 domain of composed CEIL/FLOOR

The iamlinjunhong review of 6e6171c675 (PRR_kwDOFEPiGM8AAAABYeJp7w, P1) found the widened DECIMAL256(76,0) route still rejected finite FLOAT64-domain inputs that the base VARCHAR CeilStr/FloorStr path always accepted, so previously working queries like SELECT CEIL(CAST('1e90' AS CHAR)); or SELECT FLOOR(CONVERT('1e90', CHAR)); kept failing under the new TEXT executor.

The follow-up replaces the decimal ceiling with the base's FLOAT64 route while keeping the exact-integer digits:

  • The one-argument TEXT CEIL/CEILING/FLOOR executor (pkg/sql/plan/function/func_binary.go) now keeps the exact int64/uint64-integer token rendering and falls back to strconv.ParseFloat + strconv.FormatFloat for every other numeric token, including all finite magnitudes above 76 integral digits (1e76, 1e90, 1e300, 1e308, negatives, -0). A 46-row probe corpus spanning exact integers, the FLOAT64 domain, mixed-NULL batches, trim/hex/中文 behaviors and both error paths is byte-identical to the pre-change base display oracle.
  • The VARCHAR digit rendering is display-only: a provenance retype in BindFuncExprImplByPlanExpr (pkg/sql/plan/base_binder.go) re-binds + - * / % div mod, unary +/-, = <=> != <> < <= > >=, IN and BETWEEN compositions over the render on FLOAT64, so composed results, errors and order of magnitude match the base numeric contract (CEIL(CAST('1e40' AS CHAR)) + 1 binds FLOAT64 instead of digit concatenation).
  • ORDER BY on the rendered column adds a hidden FLOAT64 sort key in the same project list (pkg/sql/plan/query_builder.go), restoring base numeric ordering while the visible column keeps its digit rendering.
  • Coverage: composition-binding UTs (arithmetic, comparison, IN, BETWEEN, unary minus, and the string/date control cases that must keep their existing bindings), ORDER BY hidden-key UTs, the unchanged exact ENUM special-order provenance battery, and BVT rows in func_cast_omitted_char_length.test for composed CAST/CONVERT queries plus finite values above the prior decimal ceiling (22,1e40+1,1e90*10, comparison and IN rows, and a numeric-ORDER-BY table). The previously committed 1e76/1e300 TEXT rejection rows now pin the restored full-digit displays.
  • Focused local BVT comparison (metadata-annotations enabled): func_cast_omitted_char_length 123/123; the adjacent func_math_ceil, func_math_floor, decimal_256, func_datetime_*, func_bit_count, func_avg_numeric_contract, Func_cast/func_coalesce/greatest_least files pass all value rows (remaining local deltas are the known local-only RSMetaData annotation compares and text_blob rows that require mo-tester $resources/blob_file fixtures absent locally — all values untouched by this change).

Residual (unchanged from the design discussion, recorded for reviewers): numeric aggregates (SUM/AVG/MAX/MIN), GROUP BY/HAVING keys, nested numeric scalar functions (ROUND/POWER/ABS) and ORDER BY through CTE/derived-table boundaries around the rendered expression still bind in the string realm; those realms have no previously committed behavior through the omitted-length TEXT route and are out of this follow-up's scope.

CI follow-up at 768075a0c8: aligned the temporal-rejection pin with the VARCHAR render

The UT Coverage run on bb387d87e7 (run 44081665066, job "UT Coverage on Ubuntu/x86") failed in TestRoundFamilyTemporalInputsKeepBindTimeRejection (func_omitted_length_consumers_test.go:1180): the retype round updated the sibling one-argument ceil/floor pins but left this one at the superseded DECIMAL256 expectation — expected 0x22 (T_decimal256), actual 0x3d (T_varchar). The pin now asserts the VARCHAR digit-rendering return that the shipped overload produces, with the comment restated; no production change. Full pkg/sql/plan/function package suite green locally after the alignment, and the focused test red at bb387d87e7 / green at 768075a0c8 with the CI-identical values.

Review follow-up at e7d8515934: complete numeric domains for every render composition

The iamlinjunhong review of 768075a0c8 (PRR_kwDOFEPiGM8AAAABYh4oUA) found two regressions of base SQL inside this PR's scope, both fixed at e7d8515934:

  1. Composed numeric consumers over the omitted-length-CHAR render (MAX(CEIL(CAST(v AS CHAR))) returned string min/max bytes, SUM(CEIL(...)) rejected its VARCHAR argument at binding, ROUND(CEIL(CAST('1e40' AS CHAR))) hit an INT64 range error). The provenance retype in retypeCeilFloorTextRenderArgs (pkg/sql/plan/base_binder.go) now also covers the MAX/MIN/SUM/AVG aggregates and the nested ROUND/TRUNCATE/POWER/ABS scalars, retargeting the render to FLOAT64 (the exact base's VARCHAR CeilStr/FloorStr route). The aggregate executors again pick their numeric min/max, SUM/AVG bind, and nested scalars keep the FLOAT64 domain. FLOOR and every CONVERT spelling share the same path, and composed INTERVAL operands still veto the retype so the temporal date_add/date_sub string rewrite keeps binding.
  2. Exact-integer domain for existing explicit TEXT compositions (CEIL(CAST('9007199254740993' AS TEXT)) = 9007199254740992 flipped to true through a FLOAT64 round). The retype is now provenance-aware: an explicit TEXT render (TEXT columns, CAST ... AS TEXT) retypes to DECIMAL128(38,0) — the exact base's comparison domain — while only the omitted-length CHAR widening takes the FLOAT64 target. Comparisons, arithmetic, aggregates, IN-lists (bindMixedInListComparison uses the same provenance target) and the ORDER BY hidden key preserve the exact integer, so the 2^53-neighbor control stays false and floor(CAST('9223372036854775807' AS TEXT)) - 1 stays exact.

Additionally, the same follow-up proof pass closed the JSON typing witnesses observed at the same head: json_object value positions and json_array entries now apply the matching retype, so the base's numeric result keeps embedding as a JSON number ({"v": 21}, [5], and {"v": 9007199254740993} for the exact-integer route) instead of a digit string; json_object keys keep their string typing.

Coverage at this head:

  • UT: TestCeilFloorOmittedCharRenderBindsProvenanceMarker, TestCeilFloorTextRenderCompositionsKeepBaseNumericDomains (composed MAX/MIN/SUM/AVG, nested scalars, BETWEEN, JSON builders on FLOAT64; exact-TEXT =/</ +/-/round/aggregate/IN rows and the =9007199254740992-false plan on DECIMAL128), order_by_keeps_exact_integer_domain_for_text_renders, plus the IN-list structural checks and JSON rows in base_binder_cast_omitted_length_test.go.
  • BVT: func_cast_omitted_char_length.test appends the composed aggregate/scalar/JSON section (max/min/sum over the ('2','10') table, round(ceil('1e40')), power/truncate/abs, floor∘ceil/ceil∘floor, IN controls, jobj_ceil/jarr_floor/jobj_exact), the large-integer comparison/arithmetic controls, and a TEXT-column control table (max/min over '2','10','9007199254740993','9007199254740992','2.5', exact WHERE and ORDER BY). Focused pkg/sql/plan and pkg/sql/plan/function suites green; full-file BVT compare 136/136.
  • The regenerated expected file is a pure append: all 454 previously committed rows are byte-identical, so CI behavior for existing cases is unchanged.

Residual update (superseding the earlier aggregates/nested-scalar note): numeric aggregates, nested numeric scalars, JSON embedding and comparisons/arithmetic over both render provenances are now covered by the retype. Still unretyped on purpose: GROUP BY/HAVING keys over the rendered expression, ORDER BY of the rendered expression across CTE/derived-table boundaries, and JSON column INSERT assignment casts.

Review follow-up #2 at 2db61d62fc44ce78a2a9a835805967da72ffb4bd: SUBSTRING_INDEX keeps the base FLOAT64 TEXT-count route

The 17:02 mo-bot review (PRR_kwDOFEPiGM8AAAABYjq4Uw) and the local review summary (PRR_kwDOFEPiGM8AAAABYjaVew) confirmed one more regression inside this PR's watch scope: SELECT SUBSTRING_INDEX('a,b,c', ',', CAST('2.9' AS TEXT)) returned 'a,b' on the exact base and failed with invalid argument cast to int at this PR's head. On the base every T_text-to-numeric implicit cast costed the same, so the count bound the first-listed FLOAT64 overload and getCount truncated 2.9 to 2. The PR's T_text-to-INT64 cast preference (which keeps BIN/SPACE and unary +/- on their signed INT64 peer routes) was winning the INT64 overload instead, whose signed-string cast rejects fractional tokens.

Fixed at 2db61d62fc44ce78a2a9a835805967da72ffb4bd with a dedicated SUBSTRING_INDEX matcher (substringIndexCheck, pkg/sql/plan/function/type_check.go, mirroring the existing unaryTildeTypeMatch pattern): a TEXT count keeps the FLOAT64 overload and the FLOAT64 implicit-cast target. The T_text cast-preference table is untouched, so BIN/SPACE and unary +/- keep their signed INT64 peers, and VARCHAR/CHAR counts keep the INT64 peer routes they already had at the base; non-TEXT inputs keep plain fixedTypeMatch.

Coverage:

  • UT TestSubstringIndexTextCountKeepsBaseFloat64Route (pkg/sql/plan/function/func_omitted_length_consumers_test.go): the TEXT count binds the FLOAT64 overload with a FLOAT64 cast target, the VARCHAR count keeps its base INT64 peer, and the restored route truncates like the working base queries (2.9 → 'a,b', 1.4 → 'a', 99.5 → 'a,b,c'). The existing TestNumericTextCompositionsKeepSignedInt64Peer still pins the untouched BIN/SPACE/unary INT64 peers, and TestSubStrIndex keeps the executor battery green.
  • BVT: func_cast_omitted_char_length.test appends the SUBSTRING_INDEX controls (fractional widened counts through both CAST AS TEXT and CONVERT(x, CHAR), an INTEGER TEXT count, the VARCHAR INTEGER peer count and a stored TEXT-column count table). The regenerated expected file is a pure append: every previously committed row stays byte-identical.

The earlier residuals stay as recorded (GROUP BY/HAVING keys over the rendered expression, ORDER BY of the rendered expression across CTE/derived-table boundaries, JSON column INSERT assignment casts).

Review follow-up #4 at 32d9933: numeric contract across query boundaries and the CTAS round trip

The two P1s of @iamlinjunhong's review (PRR_kwDOFEPiGM8AAAABYlo5Eg) and the mo-bot review's P1 (PRR_kwDOFEPiGM8AAAABYlnMzg) are fixed and answered in their threads; the mo-bot CTAS finding (P2) rides on the same grammar change:

  1. Numeric CEIL/FLOOR results through projected columns — the outer scope now retypes boundary column references on the defining scope's recorded domain: planner-local provenance (BindContext.omittedCharWidenProjects) written when the projection binds an omitted-length CAST/CONVERT-to-CHAR, plus resolveProjectedColumnSource walking the reference back to the defining expression. MAX/MIN/SUM/AVG, arithmetic, nested scalar/JSON compositions and the ORDER BY hidden key retype on it — FLOAT64 for the omitted-CHAR provenance, exact DECIMAL128 for explicit TEXT casts/columns.
  2. Omitted-CHAR provenance of a projected input — isProjectedOmittedCharWidenColumn resolves the column reference through the same walk inside the one-argument CEIL/FLOOR marker branch, so CEIL(c)+1 over (SELECT CAST(v AS CHAR) AS c ...) d keeps marker overload 15 and its base FLOAT64 domain; '1e40' and '1e90' magnitudes succeed again, and FLOOR, CONVERT, CTE and nested forms share the path.
  3. CTAS round trip — mysql_sql.y had rewritten the omitted-length target's textual signature (family "text", DisplayWith 0), so AsSource.Format rendered cast(... as text) and the CTAS re-parse bound the explicit-TEXT domain, failing your CEIL(CAST('1e90' AS CHAR)) + 1 witness with the DECIMAL128 range error. The cast target now keeps the re-parseable "char" signature (family "char", DisplayWith -1) while still mapping the Oid to MYSQL_TYPE_TEXT for plan binding, so the rendered source re-enters the omitted-length action: both the direct and the projected CTAS shapes in the BVT now create double columns carrying the value (func_cast_omit_char_ctas2/3 plus show create table rows), and explicit CAST(... AS TEXT) remains distinguishable through its own rule. mysql_sql.go is regenerated with the repository's committed goyacc (the regeneration was verified byte-identical), and the parser pins now assert the "char" rendering plus its reparse round trip (TestCastOmittedCharLengthRendersReparseableChar, TestPitrInternal).

Validation: focused pkg/sql/plan selection green (16 test roots incl. the two new boundary tests), focused pkg/sql/parsers/dialect/mysql cast/render pins green; the service was rebuilt from the worktree and the boundary probes reproduce the base values — max 10 / min 2, sum 12, numeric ORDER BY, the '1e40' FLOAT64 domain rows, and the '1e90' CTAS round trip (probe logs: loop artifacts logs-follow/probes-followup.txt, pre-fix probes in logs-follow/probes-prefixed.txt). The regenerated func_cast_omitted_char_length.result is a pure append — all previously committed rows byte-identical — and the compare run is 100% (empty error.txt).

Known domain boundary, unchanged from the accepted exact-integer design: explicit-TEXT compositions above 38 integral digits (e.g. CEIL(CAST('1e40' AS TEXT)) + 1) reject with the DECIMAL128 range error, while the omitted-CHAR route carries those magnitudes through FLOAT64.

The residual recorded after the e7d8515934 section is superseded: numeric aggregates, arithmetic, nested scalars and ORDER BY — direct and across derived/CTE boundaries — now retype on both provenances. Still unretyped on purpose: GROUP BY/HAVING keys over the rendered expression, and JSON column INSERT assignment casts.

Review follow-up #6 at a1e47f171b: omitted-CHAR numeric domains through set-operation outputs

The 22:54 mo-bot-local review (PRR_kwDOFEPiGM8AAAABYodKDQ, reviewing 32d99335c3) confirmed three findings; all three are fixed and pushed at a1e47f171b:

  1. P1 — UNION ALL render transports. Two defects surfaced behind the reported aggregate/ordering failures. First, retypeCeilFloorTextRenderArgs's consumer switch had its CASE/IF/IFF labels comma-merged into the arithmetic/aggregate label list, and a Go label list shares one body — so MAX/MIN/SUM/AVG over a projected render took the control-flow early return instead of the numeric retype. Second, the provenance walk crossed derived tables and set nodes but not AGG outputs: grouped projections export passthrough ColRefs to the group tag that no binding records, so grouped ORDER BY lost the domain. The consumer switch is split back out, the walk now resolves every set branch's defining projection (UNION/UNION ALL/INTERSECT/MINUS and their ALL forms descend the node graph branch by branch) and hops group-tag references to the defining group expression, and rewriteMySQLSpecialOrderByExpr recovers the same numeric domain for ORDER BY keys typed from a group.
  2. P2 — widen-union composition. CEIL(n)+1 over UNION ALL of CAST(v AS CHAR) branches re-bound the ordinary TEXT overload after losing the marker at the set output, rejecting '1e40' with the DECIMAL128 range error. The set-branch resolution keeps the homogeneous widen union on marker overload 15 and its base FLOAT64 domain; the explicit-TEXT branch control keeps overload 13 with the exact-integer DECIMAL128 composition; heterogeneous branches keep their ordinary binding.
  3. P3 — result metadata. func_bit_count.result (three headings) and func_coalesce.result (two headings) recorded as text where the endpoint reports BIT_COUNT(cast(64 as char)) / cast(COALESCE(a, a) as char); the committed headings now expect the actual labels and every explicit AS TEXT expectation is unchanged.

Validation at the pushed head (loop artifacts logs-r15-setops/): the focused pkg/sql/plan family green including the new TestCeilFloorSetOutputsKeepBaseNumericDomains (aggregate binds, plain and grouped sort keys, three-branch unions, deep derived chains, CASE arms, the mixed-domain require.Error control and both explicit-TEXT controls), go vet ./pkg/sql/plan clean; a three-binary mo-service matrix (fix a1e47f171b / review head 32d99335c3 / frozen base 8c77e14665) reproduces every reported failure on the review head only — SUM rejects bad value [VARCHAR], ordering 10 before 2, grouped 10|2 first, three-branch/deep-chain/CASE rejections and the widen-union 20301 — while the fixed head matches the frozen base values (sum 24, 10 / 2 / 6, orders 2,2,10,10, grouped 2|2 then 10|2, three-branch 36, deep-chain max 10, CASE sum 12, widen-union 1.0E40 rows); the regenerated func_cast_omitted_char_length.result is a pure append, the run-mode compare with metadata is 100% for both regenerated headings and 100% for func_cast_omitted_char_length, and func_coalesce keeps only its four documented pre-existing temporal metadata rows.

Known domain boundary, unchanged: a heterogeneous set output (explicit-TEXT render or cast arm beside an omitted-CHAR arm) keeps its ordinary binding — the two branches carry different base domains (FLOAT64 vs exact-integer DECIMAL128), so neither may dominate the export; pinned by a require.Error UT and a BVT rejection row.

CI follow-up at 1e0edafc69: ENUM/SET order-key rewrite restored for untagged bind scopes

The UT Coverage job at a1e47f171b (run 44217822359, job 134512084324) failed TestQueryBuilder_bindOrderByEnum / TestQueryBuilder_bindOrderByEnumDistinct. The group-output recovery branch that commit added to rewriteMySQLSpecialOrderByExpr runs before the project-tag ENUM/SET display rewrite and matched any ORDER BY key whose RelPos equals the context's groupTag — including the zero-valued groupTag == projectTag == 0 of a scope that never built groups (the manual binds in those two tests), whose keys were then returned as their unchanged VARCHAR display form, skipping the display rewrite that materializes the ENUM storage-order hidden sort key.

The branch now fires only for scopes that actually built groups (len(ctx.groups) > 0). Real binding flows assign distinct non-zero group/project tags, so every grouped numeric-recovery and set-provenance behavior of a1e47f171b is unchanged.

Validation at the pushed head (loop artifacts logs-ci-r16-enumsort/): both tests reproduce failing on a1e47f171b exactly as CI reported (ENUM type 66 expected vs VARCHAR 61 returned; 2 hidden-key projects expected vs 1) and pass at 1e0edafc69; the full pkg/sql/plan package UT — including the grouped T_float64 sort-key and homogeneous/render-union assertions of TestCeilFloorSetOutputsKeepBaseNumericDomains — and go vet ./pkg/sql/plan are green. The parent head's UT Coverage job (run 44182971168, job 134392139735) was green, isolating the regression to a1e47f171b's branch ordering.

Review follow-up #7 at a4d656ff56: per-branch render domains unify numerically in set columns and CTAS

The 05:08 mo-bot-local review (PRR_kwDOFEPiGM8AAAABYrbv6A, reviewing 1e0edafc69) found the two remaining regressions of the digit render at query boundaries; both are fixed at a4d656ff56, and the "Known domain boundary" paragraph of follow-up #6 is superseded: heterogeneous set outputs now unify numerically.

  1. P1 — set-operation columns. A UNION ALL column that combines CEIL(CAST(v AS CHAR)) with a numeric literal, with FLOOR over explicit TEXT, or with enough identical CEIL branches to exhaust the recovery walk lost the numeric type: SUM received VARCHAR and rejected binding. Root cause: the set/widen recovery lived entirely in the consumer-side provenance walk — identical branch domains required, 48-step budget — so valid mixed-domain queries and the 56-branch fan-out fell back to the unprovenanced binding.
  2. P2 — CTAS. genAsSelectCols inferred the bare render's VARCHAR for CREATE TABLE dst AS SELECT CEIL(CAST(v AS CHAR)) AS n FROM src, where the frozen base inferred DOUBLE, so downstream queries read a stored string column.

Fix: every set branch that exports a rendered one-argument CEIL/FLOOR value re-enters its own base domain — FLOAT64 for the omitted-CHAR provenance, exact-integer DECIMAL128 for TEXT inputs — through retypeSetProjectionCeilFloorRender inside buildUnionWithResultLen's coercion loop, before the existing common-type rules unify the branches; genAsSelectCols applies the same per-column recovery to the CTAS source projection. Direct renders and projected references are covered branch by branch (no cross-branch agreement, no walk budget), the bare SELECT keeps its digit rendering, and the derived/CTE/grouped consumer recovery of the earlier rounds is untouched.

Frozen-base parity (loop artifacts logs-r18-review/base-parity-probes.txt, both binaries built and probed this round): 8c77e14665 answers 13 for the literal mix, 15 for the integer-only explicit-TEXT mix, 672 for the 56-branch fan-out, 2,2,10,10 DOUBLE display for the homogeneous union, and creates n double DEFAULT NULL for the bare omitted-CHAR CTAS — a4d656ff56 reproduces each (13.0 / 15 / 672.0 / DOUBLE rows / n double DEFAULT NULL). The BVT's 17.0 mixed row also carries the fractional '2.5' TEXT value through the accepted dual-domain render (the base's UINT64 route rejects '2.5' at execution) and the '3' integer row keeps the base-verifiable 15 component.

Validation at the pushed head (loop artifacts logs-r18-review/): the plan-level probes reproduce all four findings on 1e0edafc69 (three SUM rejections bad value [VARCHAR] plus the VARCHAR CTAS inference) and pass at a4d656ff56; the full pkg/sql/plan package UT is green including the updated TestCeilFloorSetOutputsKeepBaseNumericDomains (SUM binds FLOAT64 for both mixed unions — the superseded require.Error control flipped — the 56-branch union, the DOUBLE union display column, and the DOUBLE/DECIMAL128 CTAS column inference), pkg/sql/plan/function and pkg/sql/colexec are green, go vet is clean; the focused BVT compare passes 206/206 for func_cast_omitted_char_length with the regenerated expectations — the recorded mixed-domain rejection row replaced by numeric aggregation, and new rows for the literal mix (13.0), the 56-branch union (672.0) and both bare-render CTAS regressions (show-create plus downstream SUM/MAX/AVG and ordering). func_cast.test row 772 and func_coalesce's four temporal rows keep their documented pre-existing status; greatest_least_numeric rows 123/204 fail identically to the pre-change head (recorded since 11-10).

Known divergence from the base, intentional and established by the accepted exact-integer design: CTAS of a bare explicit-TEXT render creates the DECIMAL128(38,0) column (decimal(38,0)), where the frozen base created bigint unsigned through its UINT64 cast; integer values stay exact in both.

…ngth CAST AS CHAR

CAST(expr AS CHAR) / CONVERT(expr, CHAR) without a length built the target as
VARCHAR(65535) in the grammar and the cast executor width-enforced it, silently
truncating results over 64 KiB (strings and stored LONGTEXT reads) and
invalidating serialized JSON documents and scalar strings over 64 KiB (matrixorigin#32374).
Explicit casts of JSON scalar strings also exposed the unquoted payload instead
of the serialized form, because character-target casts never bound the
explicit-cast overload and jsonToStr unconditionally unquoted scalar strings.

- mysql_sql.y: both omitted-length CHAR branches (CAST/:: and CONVERT) map the
  target to the unbounded TEXT family (MYSQL_TYPE_TEXT) with DisplayWith=0,
  matching the grammar's own TEXT token, so the canonical rendering stays a
  re-parseable bare "text" — CREATE TABLE ... AS SELECT rebuilds its INSERT ...
  SELECT by re-rendering and re-parsing the source select (build_ddl.go), and
  the previous VARCHAR target both truncated and rendered un-reparseably.
  mysql_sql.go regenerated with the committed goyacc (zero conflicts).
- base_binder.go: explicit character and binary CAST/CONVERT targets now bind
  the dedicated explicit-cast overload (4.2-dev-applicable subset of matrixorigin#29508);
  DECIMAL and LONGLONG behavior unchanged.
- func_cast.go: in explicit cast mode a JSON scalar string serializes with its
  enclosing quotes and escaping per MySQL's JSON conversion rules; implicit
  string coercion keeps the unquoted payload.
- Tests: parser round-trip and render-parity tests, binder target tests,
  executor width/serialization UTs, and a new BVT
  (func_cast_omitted_char_length) covering large strings, 65535/65536 and
  multibyte boundaries, NULL/empty, explicit CHAR(10), stored columns, JSON
  documents and escaped scalars, and both string and JSON CTAS compositions.
  Recorded expectations of existing BVT files that pinned the old VARCHAR
  rendering/metadata for these casts were aligned to the intentional TEXT
  metadata; unrelated stale rows proven pre-existing on the base commit are
  left untouched.

Related to matrixorigin#32336, Related to matrixorigin#32374
…rget

CI on the merged 4.2-dev head failed three pkg/sql/plan UTs. They still
expected the legacy VARCHAR(65535) projection of omitted-length
CONVERT(x, CHAR), or keyed cast(... AS CHAR) results as VARCHAR in the
ENUM/SET special-order provenance cases. This PR intentionally binds
omitted-length CHAR/CONVERT targets to the unbounded string type
(T_text) so the cast never width-truncates (matrixorigin#32336, matrixorigin#32374), so those
plan-level expectations move from VARCHAR to TEXT.

Only the asserted result types changed; the provenance contracts
("stays lexical" / "clears provenance") and the explicit CHAR(N)/BINARY
controls are unchanged. The recursive-CTE cast case keeps its VARCHAR
sort key because it flows through the provenance-clearing path rather
than the cast target.

Verified with the focused rerun of the three tests and the complete
pkg/sql/plan package suite (mo-cgo-test -count=1), plus go vet on the
package; all green.
@XuPeng-SH

XuPeng-SH commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

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

Commit: 768075a0c87fbda40171be59f973b0be5ce3be46

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: 768075a0c87fbda40171be59f973b0be5ce3be46

Assessment: request_changes

Existing cast capabilities are reused appropriately, but VARCHAR math results and selective FLOAT64 repairs violate numeric contracts. The existing consumer defect remains open; public SQL independently confirms an additional precision regression for existing TEXT integers.

Model: gpt-6.1-sol / max

Session: 01a1a004-90c3-73b1-acc9-3d4636452003 · slot 0 · generation 0

  • P1 pkg/sql/plan/function/list_builtIn.go:7736: Consume unary CEIL/FLOOR over omitted-length CHAR/CONVERT through aggregates, nested numeric functions, JSON or derived columns.
    Impact: Returning VARCHAR changes numeric semantics: aggregates compare strings or reject arguments, derived expressions concatenate or sort lexically, and nested functions raise range errors. Preserve numeric consumption across existing consumers and add composed regression coverage.
    Evidence: Fresh public SQL shows SUM(CEIL(CAST(v AS CHAR))) over '2','10' rejecting VARCHAR instead of returning the base's 12. ROUND(CEIL(CAST('1e40' AS CHAR))) raises an INT64 range error instead of succeeding. See discussion-candidate.jsonl and discussion-base.jsonl. Revalidated same-head controls also prove incorrect MAX/MIN, JSON typing and derived results. The author's acknowledged scope exclusions do not resolve these regressions.

  • P1 pkg/sql/plan/base_binder.go:3485: Compare or calculate with unary CEIL/FLOOR over an existing TEXT integer above 2^53.
    Impact: The unconditional FLOAT64 cast destroys the prior exact integer domain, producing false equality, incorrect arithmetic and lost filter matches. Preserve exact integer consumption for existing TEXT inputs while retaining the appropriate prior FLOAT64 behavior of CHAR compositions.
    Evidence: CEIL(CAST('9007199254740993' AS TEXT))=9007199254740992 returns 1 at head versus 0 at the exact base; FLOOR behaves identically. Subtraction returns 0 instead of 1, and CEIL(v)>9007199254740992 incorrectly excludes a stored TEXT row. All five precision witnesses fail only on the candidate. Standalone exact digits, small TEXT and approximate CHAR controls pass on both. See discussion-results.json.

Validation:

  • Revalidated and retained complete 33-path same-head coverage, four passing owner suites with all 32 added test roots, exact parser regeneration, scoped build/format/lint, two 100-repeat focused race checks and full colexec race coverage.

  • Current isolation preflight passed. Verified 173 native inputs and retained outputs before reuse; used assigned caches and test-exec.

  • New public SQL selection: seven candidate failures and three passing controls; all ten exact frozen-base production controls passed.

  • All 83 discussion keys reconciled. Source remains unchanged; retained and fresh receipts and logs are reconciled in receipt-reconciliation.json.

Limitations:

  • No full distributed BVT or multi-CN run is claimed. Existing unrelated test skips and unchanged-file molint diagnostics remain documented.

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

Codex automated review

A separate SUBSTRING_INDEX regression remains blocking: fractional TEXT counts previously used the FLOAT64 overload and now select INT64, causing valid queries to fail. My previous blocker for finite FLOAT64 values above 76 digits is fixed. The earlier string/JSON preservation, temporal and LEAST/GREATEST routing, operator, signed/unsigned coercion, standalone exact-integer, NULL-row, and borrowed-executor fixes remain in place; invalid composed YEAR behavior stays accepted as non-blocking. Another reviewer's two CEIL/FLOOR blockers remain unresolved: VARCHAR results lose numeric behavior in composed consumers, and FLOAT64 comparison retyping rounds exact TEXT integers. They are recorded only here to avoid duplicate findings. Since the previous reviewed head, only the CEIL/FLOOR return-type test expectation changed. Four focused omitted-length parser tests passed. Parser regeneration and gofmt matched the checked-in generated parser apart from the scratch output-path header. Planner/function tests were not run because this checkout lacks cgo/libmo.dylib, cgo/libmo.so, and the thirdparties/install headers and libraries; the finding follows from the inspected base/head overload-selection and cast paths.

P1 - Preserve SUBSTRING_INDEX's FLOAT64 count coercion for TEXT inputs (pkg/sql/plan/function/type_check.go:2511)

SELECT SUBSTRING_INDEX('a,b,c', ',', CAST('2.9' AS TEXT)) returns 'a,b' on the base but now fails with 'invalid argument cast to int'. On the base, TEXT-to-FLOAT64, TEXT-to-UINT64, and TEXT-to-INT64 all have preference 2, so fixedTypeMatch retains SUBSTRING_INDEX's first-listed FLOAT64 overload (list_builtIn.go:3793-3802). getCount then converts 2.9 to int64(2) (func_binary.go:6319-6329). The new global TEXT-to-INT64 preference selects the third-listed INT64 overload instead. Its implicit cast reaches strToSigned and parseSignedCastString, where strconv.ParseUint rejects the decimal token '2.9' (func_cast.go:6143-6158,6411-6418). This affects existing TEXT columns as well as omitted-length CAST AS CHAR counts. Preserve the FLOAT64 route for this argument or add a TEXT path with equivalent parsing and count semantics, and cover fractional TEXT counts. This is a distinct consumer and failure domain from the outstanding CEIL/FLOOR findings and the repaired upper-unsigned ROUND/TRUNCATE issue.

@XuPeng-SH

XuPeng-SH commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

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

Commit: 768075a0c87fbda40171be59f973b0be5ce3be46

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: 768075a0c87fbda40171be59f973b0be5ce3be46

Assessment: request_changes

New discussion establishes a SUBSTRING_INDEX regression. The two prior CEIL/FLOOR findings remain unresolved. Reusing TEXT is reasonable, but selective coercion repairs still break existing numeric contracts.

Model: gpt-6.1-sol / max

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

  • P1 pkg/sql/plan/function/list_builtIn.go:7736: Aggregates or nested numeric functions consume unary CEIL/FLOOR over omitted-length CHAR casts.
    Impact: VARCHAR results lose numeric semantics: MAX/MIN compare lexically, SUM rejects the argument, and nested ROUND can raise integer-range errors. Preserve numeric consumption and cover these compositions.
    Evidence: Retained from review 5941775973, which reports exact-head/base SQL controls. Current VARCHAR returns at lines 7736/8007 and the operator-only retyping whitelist in base_binder.go:3463 remain unchanged; aggregate and ROUND consumers are excluded.

  • P1 pkg/sql/plan/base_binder.go:3485: Compare or calculate with CEIL/FLOOR over existing TEXT integers above 2^53.
    Impact: Unconditional FLOAT64 conversion loses exact integers, causing false equality, incorrect arithmetic and missing filter matches. Preserve the existing exact-integer domain.
    Evidence: Retained from review 5941775973. Its witness CEIL(CAST('9007199254740993' AS TEXT)) = 9007199254740992 changes from false to true. Current isCeilFloorTextRenderExpr also matches explicit TEXT inputs, and this unchanged line casts their exact digit rendering to FLOAT64.

  • P1 pkg/sql/plan/function/type_check.go:2511: SELECT SUBSTRING_INDEX('a,b,c', ',', CAST('2.9' AS TEXT)); or equivalent stored TEXT counts.
    Impact: Previously successful queries now fail with an integer-cast error instead of returning 'a,b'. Preserve SUBSTRING_INDEX's former floating-point count coercion and add fractional TEXT regression coverage.
    Evidence: Newly confirmed: the unchanged registry lists FLOAT64 first. Base conversion costs tie at 6; this preference change makes INT64 cost 1. The inserted implicit cast reaches parseSignedCastString and rejects '2.9', whereas the former FLOAT64 path truncates it to count 2. Source audit confirms unchanged numeric controls.

Validation:

  • Compared new review 5942711675 with exact-head review 5941775973; reconciled all 86 discussion keys and relevant linked issues.

  • Bounded source audit passed: checks/1794934776185317672-2.json. Source hashes, selection results and log reconciliation are retained in source-audit.json and receipt-reconciliation.json.

Limitations:

  • No fresh Go/SQL tests were run. Prior runtime results are attributed to the supplied authenticated review; its raw execution artifacts were not supplied.

…tions

Review follow-up for matrixorigin#32336/matrixorigin#32374 (PR matrixorigin#32438).

The composed-consumer retype now covers every numeric consumer of the
CEIL/CEILING/FLOOR digit render, and stays provenance-aware:

- An omitted-length CAST/CONVERT-to-CHAR render retypes to FLOAT64 (the
  exact base's VARCHAR CeilStr/FloorStr route) for the arithmetic/unary
  operators, comparisons, BETWEEN/IN, and now also the MAX/MIN/SUM/AVG
  aggregates and the nested ROUND/TRUNCATE/POWER/ABS scalars:
  MAX/MIN compare numerically instead of by bytes, SUM binds again, and
  ROUND(CEIL(CAST('1e40' AS CHAR))) keeps the FLOAT64 domain instead of
  hitting an INT64 range error.
- json_object value positions and json_array entries apply the same
  retype, so the base's numeric result keeps embedding as a JSON number
  ("{"v": 21}", "[5]") instead of a digit string; json_object keys keep
  their string typing.
- An explicit TEXT render (TEXT columns, CAST ... AS TEXT) retypes to
  Decimal128(38,0) instead, preserving the exact integer domain: comparisons,
  arithmetic, aggregates, IN-lists and the ORDER BY hidden key keep
  CEIL(CAST('9007199254740993' AS TEXT)) = 9007199254740992 false, and
  json_object embeds the exact integer.
- INTERVAL operands still veto the retype, keeping the temporal
  date_add/date_sub string rewrite.

Regression coverage: plan-level composed-consumer tests (aggregates,
nested scalars, JSON builders, exact-integer TEXT compositions, IN-list
controls) plus BVT rows for the composed aggregates/scalars, the JSON
embedding columns, the large-integer comparison/arithmetic controls and
a TEXT-column control table.
The T_text-to-INT64 implicit-cast preference that keeps BIN/SPACE and
unary +/- on their signed INT64 peers (matrixorigin#32336) also flipped
SUBSTRING_INDEX's TEXT count: SELECT SUBSTRING_INDEX('a,b,c', ',',
CAST('2.9' AS TEXT)) returned 'a,b' on the exact base (the all-tie
T_text cast costs kept the first-listed FLOAT64 overload, whose
getCount truncates 2.9 to 2) but failed with 'invalid argument cast
to int' once the INT64 overload's signed-string cast won.

Register a dedicated SUBSTRING_INDEX matcher: a TEXT count keeps the
FLOAT64 overload with the FLOAT64 implicit-cast target, mirroring the
unaryTildeTypeMatch per-function pattern. The T_text cast-preference
table stays untouched for every other consumer, VARCHAR/CHAR counts
keep their own INT64 peer routes they already had at the base, and
non-TEXT inputs keep plain fixedTypeMatch.

Coverage: TestSubstringIndexTextCountKeepsBaseFloat64Route pins the
FLOAT64 selection, the VARCHAR INT64 peer and the truncating executor
route; BVT rows pin the fractional/integer widened counts, the
CONVERT spelling, the VARCHAR integer peer and a stored TEXT-column
count table (pure append: every previously committed result row stays
byte-identical).
@gouhongshen

Copy link
Copy Markdown
Contributor Author

Replying to reviews PRR_kwDOFEPiGM8AAAABYjq4Uw and PRR_kwDOFEPiGM8AAAABYihOZQ (head 768075a0c8), and to the same SUBSTRING_INDEX finding in the local PRR_kwDOFEPiGM8AAAABYjaVew summary.

CEIL/FLOOR P1s (both reviews, retained from review 5941775973) — fixed at e7d8515934: the composed-consumer retype is provenance-aware, covering the MAX/MIN/SUM/AVG aggregates, nested ROUND/TRUNCATE/POWER/ABS scalars and the json_object/json_array builders (FLOAT64 target for omitted-length-CHAR renders, exact DECIMAL128 for explicit-TEXT renders). Evidence and regression coverage: the two resolved review threads (discussion_r4603283483, discussion_r4603285158), the plan/function UTs, and the full-file BVT compare.

SUBSTRING_INDEX P1 (SELECT SUBSTRING_INDEX('a,b,c', ',', CAST('2.9' AS TEXT)) changed from 'a,b' to invalid argument cast to int) — confirmed real, fixed at 2db61d6. The exact base resolved a TEXT count through the first-listed FLOAT64 overload (every T_text-to-numeric implicit cast costed the same; getCount then truncates 2.9 to 2). This PR's T_text-to-INT64 cast preference — which keeps BIN/SPACE and unary +/- on their signed INT64 peer routes — was winning the count's INT64 overload, whose signed-string cast rejects fractional tokens.

The fix registers a dedicated matcher for SUBSTRING_INDEX (substringIndexCheck, pkg/sql/plan/function/type_check.go, in the style of unaryTildeTypeMatch): a TEXT count keeps the FLOAT64 overload with the FLOAT64 implicit-cast target; the T_TEXT→INT64 table preference stays untouched for every other consumer. VARCHAR/CHAR counts keep their own INT64 peer route they already had at the base, and non-TEXT inputs keep plain fixedTypeMatch.

  • 2db61d6 reproduces the base values verbatim: SUBSTRING_INDEX('a,b,c', ',', CAST('2.9' AS TEXT)) → 'a,b', '1.4' → 'a', CONVERT('99.5', CHAR) → 'a,b,c', stored TEXT-column counts return their truncated results, and substring_index('a,b,c', ',', '2') keeps its VARCHAR INT64 peer result.
  • UT TestSubstringIndexTextCountKeepsBaseFloat64Route (func_omitted_length_consumers_test.go) pins the selection (TEXT count == FLOAT64 overload with a FLOAT64 cast target; VARCHAR count == INT64 peer) and the executor route (2.9 → 'a,b', 1.4 → 'a', 99.5 → 'a,b,c'); TestNumericTextCompositionsKeepSignedInt64Peer still pins the untouched BIN/SPACE/unary INT64 peers.
  • BVT rows appended to func_cast_omitted_char_length.test (fractional/INTEGER widened counts, a CONVERT spelling and a stored TEXT-column count table); expected rows regenerated against the fixed binary, pure append after every previously committed row.

@XuPeng-SH

XuPeng-SH commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

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

Commit: 2db61d62fc44ce78a2a9a835805967da72ffb4bd

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: 2db61d62fc44ce78a2a9a835805967da72ffb4bd

Assessment: request_changes

The lossless CHAR and JSON cast checks passed, and SUBSTRING_INDEX again accepts fractional TEXT counts. Unary CEIL/FLOOR still loses numeric semantics across derived queries, and CTAS can change the numeric type when it reparses the source.

Model: gpt-6.2-sol / xhigh

Session: 01a1a004-90c3-73b1-acc9-3d4636452003 · slot 0 · generation 0

  • P1 pkg/sql/plan/function/list_builtIn.go:7776: A derived table projects CEIL(CAST(v AS CHAR)) over VARCHAR rows '2' and '10'. The outer query orders or sums the projected column.
    Impact: ORDER BY silently returns 10 before 2, and SUM rejects the VARCHAR argument. The frozen base returns 2 before 10 and a sum of 12.
    Evidence: The MySQL probe reproduced both failures. Direct SUM, the same queries using the legacy VARCHAR cast route, and the frozen-base controls passed. The derived binding exports the VARCHAR type at query_builder.go:10003, so the outer consumer cannot see the function marker used by the numeric rewrites. Return a numeric type that survives projection boundaries while preserving FLOAT64 for omitted CHAR and exact integers for existing TEXT inputs.

  • P2 pkg/sql/parsers/dialect/mysql/mysql_sql.y:12432: CREATE TABLE AS SELECT uses CEIL(CAST('1e90' AS CHAR)) + 1 as its source expression.
    Impact: The source SELECT succeeds on its own, but CTAS fails during table population with a DECIMAL128 range error. The same CTAS succeeds on the frozen base.
    Evidence: The MySQL probe recorded CTAS generating an INSERT with CAST('1e90' AS TEXT). Formatting drops the omitted-CHAR distinction that base_binder.go:3524 uses to select FLOAT64. Rebinding then selects DECIMAL128. Preserve the cast semantics through the CTAS round trip and cover a composed numeric source above the decimal range.

Validation:

  • Parser regeneration matched the committed parser byte for byte. The source audit verified all 34 changed paths and accounted for all 93 discussion keys.

  • All four owning Go packages passed, including all 36 added test roots. The colexec race suite and 100 race repetitions of each executor ownership test passed.

  • The current-head MySQL probe passed eight controls and reproduced all three reported failures. All six selected frozen-base production-overlay cases passed. Receipts and logs are indexed in validation-report.json.

  • Frozen CI records 14 successes, including build, UT, static analysis, coverage, PROXY and PESSIMISTIC BVT, with 13 skipped and two neutral checks.

Limitations:

  • The local SQL probe used one client connection to an embedded cluster. Full distributed BVT evidence comes from the supplied CI snapshot.

  • Two historical replies contained temporary-file references. The associated fixes were assessed from current source, tests, and the available discussion.

@iamlinjunhong iamlinjunhong 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 2db61d62fc44ce78a2a9a835805967da72ffb4bd against 4.2-dev base 8c77e14665f054b9065a1cc2789017f7b9fc98c5, within the established scope of #32336 and #32374. Two confirmed regressions require changes.

[P1] Preserve numeric CEIL/FLOOR results across query boundaries

Location: pkg/sql/plan/base_binder.go:3494.

CREATE TABLE t(v VARCHAR(8));
INSERT INTO t VALUES ('2'), ('10');
SELECT MAX(c), MIN(c)
FROM (SELECT CEIL(CAST(v AS CHAR)) AS c FROM t) d;
SELECT SUM(c)
FROM (SELECT CEIL(CAST(v AS CHAR)) AS c FROM t) d;

The exact base exports FLOAT64 from the inner CEIL, so MAX/MIN produce 10/2 and SUM produces 12. The current head exports VARCHAR. The outer argument is a ColRef, so ceilFloorTextRenderNumericTarget returns false at GetF() and the new aggregate rewrite does nothing. MAX/MIN therefore select the string executor and produce 2/10; SUM rejects VARCHAR during binding (fixedUnaryAggTypeCheck / SumSupportedTypes). The direct-expression tests added in this round do not cover this boundary. FLOOR and CTE compositions are affected too. Preserve the numeric contract through projected columns and cover these composed queries. This is the remaining numeric-consumer regression from the previous review, with a new concrete boundary witness.

[P1] Preserve omitted-CHAR provenance before selecting the numeric domain

Location: pkg/sql/plan/base_binder.go:2826.

CREATE TABLE t_domain(v VARCHAR(8));
INSERT INTO t_domain VALUES ('1e40');
SELECT CEIL(c) + 1
FROM (SELECT CAST(v AS CHAR) AS c FROM t_domain) d;

This query succeeds through FLOAT64 on the exact base. At the current head c is TEXT, but its AST is a column reference, so isOmittedLengthCharCastTree rejects it and CEIL binds ordinary overload 13 instead of marker 15. The arithmetic rewrite then runs and selects DECIMAL128(38,0) at line 3514. CeilTextUnary renders 1e40 as 41 digits; the inserted implicit decimal cast rejects that value, failing a previously valid query. FLOOR and CONVERT share this path. Unlike the first finding, the CEIL function is visible to the consumer here: the failure is the wrong numeric-domain choice after losing the input's provenance. Track that provenance through the input projection, or otherwise preserve the base FLOAT64 domain, with a regression case beyond 38 digits.

The author explicitly answered the previous two inline findings in 4603283483 and 4603285158. Their direct aggregate/scalar and exact-integer comparison witnesses are repaired; the first issue remains incomplete across query boundaries. The SUBSTRING_INDEX fractional-TEXT-count finding is also repaired by substringIndexCheck, with an explicit author reply. Earlier string/JSON, temporal, operator, unsigned-range, standalone precision, NULL-row and borrowed-executor repairs remain present. Historical replies 4539274179/4539274628 still contain only temporary-file references; their associated code repairs were independently checked.

Validation: inspected the complete 34-file diff and relevant exact-base/head binding, coercion, aggregation and ownership paths. The normalized generated-parser changes match the grammar actions. The read-only PR artifact check passed. Local Go/SQL/BVT execution was skipped because these findings follow from deterministic binding and typed executor paths; no local runtime pass is claimed. No documentation files changed, so documentation-specific checks were inapplicable. Source and GitHub state were not modified.

The supplied exact-head CI snapshot is not entirely success: 29 checks = 14 success, 13 skipped, 2 neutral, with none failed or pending. CI Required passed. Skipped and neutral checks are not passes.

Comment thread pkg/sql/plan/base_binder.go Resolved
Comment thread pkg/sql/plan/base_binder.go Resolved
@XuPeng-SH

XuPeng-SH commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

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

Commit: 2db61d62fc44ce78a2a9a835805967da72ffb4bd

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: 2db61d62fc44ce78a2a9a835805967da72ffb4bd

Assessment: request_changes

Both findings from review 5945019598 remain open. The follow-up confirmed a third regression. Projecting an omitted-length CHAR cast before calling CEIL or FLOOR can turn a valid FLOAT64 calculation into a DECIMAL128 range error.

Model: gpt-6.2-sol / xhigh

Session: 01a1a004-90c3-73b1-acc9-3d4636452003 · slot 0 · generation 0

  • P1 pkg/sql/plan/function/list_builtIn.go:7776: A derived table projects CEIL(CAST(v AS CHAR)) for rows '2' and '10'. The outer query orders or aggregates that column.
    Impact: ORDER BY returns 10 before 2, MAX and MIN return 2 and 10, and SUM rejects the argument. The frozen base sorts numerically, returns 10 and 2 for MAX and MIN, and returns 12 for SUM.
    Evidence: The retained MySQL probes reproduced the ORDER BY and SUM failures. The follow-up reproduced the MAX/MIN reversal. query_builder.go:10003 exports the VARCHAR result type, and the outer binder receives a column reference that the numeric rewrite cannot recognize. Preserve the numeric result type across projection boundaries.

  • P2 pkg/sql/plan/base_binder.go:2826: An inner query projects CAST(v AS CHAR) or CONVERT(v, CHAR) for a value of '1e40'. The outer query calls CEIL or FLOOR on the alias and adds 1.
    Impact: The previously valid FLOAT64 calculation fails with a DECIMAL128 range error.
    Evidence: The alias reaches the binder as a TEXT column reference, so it misses the omitted-CHAR overload. Arithmetic then takes the DECIMAL128 branch at line 3514. Both spellings failed through MySQL on the candidate and passed on the frozen base. The direct CHAR, projected VARCHAR, and exact TEXT controls passed. Preserve the omitted-CHAR numeric domain through input projections while retaining exact integer behavior for existing TEXT inputs.

  • P2 pkg/sql/parsers/dialect/mysql/mysql_sql.y:12432: CREATE TABLE AS SELECT uses CEIL(CAST('1e90' AS CHAR)) + 1 as its source expression.
    Impact: The source SELECT succeeds, but CTAS fails during table population with a DECIMAL128 range error. The frozen base completes the same CTAS.
    Evidence: The retained MySQL probe recorded CTAS generating an INSERT with CAST('1e90' AS TEXT), which loses the omitted-CHAR distinction before rebinding. Preserve the numeric domain through formatting and reparsing, and cover the wide numeric expression in a CTAS regression test.

Validation:

  • Matched the frozen head, base, and patch to authenticated review 5945019598. Accounted for all 98 discussion keys and verified nine retained receipts and their logs.

  • The fresh MySQL probe reproduced two input-projection range errors and the MAX/MIN reversal. Three candidate controls and all six frozen-base production-overlay cases passed. Receipts and logs are indexed in validation-report.json.

  • Reused matching parser regeneration, four normal Go package passes, the colexec race suite, and 100 race repetitions of each executor ownership test from review 5945019598.

Limitations:

  • The fresh SQL probe used one client connection to an embedded cluster. Distributed BVT evidence comes from the supplied CI snapshot.

  • Two historical replies contained only temporary-file references. Their associated fixes were assessed from the available source and tests.

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

Codex automated review

At head 2db61d6, the only commit since the previously reviewed head e7d8515 is the SUBSTRING_INDEX fix, and my prior blocking finding is repaired. The new substringIndexCheck matcher (pkg/sql/plan/function/type_check.go) keeps a T_text third argument on SUBSTRING_INDEX's first-listed FLOAT64 overload with the same implicit-cast construction fixedTypeMatch uses, exactly the route the base selected when every T_text-to-numeric cast cost the same (preferLevel 2), while VARCHAR/CHAR counts keep their base INT64 peer, every non-TEXT input keeps plain fixedTypeMatch, and the executor's getCount truncation ('2.9' producing 'a,b') is unchanged; iamlinjunhong and mo-bot independently record the same repair in their current-head reviews. A registry-wide scan I ran for this regression class found no other function whose first-listed overload for a TEXT argument position is a non-INT64 numeric; BIN/SPACE/unary peers remain on the documented 'TEXT shares the CHAR/VARCHAR string-number coercion domain' contract that earlier rounds accepted. Dispositions of all previously blocking topics: REVERSE, JSON/temporal LEAST/GREATEST, CEIL/FLOOR string parsing, TIMESTAMPADD/TIMESTAMP/EXTRACT/STR_TO_DATE routes, upper-unsigned ROUND/TRUNCATE, standalone exact-integer renders, NULL-row handling and the finite FLOAT64 domain above 76 digits remain fixed in code; the invalid composed YEAR behavior stays accepted as non-blocking; iamlinjunhong's two CEIL/FLOOR P1s from head 768075a are answered at e7d8515 by the marker-overload provenance retype, and I verified in code that the demanded direct compositions are restored (arithmetic operators, comparisons, BETWEEN/IN, MAX/MIN/SUM/AVG, ROUND/TRUNCATE/POWER/ABS, json_object/json_array, ORDER BY hidden keys, mixed IN-lists, INTERVAL veto). However, new reviews by iamlinjunhong (19:21, two inline P1s) and mo-bot (19:29, one P1 and two P2s) at this same head re-open the composed-consumer contract at query boundaries and remain unaddressed by the author: outer MAX/MIN/SUM over a derived table projecting CEIL(CAST(v AS CHAR)) see a VARCHAR ColRef that the retype cannot match, so MAX/MIN compare strings and SUM rejects VARCHAR (the base exported FLOAT64 and returned 10/2 and 12); an outer CEIL over a projected CAST(v AS CHAR) column loses the omitted-CHAR provenance because the AST is a column reference, binds ordinary overload 13 and retypes to DECIMAL128, whose cast rejects 41-digit renders like 1e40 that the base computed through FLOAT64; and CTAS formatting/reparse of CAST(x AS CHAR) loses the omitted-CHAR distinction the same way. I confirmed those mechanisms in binder and executor code (ceilFloorTextRenderNumericTarget requires a function expression; isOmittedLengthCharCastTree requires a literal cast tree; SumSupportedTypes excludes VARCHAR; the derived-table export uses the projected VARCHAR type), so those findings are valid but belong to their reviewers and are not re-emitted here. Test evidence: four focused omitted-length parser tests pass (exit 0, log retained) and gofmt is clean on the changed Go files; the new plan/function UT for SUBSTRING_INDEX and the appended BVT rows could not run locally because this checkout lacks built cgo/thirdparties prerequisites (usearch.h, xxhash.h and roaring.h missing, cgo sources unbuilt), a recorded limitation, so those expectations rest on the static overload-selection and cast-path analysis above. No blocking or non-blocking findings of my own remain.

@XuPeng-SH

XuPeng-SH commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

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

Commit: 2db61d62fc44ce78a2a9a835805967da72ffb4bd

New discussion was assessed; the previous review remains unchanged.

…boundaries

Review round of PR matrixorigin#32438 (iamlinjunhong PRR_kwDOFEPiGM8AAAABYlo5Eg, mo-bot
PRR_kwDOFEPiGM8AAAABYlnMzg) on head 2db61d6:

- Record the omitted-length CAST/CONVERT-to-CHAR widening at the defining
  projection (BindContext.omittedCharWidenProjects) and walk a boundary
  column reference back to its defining scope (resolveProjectedColumnSource),
  so outer MAX/MIN/SUM/AVG, arithmetic, nested scalar/JSON compositions and
  the MySQL special ORDER BY key retype on the recorded domain instead of
  byte-comparing the exported digit render: FLOAT64 for the omitted-CHAR
  provenance, exact DECIMAL128 for explicit TEXT casts/columns (matrixorigin#32336,
  matrixorigin#32374).
- Resolve isProjectedOmittedCharWidenColumn in the one-argument CEIL/FLOOR
  marker branch, so CEIL(c)+1 over a projected omitted-CHAR column binds
  marker overload 15 and keeps its base FLOAT64 domain ('1e40' rows work
  again).
- Keep the omitted-length signature (family "char", DisplayWith -1) in the
  grammar's CAST/CONVERT targets so tree.Format renders a re-parseable
  "as char": the CTAS render+re-parse of its INSERT ... SELECT re-enters the
  omitted-length action instead of binding an explicit TEXT cast, and
  CREATE TABLE ... AS SELECT CEIL(CAST('1e90' AS CHAR)) + 1 succeeds with
  the FLOAT64 domain. mysql_sql.go regenerated with the repository goyacc,
  parser render/reparse pins updated.
- Tests: TestCeilFloorOmittedCharWidenMarkerSurvivesQueryBoundaries and
  TestCeilFloorTextRenderNumbersSurviveQueryBoundaries (pkg/sql/plan),
  parser render/reparse pins, and the derived/CTE/nested boundary,
  projected-domain, TEXT-control and CTAS BVT sections with a regenerated
  result file whose committed rows are byte-identical.
@gouhongshen

Copy link
Copy Markdown
Contributor Author

Review follow-up #4 at 32d9933: numeric contract across query boundaries and the CTAS round trip

The two P1s of @iamlinjunhong's review (PRR_kwDOFEPiGM8AAAABYlo5Eg) and the mo-bot review's P1 (PRR_kwDOFEPiGM8AAAABYlnMzg) are fixed and answered in their threads; the mo-bot CTAS finding (P2) rides on the same grammar change:

  1. Numeric CEIL/FLOOR results through projected columns — the outer scope now retypes boundary column references on the defining scope's recorded domain: planner-local provenance (BindContext.omittedCharWidenProjects) written when the projection binds an omitted-length CAST/CONVERT-to-CHAR, plus resolveProjectedColumnSource walking the reference back to the defining expression. MAX/MIN/SUM/AVG, arithmetic, nested scalar/JSON compositions and the ORDER BY hidden key retype on it — FLOAT64 for the omitted-CHAR provenance, exact DECIMAL128 for explicit TEXT casts/columns.
  2. Omitted-CHAR provenance of a projected input — isProjectedOmittedCharWidenColumn resolves the column reference through the same walk inside the one-argument CEIL/FLOOR marker branch, so CEIL(c)+1 over (SELECT CAST(v AS CHAR) AS c ...) d keeps marker overload 15 and its base FLOAT64 domain; '1e40' and '1e90' magnitudes succeed again, and FLOOR, CONVERT, CTE and nested forms share the path.
  3. CTAS round trip — mysql_sql.y had rewritten the omitted-length target's textual signature (family "text", DisplayWith 0), so AsSource.Format rendered cast(... as text) and the CTAS re-parse bound the explicit-TEXT domain, failing your CEIL(CAST('1e90' AS CHAR)) + 1 witness with the DECIMAL128 range error. The cast target now keeps the re-parseable "char" signature (family "char", DisplayWith -1) while still mapping the Oid to MYSQL_TYPE_TEXT for plan binding, so the rendered source re-enters the omitted-length action: both the direct and the projected CTAS shapes in the BVT now create double columns carrying the value (func_cast_omit_char_ctas2/3 plus show create table rows), and explicit CAST(... AS TEXT) remains distinguishable through its own rule. mysql_sql.go is regenerated with the repository's committed goyacc (the regeneration was verified byte-identical), and the parser pins now assert the "char" rendering plus its reparse round trip (TestCastOmittedCharLengthRendersReparseableChar, TestPitrInternal).

Validation: focused pkg/sql/plan selection green (16 test roots incl. the two new boundary tests), focused pkg/sql/parsers/dialect/mysql cast/render pins green; the service was rebuilt from the worktree and the boundary probes reproduce the base values — max 10 / min 2, sum 12, numeric ORDER BY, the '1e40' FLOAT64 domain rows, and the '1e90' CTAS round trip (probe logs: loop artifacts logs-follow/probes-followup.txt, pre-fix probes in logs-follow/probes-prefixed.txt). The regenerated func_cast_omitted_char_length.result is a pure append — all previously committed rows byte-identical — and the compare run is 100% (empty error.txt).

Known domain boundary, unchanged from the accepted exact-integer design: explicit-TEXT compositions above 38 integral digits (e.g. CEIL(CAST('1e40' AS TEXT)) + 1) reject with the DECIMAL128 range error, while the omitted-CHAR route carries those magnitudes through FLOAT64.

@gouhongshen

Copy link
Copy Markdown
Contributor Author

Review follow-up #5: the three findings of the mo-bot-local review at 19:29 are fixed and re-verified at the pushed head 32d9933

Your review PRR_kwDOFEPiGM8AAAABYlxclw reviewed head 2db61d62fc44ce78a2a9a835805967da72ffb4bd. All three findings in it are fixed and pushed at 32d99335c3 (the iamlinjunhong thread counterparts PRRT_kwDOFEPiGM64nEZe / PRRT_kwDOFEPiGM64nEZh are answered and resolved); this comment is the explicit per-finding disposition for this review. Head 32d99335c3 is unchanged since that push, and every receipt below was re-measured this turn on a mo-service binary rebuilt from that exact committed head.

  1. P1 list_builtIn.go:7776 — numeric contract of CEIL(CAST(v AS CHAR)) through a derived-table projection. The defining projection now records the omitted-length CAST/CONVERT-to-CHAR widening in planner-local provenance (BindContext.omittedCharWidenProjects), and resolveProjectedColumnSource walks a boundary column reference back to its defining expression, so the outer binder and the MySQL special ORDER BY key (projectedCeilFloorRenderDomain) retype on the recorded domain — FLOAT64 for the omitted-CHAR provenance, exact DECIMAL128 for explicit TEXT casts and TEXT columns. Re-verified at the committed head: max 10 / min 2, sum 12, avg 6/count 2/max 10, numeric ORDER BY c → 2, 10 for a t(v VARCHAR(8)) with rows '2', '10', through plain derived tables, CTEs and nested derived tables; the two TEXT-column controls keep the exact DECIMAL128 route. UT pins: TestCeilFloorTextRenderNumbersSurviveQueryBoundaries, TestOmittedLengthCeilFloorTextRenderOrderByKeepsNumericKey (both re-run green on 32d99335c3, 16 roots / 100 entries focused selection). BVT rows: test/distributed/cases/function/func_cast_omitted_char_length.test derived/CTE/nested/ORDER BY ... DESC sections, regenerated result is a pure append with a 100% compare run.

  2. P2 base_binder.go:2826 — CEIL/FLOOR over a projected CAST(v AS CHAR) / CONVERT(v, CHAR) input. isProjectedOmittedCharWidenColumn resolves the projected input column through the same provenance walk inside the one-argument CEIL/FLOOR marker branch, so the alias binds marker overload 15 again and composes on its base FLOAT64 domain instead of taking the ordinary TEXT overload 13 whose DECIMAL128(38,0) retype rejects sizes above 38 integral digits. Re-verified at the committed head: for t_domain(v VARCHAR(8)) = '1e40', CEIL(c)+1 and FLOOR(c)+1 return 1e40+1 through the CAST spelling, the CONVERT spelling, a CTE and a nested derived table; direct CEIL(CAST(v AS CHAR))+1 keeps the same value; explicit-TEXT compose (CAST(v AS TEXT)) still gets the exact DECIMAL128 domain. UT pins: TestCeilFloorOmittedCharWidenMarkerSurvivesQueryBoundaries (CAST/CONVERT/CTE/nested + the two TEXT controls asserting overload 13 and the DECIMAL128 result type).

  3. P2 mysql_sql.y:12432 — CTAS render + re-parse losing the omitted-CHAR distinction. The grammar change you quote rendered the omitted-length target as family "text"/DisplayWith 0, so CREATE TABLE ... AS SELECT CEIL(CAST('1e90' AS CHAR)) + 1 rebuilt its INSERT ... SELECT with CAST('1e90' AS TEXT) and re-bound the DECIMAL128 domain. The omitted-length target now keeps its re-parseable "char" signature (family "char", DisplayWith -1) while still mapping the Oid to MYSQL_TYPE_TEXT for plan binding, so the CTAS round trip re-enters the same omitted-length action. Re-verified at the committed head: the CTAS completes and SHOW CREATE TABLE shows the double (FLOAT64) domain for both the literal 1e90 shape and the t_domain shape, and the inserted value is 1e90+1. Regression tests: TestCastOmittedCharLengthRendersReparseableChar pins the "as char" rendering + reparse round trip at the parser level; the BVT func_cast_omit_char_ctas2/ctas3 sections cover the wide numeric CTAS source expression — regenerated result committed as a pure append.

Fresh receipts for this re-verification (all against binary rebuilt from 32d99335c3): boundary probes + controls in loop artifacts logs-r4head/ (probes-r4.txt, probes mismatch count 0; explicit-TEXT control keeps the documented DECIMAL128 range-error boundary above 38 integral digits); focused UT logs re-run on the committed head (ok pkg/sql/plan, ok pkg/sql/parsers/dialect/mysql, 0 failures). Head 32d99335c3 is also running the regular MatrixOne CI; no CI failure has been observed on it so far.

@XuPeng-SH

XuPeng-SH commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

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

Commit: 32d99335c3bf4ed0c86aabd0a003bd28ff338b61

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: 32d99335c3bf4ed0c86aabd0a003bd28ff338b61

Assessment: request_changes

Lossless CHAR and JSON casts, the earlier derived-table cases, and CTAS now pass. The planner still loses numeric semantics at other query boundaries, and two BVT fixtures retain stale column headings.

Model: gpt-6.2-sol / xhigh

Session: 01a1a004-90c3-73b1-acc9-3d4636452003 · slot 0 · generation 0

  • P1 pkg/sql/plan/function/list_builtIn.go:7776: A UNION ALL combines two projections of CEIL(CAST(v AS CHAR)) over VARCHAR rows '2' and '10'. The outer query aggregates or orders the projected column.
    Impact: SUM rejects the VARCHAR result. An ordering probe returns 10 before 2. The frozen base returns a sum of 24 for the four-row UNION and sorts 2 before 10.
    Evidence: The renderer exports VARCHAR, and the ancestry walk in base_binder.go:3614 cannot recover the numeric result through a set output. Candidate and merge-base SQL probes also distinguished CASE outputs, grouped ordering, and a deep derived chain. Preserve the numeric domain through projection and set typing so consumers can bind without rediscovering the original function.

  • P2 pkg/sql/plan/base_binder.go:3637: Both branches of a UNION ALL project CAST(v AS CHAR) for v='1e40'. The outer SELECT evaluates CEIL(n)+1 on that column.
    Impact: The query fails with a DECIMAL128 range error. The frozen base evaluates both rows successfully through FLOAT64.
    Evidence: The set output loses the omitted-CHAR origin before the CEIL overload is chosen. The candidate reproduced error 20301, while the identical base query and the candidate's ordinary derived-table controls passed. Preserve the omitted-CHAR domain through homogeneous set outputs and retain the explicit-TEXT control.

  • P3 test/distributed/cases/function/func_bit_count.result:120: Run the BIT_COUNT or COALESCE cases with result metadata comparison enabled.
    Impact: The saved headers expect as text for omitted-length CHAR casts, so metadata comparison reports a mismatch.
    Evidence: The MySQL endpoint returned BIT_COUNT(cast(64 as char)) and cast(COALESCE(a, a) as char). The committed fixtures expect as text, including func_coalesce.result:196 and :216. Update the affected headings and retain the explicit TEXT expectations.

Validation:

  • Parser regeneration matched the committed file. Focused parser and planner tests passed. The SQL retry passed the earlier derived-table and CTAS probes, the fractional SUBSTRING_INDEX control, and the large string and JSON probes.

  • All 12 SQL cases passed against the frozen merge-base overlay. Candidate failures confirmed the numeric regressions, and a separate MySQL metadata probe confirmed both header mismatches.

  • The final audit reconciled nine current receipts, seven retained receipts, and all 108 discussion entries (receipt 1794956038907259634-2.json).

Limitations:

  • The full BVT suite was not rerun locally. Frozen CI recorded 14 successes, 13 skips, and two neutral checks.

  • The first embedded run hit a connection setup timeout before the earlier regression probes. The focused retry passed.

  • git diff --check reported mixed indentation in the grammar. Two historical replies exposed only unavailable temporary-file references.

Review repair for PR matrixorigin#32438 (issues matrixorigin#32336/matrixorigin#32374):

- The provenance walk in resolveProjectedColumnSource now descends
  through set-operation outputs (UNION/INTERSECT/MINUS and their ALL
  forms) branch by branch, so a consumer above a UNION ALL of
  CEIL(CAST(v AS CHAR)) projections recovers the base numeric domain
  only when every branch agrees on it. Heterogeneous outputs keep the
  ordinary unprovenanced binding. The shared step budget bounds the
  binding-walk and node-graph descent together.
- Aggregated scopes export group outputs as passthrough columns to the
  group tag, which no binding owns; the walk now hops to the defining
  group expression so grouped columns keep their provenance, and
  rewriteMySQLSpecialOrderByExpr applies the same numeric-domain
  recovery to ORDER BY keys typed from a group.
- retypeCeilFloorTextRenderArgs keeps its control-flow handling on a
  separate case arm: CASE/IF/IFF retype only their value arms while
  conditions keep their own binding, fixing an accidental comma-merge
  of the case labels that made every consumer operator take the
  control-flow early return.
- BVT regression: union-all sums, max/min/avg, plain and grouped ORDER
  BY, union distinct, three-branch unions, a deep derived chain, CASE
  arms, a mixed-domain control, a widen-union CEIL+1 probe, and the
  explicit-TEXT control retain the base numeric semantics.
- func_bit_count.result and func_coalesce.result now record the
  `as char` result-metadata headings the endpoint actually returns for
  omitted-length CAST(... AS CHAR), keeping the explicit TEXT
  expectations unchanged.
@gouhongshen

Copy link
Copy Markdown
Contributor Author

Review follow-up #6: the three findings of the mo-bot-local review at 22:54 are fixed and pushed at head a1e47f171b

Your review PRR_kwDOFEPiGM8AAAABYodKDQ reviewed head 32d99335c3bf4ed0c86aabd0a003bd28ff338b61; this comment is its explicit per-finding disposition. All three findings are confirmed valid, fixed (commit a1e47f171b, pushed), and covered by permanent planner UTs plus new service-recorded BVT rows; every receipt below was re-measured this round on mo-service binaries rebuilt from the exact pushed head, the previous head 32d99335c3 (reproducing all the reported failures first), and the frozen base merge-overlay commit 8c77e14665.

P1 — UNION ALL render transports (pkg/sql/plan/function/list_builtIn.go:7776). Confirmed, with two distinct defects behind it.

  1. retypeCeilFloorTextRenderArgs's consumer switch had the control-flow labels (case/if/iff) comma-merged into the arithmetic/aggregate label list; a Go label list shares one body, so max/min/sum/avg (and every composed operator name) hit the control-flow early return instead of retyping. The control-flow case is split back out, so aggregates over a projected render bind through the base FLOAT64 domain again.
  2. The provenance walk crossed derived tables and set nodes but not AGG outputs: a grouped projection exports passthrough ColRefs to the group tag, which no table binding or set node records. The walk now hops group-tag references to the defining group expression, so the hidden ORDER BY key of rewriteMySQLSpecialOrderByExpr recovers the same numeric domain for plain and grouped scopes alike (query_builder.go).

SQL receipts (isolated mo-service on the same data, one binary per tagged row — 2,10 rows except where noted):

-- select sum(n) from (select ceil(cast(v as char)) as n from tv union all select ceil(cast(v as char)) as n from tv) x
SUM(n)          review head -> ERROR 20203 invalid argument aggregate function sum, bad value [VARCHAR]
                frozen base -> 24      fixed head -> 24
-- ... order by n
ORDER BY n      review head -> 10,10,2,2   frozen base -> 2,2,10,10   fixed head -> 2,2,10,10
-- ... group by n order by n
GROUP+ORDER     review head -> (10,2) then (2,2)   frozen base -> (2,2) then (10,2)   fixed head -> (2,2) then (10,2)

CASE outputs, the deep derived chain (max(c2) over a union of two nested derived tables), UNION DISTINCT and a three-branch chain all keep the base aggregate values (recorded in the BVT section below). TestCeilFloorSetOutputsKeepBaseNumericDomains pins the binder-level contracts: the aggregate binds are FLOAT64, the plain and GROUP BY sort keys are FLOAT64, and the deep chain resolves.

P2 — widen-union composition (pkg/sql/plan/base_binder.go:3637). Confirmed. The set output lost the omitted-CHAR origin before the outer CEIL overload was chosen, so CEIL(n)+1 collapsed to the DECIMAL128 route and '1e40' raised 20301. The walk now resolves every branch's defining projection through the set node (the UNION ALL of CAST(v AS CHAR) and CONVERT(v, CHAR) branches over '1e40'), so the homogeneous widen union keeps the provenance marker and composes in FLOAT64: both rows evaluate to 1e40-scale values exactly like the frozen base, with no 20301. The explicit-TEXT branch control (UNION ALL with CAST(v AS TEXT) branches over '2.5') keeps the ordinary overload 13 and the exact-integer DECIMAL128 composition, asserted both at binder level (overload id + + operand type) and in SQL (4); heterogeneous branches still keep the ordinary unprovenanced binding — the outer aggregate does not assume one branch's domain over the other's.

P3 — result metadata (func_bit_count.result:120 etc.). Confirmed by a metadata probe: the endpoint's column labels are BIT_COUNT(cast(64 as char)) and cast(COALESCE(a, a) as char). The three func_bit_count.result headings and the two func_coalesce.result headings now expect as char; every explicit AS TEXT expectation in those files is unchanged, and both fixtures compare 100% clean in run-mode with metadata enabled.

New BVT section in func_cast_omitted_char_length.test/.result: render-union SUM/MAX/MIN/AVG rows (24 / 10, 2, 6), numeric and grouped ordering (2 before 10; (2,2) then (10,2)), UNION DISTINCT 12, three-branch 36, deep chain 10, CASE-arm sum 12, mixed-domain SUM(VARCHAR) rejection, widen-union CEIL(n)+1 1.0E40 rows with the explicit-TEXT 4 control.

One boundary note: heterogeneous set outputs (an explicit-TEXT render or cast arm beside an omitted-CHAR arm) intentionally keep their ordinary binding. The two branches carry different base domains (FLOAT64 vs exact-integer DECIMAL128) and neither may dominate, so such a union keeps the VARCHAR export; it is pinned by a require.Error UT plus the BVT rejection row.

CI repair for PR matrixorigin#32438 (issues matrixorigin#32336/matrixorigin#32374): the group-output
recovery branch added to rewriteMySQLSpecialOrderByExpr runs before the
project-tag ENUM/SET display rewrite and matched any ORDER BY key whose
RelPos equals the BindContext's groupTag. In a scope that never built
groups (the manual binds of TestQueryBuilder_bindOrderByEnum and its
Distinct sibling) groupTag and projectTag are both still zero-valued,
so the branch swallowed project-tagged keys and returned the VARCHAR
display form unchanged, skipping the display rewrite that materializes
the ENUM/SET storage-order hidden sort key. That is exactly what the
UT coverage job regressed at this branch's previous head.

The branch now applies only to scopes that actually built groups
(len(ctx.groups) > 0); real binding flows assign distinct non-zero
group/project tags, so the grouped numeric-domain recovery and every
other review-repair behavior is unchanged. The full pkg/sql/plan
package UT (including the grouped float64 sort-key and set-union
assertions) and go vet are green.
@XuPeng-SH

XuPeng-SH commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor

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

Commit: 1e0edafc6956e6381fa934ed4e87abd46af5f0fc

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: 1e0edafc6956e6381fa934ed4e87abd46af5f0fc

Assessment: request_changes

The cast fix reuses the existing TEXT and JSON conversion paths to preserve complete values. The earlier homogeneous UNION, grouped ordering, ENUM sort, and result-heading cases are addressed. Unary CEIL and FLOOR still expose numeric results as VARCHAR, and the planner’s recovery logic loses the numeric type in other valid UNION queries and in CTAS.

Model: gpt-6.2-sol / xhigh

Session: 01a1a004-90c3-73b1-acc9-3d4636452003 · slot 0 · generation 0

  • P1 pkg/sql/plan/base_binder.go:3635: Aggregate a UNION ALL column that combines CEIL(CAST(v AS CHAR)) with a numeric literal or FLOOR over explicit TEXT. A 56-branch UNION ALL of identical CEIL expressions also triggers the failure.
    Impact: Queries that bind on the frozen base now fail because SUM receives VARCHAR. The new mixed-domain BVT case records that regression as expected behavior.
    Evidence: The overlay probes reproduced the VARCHAR error in all three cases on the candidate. All three and the two-branch homogeneous control bound on the frozen base. The recovery walk requires identical branch domains and has a 48-step budget. Preserve numeric outputs before set coercion so the existing common-type rules can unify them, and update the BVT to expect numeric aggregation.

  • P2 pkg/sql/plan/function/list_builtIn.go:7776: Run CREATE TABLE dst AS SELECT CEIL(CAST(v AS CHAR)) AS n FROM src.
    Impact: The inferred column changes from DOUBLE to VARCHAR. Later queries read a stored string column, so SUM(n) fails and ordering uses string semantics.
    Evidence: The candidate and frozen-base CTAS probes inferred VARCHAR and DOUBLE respectively. Both inferred DOUBLE when the projection added + 1, which explains why the existing CTAS arithmetic control passes. Preserve the numeric return type for the bare expression and add a CTAS regression that checks the inferred column and a downstream numeric query.

Validation:

  • Isolation preflight, focused MySQL parser tests, and executor cleanup and coercion controls passed. Receipts 1794978147709777395-4.json, 1794978218277094350-2.json, and 1794978452459920265-2.json.

  • Focused candidate tests passed the committed homogeneous UNION and ENUM sort cases. Three new set probes and the bare CTAS probe failed on the candidate and passed with the frozen-base overlay. Logs are retained in head.jsonl, base.jsonl, head-ctas.jsonl, and base-ctas.jsonl.

  • The final audit verified the frozen checkout, overlay inputs, execution receipts, and all 111 discussion keys. Receipt 1794978489577471619-5.json.

Limitations:

  • The new regressions were reproduced through SQL planning and CTAS schema inference. The full distributed BVT and a fresh race run were outside local validation. Frozen CI records successful build, UT, coverage, and active BVT checks.

  • Two historical replies reference unavailable temporary files. Their associated fixes were assessed from current source and tests.

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

Codex automated review

Follow-up review of head 1e0edaf against previously reviewed 32d9933; the delta is a1e47f1 (set-operation/group provenance transports plus fixture-heading alignment) and 1e0edaf (five-line groups-existence guard fixing the ENUM/SET order-key regression a1e47f1 itself introduced in untagged bind scopes). Disposition of previous blockers: all three findings of the 22:54 review at 32d9933 are fixed and verified in code — the P1 set-output render transports (aggregates reach the retype switch, CASE/IF/IFF value arms retype via ceilFloorControlFlowValueIndexes, the provenance walk resolves every set branch plus AGG group exports, and rewriteMySQLSpecialOrderByExpr recovers grouped ORDER BY domains), the P2 widen-union CEIL marker loss (homogeneous unions keep marker overload 15, the explicit-TEXT branch control keeps overload 13, and heterogeneous rejection stays a documented, test-pinned boundary), and the P3 stale 'as text' headings (func_bit_count.result rows 120/129 and func_coalesce.result rows 196/216 updated to the endpoint labels). iamlinjunhong's last-round P1s were fixed at 32d9933 and remain fixed; the historical /tmp-only reply references stay informational. Two new findings remain: a P1 where GREATEST/LEAST/COALESCE keep string semantics for rendered CEIL/FLOOR arms (silent lexical wrong values and SUM bind rejection, deviating from both the exact base and MySQL's own numeric CEIL composition), and a P2 where the new group-hop leaf conflates group-list positions with select-position-keyed widen records. Tests: gofmt clean on the changed files; go vet ./pkg/sql/plan could not complete because this checkout's cgo prerequisites (xxhash.h, roaring.h, usearch.h, libmo from thirdparties/install) are unbuilt and building them is out of review scope, so no local focused Go tests could run; runtime evidence relies on the author's three-binary verification (fix head vs 32d9933 vs frozen base) recording the reported failures only on 32d9933 and base-matching values on the fixed head.

P1 - GREATEST/LEAST/COALESCE keep string semantics for rendered CEIL/FLOOR CHAR-cast arms (pkg/sql/plan/base_binder.go:3924)

The numeric-provenance retype whitelist in retypeCeilFloorTextRenderArgs now covers arithmetic, comparisons, IN/BETWEEN, unary, max/min/sum/avg, round/truncate/power/pow/abs, and case/if/iff value arms (through which IFNULL/NULLIF inherit the retype because the binder rewrites them to case), but greatest, least, and coalesce are absent, and each of those binds its own mixed-type unification. On the exact base a one-argument CEIL over an omitted-length CAST AS CHAR returns FLOAT64, so these wrappers unified numerically; on this head the wrapper instead sees the digit-render VARCHAR. Concrete regressions: (1) SELECT GREATEST(CEIL(CAST('10' AS CHAR)), 5) returns '5' instead of 10, because the VARCHAR render makes resolveLeastGreatestType take leastGreatestStringMixedType (func_builtin_leastgreatest.go:527), producing a VARCHAR result compared lexically, while the base unified [FLOAT64, INT64] through leastGreatestCommonNumericType; (2) SELECT SUM(COALESCE(CEIL(CAST(v AS CHAR)), 0)) FROM t over v in ('2','10') rejects 'bad value [VARCHAR]' at binding, because coalesceCheck routes the mixed list through mixedStringNumericToVarchar (func_binary.go:1114) and exports VARCHAR digits, where the base received [FLOAT64, INT64] and summed 12; (3) SELECT COALESCE(CEIL(CAST('1e40' AS CHAR)), 0) + 1 fails the inserted INT64 cast of the 41-digit render where the base returned the FLOAT64 composition. MySQL's own CEIL result is numeric in the same compositions, so the head deviates from both parity references. This is reported as a distinct residual of the consumer-contract family the previous rounds fixed (aggregates, nested scalars, CASE arms were reported separately and repaired); the required fix is extending the value-position retype to greatest/least/coalesce arguments that resolve to a render domain, with base-comparison regression rows in func_cast_omitted_char_length.test.

P2 - Group-hop provenance leaf conflates group positions with select-position widen records (pkg/sql/plan/base_binder.go:3747)

The group-tag branch that a1e47f1 added to resolveProjectedColumnSource returns a projectedColumnSource whose colPos is a GROUP-list position, but its consumer isProjectedOmittedCharWidenColumn (base_binder.go:3824) checks leaf.colPos against BindContext.omittedCharWidenProjects, which bindProjectionExprWithNumericTarget (query_builder.go:8778) records by SELECT-list position, while ProjectionBinder.BindExpr (projection_binder.go:44) folds select items to ColRef(groupTag, group-position) in GROUP BY clause order. When the GROUP BY order differs from the select order, both directions misfire. Marker loss: SELECT CEIL(c) + 1 FROM (SELECT CAST(v AS CHAR) AS c, x FROM t GROUP BY x, CAST(v AS CHAR)) d — the export folds select position 0 to the cast's group position 1, the walk checks position 1 against a record stored at select position 0, finds nothing, and CEIL binds ordinary overload 13, so '1e40' fails with the DECIMAL128 range error where the base evaluated the FLOAT64 route. Marker misfire: SELECT CEIL(c) + 1 FROM (SELECT CAST(v AS CHAR) AS w, CAST(u AS TEXT) AS c FROM t GROUP BY CAST(u AS TEXT), CAST(v AS CHAR)) d — c folds to group position 0, which collides with w's widen record at select position 0, so an explicit-TEXT provenance binds marker overload 15 and its compositions retype through FLOAT64, silently rounding exact integers the explicit-TEXT controls elsewhere pin exact ('9007199254740993' + 1 returns ...993 instead of exact ...994, and '1e40' succeeds where the documented explicit-TEXT contract rejects above 38 integral digits). The fix is to carry the select-list fold position into the group-hop leaf (or record widen markers on the group expressions), and pin grouped-boundary marker compositions beside TestCeilFloorSetOutputsKeepBaseNumericDomains, whose grouped coverage currently exercises only the position-independent ORDER BY recovery path.

@XuPeng-SH

XuPeng-SH commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor

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

Commit: 1e0edafc6956e6381fa934ed4e87abd46af5f0fc

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: 1e0edafc6956e6381fa934ed4e87abd46af5f0fc

Assessment: request_changes

The same-head discussion adds two substantiated regressions. GREATEST, LEAST and COALESCE can consume numeric CEIL/FLOOR results as strings, and grouped projections can recover the wrong cast domain. The earlier UNION and CTAS findings remain open. Preserving numeric result types through the existing coercion and schema inference paths would address the shared cause.

Model: gpt-6.2-sol / xhigh

Session: 01a1a004-90c3-73b1-acc9-3d4636452003 · slot 0 · generation 0

  • P1 pkg/sql/plan/base_binder.go:3950: Pass unary CEIL or FLOOR over an omitted-length CHAR cast to GREATEST, LEAST or COALESCE alongside a numeric value.
    Impact: GREATEST can choose the wrong value by comparing digits as strings. SUM over the resulting COALESCE expression can fail to bind.
    Evidence: The recovery switch skips all three functions. The existing coercion then chooses VARCHAR for the rendered result and numeric peer. GREATEST(CEIL(CAST('10' AS CHAR)), 5) takes the byte comparison path and selects '5' where the base numeric path selects 10. Preserve the numeric domain before these functions resolve their common type.

  • P1 pkg/sql/plan/base_binder.go:3635: Aggregate a UNION ALL column that combines an omitted-CHAR CEIL result with a numeric literal or an explicit-TEXT FLOOR result, or aggregate a 56-arm homogeneous CEIL union.
    Impact: SUM receives VARCHAR and rejects queries that bind on the frozen base.
    Evidence: The retained candidate probes failed all three cases. The frozen-base overlay passed all three, and both passed the small homogeneous control. The recovery walk requires matching branch domains and has a 48-step budget. Preserve numeric values before set coercion and update the mixed-domain BVT to expect successful aggregation.

  • P2 pkg/sql/plan/base_binder.go:3747: A grouped derived table exports an omitted-CHAR or explicit-TEXT cast at a SELECT position that differs from its GROUP BY position, and an outer CEIL or FLOOR consumes it.
    Impact: The omitted-CHAR value can lose its FLOAT64 route and fail on a value such as '1e40'. An explicit-TEXT value can acquire the FLOAT64 route and lose integer precision.
    Evidence: The group hop returns a GROUP BY index. The caller uses it to read markers recorded by SELECT position at pkg/sql/plan/query_builder.go:8783. Swapping the positions of the two cast expressions can therefore lose or falsely apply the marker. Carry the original SELECT position or look up provenance on the defining group expression.

  • P2 pkg/sql/plan/function/list_builtIn.go:7776: Create a table with CREATE TABLE dst AS SELECT CEIL(CAST(v AS CHAR)) AS n FROM src.
    Impact: The inferred column changes from DOUBLE to VARCHAR. Later SUM(n) fails and ordering uses string semantics.
    Evidence: The retained CTAS probe inferred VARCHAR on the candidate and DOUBLE on the frozen base. Adding + 1 inferred DOUBLE on both. Preserve the numeric type of the bare projection and cover the stored column with a downstream numeric query.

Validation:

  • Verified the exact head, byte-identical patch, and authenticated prior review 5951123432. Reconciled all 114 discussion entries and matched the retained UNION and CTAS controls to their receipts and logs. See checks/1794980157008697951-2.json and checks/1794980312386128507-2.json.

  • Isolation preflight passed in checks/1794980156876902532-2.json. Traced the new findings through the current binder, GROUP BY projection binding, and scalar common-type rules.

Limitations:

  • The two fresh planner probe attempts timed out before producing test events. The wrapper and grouped-projection findings rely on source analysis. See checks/1794980329908058141-2.json and checks/1794980399365204551-2.json.

… CTAS

mo-bot review P1/P2 on 1e0edaf: the one-argument CEIL/FLOOR digit
renders exported through a set-operation branch or a CTAS source still
carried their VARCHAR display type at the boundary, so numeric
aggregation over the unified column failed with a VARCHAR argument in
three shapes - a UNION ALL mixing the render with a numeric literal,
the same mix with FLOOR over an explicit TEXT cast, and a 56-branch
homogeneous UNION ALL that exhausted the consumer-side provenance
walk's 48-step budget - and CREATE TABLE ... AS SELECT of the bare
render inferred a VARCHAR column where the base created DOUBLE.

Every set branch now re-enters its base numeric domain (FLOAT64 for
the omitted-CHAR provenance, exact-integer DECIMAL128 for TEXT inputs)
before buildUnionWithResultLen's common-type unification composes the
branches, and genAsSelectCols applies the same recovery to a CTAS
source projection, so the created column keeps the base's numeric
type: the frozen base 8c77e14 created `n double DEFAULT NULL` for
the omitted-CHAR case and summed 13/15/672 over the
literal/TEXT/wide probes; this head reproduces each value. The bare
SELECT keeps its digit rendering and the derived/CTE/grouped
cross-boundary recovery is untouched.

UT: TestCeilFloorSetOutputsKeepBaseNumericDomains requires SUM to bind
through FLOAT64 for the mixed marker/TEXT-render union instead of
rejecting it, adds the numeric-literal, 56-branch and union-display
assertions, and pins the DOUBLE/DECIMAL128 columns a bare-render CTAS
infers. BVT: the mixed SUM row that recorded the pre-fix VARCHAR
rejection now records 17.0; new rows cover the literal mix (13.0), the
56-branch union (672.0), and both bare-render CTAS regressions with
show-create, ordering and downstream SUM/AVG proofs.
@gouhongshen

Copy link
Copy Markdown
Contributor Author

Addressing the mo-bot-local review of 1e0edafc69 at the new head a4d656ff56 — both findings are fixed, regression rows added, and frozen-base parity re-verified on both binaries.

  • P1 (pkg/sql/plan/base_binder.go:3635) — Fixed. The recovery previously lived only in the consumer-side provenance walk (resolvedProjectedColumnDomain requires identical branch domains, 48-step budget), which is why the mixed-domain unions and the 56-branch fan-out lost the numeric type. Every set branch that exports a rendered one-argument CEIL/FLOOR value now re-enters its own base domain before the set's common-type unification (retypeSetProjectionCeilFloorRender in buildUnionWithResultLen's coercion loop): FLOAT64 for the omitted-CHAR provenance, exact-integer DECIMAL128 for TEXT inputs. The existing coalesce rules then unify the branches numerically — SUM over the CEIL(CAST(v AS CHAR)) + numeric-literal union binds FLOAT64 (BVT 13.0 for rows 2/10+1), the CEIL render + FLOOR(CAST(... AS TEXT)) union sums numerically (17.0; the BVT rejection row that recorded the regression is gone), and the 56-branch UNION ALL sums 672.0 with no cross-branch walk or budget. Frozen-base 8c77e14665 parity (built and probed this round): 13 for the literal mix, 15 for the integer-only TEXT mix, 672 for the 56 branches, DOUBLE union display — identical.
  • P2 (pkg/sql/plan/function/list_builtIn.go:7776) — Fixed. genAsSelectCols applies the same per-column recovery to the CTAS source projection, so CREATE TABLE dst AS SELECT CEIL(CAST(v AS CHAR)) AS n FROM src infers the base's DOUBLE column (show create table → n double DEFAULT NULL, matching the frozen base) instead of the render's VARCHAR; the new BVT rows check the inferred column, the stored rows, numeric ordering and the downstream SUM/MAX/AVG (12.0/10.0/6.0).

Validation at a4d656ff56: plan-level probes reproduce all three SUM rejections (bad value [VARCHAR]) and the VARCHAR CTAS inference on the old head, and pass at the new head; the full pkg/sql/plan package UT is green including the flipped and new assertions of TestCeilFloorSetOutputsKeepBaseNumericDomains (SUM/FLOAT64 for both mixed shapes, the 56-branch union, the DOUBLE union display column, and the CTAS DOUBLE/DECIMAL128 inference), pkg/sql/plan/function + pkg/sql/colexec green, go vet clean, and the focused BVT compare passes 206/206 for func_cast_omitted_char_length with the regenerated expectations (loop artifacts logs-r18-review/). One documented divergence stays intentional: CTAS of a bare explicit-TEXT render creates the accepted exact-integer decimal(38,0) column where the base's UINT64 cast created bigint unsigned; integer values stay exact in both.

This branch was successfully deployed

No deployments
ci — a4d656ff Deployed Nov 18, 2026 by gouhongshen
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/XXL Denotes a PR that changes 2000+ lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants