Skip to content

fix(sql): enforce DECIMAL width for integer assignments (#30367) - #30639

Merged
mergify[bot] merged 28 commits into
matrixorigin:mainfrom
daviszhen:fix-30367-decimal-int-range
Oct 26, 2026
Merged

mergify[bot] merged 28 commits into
matrixorigin:mainfrom
daviszhen:fix-30367-decimal-int-range

Conversation

@daviszhen

@daviszhen daviszhen commented Oct 20, 2026 •

Copy link
Copy Markdown
Contributor

What type of PR is this?

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

Which issue(s) this PR fixes:

issue #30367

What this PR does / why we need it:

Signed/unsigned integer, hexnum and bit sources converted to DECIMAL skipped the declared width check, while string and decimal sources enforced it via ParseDecimal64/128. In strict SQL mode, INSERT INTO t VALUES (1, 2) into DECIMAL(2,2) persisted 2.00 (max 0.99), and the same gap let ALTER TABLE ... ALGORITHM=COPY keep out-of-range rows when narrowing an INT column to DECIMAL.

Two layers had the gap:

  1. Runtime casts (pkg/sql/plan/function/func_cast.go): signedToDecimal64/128/256 and unsignedToDecimal64/128/256 scaled integers into the target decimal without a width check and silently dropped Scale errors (raised by 64/128-bit scale overflow). Unsigned magnitudes beyond MaxInt64 additionally wrapped negative inside Decimal64, escaping every bound.
  2. VALUES literal fast path (pkg/sql/util/eval_expr_util.go): SetInsertValueDecimal64/128 applied Scale() 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^width for every integer-family source in both layers, reusing the exact ParseDecimal64/128 rule 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-minus uint64 -> decimal128 promotion) 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: persisted 2.00)
  • INSERT ... SELECT, prepared INSERT with ? params, INSERT IGNORE, hexnum/bit literals → same rejection; 0.99/-0.99/0 boundaries still accepted
  • ALTER TABLE src MODIFY rawv DECIMAL(2,2), ALGORITHM=COPY on an INT source with 2, 3 → rejected, source table unchanged
  • 9223372036854775807 into DECIMAL(18,0) rejected; 999999999999999999 accepted; 18446744073709551615 rejected without wraparound
  • huge literal SELECTs (select -10000000000000000001) unchanged vs main

Tests

  • New unit tests: TestIntToDecimalWidthContract (cast layer, 13 cases across DECIMAL64/128/256 with boundary, MaxInt64/MaxUint64 and wrap inputs) and TestIntLiteralIntoColumnKeepsDecimalWidth (VALUES literal layer). Both fail on main.
  • pkg/sql/plan, pkg/sql/plan/function, pkg/sql/util, and the downstream pkg/vm/engine/readutil suites pass with -count=1.
  • Added comparison-domain controls for both operand orders. The existing public-plan Decimal128 low-scale assertion is retained, with a new boundary case proving both general and compiled zone-map pruning agree when a block must be excluded. Focused pruning tests also pass with -short -tags=matrixone_test -covermode=set.
  • Existing temporal predicate and row-constructor BVT cases pass on the rebuilt local service, twice on the same instance (250/250 statements each run); schema teardown is checked directly through JDBC.
  • Incremental standard vet and configured golangci-lint pass (0 issues).
  • Arithmetic follow-up: the four complete function/plan/util/readutil suites pass with -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.
  • Reused 4,096-row integer-cast benchmark: all three decimal widths drop from 4,097 allocations / 32,864 bytes per batch to 1 allocation / 96 bytes (the unchanged fixed NewCast dispatch 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.
  • Revalidated after merging main ef07d45cf6 in 103e93c605: 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.
  • BVT comparison on identical local instances (same commit, with/without fix): test/distributed/cases/dtype and test/distributed/cases/dml/insert produce 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.

@qodo-code-review

Copy link
Copy Markdown

Qodo reviews are paused for this user.

Troubleshooting steps vary by plan Learn more →

On a Teams plan?
Reviews resume once this user has a paid seat and their Git account is linked in Qodo.
Link Git account →

Using GitHub Enterprise Server, GitLab Self-Managed, or Bitbucket Data Center?
These require an Enterprise plan - Contact us
Contact us →

@daviszhen

Copy link
Copy Markdown
Contributor Author

Local verification at head 88cb80c (isolated 1 LogService / 1 TN / 2 CN instance):

-- exact issue repro
insert into t values (2, 2);
-- ERROR 20301 (HY000): invalid input: 2 beyond the range, can't be converted to Decimal64(2,2).
-- (main: silently stored 2.00)

insert into t values (1, 0.99),(3,-0.99),(4,0);       -- OK, stored
insert into t select 9, 5;                             -- ERROR 20301
insert ignore into t values (10, 6);                   -- ERROR 20301 (consistent with tinyint overflow under IGNORE -> 1690 error)
insert into tw values (1, 999999999999999999);         -- OK into DECIMAL(18,0)
insert into tw values (2, 18446744073709551615);       -- ERROR 20301, no negative wrap
alter table src modify column rawv decimal(2,2), algorithm=copy;  -- INT rows 2,3 -> ERROR 20301, table unchanged
select +9999999999999999999, -10000000000000000001;    -- unchanged vs main (zero-width synthesized cast guard)
  • go test ./pkg/sql/plan/ ./pkg/sql/plan/function/ ./pkg/sql/util/ — all pass at 88cb80c.
  • BVT: test/distributed/cases/dtype (2022 statements) and test/distributed/cases/dml/insert (1269 statements) run against a pristine baseline instance (upstream/main @ 309f618) and against this head on identical fresh data dirs: the failure sets are byte-identical between the two runs (environment-dependent noise like datalink/mo_ctl), and 0 failures contain the new 'beyond the range ... Decimal' diagnostic.

…#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.
@daviszhen
daviszhen force-pushed the fix-30367-decimal-int-range branch from 5092df5 to 25c6eef Compare October 20, 2026 04:53
@daviszhen

Copy link
Copy Markdown
Contributor Author

Rebased onto upstream/main @ 79298b1 (head now 25c6eef; git range-diff shows the change identical to 88cb80c, so the local verification above still applies). This re-triggers the pr-size-label job that failed earlier on a CI-side TLS disconnect.

…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.
@XuPeng-SH

XuPeng-SH commented Oct 22, 2026 •

Copy link
Copy Markdown
Contributor

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

Commit: a1027b586d37b067ab0b67e0187de8fe28503c0e

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: 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 escaping owned copy allocates 352 bytes per column even when changed remains 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.

@daviszhen

Copy link
Copy Markdown
Contributor Author

Addressed both performance P2 findings from review 5611360387 in commit 4881c51581.

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, -cpu=1 -p=1 -benchtime=500ms -count=3; times below are medians. The before run overlays only the two production files from the original head a1027b586d; both runs use the same benchmark/test sources and strict validation contract.

Operation Before After
Resolve 100 columns, no defaults 6.765 us; 36,544 B; 102 allocs 1.040 us; 1,344 B; 2 allocs
Resolve 100 columns, NULL defaults 13.775 us; 71,744 B; 202 allocs 8.121 us; 36,544 B; 102 allocs
4,096 integer rows to DECIMAL128 22.525 us 15.714 us
4,096 integer rows to DECIMAL256 63.420 us 18.249 us

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:

  • Complete planner and function suites with -vet=all -count=1: PASS (20.227s / 10.026s).
  • All persisted-decimal regressions under -race, including parallel copy-on-write readers: PASS (2.648s).
  • Frontend ResolveById and internal SQL resolver old-catalog regressions: PASS, including cancellation controls.
  • Configured incremental static checks for planner/function: 0 issues.
  • git diff --check: PASS.

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.

@daviszhen

Copy link
Copy Markdown
Contributor Author

Re-reviewed head 4881c515818c7680202e9f5927d5171d2695546b, focusing on the changes since my review of 28c88c9deb and the subsequent performance findings. No new blocking finding from this source review.

The previously reported correctness issues are addressed:

  • Multiplication's Decimal128-to-Decimal64 optimization now excludes signed BIGINT as well as UINT64/BIT. The final targets therefore retain the 19-digit signed domain. Public SQL regression cases cover both operand orders, positive/negative 10^18, MinInt64/MaxInt64 and the adjacent 18-digit control.
  • Catalog normalization recognizes genuine three-argument BETWEEN and four-argument in_range. The added serialized old-catalog fixtures exercise these operators directly, with fresh-binding comparisons, endpoint modes, explicit-CAST controls, catalog immutability and idempotence. The earlier NOT BETWEEN-only coverage gap is closed.

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: git diff --check passed. This was source/test review; I did not rerun native Go suites, benchmarks, race tests, distributed BVT or a live upgrade. The author's runtime/performance results are reported evidence. At the final status check, this exact head still had pending/running build, UT, SCA, coverage and Connector/J checks, and Matrixone Utils CI / pr-size-label reported FAILURE. Therefore this is not merge clearance: resolve the failed check and obtain required current-head results first. My earlier correctness request-changes items are closed at source level. Discussion comment only, not formal approval.

@daviszhen

Copy link
Copy Markdown
Contributor Author

Fixed the UT failure from run 39755014293, job 119744814023 in commit 78c61bd830.

The sole failing test was TestEmbeddedPrebuiltAdmission/serial. Its controller started read -t 5 while asynchronous precompilation was still running. The controller returned its fixture-defined exit code 100 before the first execution event arrived; its cleanup then released the mock children, which all finished successfully. The failure was in the scheduling fixture's latency assumption. The planner/function packages, SCA, both BVT variants and coverage passed in that run.

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 slow-prebuild case that holds the first mock compilation for six seconds. With the original per-read timers, the new regression reproduced exit status 100 despite all five mock executions passing. With the correction, serial, pool, heavy-failure and slow-prebuild cases all pass.

Validation:

  • Complete go test -mod=readonly -vet=all -race ./optools -count=1: PASS (101.595s).
  • Focused four-case admission regression under -race: PASS (14.965s).
  • Configured incremental static checks: 0 issues.
  • git diff --check: PASS.

The separate pr-size-label failure was a GitHub API TLS connection interruption. This push triggers new CI, including a fresh label check. New-head CI results remain pending; the local passes above are not a claim of completed CI.

@XuPeng-SH

XuPeng-SH commented Oct 22, 2026 •

Copy link
Copy Markdown
Contributor

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

Commit: 78c61bd8309c613c616cd59d72592064beed538e

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

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 --check passed. 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
aptend previously requested changes Oct 23, 2026

@aptend aptend left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

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

XuPeng-SH commented Oct 24, 2026 •

Copy link
Copy Markdown
Contributor

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

Commit: e6dcda13d2dcc0ae5e285ead76e6ec1a0e1adccb

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

@daviszhen

Copy link
Copy Markdown
Contributor Author

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

  • Generated six additional frozen definitions and actual frontend payloads at exact old writer 63a964a82fbaae4759cfabb45655e0185bc0979c, using its real parser/planner and tableDumpBoundExpressions. Every predicate was checked to remain a three-argument BETWEEN. The fixture includes both SIGNED/SMALLINT orders, a CHECK variant, same-width controls and explicit DECIMAL control. Generation procedure and fixture digest are recorded in LEGACY_DECIMAL_CATALOG.md.
  • Before the fix, the three mixed-width generated/CHECK fixtures fail origin verification; all three controls pass. After the fix, all 16 historical frontend fixtures pass, retaining original payload bytes/digests and source/target immutability. Rehashed constant substitutions and the existing mixed-era forgery remain rejected.
  • Typed regressions cover both BIGINT/TINYINT, BIGINT/SMALLINT and BIGINT/INT orders, unchanged normal binding, invalid signatures/arity and invalid IN_RANGE flags.
  • Real SQL TestDecimalHistoricalDumpRoundtrip passes with -count=2 on the same shared single-CN fixture: five scenarios per run, including both mixed-width orders and CHECK. It exercises physical-row DUMP/LOAD, subsequent INSERT/UPDATE, rejection of rehashed forged LOAD, preservation of the original constraint after failed LOAD, strict DECIMAL(18,0) rejection and catalog-verified teardown. This uses genuine old expressions with current native archive transport, not a deployed historical server or live binary upgrade.
  • Complete plan/function/frontend/compile suites pass with -vet=all -count=1; targeted account-cleanup tests and the real concurrent-account regression pass. Configured incremental golangci-lint reports 0 issues.

Also merged current main b264f5df89 in ed35fcfe86, resolving the conflicts while keeping DDL-scope, incomplete-temporal and integer-decimal validation flags distinct and composable.

CI triage: the previous exact head e6dcda13d2 has successful required UT/SCA/coverage/BVT checks in run 40051132732; there were no current failed jobs to rerun. The newly pushed head requires fresh CI; no new-head green-CI claim is made here.

@daviszhen

Copy link
Copy Markdown
Contributor Author

CI follow-up for exact head b1bc9efae6cf3e6c4d4f73ec4c4fbb99b6edff0f:

  • The only failed leaf check in attempt 1 is arm64 SCA, job 121042830434. Its check annotation states: “The self-hosted runner lost communication with the server.”
  • Runner arm64-mo-shanghai-4c8g-dcv8r-runner-4knj2 started SCA at 01:44:15 UTC. The job was marked failed at 02:30:20 UTC, without a terminal result for that step or post-job cleanup. This was before the workflow's 90-minute limit.
  • The job-log download returns HTTP 404 / BlobNotFound, and no SCA execution artifact was published. There is no retrievable lint diagnostic to justify a source change. The available evidence establishes runner communication loss, not whether its underlying cause was network, process failure or memory pressure.
  • Exact-head UT, UT coverage, merged coverage, both active BVT lanes and Connector/J passed. Rechecked all paginated reviews, inline comments and discussion: no new reviewer finding after the historical BETWEEN fix and its posted evidence.

Triggered only the failed SCA job again on the same SHA. Attempt 2 / job 121054362269 is now running on a different runner, arm64-mo-shanghai-4c8g-dcv8r-runner-86rdb. Its result is pending.

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.

@XuPeng-SH

XuPeng-SH commented Oct 25, 2026 •

Copy link
Copy Markdown
Contributor

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

Commit: b1bc9efae6cf3e6c4d4f73ec4c4fbb99b6edff0f

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

@XuPeng-SH

XuPeng-SH commented Oct 25, 2026 •

Copy link
Copy Markdown
Contributor

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

Commit: 9ba0f353784c29707807b5c1bd029f21c41b1575

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: 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 aptend left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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=100 runs.
  • Four additional constant DEFAULT/IN cases captured with the real planner at 63a964a82fbaae4759cfabb45655e0185bc0979c passed current-reader DUMP/LOAD, including the 10^18 boundary.
  • 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.

@mergify

mergify Bot commented Oct 26, 2026 •

Copy link
Copy Markdown
Contributor

Merge Queue Status

  • ✅ Entered queue — 2026-10-26 10:41 UTC · Rule: main · triggered by rule Automatic queue on approval for main
  • ✅ Checks passed · in-place
  • ✅ Merged — 2026-10-26 11:33 UTC · at 3de2ee56e840fedb8b9994002a4fcbcb049c37e0 · squash

This pull request spent 51 minutes 55 seconds in the queue, including 51 minutes 10 seconds running CI.

Required conditions to merge

This branch was previously deployed

1 inactive deployment
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

kind/bug Something isn't working size/XXL Denotes a PR that changes 2000+ lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants