Repository navigation
fix(plan): preserve prepared DECIMAL precision in common-value functions - #29428
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? |
XuPeng-SH
left a comment
There was a problem hiding this comment.
Review verdict: REQUEST_CHANGES — two verified remaining precision failures. Submitted as a COMMENT review because the authenticated account is also the PR author.
Reviewed head 13f625eb2e1f5e43d65d8af544688a7b5f8a6279 against main/merge-base b9013dc6bb058ec74935a62ac3a35f57d13c2f98. Read all four changed files and the SQL result metadata. No subagents or production edits; no waiting for CI.
The original issue query is fixed, but the design still conflates a parameter-dependent value with a parameter-dependent type, and the generic numeric-prefix conversion can discard the exact DECIMAL domain that this patch is intended to preserve. These are incomplete same-root closures, not claims that every failure was newly introduced by this PR.
Shared reproduction data:
CREATE TABLE t(id INT PRIMARY KEY, d DECIMAL(38,10));
INSERT INTO t VALUES
(1,9007199254740992.0000000001),
(2,9007199254740992.0000000002),
(3,9007199254740992.0000000003);| Probe | PR head | MySQL 8.0.44 |
|---|---|---|
COALESCE(?,CAST(? AS DECIMAL(38,10)))=d, both markers text 9007199254740992.0000000002 |
IDs 1,2,3; text result | ID 2; DECIMAL result |
GREATEST(?,COALESCE(?,d))=d, same markers |
IDs 1,2,3; text result | ID 2; DECIMAL result |
GREATEST(d,?)=CAST(9007199254740992.0000000002 AS DECIMAL(38,10)), text 1e-48 |
ID 2; DECIMAL result | ID 2; DECIMAL result |
Same query, text 1e-49 |
IDs 1,2,3; DOUBLE result | ID 2; DECIMAL result |
The last failure also reproduces with COALESCE(d,?). 1e-77 fails in MO while MySQL remains exact; 1e-1000 also makes MySQL choose DOUBLE, so that more extreme case is not used as a compatibility finding.
Design recommendation: separate semantic type provenance from value rebinding. An explicit DECIMAL cast has a fixed result type even when it contains a marker; a nested common-value expression must propagate its established type to its consumer. Keep the guard that prevents restoring an unbound expression separate from deciding whether its type is fixed. Then make conversion/width handling honor the established exact numeric domain instead of silently allowing the generic FLOAT fallback to decide it. Reuse the existing binder/specialization machinery; no new framework or protocol version is justified here.
Engineering/performance: the approximately 50 production lines add no worker, cache, lock, or persistent state, so there is no evidence of overengineering or a new lifecycle/race issue. The helper is per specialization, but it calls a source-restoration helper that can copy expression subtrees; it is not literally allocation-free. More importantly, runtime text currently inflates the common DECIMAL width (or promotes every row to DOUBLE). Resolve the type contract before claiming a performance improvement. No independent performance regression has been measured.
Test quality: the existing 4-row BVT is small and deterministic, and the typed UT proves cached-template immutability. The second-marker BVT always retains a separate DECIMAL column, which masks the fixed-type/value-dependency gap. Add the two distinct composition cases and the precision-capacity boundary rather than more repetitions of the original query.
Evidence reused: planner package, targeted race, vet/lint, BVT 80/80 twice plus metadata 80/80, and original MOTR 3/3. New QA: live SQL result/metadata comparisons against MySQL 8.0.44, NULL/conversion/width boundaries, and invalid explicit DECIMAL cast followed by a valid execution of the same statement (recovery passed). Test-owned databases were removed.
Comment audit: at review time there were no human reviews or inline technical comments; the only conversation comment was the Qodo paused-service notice. Thus there is no previous technical-comment checklist to mark resolved. The two findings below are open blockers.
| if oid.IsFloat() || !preparedNumericCommonOperandType(oid) { | ||
| return false | ||
| } | ||
| hasDecimalPeer = hasDecimalPeer || oid.IsDecimal() && !preparedExprContainsParam(arg) |
There was a problem hiding this comment.
[P1] Do not use absence of parameters as the proof of a fixed DECIMAL type
CAST(? AS DECIMAL(38,10)) has a fixed result type, but !preparedExprContainsParam(arg) rejects it as a peer. On this head, using the review's three-row fixture:
PREPARE p FROM 'SELECT id FROM t WHERE COALESCE(?,CAST(? AS DECIMAL(38,10)))=d ORDER BY id';
SET @p='9007199254740992.0000000002';
EXECUTE p USING @p,@p;returns 1,2,3, while MySQL 8.0.44 returns 2. GREATEST with the same typed peer also fails. The same gap is reachable with the original fixed DECIMAL column nested inside GREATEST(?,COALESCE(?,d))=d: the outer consumer retains text and its comparison loses precision.
Keep the protection against restoring an expression containing unbound markers, but separate it from type provenance and propagate fixed DECIMAL result types through nested consumers. The existing multi-marker BVT always includes a separate d operand and therefore does not detect this.
There was a problem hiding this comment.
Addressed in 8b3fee9. Fixed DECIMAL peers now include explicit CAST(? AS DECIMAL) and nested common-value results. Added typed and nested planner cases plus SQL BVT; the original CI-failing issue UT groups pass locally. MySQL 8.0.44 gives the same DECIMAL result.
| // Common results preserve concrete SQL strings, including typed NULL. | ||
| // Prefix eligibility belongs to transport-only text and numeric consumers. | ||
| if hasParamPos && isPreparedCommonValueFunction(functionName) && paramPos < len(rule.paramValues) { | ||
| if hasParamPos && isPreparedCommonValueFunction(functionName) && !fixedDecimalCommonValue && paramPos < len(rule.paramValues) { |
There was a problem hiding this comment.
[P1] Preserve exact DECIMAL when the generic prefix type exceeds the common precision budget
This exception admits the string marker into preparedNumericPrefixCast and normalizePreparedNumericCommonArgs, whose generic FLOAT64 fallback can undo the fixed DECIMAL decision. With the review's three-row fixture:
PREPARE p FROM 'SELECT id FROM t WHERE GREATEST(d,?)=CAST(9007199254740992.0000000002 AS DECIMAL(38,10)) ORDER BY id';
SET @p='1e-49';
EXECUTE p USING @p;returns 1,2,3 here, versus 2 on MySQL 8.0.44. 1e-48 is the passing nearest control. The fixed peer needs 28 integral digits; adding scale 49 exceeds Decimal256's 76-digit common width, so preparedNumericCommonType returns FLOAT64 and all three distinct DECIMAL values collapse. COALESCE(d,?) has the same failure even when the fallback value is not selected.
An established exact DECIMAL context needs intentional range/scale conversion rather than silently promoting the whole expression to FLOAT64. Add this capacity boundary and verify both rows and metadata; the current 10-digit fractions do not exercise it.
There was a problem hiding this comment.
Addressed in 8b3fee9. When the generic common precision exceeds Decimal256, specialization preserves the fixed DECIMAL peer and rounds only the eligible text marker to the available scale. Added 1e-48/1e-49/1e-1000 width cases and a cache regression for overflow after underflow; BVT passed 106/106 twice with result metadata.
XuPeng-SH
left a comment
There was a problem hiding this comment.
Deep review of 8b3fee9 against b9013dc: recommendation REQUEST_CHANGES.
The exact examples in the two previous P1 comments now pass, including the typed peer, the direct nested COALESCE peer, and the 1e-48/1e-49 capacity pair. However, the general contracts are not closed: an exact DECIMAL result loses its domain through an ABS/arithmetic wrapper, and the new overflow branch underallocates integral digits for long text prefixes. The new cache fingerprint also makes ordinary binary DOUBLE executions miss the existing type-category cache.
Validation: rebuilt the current head and ran public SQL boundary/metamorphic probes; compared the same probes with the clean b9013dc binary. A focused frontend cache-reuse test fails on head and passes on base. Existing planner UT, targeted race, issue UT, and 106-statement BVT evidence was reused where its inputs were unchanged. No subagents were used and remote CI was not awaited. The three inline findings include concrete inputs and outcomes.
Design recommendation: derive the outer domain from specialized child result types, keep text integral/scale requirements available before reducing precision, and make cache value dependence follow actual materialization. These belong at the existing specialization/common-type boundary; another function-name whitelist or a blanket FLOAT value key would leave the same problem in a different shape.
| if fn := source.GetF(); fn != nil && fn.Func != nil && | ||
| preparedCommonValueFixedDecimalPeer(fn.Func.GetObjName(), fn.Args, positions) { | ||
| hasDecimalPeer = true | ||
| continue | ||
| } | ||
| oid := types.T(source.Typ.Id) | ||
| if oid.IsFloat() || !preparedNumericCommonOperandType(oid) { | ||
| return false | ||
| } | ||
| hasDecimalPeer = hasDecimalPeer || oid.IsDecimal() && | ||
| (!preparedExprContainsParam(arg) || isExplicitPreparedCast(source)) |
There was a problem hiding this comment.
[P1] Propagate the fixed DECIMAL domain through numeric wrappers
The recursive proof still only recognizes COALESCE/GREATEST/LEAST, and the final predicate rejects a non-cast numeric result containing a marker. On this head, create three positive DECIMAL(38,10) rows with d = 9007199254740992.0000000001, ...0002, ...0003 (ids 1/2/3), then:
SET @p='9007199254740992.0000000002';
PREPARE p FROM 'SELECT id FROM t WHERE GREATEST(?,ABS(COALESCE(?,d)))=d ORDER BY id';
EXECUTE p USING @p,@p;This returns 1,2,3; removing ABS returns only 2, as does explicitly casting the nested result to DECIMAL(38,10). ABS is the identity on this positive fixture, so the wrapper must not change the selected rows. COALESCE(?,ABS(COALESCE(?,d))) and GREATEST(?,COALESCE(?,d)+0) expose the same precision loss. This is a remaining part of the previous type-provenance finding, not a new baseline regression. Resolve the outer domain from the specialized child's semantic result instead of limiting provenance propagation to this short list of function names.
There was a problem hiding this comment.
Addressed in rebased head 4daac96. The outer common-value binder uses the rebound child DECIMAL result and checks for a fixed DECIMAL source, so ABS(COALESCE(?,d)) and COALESCE(?,d)+0 preserve the exact domain without a wrapper-name whitelist. Added planner UT and SQL BVT for the three reported forms; independent QA checked five nested forms against three adjacent values above 2^53. Full planner, frontend, and issue UT pass.
| case typ.Oid.IsFloat(): | ||
| if !eligibleText { | ||
| return types.Type{}, false, nil | ||
| } | ||
| maxScale = types.T_decimal256.ToType().Width |
There was a problem hiding this comment.
[P2] Include the text prefix's integral digits in the capped DECIMAL envelope
When an eligible text prefix exceeds 76 total digits, this branch records only maxScale=76 and discards its integral width. The target consequently reserves only the fixed peer's integral digits. Reproduced on the current head:
PREPARE p FROM 'SELECT LEAST(?,CAST(1.25 AS DECIMAL(10,2)))';
SET @p=CONCAT('123456789.',REPEAT('0',67),'1');
EXECUTE p USING @p;It raises error 20301 while converting to Decimal256(76,68), which has only 8 integral digits although the marker requires 9. With REPEAT(...,66) it succeeds and returns 1.25. This value is representable after rounding (even CAST(@p AS DECIMAL(65,30)) succeeds); its insignificant 68th fractional digit can be removed while preserving both the 9 integral digits and the fixed peer's scale 2. Baseline also executes the LEAST query successfully. GREATEST and COALESCE hit the same new rejection. Preserve the prefix's integral requirement when selecting the capped scale rather than deriving that requirement solely from the fixed operands.
There was a problem hiding this comment.
Addressed in rebased head 4daac96. Numeric-prefix shape now retains both integral width and scale beyond 76 digits. The capped common type reserves the prefix integral digits and the fixed peer scale before reducing only eligible text scale. The exact 9-integral-digit/68-fractional-digit example now returns 1.25 with DECIMAL(76,67) metadata. Added planner UT and SQL BVT; the 130-statement BVT passed twice on the rebased binary.
| if param.EnableNumericPrefix && runtimeType.Oid.IsFloat() { | ||
| // Out-of-range DECIMAL prefixes can be folded to a value-specific | ||
| // zero or error during specialization. A type-only cache key would | ||
| // reuse that result for a different prefix in the FLOAT64 domain. | ||
| fmt.Fprintf(&key, "float-prefix:%x;", sha256.Sum256([]byte(rawValue))) |
There was a problem hiding this comment.
[P2] Restrict value fingerprints to the materialized DECIMAL-prefix path
EnableNumericPrefix is also left true for ordinary binary numeric parameters when filterBinaryNumericPrefixCandidates is not invoked. Therefore this condition hashes regular MYSQL_TYPE_DOUBLE payloads even in SELECT ABS(?), where no DECIMAL peer or value-dependent folding exists. A focused test using newPreparedExecuteEnvForSQL, installing the first runtime compile for -1.5 and executing again with -2.5, fails on this head: the keys differ, initExecuteStmtParam returns a new logical plan and no cached compile. The identical test passes on b9013dc, reusing both objects.
Changing values within a normal DOUBLE domain now causes repeated specialization and recompilation across unrelated prepared queries. Keep their type-based key; attach value dependence only to parameters actually materialized by the exceptional DECIMAL conversion (or retain a runtime parameter expression). The current new UT only distinguishes two extreme text inputs, so it misses this ordinary numeric control.
There was a problem hiding this comment.
Addressed the measured regression in rebased head 4daac96. A concrete binary DOUBLE no longer gets a value fingerprint even when EnableNumericPrefix is broadly enabled. The new frontend test executes ABS(?) with -1.5 then -2.5 and verifies reuse of both the logical plan and installed compile; full frontend UT passed. The fingerprint remains for inferred text FLOAT prefixes because exact DECIMAL conversion can fold those values to zero or overflow. This conservative boundary may cause extra cache misses for unusual text FLOAT values outside a fixed-DECIMAL expression; I kept it small instead of adding another plan scan or protocol state solely for that rare performance case.
aptend
left a comment
There was a problem hiding this comment.
Reviewed exact head 8b3fee90e1fc9b40a8578c55691005ecb3fe962c against merge-base b9013dc6bb058ec74935a62ac3a35f57d13c2f98, including the 13f625e..→8b3fee9.. increment, all previous reviews, inline replies, and unresolved threads. REQUEST_CHANGES: the first two functional failures below remain blockers. The earlier typed-peer and 1e-49 examples are fixed, but the general contracts are not closed.
-
P1 — fixed DECIMAL provenance is lost through wrappers (
pkg/sql/plan/visit_plan_rule.go:807-852).preparedCommonValueFixedDecimalPeeronly recurses through COALESCE/GREATEST/LEAST; for ABS or arithmetic around a marker-containing DECIMAL child, the fallback rejects it viapreparedExprContainsParam. Witht(id,d DECIMAL(38,10))holding 9007199254740992.0000000001/.0000000002/.0000000003,GREATEST(?,ABS(COALESCE(?,d)))=dwith both parameters'9007199254740992.0000000002'returns IDs 1,2,3 at this exact head, while removing ABS or explicitly casting the child returns only ID 2. ABS is identity for these positive rows; losing the exact domain changes the predicate. This is the remaining form of the previous type-provenance issue (see discussion_r4119233193). -
P2 — capped DECIMAL width drops the text prefix's integral digits (
pkg/sql/plan/visit_plan_rule.go:4367-4417). InpreparedFixedDecimalCommonType, a FLOAT-classified eligible text operand only setsmaxScale=76;maxIntegralcomes solely from fixed peers.PREPARE p FROM 'SELECT LEAST(?,CAST(1.25 AS DECIMAL(10,2)))'; SET @p=CONCAT('123456789.',REPEAT('0',67),'1'); EXECUTE p USING @p;then chooses Decimal256(76,68), leaving eight integral digits for a nine-digit input, and errors 20301. The same query with 66 zeroes succeeds, and the 67-zero value is representable after dropping insignificant fractional digits. This is a newly introduced rejection; see exact-head reproduction in discussion_r4119233199. Preserve the eligible prefix's integral requirement when capping scale. -
P2 — normal binary DOUBLE parameters now miss the prepare cache (
pkg/frontend/computation_wrapper.go:2363-2367).EnableNumericPrefixdefaults true for protocol-v30+ binary parameters, even forSELECT ABS(?);filterBinaryNumericPrefixCandidatesis not always invoked. The new SHA-256 value key therefore makes -1.5 and -2.5 different cache identities although both are ordinary DOUBLE values and no DECIMAL-prefix materialization occurs. Re-execution reparses/recompiles instead of reusing the cached plan (focused head-vs-base reproduction in discussion_r4119233204). Gate value hashing on actual exceptional conversion, not the broad eligibility flag.
The added BVT/UT checks cover direct typed peers and the 1e-49 boundary but omit ABS/arithmetic wrappers, long integral prefixes, and normal binary DOUBLE cache reuse. Exact-head CI is green; I did not run an additional local Go test because this isolated worktree cannot reuse the primary worktree's mismatched CGo/native artifacts. No production files were changed in the review worktree.
8b3fee9 to
4daac96
Compare
aptend
left a comment
There was a problem hiding this comment.
Reviewed exact head 5d836ab against the PR base and the previous reviewed head, including prior reviews, inline replies, and unresolved threads. The earlier blockers—fixed DECIMAL provenance through wrappers, capped precision/integral carry, and ordinary DOUBLE cache reuse—are addressed in the current implementation and tests. I also checked a 0xx → 1xx SQL EXECUTE cache-reuse counterexample: the same cached plan produced 0.00 and then 1.00 correctly. Focused planner and frontend regression tests passed in an isolated exact-head worktree. No remaining blocking issue found.
## What type of PR is this? - [ ] API-change - [x] BUG - [ ] Improvement - [ ] Documentation - [ ] Feature - [ ] Test and CI - [ ] Code Refactoring ## Which issue(s) this PR fixes: issue #26879 Incremental follow-up to merged #29428. ## What this PR does / why we need it: Prepared common-value expressions still lose type context across unresolved nested results or IFNULL lowering, and a plain NULL before a DECIMAL peer incorrectly inherits the later DECIMAL domain. - Propagate the combined domain of **all** fixed numeric peers into marker-only common-value children before overload selection, preserving every DECIMAL scale constraint and reusing the existing numeric-prefix and precision/overflow binder. Fixed-peer order must not turn an exact overflow into a rounded DOUBLE. - Jointly normalize runtime marker shapes across unresolved nested/sibling results before child overloads are rebuilt; do not promote one marker's roundable scale into another marker's fixed-scale constraint. Root operands keep the existing spelling-sensitive inference gate; a concrete SQL PREPARE string boundary protects the **whole** region before any child conversion. - Bind IFNULL's result operands in their original SQL order without including its CASE control expression. - Preserve NULL-first inference ordering and concrete string, FLOAT, and explicit CAST boundaries. - Keep executable parameter references and mark value-derived bindings as value-dependent, rather than caching a value-specific plan by source type. Regression coverage includes DECIMAL64/128/256, both SQL PREPARE and COM_STMT, nested/reversed/deep common-value calls, typed/untyped NULL controls, same-type value changes, invalid-text recovery, ABS-derived results, and explicit CHAR/DOUBLE boundaries. Original comparison results were checked against MySQL 8.0.45. The review follow-up also covers mixed DECIMAL(65,30)/DECIMAL(38,0) peers in both orders, nested versus direct-marker controls, 65-digit overflow (error 1690), the Decimal256 46/47-integral-digit boundary at scale 30, and recovery on the same prepared statement. These precision cases use the existing direct-marker behavior and MatrixOne's 76-digit bound as their oracle. The second review follow-up covers heterogeneous marker values (65 nines and `1e-30`) in nested COALESCE, IFNULL, deep nesting, and separate big/big versus tiny/tiny sibling subtrees. All use the exact DECIMAL(76,11) domain rather than rejecting or falling back to DOUBLE; 77-digit overflow and recovery remain covered in both protocols. The root-string review follow-up covers LEAST/GREATEST with direct, COALESCE, IFNULL, deep and sibling operands. SQL PREPARE root values such as `abc`, `!` and the empty string retain lexical child spellings (`0002`) and do not spuriously reject 77-digit strings. Same-type string→numeric-prefix→string rebinding is value-dependent; COM_STMT retains its existing numeric-prefix policy. The new public matrix contains 200 executions. ### Validation - Go 1.26.4 with verified worktree-local CGo artifacts and the repository test wrapper. - Complete `pkg/sql/plan` tests in normal mode; focused changed-code coverage: 202/229 executable lines (88.2%). - Public two-protocol regressions and existing issue #27088 regressions. - Six frontend DECIMAL/source-binding/runtime-cache regressions. - Independent public-protocol probe: 182/182 executions passed. - mo-tester-generated and oracle-reviewed results; normal comparison twice against the same owned standalone instance: 208/208 each, with teardown checks. - `go vet`, incremental repository lint, matching gofmt, and `git diff --check`. Latest verified `mo/main` (`fcd9686e0d`, including the subsequent prepared numeric/temporal, peer-pruning and remote-expression changes) was merged before the review update; the final build and tests were rerun on that baseline. Local CLAUDE documents, logs, and caches are not included in the PR. Validation note: the initial delivery's full-package atomic coverage hit the unchanged trailing-zero allocation assertion (`2` allocations versus a limit of `1`). The complete package passed in normal mode, and the focused changed-code coverage run passed; no allocation assertion was relaxed. Incremental lint passed; the earlier full-package lint report contained only formatting findings in two untouched baseline test files. --------- Co-authored-by: XuPeng-SH <[email protected]>
What type of PR is this?
Which issue(s) this PR fixes
Fixes #29389. Restores the prepared DECIMAL behavior covered by #26879.
What this PR does
SQL
PREPARE/EXECUTEcould bindGREATEST,LEAST, andCOALESCEwith a text marker and a fixed DECIMAL peer as string or FLOAT64. Values above 2^53 then lost distinct DECIMAL fractions. Fixed DECIMAL peers now include explicitCAST(? AS DECIMAL)and nested expressions whose rebound result has a fixed DECIMAL source. A separate concrete string keeps its string domain.The latest review exposed three remaining boundaries. The runtime cache now distinguishes concrete SQL strings with and without a numeric prefix, so cached
abcand0xxexecutions match fresh preparation in either order. A generic numeric parent now discards a binder-inserted cast when its parameterized child rebinds to DECIMAL; a user-authoredCASTstays authoritative. When a long text prefix loses fractional digits to fit Decimal256, the selected scale reserves a possible carry into the next integer digit while preserving the fixed peer's scale. The same rule covers positive, negative, and exponent spellings. These changes add no storage or wire format and no per-row work.Validation on current main
d99187d7b3(origin/main); local rebuild with repository native dependencies, Go 1.26.4 on Linux amd64.pkg/sql/plan,pkg/frontend, andpkg/tests/issuesUT passed on the final code.ROUNDrows, positive and negative Decimal256 carry values and metadata, and string-prefix cache transitions; existing NULL, underflow/overflow, typed-peer, and explicit-cast checks remain.LEAST/GREATEST/COALESCEagainst explicit DECIMAL casts, and checked seven nested expression shapes. Test database cleanup was verified.gofmt,git diff --check, incrementalgo vet, and golangci-lint 2.6.2 (built with Go 1.26.4) passed for the changed Go package closure (pkg/sql/plan,pkg/frontend,pkg/tests/issues); lint reported 0 issues.The earlier typed-peer, wrapper, width, and ordinary binary DOUBLE review comments remain covered. The three latest review comments are addressed by the cache-class bit, rebound numeric child, and rounded-capacity calculation. Remote CI was not awaited.