Repository navigation
fix(sql): enforce DECIMAL width for integer assignments (#30367) - #30639
Conversation
Qodo reviews are paused for this user.Troubleshooting steps vary by plan Learn more → On a Teams plan? Using GitHub Enterprise Server, GitLab Self-Managed, or Bitbucket Data Center? |
|
Local verification at head 88cb80c (isolated 1 LogService / 1 TN / 2 CN instance):
|
…#30367) Signed integer, unsigned integer, hexnum and bit sources converted to DECIMAL skipped the declared width check while string and decimal sources enforced it via ParseDecimal64/128. As a result, strict-mode assignments persisted out-of-range values: - runtime casts scaled integers into the target decimal silently (INSERT ... SELECT, prepared parameters, ALTER TABLE COPY), and - VALUES literals were parsed at plan time through SetInsertValueDecimal64/128 with the same gap. - unsigned magnitudes beyond MaxInt64 wrapped negative inside Decimal64, escaping every bound check. Enforce the -10^width < value < 10^width bound for all integer sources in both layers, with the same 'beyond the range' diagnostic as string sources. Synthesized casts carrying no declared precision (width 0, e.g. binder unary-minus promotion to decimal128) keep the previous saturation-free behavior. Regression tests cover literal and runtime paths across DECIMAL64/128/256, including boundary and wrap cases.
5092df5 to
25c6eef
Compare
…e casts (matrixorigin#30367) The strict integer->DECIMAL conversion from the previous commit made the col-vs-const comparison rewrite fail at execution time for constants that exceed the column's declared domain: checkNoNeedCast accepted any int32- bounded constant for a DECIMAL64 column without consulting the declared (width, scale), so n < 1000 against DECIMAL(5,2) became cast(1000 AS DECIMAL64(5,2)) and raised the new range error, breaking recursive-CTE iteration and BVT row_constructor expectations. Only rewrite the constant into the column type when that typed cast cannot fail: add integerConstantFitsDeclaredDecimalDomain, mirroring the enforced bound (scaled magnitude strictly below 10^width), and keep the legacy physical bound for synthesized zero-width decimal types whose conversion skips the check. Out-of-domain constants now keep the widened comparison plan, which evaluates numerically without an error. row_constructor.result records the intended new behavior for row03: the DECIMAL(20,10) insert of -93298439024 now errors like MySQL 1264, and the twelve row scans lose the rejected row. Verified on a live instance: recursive_cte_decimal_precision now errors with the exact golden text (1000.00 beyond the range ...), ordered comparisons and BETWEEN with out-of-domain literals evaluate correctly, and the issue repros (INSERT 2 INTO DECIMAL(2,2), ALTER COPY narrowing) still reject. Full pkg/sql/plan suite passes with a new 16-case UT.
|
mo-bot review · Commit: Review completed. Read the assessment. |
XuPeng-SH
left a comment
There was a problem hiding this comment.
mo-bot review · mo-bot-local · review
Commit: a1027b586d37b067ab0b67e0187de8fe28503c0e
Assessment: request_changes
Reviewed the complete 46-file delta and frozen review concerns. The existing cast, VALUES and catalog resolver owners appropriately enforce declared precision while preserving synthesized integer domains. Prior compatibility findings are addressed, but two measured performance regressions remain.
Model: gpt-6-astra / xhigh
Session: 01a13dcf-1517-7f90-b3f9-c5f9f9e7031b · slot 0 · generation 1
-
P2
pkg/sql/plan/catalog_decimal_compat.go:65: Ordinary frontend or internal table resolution invokes this loop, including schemas with no legacy decimal expressions.
Impact: The escapingownedcopy allocates 352 bytes per column even whenchangedremains false, adding allocation and GC costs to unaffected SQL. Allocate the column copy only after establishing that an expression changed.
Evidence: Three-sample benchmarks of CloneTableDefForPlan plus migration show a 100-column schema without defaults increasing from 2 allocations/1,344 bytes to 102 allocations/36,544 bytes per resolution. With NULL defaults, allocations increase from 102 to 202, again adding 35,200 bytes. The baseline HEX migration and clone implementations are byte-identical to merge-base. See catalog-bench-corrected.log. -
P2
pkg/sql/plan/function/func_cast.go:4093: Successful integer-vector casts to wide DECIMAL targets call the width validator for every row.
Impact: The validator reconstructs the invariant power-of-ten bound using wide multiplications per row. This introduces avoidable CPU overhead; compute the bound once per batch or reuse a precomputed bound while retaining all strict checks.
Evidence: Serial 4,096-row benchmark medians: DECIMAL256 rises from 14.29 µs with the exact base cast implementation to 95.80 µs on the candidate; DECIMAL128 rises from 14.54 to 30.13 µs. A diagnostic control changing only bound construction reduces these to 26.59 and 22.12 µs respectively, retaining strict validation and passing width-contract tests. See serial-base.log, serial-head.log and serial-control.log.
Validation:
-
Isolation preflight passed; verified 192 native/module inputs and seven retained native outputs against the repository build-owner evidence.
-
21 focused regression roots passed, covering casts, domain widening, persisted catalog migration, resolver contexts and prepared MySQL execution.
-
Separate pruning and real SQL assignment checks passed, including VALUES, INSERT SELECT, prepared INSERT, UPDATE and failed ALTER COPY atomicity.
-
The complete planner package passed under -race; the concurrent catalog ownership regression also passed 100 repetitions.
-
git diff --check passed. Frozen exact-head CI reports successful UT, SCA, coverage, multi-CN BVT and Connector/J checks.
-
Reconciled commands, terminal receipts, logs and source/artifact hashes in /home/xupeng/.local/state/mo-bot/jobs/fbb6485390ae0e45528ae8c9/attempt-1/review-evidence.json. Source remains unchanged.
Limitations:
-
Performance measurements are component benchmarks, not whole-query or distributed latency measurements.
-
Catalog upgrade validation exercises stored protobufs, resolvers and execution; no live rolling upgrade was performed.
-
Raw CI logs and the linked issue body were not supplied. The documented issue repro and assignment contracts were independently exercised.
|
Addressed both performance P2 findings from review 5611360387 in commit Catalog normalization now identifies changed DEFAULT / ON UPDATE / generated expressions before allocating the escaping column copy. Unchanged columns keep their original pointers. The existing copy-on-write behavior for changed wrappers and shared catalog expressions is retained. Signed and unsigned integer casts compute the DECIMAL128 / DECIMAL256 precision bound once per vector and pass it to each row's validator. Successful rows no longer rebuild powers of ten with wide multiplications. Strict declared precision checks, synthesized zero-width behavior, signed comparisons, scaling failures and error diagnostics are preserved. Added an allocation regression comparing the full catalog normalizer with the existing clone-plus-HEX path, for 100 columns both without defaults and with NULL defaults. It failed before the fix: 102 vs 2 allocations, and 202 vs 102 respectively. It passes after the fix. Expanded actual vector-cast tests cover signed/unsigned inputs, positive/negative exact cutoffs at DECIMAL(38,37) and DECIMAL256(76,75), NULLs and accepted adjacent values. Serial local benchmarks on the same Apple M5 host, Go 1.27.1,
The 100 extra column allocations / 35,200 bytes are removed in both schema shapes. Vector casts retain one allocation per batch. The unchanged DECIMAL64 control measured 12.993 vs 13.796 us; these component measurements are not a whole-query or distributed throughput claim. Validation on the final source:
Required CI was green at the previous head. The new commit starts fresh checks; the results above are local validation, not a claim that the new CI has completed. Please re-review both corrections. |
|
Re-reviewed head The previously reported correctness issues are addressed:
Both performance concerns in review 5611360387 are also addressed structurally: unchanged columns return before allocating the escaping ColDef copy, and signed/unsigned Decimal128/256 casts build the invariant precision limit once per vector rather than per row. Changed wrappers still use copy-on-write; strict width checks, zero-width synthesized casts and scaling-error propagation remain. The new allocation comparison and wide positive/negative cutoff/NULL tests cover these changes. I do not independently claim the reported benchmark speedups. Also checked the added cleanup-test adjustments: they retain bounded contexts and error reporting, continue cleaning subsequent accounts after an error, and keep the branch-DDL independence checks from crediting progress caused by cancellation of the competing transaction. Validation: |
|
Fixed the UT failure from run 39755014293, job 119744814023 in commit The sole failing test was The fixture now uses blocking FIFO reads for event ordering under one bounded 30-second harness deadline. Package order, live-PID checks, heavy-package exclusion, exact concurrency peaks, expected failure propagation and cleanup assertions are retained. Other scheduling fixtures keep their existing 15-second deadline. Added a Validation:
The separate |
|
mo-bot review · Commit: Review completed. Read the assessment. |
XuPeng-SH
left a comment
There was a problem hiding this comment.
mo-bot review · mo-bot-local · review
Commit: 78c61bd8309c613c616cd59d72592064beed538e
Assessment: approve
Reviewed the complete 48-file delta and supplied review concerns. Precision enforcement uses the existing conversion owners; conditional widening preserves expression domains, and catalog repair reuses the binder with copy-on-write ownership. Earlier correctness, compatibility and performance findings are addressed. No actionable findings remain.
Model: gpt-6-astra / xhigh
Session: 01a13dcf-1517-7f90-b3f9-c5f9f9e7031b · slot 0 · generation 1
Validation:
-
Verified frozen patch equivalence, clean source and git diff --check. Isolation preflight passed; 192 native inputs and seven native outputs matched retained repository build-owner evidence.
-
Eight targeted test roots passed three repetitions, covering precision boundaries, NULLs, allocations, catalog ownership, cancellation and explicit-cast preservation.
-
Independently reconciled 43 retained artifacts and 17 receipts. Reused compatible SQL assignment/ALTER COPY, pruning, prepared-protocol, catalog-upgrade and planner race evidence after checking the intervening six-file delta.
-
Serial 4,096-row benchmarks confirmed DECIMAL128 improvement from 29.50 to 22.41 microseconds and DECIMAL256 from 96.33 to 27.18 microseconds versus the previously reviewed implementation. Both retain one allocation per batch.
-
Catalog normalization adds no allocations for unchanged columns. Measured additional traversal cost was approximately 0.41–0.56 microseconds per 100 columns. Strict casts remain slower than unchecked base conversions: 20.64/22.41/27.18 versus approximately 14.75 microseconds for DECIMAL64/128/256.
-
Frozen current-head CI reports successful build, UT, SCA, coverage, PROXY/PESSIMISTIC BVT and Connector/J checks. Command, source, exit and log reconciliation is retained in /home/xupeng/.local/state/mo-bot/jobs/ea99985ba235c3f47f76d261/attempt-1/review-evidence.json; scope and design analysis are in review-record.json.
Limitations:
-
Upgrade evidence exercises stored protobufs, resolvers and execution; no live rolling upgrade was performed.
-
Benchmarks measure components, not whole-query or distributed throughput. Base controls replace only the cast implementation.
-
Raw current CI logs and the linked issue's full body were not supplied. Earlier executions are explicitly distinguished from current-head local checks.
XuPeng-SH
left a comment
There was a problem hiding this comment.
Deep-reviewed exact head 78c61bd8309c613c616cd59d72592064beed538e against base/merge-base 63a964a82fbaae4759cfabb45655e0185bc0979c. Read the complete 48-file delta, issue #30367, all reviews/discussion and both resolved inline threads. Approve: no remaining actionable blocker found. No subagents were used.
Design and closure:
- Strict integer precision belongs in the existing runtime-cast and VALUES conversion owners. Scaling errors and unsigned wrap are checked; literal conversion reuses the decimal parser. Synthesized comparison/arithmetic targets preserve the full integer/BIT domain without relaxing declared assignments. Sufficient low-scale targets and pruning behavior remain intact.
- Catalog repair is necessary even for a shutdown upgrade: previously stored implicit casts survive the restart. It runs through the existing frontend/internal resolver boundary, reuses binding, detaches changed wrappers only, and preserves stored bytes, explicit CASTs and assignment domains. Genuine BETWEEN and IN_RANGE, current-statement cancellation, ancestor rebinding, and idempotence are covered. No new storage format or protocol is introduced.
- Historical comparison/BIT, pruning, arithmetic/prepared metadata, multiplication, persisted CHECK/BETWEEN/IN_RANGE, per-row boxing, eager column copying, and repeated wide-bound construction findings are addressed in the current code and retained oracles. Both inline threads are already resolved.
- Reviewed production (+589/-38), UT (+1586/-162), BVT/results (+223/-25), and fixture/provenance documentation separately. Fixture changes preserve failure reporting, bounded cleanup, ordering/independence assertions and metadata checks. The CDC test now uses an explicit barrier; the scheduling harness retains its existing deadline/child-cleanup owner.
Validation:
- Local exact-head CGo-wrapper execution: 19 selected
TestPersistedDecimal*roots passed (119 root/subtest pass events; package 1.133s), including old-writer/new-reader fixtures, explicit/assignment controls, copy-on-write readers, cancellation, idempotence and unchanged-column allocations. - Independent temporary MySQL-protocol challenge: all five scenarios passed (package 6.512s): strict INSERT/UPDATE/INSERT SELECT/hex/bit rejection and statement atomicity; binary-prepared reject/NULL/type-switch/recovery; failed COPY ALTER preserving source data/schema; adjacent IN/conditional/coalesce/arithmetic paths; reversed prepared fractional boundaries. Native source identity and provenance were verified before reuse. An initial probe used unsupported SUM(BOOL); it was corrected to COUNT ... WHERE and rerun, not treated as a product finding.
- Independently inspected exact-head run 39768759884: successful UT race stages/checkpoints and SCA log reporting 0 issues. Downloaded actual execution artifacts from both BVT lanes: time 83/83, arithmetic-domain 28/28, temporal predicates 25/25, row constructors 234/234, prepared arithmetic 62/62 — 432/432, with zero failed/ignored/abnormal cases. Current-head coverage and other required checks are successful.
git diff --checkpassed. Primary uncommitted work was preserved; reviewer probes/native links were archived or removed, with no production edit.
Limits: reused current-head full CI rather than rerunning the repository locally. Historical benchmark numbers remain prior author/reviewer evidence; this pass verified the optimized structure and allocation regression, without claiming a new throughput measurement. Upgrade evidence is persisted-protobuf/new-reader execution, not a live binary upgrade. Detailed scope, evidence and logs are retained locally in /private/tmp/mo-review-30639-20261023/.
aptend
left a comment
There was a problem hiding this comment.
Deep re-review of exact head 78c61bd8309c613c616cd59d72592064beed538e against base/merge-base 63a964a82fbaae4759cfabb45655e0185bc0979c, including all historical reviews, inline replies and resolved threads, the delta since my previous review, and all 48 files in the complete diff.
The prior persisted-CHECK execution blocker is fixed: my original base-produced protobuf now evaluates both 10^18-1 and 10^18 after the current migration. The BIT/domain, explicit assignment, request-context, copy-on-write and success-allocation controls also pass. One independently reproduced upgrade compatibility blocker remains in DUMP/LOAD, detailed inline; requesting changes for that issue.
Validation: focused tests in plan/function/util/readutil/frontend/compile; eight-reader catalog race stress (100 repetitions); exact-head CI full owning-package race, successful final coverage attempt and actual 432 SQL assertions reused. Separate exact-base/head native builds and differential real-planner/payload tests establish the new failure. Temporary review probes do not alter production code. No live server upgrade or physical archive roundtrip was claimed.
|
mo-bot review · Commit: Review completed. Read the assessment. |
XuPeng-SH
left a comment
There was a problem hiding this comment.
mo-bot review · mo-bot-local · review
Commit: e6dcda13d2dcc0ae5e285ead76e6ec1a0e1adccb
Assessment: request_changes
Reviewed the complete 55-file delta and frozen discussion. Precision enforcement and catalog repair use appropriate existing owners, but historical DUMP/LOAD verification still rejects a valid BETWEEN expression.
Model: gpt-6-astra / xhigh
Session: 01a13dcf-1517-7f90-b3f9-c5f9f9e7031b · slot 0 · generation 1
- P2
pkg/sql/plan/function/legacy_integer_decimal.go:41: Restore a base-authored table containing tm TIME(0) and g BOOL GENERATED ALWAYS AS (tm BETWEEN CAST(0 AS SIGNED) AND CAST(2 AS SMALLINT)) STORED. A MONTHNAME default makes the dump include bound expressions.
Impact: Current BETWEEN resolution selects incompatible Decimal128/Decimal64 domains and fails. This early return prevents reconstruction of the valid historical signature. Ordinary SQL succeeds through comparison fallback, but that replacement tree cannot match the persisted BETWEEN tree, blocking DUMP verification and LOAD. Resolve supported historical signatures independently of current checker success while retaining complete-tree verification.
Evidence: Generated the catalog protobuf using the exact merge-base Go-source overlay. Base verification passes; head verification rejects only the mixed-width BETWEEN control. Real SQL LOAD followed by INSERT passes on the base, while head LOAD returns Error 20301: table dump cannot verify bound generated expression g. Retained base-historical.log, head-historical.log, base-load.log and head-load.log have matching exit receipts.
Validation:
-
Verified frozen patch equivalence, clean source, 192 matching native inputs, repository-owned native provenance and private-runtime preflight.
-
Focused tests passed in function, plan, frontend and sqlintegration, including the PR's historical DUMP/LOAD roundtrip and forged-payload rejection.
-
Audited commands, source fingerprints, overlay contents, terminal receipts and logs. Reproducers and reconciliation are retained under /home/xupeng/.local/state/mo-bot/jobs/5e22dc5d9556dedb71832efa/attempt-1/review-evidence.json.
-
Measured 4,096-row cast medians: Decimal64/128/256 increased from 15.65/14.28/14.65 to 20.25/22.53/26.28 microseconds, retaining one allocation per batch. Ordinary 100-column normalization added approximately 0.49–0.75 microseconds without additional allocations.
-
Frozen current-head CI reports successful build, UT, SCA, coverage, active BVT lanes and Connector/J.
Limitations:
-
CI evidence contains statuses rather than raw case logs; no full repository suite or fresh race run was repeated locally.
-
Compatibility validation used serialized base catalog expressions and real LOAD entrypoints, not a deployed old-server restart or rolling upgrade.
-
Performance measurements are component benchmarks, not whole-query throughput. Issue #30367's full body was not supplied.
|
@XuPeng-SH Addressed the mixed-width historical BETWEEN blocker from review 5636502882 in b1bc9ef. The legacy range resolver now reconstructs supported BETWEEN / IN_RANGE signatures before checking the modern checker's success status. It validates the original operand domains, scales, arity, comparison support and UINT8 boundary flag, and uses the historical overload identity rather than an unsuccessful modern result. Ordinary binding and runtime DECIMAL assignment/explicit-CAST bounds are unchanged. Complete SQL-origin tree verification is still required; the reader does not normalize an untrusted tree into acceptance. Evidence:
Also merged current main CI triage: the previous exact head |
|
CI follow-up for exact head
Triggered only the failed SCA job again on the same SHA. Attempt 2 / job 121054362269 is now running on a different runner, No code, assertions, skips or workflow retries were added for this infrastructure failure. The branch remains at the previously pushed fix; no new-head green-CI claim is made. |
|
mo-bot review · Commit: Review completed. Read the assessment. |
XuPeng-SH
left a comment
There was a problem hiding this comment.
mo-bot review · mo-bot-local · review
Commit: b1bc9efae6cf3e6c4d4f73ec4c4fbb99b6edff0f
Assessment: approve
Reviewed the complete 56-file delta, callers, tests, fixtures and recorded review concerns. The design appropriately separates strict assignment precision, synthesized expression domains, copy-on-write catalog repair and historical backup verification. The mixed-width BETWEEN compatibility concern is resolved. No actionable findings remain.
Model: gpt-6-astra / xhigh
Session: 01a13dcf-1517-7f90-b3f9-c5f9f9e7031b · slot 0 · generation 1
Validation:
-
Verified the frozen HEAD, unchanged source and matching patch. Isolation preflight and repository native-provenance verification passed; native inputs were reconciled before testing.
-
Passed 29 focused test roots and 45 caller-specific roots with vet enabled and uncached execution. Coverage includes precision boundaries, allocations, catalog ownership/cancellation, historical payloads, forgery rejection, prepared TIME arithmetic, literals and pruning.
-
Passed two SQL integration test roots twice: five historical backup scenarios exercised LOAD, writes, DUMP and restoration; diagnostic tests verified assignment failure atomicity and failed ALTER COPY preservation.
-
Frozen evidence reports successful exact-head Ubuntu UT, coverage, arm64 SCA, shared build, BVT and CI Required checks.
-
Audited retained benchmarks against compatible execution paths: 4096-row integer casts increased from 15.6/14.3/14.6 to 20.3/22.5/26.3 microseconds for Decimal64/128/256, with unchanged allocations. Unchanged 100-column catalog traversal added approximately 0.49–0.75 microseconds without additional allocations. These bounded costs support the precision and compatibility guarantees.
-
Commands, source fingerprints, exits and logs are reconciled in /home/xupeng/.local/state/mo-bot/jobs/57b9e1078a807fd58d252ca5/attempt-1/review-evidence.json. Final audit receipt: checks/1792899513655915335-13.json. Superseded diagnostic audit failures are retained and distinguished from product tests.
Limitations:
-
CI evidence contains terminal statuses rather than raw per-case logs; local_validation was empty.
-
Compatibility validation used historical serialized metadata and current SQL entry points, not a live rolling upgrade.
-
Performance measurements are retained component benchmarks, not current whole-query measurements; literal parsing costs were not separately benchmarked.
-
The linked issue's full body was unavailable; its contract was assessed from the frozen PR description and discussion.
|
mo-bot review · Commit: Review completed. Read the assessment. |
XuPeng-SH
left a comment
There was a problem hiding this comment.
mo-bot review · mo-bot-local · review
Commit: 9ba0f353784c29707807b5c1bd029f21c41b1575
Assessment: approve
Reviewed the complete 56-file delta and prior review concerns. Precision enforcement uses the existing conversion owners; synthesized expression domains preserve integer capacity without weakening assignment limits. Catalog repair preserves shared metadata through copy-on-write, and historical DUMP/LOAD verification retains whole-tree validation. No actionable findings remain.
Model: gpt-6-astra / xhigh
Session: 01a13dcf-1517-7f90-b3f9-c5f9f9e7031b · slot 0 · generation 1
Validation:
-
Verified frozen patch equivalence, clean source and git diff --check.
-
Audited exact-head CI run 40187169956, artifact digests, commands and results. Raw coverage events record all 36 selected added or changed test roots passing, including historical DUMP/LOAD, resolver ownership, cancellation and precision boundaries.
-
Verified 374 passing SQL assertions across the two BVT lanes covering arithmetic domains, temporal comparisons, row constructors, recursive decimal precision and prepared arithmetic.
-
Regular UT race stages completed successfully. Coverage attempt 1 failed in CrossTargetUpgradeRecovery; the later attempt reports producer exit 0 and no failed test events. The earlier failure was retained separately.
-
Reconciled retained benchmarks against unchanged exercised paths: 4,096-row Decimal64/128/256 casts increased from 15.65/14.28/14.65 to 20.25/22.53/26.28 microseconds, retaining one allocation per batch. Unchanged 100-column catalog normalization added approximately 0.49–0.75 microseconds without extra allocations.
-
Evidence and receipt reconciliation are retained under /home/xupeng/.local/state/mo-bot/jobs/e6472c33a3ff20f32a48509c/attempt-1/review-evidence.json; final audit receipt 1792936035188457261-4.json records exit 0.
Limitations:
-
Reused exact-head CI and compatible retained benchmarks; no local native rebuild or duplicate test run.
-
Compatibility evidence uses historical serialized metadata and current production DUMP/LOAD, not a deployed old-server restart or rolling upgrade.
-
Performance measurements are component benchmarks, not end-to-end throughput.
-
The linked issue's full body was absent; its behavioral contract was assessed from the frozen PR description and discussion.
aptend
left a comment
There was a problem hiding this comment.
Re-reviewed exact head 9ba0f353784c29707807b5c1bd029f21c41b1575, including the complete 56-file diff, changes since my previous reviewed head 78c61bd8309c613c616cd59d72592064beed538e, and all review/thread history and author replies. No blocking issue remains.
My previous historical DECIMAL DUMP/LOAD finding is closed. I replayed the unchanged old-writer TableDefs and bound payloads saved during that review. The new verifier reconstructs complete historical bindings, including mixed-width BETWEEN, while retaining schema/declaration checks, payload checksums, full-tree comparison and rejection of rehashed forgeries. Catalog execution repairs preserve shared metadata, explicit CAST and declared assignment bounds.
Validation on this head:
- Reviewer-owned historical artifacts, all 16 frozen old-writer bound payloads, catalog migration/resolver/immutability/idempotence/cancellation controls passed.
- Five real SQL DUMP/LOAD scenarios passed twice in one process on the shared single-CN instance, including physical rows, later INSERT/UPDATE, strict assignment rejection, failed-LOAD integrity and verified cleanup.
- Shared catalog normalization and CDC rollback serialization each passed adaptive
-race -count=100runs. - Four additional constant DEFAULT/IN cases captured with the real planner at
63a964a82fbaae4759cfabb45655e0185bc0979cpassed current-reader DUMP/LOAD, including the10^18boundary. - Audited and reused successful exact-head CI run 40187169956: ordinary/race UT, final coverage producer, arm64 SCA and both BVT lanes; independently checked 349 relevant successful SQL assertions.
The historical captures are old-writer/new-reader component evidence; the SQL runs use the current server and do not claim a live old-binary upgrade.
Merge Queue Status
This pull request spent 51 minutes 55 seconds in the queue, including 51 minutes 10 seconds running CI. Required conditions to merge
|
What type of PR is this?
Which issue(s) this PR fixes:
issue #30367
What this PR does / why we need it:
Signed/unsigned integer, hexnum and bit sources converted to
DECIMALskipped the declared width check, while string and decimal sources enforced it viaParseDecimal64/128. In strict SQL mode,INSERT INTO t VALUES (1, 2)intoDECIMAL(2,2)persisted2.00(max0.99), and the same gap letALTER TABLE ... ALGORITHM=COPYkeep out-of-range rows when narrowing an INT column toDECIMAL.Two layers had the gap:
pkg/sql/plan/function/func_cast.go):signedToDecimal64/128/256andunsignedToDecimal64/128/256scaled integers into the target decimal without a width check and silently droppedScaleerrors (raised by 64/128-bit scale overflow). Unsigned magnitudes beyondMaxInt64additionally wrapped negative insideDecimal64, escaping every bound.pkg/sql/util/eval_expr_util.go):SetInsertValueDecimal64/128appliedScale()directly to integer literals at plan time; string literals in the same code path already went through precision-aware parsing.Fix: enforce
-10^width < value < 10^widthfor every integer-family source in both layers, reusing the exactParseDecimal64/128rule and 'X beyond the range, can't be converted to DecimalW(p,s).' diagnostic so integer, string and decimal sources share one contract. Synthesized casts that carry no declared precision (width 0, e.g. the binder's unary-minusuint64 -> decimal128promotion) skip the width bound, preserving previous SELECT-context behavior; declared column widths are always >= 1.Comparison casts check each integer operand against its own synthesized Decimal target. An insufficient target (for example BIGINT/TIME synthesized as Decimal64(18,0)) is widened to retain the integer domain. A sufficient target keeps its width and scale, preserving the low-scale Decimal128 literal used by ordinary range predicates and zone-map pruning. Constant narrowing into a declared Decimal domain is also guarded so out-of-domain comparison literals do not raise assignment-range errors.
Arithmetic coercion likewise widens insufficient synthesized integer targets (including TIME + BIGINT and integer division), retaining separate operand scales and a common decimal precision envelope. Prepared TIME arithmetic resolves its integer boundary from the original TIME provenance, rather than narrowing execute-time integers to the provisional Decimal64 envelope. Fractional
/keeps its existing precision-specific coercion. Integer-source width validators are generic so successful rows no longer box their source value; diagnostics still format it only on the error path. Strict declared assignment bounds are unchanged.Behavior with the fix (verified against a live instance):
INSERT INTO t VALUES (2, 2)→ERROR 20301: invalid input: 2 beyond the range, can't be converted to Decimal64(2,2).(was: persisted2.00)INSERT ... SELECT, preparedINSERTwith?params,INSERT IGNORE, hexnum/bit literals → same rejection;0.99/-0.99/0boundaries still acceptedALTER TABLE src MODIFY rawv DECIMAL(2,2), ALGORITHM=COPYon an INT source with2,3→ rejected, source table unchanged9223372036854775807intoDECIMAL(18,0)rejected;999999999999999999accepted;18446744073709551615rejected without wraparoundselect -10000000000000000001) unchanged vs mainTests
TestIntToDecimalWidthContract(cast layer, 13 cases across DECIMAL64/128/256 with boundary, MaxInt64/MaxUint64 and wrap inputs) andTestIntLiteralIntoColumnKeepsDecimalWidth(VALUES literal layer). Both fail on main.pkg/sql/plan,pkg/sql/plan/function,pkg/sql/util, and the downstreampkg/vm/engine/readutilsuites pass with-count=1.-short -tags=matrixone_test -covermode=set.-vet=all -count=1; configured lint for function and plan exits successfully, with golangci-lint reporting 0 issues. Pinned molint additionally emits six existing JSON diagnostics in five files byte-identical to current main and outside this PR's changes; no claim is made that it emitted no diagnostics. Six real-service SQL files pass 406/406 statements, including the new signed/reversed/TIME/unsigned/BIT/NULL/prepared boundary case and the existing metadata-enabled prepared TIME regression. Updated metadata expectations reflect the necessary widening, without disabling comparison.NewCastdispatch wrapper); all 4,096 per-row boxes are removed. Allocation regressions cover signed and unsigned inputs. These local microbenchmarks do not establish whole-query or distributed performance.ef07d45cf6in103e93c605: canonical native rebuild/provenance verification, all four complete owning suites, targeted frontend DUMP tests, configured static checks and the same 406 real-service SQL statements pass. Main's historical DIV origin checker is preserved unchanged; a new control proves normal widened operands do not alter that historical signature.test/distributed/cases/dtypeandtest/distributed/cases/dml/insertproduce identical failure sets to pristine upstream (pre-existing environment-dependent noise), and zero failures carry the new diagnostic. The 5 statements initially broken by the width check (huge uint64 literals / unary-minus promotion) pass after the zero-width guard.