Skip to content

feat(plan): propagate numeric assignment context across DML paths - #25861

Merged
XuPeng-SH merged 31 commits into
matrixorigin:mainfrom
ck89119:issue-25752-main
Jul 23, 2026
Merged

XuPeng-SH merged 31 commits into
matrixorigin:mainfrom
ck89119:issue-25752-main

Conversation

@ck89119

@ck89119 ck89119 commented Jul 18, 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 #25752

What this PR does / why we need it:

Propagates the numeric assignment context (the target column type) through every
DML statement shape after the arithmetic resolver from #25751, so a prepared
numeric parameter resolves against the column it is assigned to.

Covered paths, all through one context API (bindNumericExprWithContext):

  • INSERT ... VALUES
  • direct, parenthesized, and UNION INSERT ... SELECT
  • legacy and modern UPDATE
  • ON DUPLICATE KEY UPDATE

An explicit approximate sibling (e.g. DOUBLE) still overrides an exact target
column. The context is seeded only for numeric target columns: a non-numeric
target (varchar, date, ...) keeps the default binding path, because
InferNumericParameterType falls back to float64 for a non-numeric outer type
and would otherwise mistype a bare parameter (e.g. UPDATE t SET status = ?
would store 0).

The numeric target is applied only to a projection that is bound fresh: it is
checked after the group-by / aggregate / window / time-window / sample lookups so
a grouped arithmetic projection assigned to a numeric column resolves to its
grouped column instead of being re-bound against the raw scan columns.

Tests: focused plan tests for each statement shape (VALUES above 2^53, decimal
and integer targets, approximate siblings, non-numeric targets, grouped
projections, legacy and modern paths). Full pkg/sql/plan unit tests and the
prepare, dml/insert, and dml/update BVT suites pass.

ck89119 and others added 4 commits July 17, 2026 22:31
Check the numeric assignment target after the group/aggregate/window/
time-window/sample lookups so a grouped arithmetic projection assigned to a
numeric column resolves to its grouped column instead of being re-bound
against the raw scan columns. Align the post-sample projection's numeric
target index with the bound expression, and share the numeric-target
predicate and the mod arithmetic-name check.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Claude-Session: https://claude.ai/code/session_01VcbtXrvbYB6mJsYhSDwq6M

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

Codex automated review

One blocking correctness issue remains. Focused tests could not run because required CGo headers are unavailable; diff checks passed and the worktree is clean.

P1 - Cluster-table star expansion uses the hidden account_id column for target-position mapping (pkg/sql/plan/query_builder.go:4025)

numericPhysicalTableOutputNames includes every non-hidden TableDef column, but non-system cluster-table star expansion explicitly omits account_id in bind_context.go. Since account_id is physically added to cluster tables, a query such as INSERT INTO dst SELECT * FROM cluster_src CROSS JOIN (SELECT ? + ? AS x) d, executed by a tenant, is mapped as [visible columns, account_id, x] by this helper while the actual projection is [visible columns, x]. The numeric target for x is therefore assigned to the hidden account_id slot and the derived expression receives no target context, so its parameters fall back to FLOAT64 and can lose decimal precision. The mapping must use the same account-specific visibility rules as actual star expansion.

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

Codex automated review

Two P1 prepared-statement type-resolution defects remain. Local focused tests could not run because cgo/libmo.dylib is absent; current CI is green.

P1 - Preserve explicit DOUBLE precedence through conditional operands (pkg/sql/plan/base_binder.go:951)

numericAstTypesInternal falls through to the default case for CASE, so it does not discover a typed approximate operand nested in a conditional. For INSERT INTO constraint_test.emp (sal) SELECT ? + CASE WHEN 1=1 THEN CAST(1 AS DOUBLE) ELSE 0 END, the scan sees no strong type and infers the parameter as the destination DECIMAL(7,2). baseBindParam therefore installs a text→DECIMAL cast before the later arithmetic resolver sees the CASE result is DOUBLE and adds a second cast. Inputs outside DECIMAL(7,2) consequently overflow/round before the DOUBLE operation, violating the required explicit-DOUBLE-overrides-target rule. Resolve the output domain of conditional/wrapper expressions before selecting numericParamType, and add this regression case.

P1 - Do not overwrite assignment context when one derived output feeds incompatible targets (pkg/sql/plan/query_builder.go:4324)

A derived/CTE output is evaluated once, but this assignment unconditionally replaces its previously seeded target. In INSERT INTO constraint_test.emp (sal, empno) SELECT d.x, d.x FROM (SELECT ? + ? AS x) d, the first reference seeds d.x with DECIMAL(7,2) and the second overwrites it with UINT32. The derived expression and both parameters are then bound as UINT32 before sal is cast, so fractional or large decimal inputs are lost/rejected; reversing the output order changes the computation type. storeNumericTableProjectionTargets cannot detect this because it receives only the already-overwritten slice. Treat distinct target types for the same source position as ambiguous and withhold propagation (including CTE/star paths), then add a regression test.

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

Requesting changes on current head 1f9f54df.

The blockers from the earlier rounds appear closed, but two P1 prepared-statement correctness gaps remain.

P1 - Preserve explicit approximate precedence through numeric function results (pkg/sql/plan/base_binder.go:931)

numericAstTypesInternal treats every FuncExpr except MOD as if it contributed no typed operand. Consequently, a numeric function whose resolved result is DOUBLE is invisible when the outer arithmetic parameter type is selected. For example:

INSERT INTO dst_decimal(v)
SELECT ? + IF(1 = 1, CAST(-100000 AS DOUBLE), 0);

The explicit DOUBLE operand must override the exact destination context, but this head binds ? as the destination DECIMAL before the outer addition. With a narrow destination and ? = 100000, that early cast can overflow even though the DOUBLE computation cancels to 0 and the final value fits. COALESCE(CAST(... AS DOUBLE), 0) reproduces the same type error. The newly added CASE traversal fixes only one AST form; numeric operand-result domains need to be visible without blindly pushing assignment context into nonnumeric functions.

P1 - Propagate the resolved target through derived/CTE columns embedded in arithmetic (pkg/sql/plan/query_builder.go:3835)

seedNumericTableProjectionTypes seeds only a bare column reference or a star. If the forwarded column is an operand of an outer arithmetic expression, the default branch drops the destination context:

INSERT INTO dst_decimal(v)
SELECT d.x + 0 FROM (SELECT ? + ? AS x) d;

INSERT INTO dst_decimal(v)
WITH c AS (SELECT ? + ? AS x)
SELECT x + 0 FROM c;

Both inner parameter pairs are FLOAT64 on this head instead of the exact destination domain. On a wide decimal destination, inputs 9007199254740993 and -9007199254740992 therefore compute 0 in the derived node rather than exact 1; the outer arithmetic/final cast cannot recover the lost bit. Resolve the containing arithmetic domain first and seed referenced derived/CTE outputs with that domain, while retaining the existing ambiguity fallback when one source output feeds incompatible targets.

Validation:

  • full pkg/sql/plan tests, build, and vet pass on the exact PR head;
  • the PR-focused numeric tests pass 10x after a clean merge with latest main;
  • both independent reproductions fail on the exact head and remain failing after that latest-main merge;
  • latest main merges automatically with no conflicts, git diff --check passes, and required PR CI is green;
  • Q1-Q3 audit found no resource, wait, or unbounded-growth blocker; the new state is statement-scoped and AST/column/CTE bounded.

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

Codex automated review

Three blocking planner correctness defects remain despite green CI. Focused tests could not compile locally because this checkout lacks required CGo artifacts and third-party headers; the worktree remains clean.

P1 - Preserve numeric context inside CASE result branches (pkg/sql/plan/base_binder.go:944)

The scanner now descends into CASE result arms, but isNumericContextNode still excludes CaseExpr. Consequently, after bindNumericExprWithContext infers the assignment type, baseBindExpr clears numericParamType before bindCaseExpr binds those arms. For INSERT INTO constraint_test.emp(sal) SELECT CASE WHEN 1=1 THEN ? + ? ELSE 0 END, the inner arithmetic therefore starts a new context with no outer type and both markers remain FLOAT64; values above 2^53 lose precision before the final DECIMAL assignment cast. The added CASE tests place the marker outside CASE and do not cover this path.

P1 - Keep CTE target conflicts permanently ambiguous (pkg/sql/plan/query_builder.go:3990)

storeNumericTableProjectionTargets represents both “unset” and “conflicted” with Type{}. After one incompatible merge clears a position, the next target refills it here. For INSERT INTO constraint_test.emp(sal,empno,mgr) WITH c AS (SELECT ? + ? AS x) SELECT a.x,b.x,d.x FROM c a CROSS JOIN c b CROSS JOIN c d, the shared CTE target transitions DECIMAL -> empty -> UINT32. The CTE parameters are then bound as UINT32, so fractional arithmetic is lost before reaching sal; changing consumer order changes the computation domain. The per-source targetAmbiguous flag added in this commit does not protect this map-level merge across aliases/references.

P1 - Retain parameterized GROUP BY positions for grouping sets (pkg/sql/plan/group_binder.go:95)

Skipping groupByAst registration for every independently written expression containing a parameter breaks the later grouping-set lookup at line 111, which reads a missing map key as position 0. In SELECT count(*) FROM nation GROUP BY GROUPING SETS ((n_regionkey + ?), (n_nationkey + ?)), both expressions are appended to ctx.groups but neither is registered; the second UNION branch therefore marks group 0 active instead of group 1 and groups by n_regionkey rather than n_nationkey. Parameter identity needs a representation that still records each exact grouping expression’s position.

@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 review on 3cf258a982: two numeric-domain closure gaps still produce observable prepared-DML failures.

[P1] Numeric-result functions outside the five-name whitelist are opaque to domain inference. numericAstTypesInternal returns an empty scan for every function rejected by numericFunctionResultArgs (pkg/sql/plan/base_binder.go:933-938, :1309-1346). Repro:

INSERT INTO constraint_test.emp(sal)
SELECT ? + ABS(CAST(-100000 AS DOUBLE));

sal is DECIMAL(7,2). Expected parameter #1: FLOAT64, because ABS(DOUBLE) is the explicit approximate sibling. Actual: DECIMAL64(7,2). Binding -100000 therefore overflows before the DOUBLE addition even though the DOUBLE-domain result is 0. This is not ABS-specific; a hard-coded IF/COALESCE/IFNULL/NULLIF/MOD list leaves other numeric-result functions with the same hole. Please derive numeric result/argument behavior from common function metadata or otherwise cover the full supported numeric-function family, and add a plan-type regression for this query.

[P1] Assignment targets still stop at IF/CASE/COALESCE roots before reaching derived tables or CTEs. numericProjectionExprTarget rejects anything for which isNumericArithmeticRoot is false (pkg/sql/plan/query_builder.go:3870-3877), even though seedNumericExprColumnTargets immediately below already knows how to recurse through those result arms. All of these bind the inner parameters as default FLOAT64; they must be DECIMAL64(7,2):

INSERT INTO constraint_test.emp(sal)
SELECT IF(1=1, d.x, 0) FROM (SELECT ? + ? AS x) d;

INSERT INTO constraint_test.emp(sal)
SELECT CASE WHEN 1=1 THEN d.x ELSE 0 END FROM (SELECT ? + ? AS x) d;

INSERT INTO constraint_test.emp(sal)
WITH c AS (SELECT ? + ? AS x)
SELECT COALESCE(c.x, 0) FROM c;

With values 9007199254740993 and -9007199254740992, the current FLOAT64 inner expression becomes 0 instead of the exact 1; the final assignment cast cannot recover the lost bit. Please make the root eligibility consistent with the recursive result-arm logic and cover function/CASE wrappers over both derived and CTE sources.

Validation: existing focused numeric-context tests, full ./pkg/sql/plan, and the focused race run pass; the four added review-only reproductions above fail deterministically with the actual/expected types described. Latest main merge-tree is conflict-free and does not close either gap.

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

Codex automated review

Two P1 prepared-DML numeric-context correctness gaps remain. CI is green; local focused tests could not start because go is unavailable.

P1 - Numeric-result functions outside the whitelist lose explicit FLOAT/DOUBLE precedence (pkg/sql/plan/base_binder.go:935)

numericAstTypesInternal returns an empty scan for any function absent from numericFunctionResultArgs; ABS is absent even though its FLOAT64 overload returns FLOAT64. In INSERT INTO constraint_test.emp(sal) SELECT ? + ABS(CAST(-100000 AS DOUBLE)), the scan sees no typed sibling, so it seeds ? from sal as DECIMAL(7,2) and baseBindParam installs that cast before ABS later resolves to FLOAT64. Binding -100000 then overflows in the premature decimal cast although the intended DOUBLE calculation produces 0, which fits the target. The new tests cover the five whitelisted function names but not this supported numeric function family.

P1 - Conditional wrappers do not propagate an assignment target into derived/CTE outputs (pkg/sql/plan/query_builder.go:3876)

seedNumericExprColumnTargets already descends through IF/COALESCE/CASE result arms, but numericProjectionExprTarget rejects those roots because isNumericArithmeticRoot accepts only binary/unary operators and MOD. Thus INSERT INTO constraint_test.emp(sal) SELECT IF(1=1,d.x,0) FROM (SELECT ? + ? AS x) d never seeds d.x; the derived query binds both markers as default FLOAT64 instead of DECIMAL(7,2). Inputs 9007199254740993 and -9007199254740992 consequently compute 0 in the derived expression rather than exact 1, and the outer assignment cast cannot recover it. CASE and COALESCE have the same gap; existing coverage only exercises bare and arithmetic-wrapped forwarded columns.

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

Codex automated review

One prepared-DML numeric-context propagation gap remains.

P1 - Propagate target context through derived VALUES sources (pkg/sql/plan/query_builder.go:4258)

numericProjectionOutputNames only recognizes SelectClause/UNION roots, so a valid derived value table has unknown output names and seedNumericTableProjectionTypes never records a target for it. Consequently INSERT INTO dst(v) SELECT d.x FROM (VALUES ROW(? + ?)) AS d(x) binds the derived ? + ? through bindValues' WhereBinder (line 5904) with no assignment context, leaving it on the default FLOAT64 path before the final destination cast. For a wide DECIMAL target, inputs 9007199254740993 and -9007199254740992 therefore compute 0 instead of exact 1. Derived VALUES is supported by the parser/planner; add its column_N output lineage and apply numericProjectionTypes while binding its cells.

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

Codex automated review

Reviewed final diff, all existing reviews, PR comments, and inline-thread state. No remaining findings. Local focused tests could not run because go is unavailable; head CI is green and diff check passes.

# Conflicts:
#	pkg/sql/plan/query_builder.go

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

Re-reviewed exact head 036ee26. No blocking findings remain.

The latest main merge correctly keeps CTE name resolution on the declaration context while injecting numeric assignment targets from each use site into a fresh bind context. I revalidated the prior review gaps across numeric function domains, IF/CASE/COALESCE, scalar/derived/VALUES lineage, GROUP BY parameter identity, legacy INSERT, UPDATE FROM, ODKU subqueries, chained CTEs, conflicting targets, and recursive CTE members. The merge does not reintroduce target leakage or declaration-scope capture.

Unhappy-path check: this change creates no external resources or waits; the temporary planner maps and CTE propagation queue are scoped to one build and bounded by AST projections/CTE definitions plus monotonic target-state changes.

Fresh local validation on this head:

  • focused numeric-assignment and CTE lazy-binding tests: PASS
  • full pkg/sql/plan test suite: PASS
  • focused race tests for INSERT/UPDATE/CTE paths: PASS
  • go vet ./pkg/sql/plan: PASS
  • go build ./pkg/sql/plan: PASS
  • diff check: PASS

Current required CI checks are green.

@mergify

mergify Bot commented Jul 23, 2026 •

Copy link
Copy Markdown
Contributor

Merge Queue Status

  • ✅ Entered queue — 2026-07-23 04:09 UTC · Rule: main · triggered by rule Automatic queue on approval for main
  • 🟠 Checks running · in-place
  • 🚫 Left the queue — 2026-07-23 05:06 UTC · at 85e10a1372ab45b13e97df49dda009eb1a355aa6

This pull request spent 57 minutes 29 seconds in the queue, with no time running CI.

Waiting for any of
  • check-neutral = Matrixone Utils CI / Coverage
  • check-skipped = Matrixone Utils CI / Coverage
  • check-success = Matrixone Utils CI / Coverage
All conditions
  • any of [🛡 GitHub branch protection]:
    • check-neutral = Matrixone Utils CI / Coverage
    • check-skipped = Matrixone Utils CI / Coverage
    • check-success = Matrixone Utils CI / Coverage
  • #review-threads-unresolved = 0 [🛡 GitHub branch protection]
  • github-review-approved [🛡 GitHub branch protection] (documentation)
  • github-review-decision = APPROVED [🛡 GitHub branch protection] (documentation)
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone Compose CI / multi cn e2e bvt test docker compose(PESSIMISTIC)
    • check-neutral = Matrixone Compose CI / multi cn e2e bvt test docker compose(PESSIMISTIC)
    • check-skipped = Matrixone Compose CI / multi cn e2e bvt test docker compose(PESSIMISTIC)
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone Standlone CI / Multi-CN e2e BVT Test on Linux/x64(LAUNCH, PROXY)
    • check-neutral = Matrixone Standlone CI / Multi-CN e2e BVT Test on Linux/x64(LAUNCH, PROXY)
    • check-skipped = Matrixone Standlone CI / Multi-CN e2e BVT Test on Linux/x64(LAUNCH, PROXY)
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone Standlone CI / e2e BVT Test on Linux/x64(LAUNCH, PESSIMISTIC)
    • check-neutral = Matrixone Standlone CI / e2e BVT Test on Linux/x64(LAUNCH, PESSIMISTIC)
    • check-skipped = Matrixone Standlone CI / e2e BVT Test on Linux/x64(LAUNCH, PESSIMISTIC)
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone CI / UT Test on Ubuntu/x86
    • check-neutral = Matrixone CI / UT Test on Ubuntu/x86
    • check-skipped = Matrixone CI / UT Test on Ubuntu/x86
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone CI / SCA Test on Linux/arm64
    • check-neutral = Matrixone CI / SCA Test on Linux/arm64
    • check-skipped = Matrixone CI / SCA Test on Linux/arm64

Reason

Pull request #25861 has been dequeued

Pull request from fork cannot be queued. This pull request comes from a fork, and Mergify needs the author's permission to update its branch.

The author needs to enable "Allow edits from maintainers" on this pull request.

Failing checks:

Hint

You should look at the reason for the failure and decide if the pull request needs to be fixed or if you want to requeue it.
If you do update this pull request, it will automatically be requeued once the queue conditions match again.
If you think this was a flaky issue instead, you can requeue the pull request, without updating it, by posting a @mergifyio queue comment.

Tick the box to put this pull request back in the merge queue (same as @mergifyio queue).

  • Requeue this pull request

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/feature size/XXL Denotes a PR that changes 2000+ lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants