Skip to content

fix(plan): preserve prepared source domains across FIELD and relational consumers - #29379

Merged
XuPeng-SH merged 8 commits into
matrixorigin:mainfrom
XuPeng-SH:codex/issue-29378-field-fixed-peer
Sep 26, 2026
Merged

XuPeng-SH merged 8 commits into
matrixorigin:mainfrom
XuPeng-SH:codex/issue-29378-field-fixed-peer

Conversation

@XuPeng-SH

@XuPeng-SH XuPeng-SH commented Sep 25, 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:

Fixes #29378

What this PR does / why we need it:

Prepared FIELD could round a fixed DECIMAL peer through PREPARE's provisional DOUBLE domain. The same source-domain loss appeared across aggregate/window/group/set outputs and surviving derived columns. A later review found the complementary gap: multiple projected markers entering FIELD, GREATEST/LEAST, COALESCE, IF/CASE, comparisons, retained IN, or BETWEEN could keep their PREPARE-time TEXT domain. The latest Compose PROXY CI also exposed an aggregate-owned BOOL→TINYINT cast that was incorrectly removed at EXECUTE.

Resolve the selected producer before folding, preserve exact fixed-peer provenance through repeated folds, and restore the original operand tuple after runtime producer types become available. The bottom-up projection refresh and specialization admission now also recover proven projected source domains at each value consumer while leaving the physical column intact. Retained IN uses the existing binder after decoding a folded constant vector back to its typed scalar list only when rebinding is needed. The mode-authorized SUM/AVG BOOL→TINYINT adapter keeps its aggregate ownership. Explicit casts and actual STRING/REAL sources remain authoritative. No new protocol field, cache, execution graph pass, or test cluster fixture is introduced.

Expected behavior is based on MatrixOne's direct SQL and protocol source contracts, including intentional distinctions rather than blanket MySQL emulation. Let A=DECIMAL(20,0) 9007199254740992, B=DECIMAL(20,0) 9007199254740993:

Input/context Expected behavior
FIELD(B,ABS(A)) 0; fixed exact peers never lose their digits through provisional DOUBLE casts.
COALESCE(DECIMAL NULL, CHAR NULL, ABS(B)) inside FIELD(...,ABS(A)) 1, also when the first two operands are swapped. Concrete string operands participate in the whole common type. All-DECIMAL NULL operands give 0.
SQL string selected by COALESCE, including abc or 12.5tail Keep the original string and result type, including SELECT/SET and scalar-subquery forms. Numeric comparison remains a numeric-prefix consumer.
SQL variable assigned bare NULL TEXT source. FIELD(COALESCE(@n,ABS(B)),ABS(A)) gives 1; FIELD(B,@n,ABS(A),ABS(B)) gives 2. The direct oracle uses the same variable, not a literal NULL.
COM_STMT nil without a concrete type Domainless NULL. The preceding two expressions give 0 and 3, including a marker projected through LIMIT. Concrete CHAR/DOUBLE NULL retains its type.
Exact producer behind LIMIT/nested projection, MAX/SUM/AVG, GROUP/DISTINCT, windows or UNION The consumer uses the producer's actual domain; WHERE/HAVING agree with projection and preserve row counts. SUM may legitimately widen to DECIMAL256.
Bare SQL marker returned alongside a numeric consumer Its existing visible TEXT result stays TEXT; only the consumer converts the physical column to the runtime source type.
Two projected DECIMAL markers in GREATEST/LEAST, FIELD, IF/CASE or comparison Use their exact numeric source domains, including scale/precision and result metadata; the same SQL-variable values agree with direct SQL. After STRING execution, the same prepared handle recovers numeric semantics. STRING values keep lexical semantics.
Projected DECIMAL(10,1) 1.0 in x IN ('1','2') / NOT IN [1,0]; concrete STRING '1.0' gives [0,1]. An unmatched RHS containing NULL yields UNKNOWN for both predicates.
Projected DECIMAL 10 in x BETWEEN '1' AND '2' / NOT BETWEEN [0,1]; concrete STRING '10' gives [1,0]. Projected DECIMAL 2 between 1 and 10 is true, while STRING '2' between '1' and '10' is false. NULL bounds retain UNKNOWN.
SUM(? LIKE '____') and AVG(? LIKE '____') under ENABLE_BOOL_SUMAVG Keep the mode-authorized BOOL→TINYINT argument; both execute with numeric result types. Mode-disabled direct/PREPARE binding still rejects BOOL aggregation. The CI-shape two-aggregate query returns (12,3) for three binary abcd rows, (6,0) for three selected 你好 rows, and (NULL,NULL) for NULL.
Explicit CHAR/DOUBLE, unrelated marker, null-extended outer-join side Preserve the explicit domain, selected-column identity and NULL semantics.

A transparent physical TEXT column is read through a consumer-local conversion, preserving filtering and outer-join null extension. Only an exact projected marker proven to be domainless NULL may become an ANY NULL at that consumer. A UNION/JOIN output retains its physical column: a string-domain witness for one branch does not prove the value of every row. Each set arm supplies its own execute-time SQL or binary source domain before the set output is reconciled. If every arm is domainless NULL, the set keeps its physical prepared type so no ANY vector reaches its spool. The cached PREPARE template is unchanged across execution and error/reuse.

The five latest review comments are addressed together: mixed UNION rows keep their distinct values (NULL, abc → FIELD [0,1]); a SQL DECIMAL/VARCHAR UNION stays in its actual common string domain ([1,1]); a table-backed scalar subquery follows its selected output without losing scalar cardinality; restored common-result dependence reaches outer consumers; and uncast projected markers in common-value/relational consumers use their execute-time source domains. IF(condition, binary NULL, NULL) retains its conditional producer while its domainless result allows an outer DECIMAL COALESCE ([0,0]). An explicit VARCHAR or DOUBLE NULL still chooses its string/approximate result ([1,1]). Existing issue27088 tests also check independently evaluated direct SQL values and types for concrete SQL strings; their numeric-comparison and COM_STMT transport-prefix controls remain intact.

Validation

  • Latest completed CI on previous head c5a1e15b8b failed only two SQL commands in Compose PROXY's binary_string_function_semantics.test: prepared SUM(? LIKE '____') rejected BOOL, while direct SQL succeeded. Coverage/Required failures were downstream. A matching embedded public test and typed PREPARE-plan probe failed before the fix, then passed after it. The same red→green public pass also caught retained BETWEEN numeric-vs-string disagreement.
  • Full pkg/sql/plan, pkg/sql/plan/rule, pkg/frontend, and pkg/tests/issues packages passed with -count=1 after the current correction (5.040 s / 0.048 s / 20.559 s / 51.628 s). Focused final expected-value assertions passed (11.442 s). Public regressions assert direct-query values and types, SQL/binary/typed NULL domains, same-handle numeric/string/numeric reuse, set-arm order, scalar output, predicate behavior, and unchanged cached templates.
  • On previous head c5a1e15b8b, an owned standalone instance passed the existing JDBC BVT (83/83 commands). This is historical evidence; the latest planner delta is covered locally by the embedded SQL regression, and the remote multi-CN PROXY rerun remains pending. Result metadata is separately asserted in public Go tests.
  • CGo-configured go vet, formatting and git diff --check passed. Incremental golangci-lint v2.6.2 reported 0 issues on the current code.
  • Independent GPT-6 Astra medium design and final overall review of the complete diff d654560c…c826594 found no confirmed unresolved blocker. Separate independent QA challenged the new projected-consumer, retained-predicate, and aggregate-cast rules and found no concrete blocker.
  • Rebased against verified latest main at b1b68925d7 (fix(ddl): serialize foreign key validation with concurrent writes #29066); it was already up to date, and the complete diff fingerprint stayed unchanged. Published head: 59d318a83d. Fresh CI for this commit remains pending; no CI success is claimed.

Performance and scope

Earlier per-EXECUTE microbenchmarks (1000 iterations, three samples) against PR head fbe380d0: 1/16/64 fixed-peer cases retained the same allocation counts (161/608/2012) and added about 31–34 B/op. A nested relational case added 6 allocations and 512 B/op for execution-local output provenance. These measurements predate the latest projected-consumer/IN changes and are not final-delta measurements; there is no supported throughput or speedup claim. The full PR remains more expensive than the pre-PR baseline for large fixed-peer expressions, as disclosed in the earlier review.

There is no per-row producer traversal. A surviving physical TEXT marker can require a per-row numeric conversion at its consumer; this correctness cost is explicit. Rebinding a changed IN left operand with a folded constant list materializes that list once per specialized EXECUTE, with cost proportional to its length; no throughput gain is claimed. Separate direct-query optimizer defects observed while challenging the change—lifting a constant projection across LEFT JOIN ... ON FALSE, and pruning an unused earlier mixed-type window—are outside this prepared-source fix. Null extension is covered with an aggregate producer, and both live window ordinals are covered without accepting those unrelated wrong results.

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

@XuPeng-SH XuPeng-SH left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Decision: changes requested — the fixed-peer repair is incomplete

Reviewed exact head b85a90231da21c9c561cd3e88f52eab95004f50c against merge-base / declared base ce7f84dabc563fa5bb29c648e8b02aa6581b608b. All six changed files and the prepare → isolated execute-time plan → overload/cast → public SQL paths were reviewed.

P2: nested numeric operands still retain the lossy fixed-peer envelope

See the inline finding. The original bare-marker example is fixed, including reverse operand order, DECIMAL(38,0), fractional precision, integer peers, scalar-subquery markers and an enclosing arithmetic consumer. However, ABS(?), COALESCE(?, CAST(0 AS DECIMAL(20,0))), and IF(true, ?, CAST(0 AS DECIMAL(20,0))) still produce false matches beside a fixed DECIMAL peer. Reversing the needle/candidate also fails.

The planner probe shows the nested child correctly becomes DECIMAL128, while FIELD receives DOUBLE/DOUBLE and overload 10 because the peer's provisional cast survives. This is an unclosed path in the same SQL EXECUTE precision problem, not a newly introduced regression.

Additional pre-existing protocol gap

A real database/sql prepared statement (COM_STMT_PREPARE/EXECUTE), SELECT FIELD(?, CAST(9007199254740992 AS DECIMAL(20,0))), executed with Go uint64(9007199254740993), also returns 1 instead of 0. The new restoration is reached through variadicSource, whose guard excludes binary-protocol parameters. This fails with both base and head production code. I am recording it as related scope still requiring tracking, not attributing a new regression to this SQL-user-variable fix.

Evidence and engineering assessment

  • Local public SQL counterexamples: 19 scenarios, 14 passed / 5 failed at this head. All five failures also fail with both changed production files restored to the exact base via a Go overlay. Direct SQL is an independent oracle with explicit expected results.
  • Local planner diagnosis: bare marker uses DECIMAL128/DECIMAL128; the three nested forms retain DOUBLE/DOUBLE. The PR's TestPreparedVariadicRuntimeSourceDomains passes.
  • Explicit DECIMAL/DOUBLE boundaries, arithmetic marker, unsigned boundary and a rejected invalid DECIMAL followed by successful reuse pass. Existing PR tests cover alternating source types and column peers.
  • Exact-head CI evidence reused: arm64 SCA reports 0 issues; coverage UT producer reports passed, exit 0, 486 packages with no failed package/test events; completed compose/PROXY BVT includes prepared_variadic_comparison.sql 42/42. The separate Linux UT/race and pessimistic BVT jobs were still running when checked; this review does not claim those are green.
  • The change is small and sensibly reuses existing provenance and deep-copy machinery. No new shared state, waits, protocol fields or per-row algorithm is introduced. Added work is source retention and execute-time rebinding; no separate throughput benchmark was run. No independent performance or overengineering blocker found.
  • Previous comments: zero technical comments/review threads; only Qodo's paused-review notice existed. There is no earlier technical discussion to mark resolved.

Evidence (local): /home/xupeng/mo-validation/pr29379-review-b85a/ (probe-head.log, probe-base.log, probe-plan-head.log, source probes, overlays and CI records). Repository source remains unchanged.

Submitted as COMMENT because the authenticated account is also the PR author; the technical recommendation above is REQUEST_CHANGES.

Comment thread pkg/sql/plan/visit_plan_rule.go Resolved

@XuPeng-SH XuPeng-SH left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Technical decision: REQUEST_CHANGES — the fixed-peer precision repair is still incomplete.

Reviewed 90bde35db972e34f6fda74febdca3a52f3711f55 against merge-base/main 27ea64ab038c80cfc94ad4368315ab30d21e6d56, including all six changed files and the PREPARE → constant folding → isolated execution plan → overload selection → public SQL paths.

P2: folded fixed numeric expressions still lose their exact source. The inline finding has a minimal reproduction. FIELD(?, ABS(CAST(9007199254740992 AS DECIMAL(20,0)))), executed with DECIMAL 9007199254740993, returns 1, while equivalent direct SQL returns 0. A fixed COALESCE(CAST(9007199254740992 AS DECIMAL(20,0)), CAST(0 AS DECIMAL(20,0))) peer fails identically. The prepared plan retains a DOUBLE literal with provisional DECIMAL metadata but no Literal.Src; execution therefore leaves FIELD on DOUBLE/DOUBLE overload 10. Retaining the exact peer domain must survive constant folding, not just the bare explicit-CAST shape.

Two related nested cases also remain wrong: FIELD(GREATEST(?, CAST(0 AS DECIMAL(20,0))), CAST(9007199254740992 AS DECIMAL(20,0))) and the analogous LEAST(?, CAST(9007199254740994 AS DECIMAL(20,0))) return 1 instead of direct SQL's 0. Their inner fixed numeric peer remains TEXT without source provenance; the GREATEST/LEAST string-boundary check suppresses numeric restoration, leaving the outer FIELD approximate. These are recorded as related pre-existing closure gaps, not additional newly introduced regressions.

The previous resolved thread was rechecked: the reported ABS(?), COALESCE(?, ...), IF(...), reverse ABS operand and typed binary integer paths now pass. Those fixes are effective; the new finding concerns the fixed-expression/folding boundary.

Validation:

  • Complete pkg/sql/plan, -vet=all -count=1: passed (5.913s).
  • Existing real three-CN TestIssue28397FieldKeepsExactNumericComparison: passed (11.528s).
  • Independent public SQL matrix at this head: 29/33 scenarios passed, four failed, with direct SQL and explicit expected values as the oracle. The passing scenarios include further CASE/IFNULL/NULLIF nesting, arithmetic, scalar subquery, DECIMAL(38,0), fractional precision, explicit DOUBLE/text boundaries, NULL and UINT64 boundaries.
  • Three actual COM_STMT statement shapes passed 24 executions alternating signed/unsigned integers, DOUBLE, text, bytes, NULL and numeric reuse. A rejected invalid DECIMAL followed by successful executions also passed.
  • Both changed production files restored to the exact base through a Go overlay: 14/33 passed, 19 failed, including the same four remaining head failures. This demonstrates an incomplete repair of existing behavior; no new regression was found in this matrix.
  • Planner probes independently confirm the missing fixed-peer source and selected overload. No full pkg/tests/issues rerun or throughput benchmark is claimed.

Engineering/performance: the change reuses existing provenance, per-execution dependency maps and deep-copy rebinding, with no new framework, shared mutable state, waits or per-row algorithm. No independent lifecycle, performance or overengineering blocker was found. The correctness gap above remains blocking.

Exact-head CI at submission: shared build and preflight passed; Linux UT, coverage, arm64 SCA and both active BVT jobs were still running. This review does not claim CI is green.

Reproducible local evidence: /home/xupeng/.codex/reviews/pr29379/ — repro.sql, probe-public_test.go, probe-plan_test.go, probe-head-confirmed.log, probe-base.log, probe-plan-head.log, plan.jsonl, field-sql.log, and the exact base overlay. Temporary probe files are removed from the review worktree; production source is unchanged.

Submitted as COMMENT because the authenticated account is also the PR author. The technical recommendation is REQUEST_CHANGES.

if b.builder != nil && b.builder.isPrepareStatement &&
(isNumericContextFunction(name) || supportsGenericNumericFunctionContext(name) ||
preparedSQLExecuteNumericResultConsumer(name) || name == "iff") {
preparedSQLExecuteNumericResultConsumer(name) || name == "iff" || name == "field") {

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

[P2] Preserve exact fixed-expression sources through constant folding

Enabling FIELD provenance here still does not retain a fixed numeric expression's source through folding. On this head:

SET @n = CAST(9007199254740993 AS DECIMAL(20,0));
SELECT FIELD(CAST(9007199254740993 AS DECIMAL(20,0)),
             ABS(CAST(9007199254740992 AS DECIMAL(20,0)))); -- 0
PREPARE p FROM 'SELECT FIELD(?, ABS(CAST(9007199254740992 AS DECIMAL(20,0))))';
EXECUTE p USING @n; -- 1, expected 0

Using a fixed COALESCE(CAST(9007199254740992 AS DECIMAL(20,0)), CAST(0 AS DECIMAL(20,0))) peer also fails. The final PREPARE plan contains a DOUBLE literal with ProvisionalResultPeerTypeId=DECIMAL128 but no Literal.Src. provisionalNumericPeerSource cannot recover it, and FIELD keeps the lossy DOUBLE/DOUBLE overload. Please retain the exact source through folding and cover fixed numeric expressions in the public SQL regression; casting the already-rounded DOUBLE back to DECIMAL cannot generally recover lost digits.

Both examples also fail with the two production files restored to the exact merge-base, so this is an unclosed path in #29378 rather than a new regression.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed at rebased head 997373d63b4e95ba3145d25d64edbe94608bd0f5. Both constant-folding paths now retain the exact numeric source behind a provisional FLOAT or TEXT literal, so EXECUTE restores the fixed peer instead of casting an already-rounded value. Added prepared-vs-direct SQL regressions for fixed ABS and COALESCE expressions, reverse operand order, and nested GREATEST/LEAST; all pass. The focused embedded SQL test passes, and the updated BVT passes 53/53 twice on one instance. Full pkg/sql/plan and pkg/sql/plan/rule, go vet, and incremental lint pass. The full pkg/tests/issues package remains unverified; see the PR validation section.

@XuPeng-SH XuPeng-SH changed the title fix(plan): preserve prepared FIELD source domains across NULL and projections fix(plan): preserve prepared source domains across FIELD and relational consumers Sep 26, 2026
@matrix-meow matrix-meow added size/XL Denotes a PR that changes [1000, 1999] lines and removed size/L Denotes a PR that changes [500,999] lines labels Sep 26, 2026

@XuPeng-SH XuPeng-SH left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Commit review and validation: fbe380d (rebased onto main 9c79a6e).

The latest three findings are accepted and fixed together:

  • review comment 4111134593: concrete SQL strings/typed NULL retain their domain across the complete common-value tuple; selected text and result metadata now match direct SQL using the same variables.
  • review comment 4111134598: selected AGG/group/window producers are resolved before folding, including pending HAVING bindings and both live window ordinals.
  • review comment 4111134601: surviving relational consumers trigger specialization and rebind after producer refresh; LIMIT, UNION, predicates, row counts and visible bare TEXT metadata are covered.

QA additionally exposed and closed projected COM_STMT domainless NULL used as a candidate/common result, repeated outer folding that dropped exact peers, and a VARCHAR/TEXT mismatch for SQL SET + COALESCE. Existing numeric-comparison and COM_STMT prefix controls remain; three obsolete SQL common-result oracles were replaced by independently evaluated direct-variable value/type assertions.

Final local acceptance: complete planner, rule, frontend and issues packages PASS; BVT normal comparison twice 83/83; cached-template and failed-execution/reuse checks PASS; go vet PASS; incremental lint 0 issues. Independent GPT-6 Astra medium final overall review: PASS, no unresolved scoped blocker. The PR body records the expected semantics, measured allocation/per-row conversion costs and separate direct-query optimizer exclusions. CI is not awaited or claimed green.

@XuPeng-SH XuPeng-SH left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Deep re-review of fbe380d against main@9c79a6edfcad5ce9635d91b0f1646d0bde375cc3, including the full 9-file PR diff and the closure of the previous three findings.

Technical verdict: REQUEST_CHANGES — 1 P1 and 3 P2 findings. The previous exact witnesses now pass. The new relational implementation introduces two further public regressions, and two neighboring scalar/nested-result cases remain incomplete. Each attached finding has a real SQL/protocol witness, exact-base attribution, and typed-plan evidence.

The authenticated account is also the PR author (XuPeng-SH), so GitHub requires this to be a COMMENT review rather than a self-request-changes review.

Findings and attribution

Finding Direct / base Current head Classification
UNION (binary NULL, "abc"), FIELD(x,0) [0,1] / [0,1] [0,0] P1 new regression: the consumer loses its physical ColRef
UNION (SQL DECIMAL B, SQL VARCHAR B), FIELD(x,ABS(A)) [1,1] / [1,1] [0,0] P2 new regression: concrete string source becomes numeric
Scalar subquery reading a table, DECIMAL B 0 / 1 1 P2 incomplete projection closure
Nested COALESCE, domainless COM_STMT NULL 0 / 1 1 P2 incomplete nested-result closure

Here A/B are the distinct DECIMAL values 9007199254740992 / 9007199254740993. The first finding uses only NULL, abc, and zero.

Verification and positive evidence

  • Reran the previous independent SQL and COM_STMT probes, mixed-source COALESCE probes, valid/error/valid handle-reuse probes, and cached-plan immutability checks on the new head: all pass. Public probe package: 10.922 s; planner probe package: 0.040 s.
  • Added a two-row public relational matrix covering UNION source permutations, EXCEPT/INTERSECT, outer joins and null extension, filter/HAVING cardinality, shared CTEs, windows, scalar empty results, and row-dependent IF/CASE/COALESCE/string projections. Passing controls distinguish actual source changes from explicit string conversions. The binary NULL/string UNION control with a purely textual COALESCE also passes; the new regression specifically reaches the numeric consumer's substitution path.
  • Repeated the failing candidates against the exact PR base by restoring all seven changed Go files through a Go overlay. New and pre-existing failures are kept separate. Typed-plan probes verify both the wrong type/value flow and the cached template's unchanged representation.
  • Inspected the changed issue27088 oracles: they now compare independently evaluated direct-variable values and types, retain numeric-comparison and binary-transport controls, and correctly distinguish SQL TEXT NULL from domainless COM_STMT NULL. These changes do not merely weaken the old assertions.
  • Checked the saved author logs for full planner/rule/frontend/issues package passes (6.616 / 0.064 / 24.953 / 116.917 s), and normal BVT comparison twice, 83/83 commands each. Those full runs were reused, not independently repeated. CGo native provenance and git diff --check pass. CI was still in progress when inspected; no CI success is claimed.

Unhappy paths, performance, and engineering

The execution plan remains privately copied. Source maps and retained expressions have execution/plan ownership; no new shared cache, goroutine, wait, lock, I/O or wire-format change was found. Invalid DECIMAL execution followed by valid execution on the same SQL/COM_STMT handle passes, as do template immutability and zero-row controls. No separate leak/hang blocker was found.

The PR now accurately records its cost: compared with the previous PR revision, saved 1/16/64-peer specialization benchmarks add roughly 192 bytes and 2 allocations per EXECUTE; the tested relational case adds about 3.6 KB / 48 allocations. The full retained-provenance cost against pre-PR code remains about +54% bytes for 64 peers. Shared-host timings are directional, not a production throughput guarantee. Consumer-local conversion of a physical TEXT vector adds per-row conversion work, with no per-row producer traversal. These are disclosed, non-blocking costs.

The key engineering correction is to distinguish string-domain evidence from value identity, and propagate complete source changes through existing selected-output and common-result machinery. The current compact witness cannot justify replacing values from every UNION branch. Address the concrete producer/consumer boundaries and extend the existing small test matrices; a new general framework or broad refactor is unnecessary.

Comment thread pkg/sql/plan/utils.go Outdated
Comment on lines +7553 to +7558
if known && types.T(runtimeSource.Typ.Id) == types.T_any && runtimeSource.GetLit().GetIsnull() {
// An exact marker known to be domainless NULL stays NULL in
// every row, including outer-join null extension. Only this
// state permits substituting the value without reading the
// physical TEXT column; a non-NULL source must keep its ColRef.
source = runtimeSource

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

[P1] Do not replace a UNION output with one branch's NULL

StringDomainSource.GetP() is not proof that every row of this physical column comes from that marker. A UNION output can carry StringDomainSource = P0 while its other branch contains a different, non-NULL value. The new shortcut then replaces the consumer's entire ColRef with P0's NULL:

SELECT FIELD(x, CAST(0 AS DECIMAL(20,0)))
FROM (SELECT ? AS x UNION ALL SELECT ?) d
ORDER BY 1;

Using an actual COM_STMT prepared handle with arguments nil, "abc", direct SQL with NULL, 'abc' and the exact base both return [0,1]; this head returns [0,0]. No large-number precision boundary is involved. The typed EXECUTE plan still has UNION inputs ANY NULL and TEXT 'abc', but its outer expression is now FIELD(CAST(ANY NULL AS DECIMAL128), DECIMAL128 0) and no longer reads x.

Keep the physical column unless value provenance proves that all its producers yield that NULL. A compact string-domain witness, or a witness for just one set-operation branch, cannot authorize replacing the column's values. This is a new wrong-result regression from the added substitution.

Comment thread pkg/sql/plan/utils.go
Comment on lines +7623 to +7626
for i, arg := range rebindArgs {
if arg.GetPreparedNumeric().GetProvisionalResultPeer() {
if source, ok := provisionalNumericPeerSource(arg); ok {
rebindArgs[i] = source

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

[P2] Preserve concrete SQL string domains before rebinding a UNION consumer

Exact-peer restoration now exposes an unresolved set-output coercion: a real SQL VARCHAR parameter is inferred as a number inside the UNION, so the refreshed consumer sees an incorrectly exact tuple.

SET @d = CAST(9007199254740993 AS DECIMAL(20,0)),
    @s = '9007199254740993';
SELECT FIELD(x, ABS(CAST(9007199254740992 AS DECIMAL(20,0))))
FROM (SELECT @d AS x UNION ALL SELECT @s) d ORDER BY 1; -- 1,1
PREPARE p FROM 'SELECT FIELD(x, ABS(CAST(9007199254740992 AS DECIMAL(20,0))))
                FROM (SELECT ? AS x UNION ALL SELECT ?) d ORDER BY 1';
EXECUTE p USING @d, @s; -- 0,0; base 9c79a6edfc returns 1,1
DEALLOCATE PREPARE p;

Swapping the two sources also fails. The typed plan converts the VARCHAR-source marker into a BIGINT literal and reconciles the UNION to DECIMAL128 before this loop restores the fixed DECIMAL peer. A concrete SQL TEXT NULL combined with a fixed DECIMAL branch likewise changes direct/base [0,1] into [0,0].

The all-DECIMAL UNION controls pass. This is a new public FIELD regression, distinct from substituting a binary NULL: it occurs with two non-NULL inputs. Reconcile set outputs from both operands' actual source domains, including concrete strings and typed NULLs, before selecting the consumer's restored overload.

Comment on lines 4333 to 4336
fn := arg.GetF()
if fn == nil || fn.Func == nil || !strings.EqualFold(fn.Func.GetObjName(), "cast") ||
len(fn.Args) == 0 || !preparedExprContainsParam(fn.Args[0]) {
len(fn.Args) == 0 || !b.preparedExprContainsProjectedParam(fn.Args[0]) {
continue

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

[P2] Carry scalar-subquery sources into the provisional cast annotation

The new projected-parameter check still misses a marker inside a scalar subquery with a real input. At this binding stage the source is a SubqueryRef; the helper follows ColRefs but does not follow that subquery's output. After flattening, the resulting physical ColRef has no provisional-cast/source annotation, so the new refresh path never handles it.

CREATE TABLE r (id INT);
INSERT INTO r VALUES (1),(2);
SET @n = CAST(9007199254740993 AS DECIMAL(20,0));
SELECT FIELD((SELECT @n FROM r WHERE id=1 LIMIT 1),
             ABS(CAST(9007199254740992 AS DECIMAL(20,0)))); -- 0
PREPARE p FROM 'SELECT FIELD((SELECT ? FROM r WHERE id=1 LIMIT 1),
                            ABS(CAST(9007199254740992 AS DECIMAL(20,0))))';
EXECUTE p USING @n; -- 1
DEALLOCATE PREPARE p;
DROP TABLE r;

The typed plan retains the fixed peer's exact Src, but the scalar producer stays TEXT and FillValuesOfParamsInPlanWithSpecialization reports specialized=false; FIELD still uses DOUBLE. The no-input scalar-subquery control and empty-result control pass. This failure also exists on the base and is an unclosed source/projection case. Follow the scalar output through binding/flattening while retaining its empty/multiple-row semantics, so a table-backed scalar behaves consistently with the already-fixed direct marker and derived-column cases.

Comment on lines +3260 to +3262
sqlExecuteNumericPeerDependent := commonValueSourceChanged || !variadicStringBoundary && (sqlExecuteNumericNestedDependent ||
(sqlExecuteNumericSourceDependent &&
(functionName == "/" || preparedSQLExecuteNumericResultConsumer(functionName))))
(functionName == "/" || functionName == "field" || preparedSQLExecuteNumericResultConsumer(functionName))))

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

[P2] Finish NULL source propagation through nested common results

commonValueSourceChanged restores the current tuple, but it does not mark the returned common-value expression as a runtime source dependency. With a domainless binary NULL there is no numeric marker to set sqlExecuteNumericSourceDependent, so a numeric result restored by the inner COALESCE leaves its enclosing provisional VARCHAR cast and peer intact:

SELECT FIELD(
  COALESCE(x, ABS(CAST(9007199254740993 AS DECIMAL(20,0)))),
  ABS(CAST(9007199254740992 AS DECIMAL(20,0))))
FROM (SELECT COALESCE(?, CAST(9007199254740993 AS DECIMAL(20,0))) AS x) d
ORDER BY 1;

Actual COM_STMT execution with nil returns 1, while replacing that marker with a literal NULL returns 0. The same failure occurs with a two-row table under the derived projection. Both forms also fail on the exact base, so this is an incomplete nested-NULL fix.

The typed EXECUTE plan shows an inner DECIMAL128 COALESCE, wrapped back into VARCHAR inside the outer COALESCE; its fixed B peer is still a provisional VARCHAR literal. The outer FIELD consequently chooses DOUBLE. Carry the restored common-result source dependency into enclosing consumers so their provisional tuple is rebuilt too. This must retain the passing concrete SQL TEXT-NULL control, whose expected approximate result is different from binary domainless NULL.

An additional conditional producer also remains incomplete: replacing the derived source with SELECT IF(id=1, ?, NULL) AS x FROM r LIMIT 2 for r.id IN (1,2) gives [1,1] with binary nil versus direct [0,0]. Its typed IF still contains TEXT NULL operands. This variant fails on both base and head. Cover both a restored numeric common result and an all-NULL conditional result in the nested source-propagation tests.

@XuPeng-SH XuPeng-SH left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Reviewed commit c5a1e15b8b7fc241ac0f3de3eac9d504f1c161fd against main at b1b68925d7. The four latest findings are resolved:

  • 4111297261: only transparent projected markers provide exact NULL value identity; a mixed UNION retains both physical rows. Binary nil, "abc" returns [0,1], including after reuse through all-NULL and numeric executions.
  • 4111297267: set arms contribute their actual execute-time domains before reconciliation. SQL DECIMAL/VARCHAR inputs return the direct-SQL [1,1] in both arm orders; typed CHAR NULL keeps its string boundary.
  • 4111297269: table-backed scalar subqueries follow the selected output rather than unrelated internal expressions. The selected numeric source returns 0; independent multi-row-error and subsequent-reuse probes preserve scalar cardinality.
  • 4111297272: restored common-value dependence propagates through nested consumers. Binary nil returns 0 in the nested COALESCE witness; the all-NULL IF producer returns [0,0] through outer COALESCE while SQL TEXT/explicit DOUBLE NULL returns [1,1]. The IF condition and physical two-row result remain executable.

Full planner, rule, frontend, and issues packages passed after rebase; final focused QA, CGo vet, incremental lint (0 issues), and JDBC BVT (83/83) passed. Independent GPT-6 Astra medium final review and a separate QA challenge found no remaining confirmed blocker. Allocation counts are unchanged in the 1/16/64 fixed-peer microbenchmarks, with about 31–34 B/op added; no throughput gain is claimed. CI has not been waited on.

@XuPeng-SH XuPeng-SH left a comment •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Update: this no-blocker conclusion is superseded by the subsequent counterexample-based review. Public and typed-plan tests found one confirmed P2 incomplete producer-domain repair on this same commit. Technical recommendation is REQUEST_CHANGES.

Original review, retained for history:

Deep review at c5a1e15: no newly confirmed blocking defect. I checked the original FIELD exact-DECIMAL failure and the follow-on comments against the current change: mixed UNION values are not replaced by a branch witness; each set arm contributes its runtime domain; a table-backed scalar subquery keeps its selected output and cardinality; common-value result dependence reaches outer FIELD/COALESCE/IF consumers. Regression coverage exercises direct-value/type controls, SQL vs COM_STMT NULL and string domains, changed-source reuse, error/reuse, predicates, aggregate/window/group/set projections, and cached PREPARE immutability. The execution-local provenance maps and plan-size traversal have no new persistent cache, goroutine, or wait path. Performance caveat remains: large fixed-peer expressions are more expensive than the pre-PR baseline, despite stable allocation counts against the immediately preceding PR head; no throughput improvement is claimed. This is a self-authored COMMENT review, not an independent APPROVAL. Existing GitHub review threads still need their resolution state checked/closed separately, and CI was still running at review time.

@XuPeng-SH XuPeng-SH left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Deep review at c5a1e15, base/merge-base b1b6892.

Technical recommendation: REQUEST_CHANGES — one confirmed P2 repair gap. This supersedes my earlier no-blocker review on the same commit. The added independent counterexamples show that projected SQL numeric parameters used together inside a common-value function still retain their provisional TEXT domain. The inline finding contains the public witness and root cause.

Historical comments

The earlier exact witnesses are covered by the current fixes/tests: nested fixed peers and both folding paths; explicit CHAR and known NULL domains; binary domainless NULL, IFNULL return occurrences and extra FIELD operands; aggregate/window/derived outputs; mixed UNION value identity and source domains; scalar selected outputs; and restored nested common-result dependence. The original SQL-variable-NULL witnesses corrected in the discussion must remain withdrawn: TEXT NULL is not a domainless COM_STMT NULL.

However, the broader producer-to-consumer closure raised by comments 4111134601 and 4111297272 is not complete for a common-value function over multiple surviving TEXT ColRefs. Therefore “all review issues are completely resolved” is not a supported conclusion. The previously reported 15 unresolved GitHub thread flags were not changed in this review.

New verification

  • Reviewed the full 11-file range and followed prepare provenance, both constant folders, execute-time materialization, bottom-up projection/set reconciliation, public SQL/protocol entry points, and the test/result oracles.
  • Built matching native artifacts in an isolated worktree; Go 1.26.4 darwin/arm64, GOMAXPROCS=8, controlled CGo wrapper.
  • Added temporary subtests to the existing embedded FIELD fixture: 60 direct/prepared comparisons across 10 relational/common-result shapes, with exact numeric, concrete string, CHAR NULL, DECIMAL NULL, nonnumeric string and same-handle reuse. 55 passed; five executions failed in the grouped-COALESCE and limited-GREATEST families, all explained by the one inline finding. SQL result cardinalities are compared, not merely successful execution.
  • Limited/three-arm/computed-arm UNION, INTERSECT/EXCEPT, row-dependent CASE/IF and scalar selected common-result controls passed. A COM_STMT scalar valid -> multiple-row error -> valid sequence also passed.
  • Repeated both failing families against the exact base using a Go overlay restoring every PR-modified production Go file and the signature-dependent planner test file. Same wrong-result signatures, exit 1: incomplete fix attribution confirmed.
  • Existing TestPreparedVariadicRuntimeSourceDomains plus four new typed-plan probes passed (1.172 s, exit 0). The probes assert cached-template immutability and localize TEXT common-result inputs versus the DECIMAL direct-marker control; they are diagnostic evidence, not a claim that the failing public contract passed.
  • Reused the previously recorded exact-head owning-package/BVT/vet/lint evidence; did not rerun those broad suites or wait for CI. git diff --check is clean for the PR range.

Unhappy paths, performance and engineering

Execution plans remain deep-copied; added maps and retained expressions have plan/execution lifetime and size bounds. No new shared cache, goroutine, wait or external I/O was introduced. Error/reuse and cached-template checks pass; no separate leak/hang blocker was established.

The full fix has a disclosed allocation cost against pre-PR code for larger peer tuples; unchanged allocations versus the preceding PR revision do not measure that full cost. There is no new per-row graph traversal, but consumer-local conversion of a physical TEXT vector can add per-row work. These remain non-blocking cost observations, not throughput claims.

The design uses existing provenance and bottom-up rebinding mechanisms, with no demonstrated overengineering blocker. Fix the missing consumer boundary within that mechanism, preserving physical values and true source-domain boundaries; a new framework or per-query-shape exception is unnecessary.

Review artifacts and logs: /private/tmp/mo29379-recheck.hBgUci/. Production files and the PR branch were not modified. Submitted as COMMENT because the authenticated account also owns the PR; this is not an independent APPROVAL.

Comment thread pkg/sql/plan/visit_plan_rule.go Outdated
Comment on lines +869 to +870
if fn := expr.GetF(); fn != nil && expr.GetPreparedNumeric().GetProvisionalResultCast() &&
len(fn.Args) > 0 && fn.Args[0].GetCol() != nil {

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

[P2] Resolve projected marker domains below common-value consumers

The new provenance registration only accepts an annotated cast whose immediate child is a ColRef. When two projected parameters first enter GREATEST/COALESCE, neither TEXT operand needs a prepare-time cast, so their runtime domains are never registered or restored. The annotated outer CAST wraps the common-value function instead; removing it still leaves a TEXT result and FIELD reselects DOUBLE.

Verified through SQL PREPARE/EXECUTE at this head:

SET @a = CAST(9007199254740993 AS DECIMAL(20,0)),
    @b = CAST(9007199254740992 AS DECIMAL(20,0));
PREPARE p FROM
'SELECT FIELD(GREATEST(x,y), ABS(CAST(9007199254740992 AS DECIMAL(20,0))))
 FROM (SELECT ? AS x, ? AS y LIMIT 1) d';
EXECUTE p USING @a, @b; -- 1; direct query with the same @a/@b returns 0
DEALLOCATE PREPARE p;

A second public witness, FIELD(COALESCE(x,y),ABS(A)) FROM (SELECT ? AS x, ? AS y FROM r GROUP BY x,y) d, also returns 1 instead of 0, including a DECIMAL-typed NULL first source. Typed EXECUTE plans retain TEXT ColRefs and TEXT GREATEST/COALESCE, then cast their result to DOUBLE; the fixed peer's exact Src is present, so this is the unresolved producer domain rather than lost constant-fold provenance. The direct-marker GREATEST control specializes to DECIMAL, and actual string controls pass.

Both failing shapes reproduce against all five production files restored to exact base b1b6892, so this is an incomplete repair of the promised derived/common-result closure, not a new regression. Resolve the selected columns' runtime domains at the common-value consumer, retaining physical row values and explicit string/REAL boundaries; extend the existing regression table with the surviving-ColRef plus common-value combination.

@XuPeng-SH XuPeng-SH left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Commit review at 59d318a, against main b1b6892. Technical decision: PASS for the reviewed diff; this is a self-authored COMMENT, not an independent approval. Complete diff SHA-256: d654560ccd2fb3372ac446962b7cd9a62a11eed5b22e100bf7fd8fe6dc826594.

The latest inline finding 4111490879 was correct: multiple projected parameters inside GREATEST/grouped COALESCE were still TEXT when PREPARE inserted no child cast. The repair uses one value-operand rule for specialization admission, selected-source registration and bottom-up execute-time recovery. Independent public counterexamples also exposed IF/CASE comparisons, ordinary IN/NOT IN with folded RHS vectors, and retained BETWEEN. The fix keeps physical columns and explicit source boundaries intact, decodes an IN list only when its left operand changes, and lets the ordinary binder choose the complete operand tuple. Numeric/string/numeric handle reuse, NULL and result metadata are asserted.

The previous head's Compose PROXY CI failure had two prepared SUM(? LIKE '____') failures. A local public repro and typed plan showed its mode-authorized BOOL→TINYINT adapter was mislabeled provisional and removed. This commit preserves only that aggregate-owned adapter under ENABLE_BOOL_SUMAVG; SUM/AVG execute, while mode-disabled binding remains strict. Coverage/Required in that run failed downstream.

Validation on this diff: four owning Go packages passed (plan, rule, frontend, issues); the failing-shape embedded SQL and independently hardcoded values passed; CGo vet passed; incremental golangci-lint reported 0 issues. Independent QA found no further confirmed counterexample. The mandatory GPT-6 Astra medium overall review of the complete fingerprint returned PASS with no unresolved material finding. Latest main refresh and requested rebase left the diff unchanged. The prior 83/83 standalone BVT belongs to the previous head; new remote multi-CN CI for this commit is pending and is not claimed green.

Performance: no added per-row provenance traversal or persistent cache. Consumer-local numeric conversion and folded-IN-list materialization during a changed-domain EXECUTE have real cost; older benchmark figures predate this delta and are not presented as its measurement. The PR body now records the main/expected behavior matrix and this limit.

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.

[Bug]: prepared FIELD loses DECIMAL precision beside a fixed numeric peer

2 participants