Skip to content

fix(plan): support scalar subqueries in INSERT VALUES with cold admission - #30220

Merged
XuPeng-SH merged 9 commits into
matrixorigin:mainfrom
aunjgr:fix/insert-values-scalar-subqueries-29902
Oct 16, 2026
Merged

XuPeng-SH merged 9 commits into
matrixorigin:mainfrom
aunjgr:fix/insert-values-scalar-subqueries-29902

Conversation

@aunjgr

@aunjgr aunjgr commented Oct 14, 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:

Refs #29902. This change targets main; it does not backport the fix to the reported release.

What this PR does / why we need it:

Support scalar subqueries in ordinary INSERT VALUES by reusing the existing REPLACE VALUES relational lowering. INSERT currently rejects these expressions with an unrelated unsupported-JOIN-condition error, including simple scalar lookups and nested IF expressions.

Initialize a shared VALUES binding context only when the subquery binder or numeric scalar-subquery type analyzer actually encounters a subquery. Validate the existing 32-subquery-row admission bound before creating subquery plan nodes, and restore the borrowed statement-local binding scope on every exit. Keep subquery-free literals, parameters, DEFAULT values and expressions on their existing path without an unconditional AST preflight.

Reject SQL UDF bodies that introduce subqueries directly in INSERT VALUES before creating subquery plans. Check parsed expression bodies as well as query bodies so uppercase or mixed-case SELECT, parentheses, expression wrappers and nested UDF calls cannot bypass admission. Parse each body once and release its AST on every binding exit. Expression-only UDFs and calls inside explicitly admitted scalar subqueries retain their existing paths.

Preserve literal-row batching, incoming VALUES order, assignment casts, IGNORE policy and duplicate-key handling. Generalize the shared VALUES admission diagnostics and update the corresponding REPLACE expected error. This does not expand correlated subquery support in ON DUPLICATE KEY UPDATE assignments or change parser, execution-operator, catalog or wire contracts.

Add planner regressions and public SQL coverage for nested scalar expressions, zero/one/multiple-row cardinality, statement rollback, mixed-row ordering, prepared reuse, source privileges and UDF admission before plan creation. Add baseline-comparable planning benchmarks for literal, parameter, DEFAULT, expression and typed VALUES at 1, 100 and 1,000 rows.

Validation

  • The new expression-form UDF regression fails before the follow-up fix and passes afterward at 1/32/33 rows, with empty-plan and restored-scope assertions and supported expression/explicit-subquery controls.
  • Full planner suite passes after merging newest main. The updated public SQL case passes 91/91 statements twice; teardown verifies no test database, user, role or UDF remains.
  • The original CI failure was the cancellation-harness test TestHeavyPlanCancellationStopsWritersBeforeMerge, whose helper was forcibly killed before acknowledging completion. It passes ten local normal repetitions, 100 race repetitions and the full optools package. No CI assertion, timeout or skip was changed. The new remote CI result is tracked separately.
  • The service build and full repository static-analysis gate pass. Prior REPLACE, binary prepared execution and ordinary VALUES planning evidence is retained; the follow-up adds work only to SQL-UDF expansion, not literal/parameter VALUES.

…ht overhead

Allow ordinary INSERT VALUES to reuse the existing relational lowering for
REPLACE scalar lookups. Initialize a shared VALUES binding context only when
the existing subquery binder or numeric type analyzer encounters a subquery,
and enforce the 32-subquery-row bound before binding any subquery plan nodes.
Restore the borrowed planner scope on every exit, retaining the original
literal, parameter, DEFAULT and subquery-free expression paths.

Preserve literal-row batching, incoming VALUES order, assignment casts, IGNORE
policy and duplicate-key handling. Generalize the shared admission diagnostics
and update their existing REPLACE golden. Add planner regressions, public SQL
coverage for cardinality, rollback, prepared reuse and source privileges, and
baseline-comparable literal/parameter/typed-expression planning benchmarks.

Refs matrixorigin#29902.
@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 commented Oct 15, 2026 •

Copy link
Copy Markdown
Contributor

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

Commit: e3d1b0051025482b6f58efa31671e41a98ba9e0b

Review completed. Read the assessment.

@XuPeng-SH XuPeng-SH left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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

Commit: e3d1b0051025482b6f58efa31671e41a98ba9e0b

Assessment: request_changes

Reviewed the complete eight-file delta. Reusing REPLACE’s lowering preserves assignment and duplicate-key ownership, while lazy context creation avoids scanning ordinary VALUES. However, SQL UDF expansion bypasses the required subquery-row admission limit.

Model: gpt-6-astra / xhigh

Session: 01a13dcf-1517-7f90-b3f9-c5f9f9e7031b · slot 0 · generation 1

  • P2 pkg/sql/plan/bind_insert.go:5545: Define lookup_value() RETURNS INT LANGUAGE SQL AS 'select id from src', with one row in src, then INSERT 33 VALUES rows calling lookup_value().
    Impact: The INSERT succeeds despite the 32-subquery-row limit. Each expanded lookup creates a separately scheduled relational branch, allowing larger batches to evade the intended fan-out bound. Account for expanded subqueries during admission, or reject these expansions before creating unbounded branches.
    Evidence: The validator inspects the original VALUES AST, where lookup_value() contains no tree.Subquery. bindFuncExprImplUdf subsequently creates one at base_binder.go:5117–5118. The public SQL probe rejected 33 direct subqueries but accepted and persisted all 33 UDF rows. The same UDF INSERT was rejected on the base revision. Reproduction: udf_admission_test.go and udf-admission.log; receipt checks/1792086003557718551-3.json.

Validation:

  • Artifacts and reconciled command/source/exit receipts: /home/xupeng/.local/state/mo-bot/jobs/040f858cd2899f62a0351d12/attempt-1/validation-audit.json. Source remained clean at the assigned head.

  • Isolation preflight passed. Verified native inputs and artifact hashes, then ran the current Makefile cgo owner.

  • Six targeted INSERT/REPLACE planner tests passed, covering lowering, ordinary VALUES, scope restoration, batching and admission boundaries.

  • Replayed all 65 new SQL-case statements twice on one embedded cluster; expected rows, column names, errors, privileges and cleanup passed.

  • Additional public SQL checks passed for duplicate ordering, atomic rollback, binary prepared recovery, numeric rebinding, nested correlation and self-table reads.

  • Confirmed the UDF admission bypass through the public SQL endpoint; the matching base control rejected the INSERT and persisted zero rows.

  • Three alternating base/head benchmark pairs covered all 30 planning configurations. Allocations were essentially unchanged; median timing differences ranged from -12.1% to +4.6%, without a consistent slowdown.

Limitations:

  • Inactive IF/CASE/IFNULL subqueries can raise cardinality errors; base SELECT and REPLACE controls reproduced this shared limitation, so it is not reported as introduced here.

  • SQL replay compared values, column names and errors, not JDBC type/width metadata. Its initial credential-format harness failure was corrected and retained separately.

  • Supplied CI statuses were green, but raw CI logs and the author’s detailed local validation artifacts were unavailable. Local benchmark samples do not establish statistical significance.

Keep INSERT VALUES scalar-subquery admission based on explicit caller ASTs. Reject SQL UDF bodies that introduce a scalar subquery before creating any subquery plan nodes, including nested expression UDF expansion. Expression-only UDFs and UDF calls inside explicitly admitted scalar subqueries retain their existing paths.

Add planner regressions at one, 32 and 33 rows, assert early rejection and binding-scope restoration, and extend public SQL coverage for atomic failure and supported controls.
Parse each SQL UDF body once and inspect expression-form bodies before binding them in direct INSERT VALUES. Parenthesized, wrapped, mixed-case and nested SELECT expansions must not create relational branches hidden from the caller-AST admission limit.

Retain expression-only UDFs and calls inside explicitly admitted scalar subqueries. Keep ordinary literal and parameter VALUES on their existing cold-admission path, and release the parsed body on every binding exit.

Extend the existing planner admission fixture at 1/32/33 rows with empty-plan and scope-restoration assertions. Add public SQL rejection/no-partial-write checks and an explicit-subquery success control.
@XuPeng-SH

XuPeng-SH commented Oct 16, 2026 •

Copy link
Copy Markdown
Contributor

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

Commit: 54f6cb40e41496b381e207e9bdb1bff788521897

Review completed. Read the assessment.

@XuPeng-SH XuPeng-SH left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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

Commit: 54f6cb40e41496b381e207e9bdb1bff788521897

Assessment: approve

Reviewed the complete nine-file delta and affected callers. Lazy admission belongs in the existing VALUES binding owner and correctly reuses REPLACE lowering. Both previously reported UDF admission bypasses are closed. Scope restoration, assignment semantics, ordering, privileges and failure recovery are covered; no actionable findings remain.

Model: gpt-6-astra / xhigh

Session: 01a13dcf-1586-7a01-9000-d45e20995cf8 · slot 1 · generation 1

Validation:

  • Verified the frozen source remained unchanged. Native prerequisites were built and verified through the repository owner after successful isolation preflight.

  • Seven focused INSERT VALUES and REPLACE planner test groups passed with vet enabled, including UDF rejection before plan creation, scope restoration and 32/33-row admission.

  • All 91 checked-in SQL statements passed twice on the same embedded cluster, including expected results/errors and database/user/role/UDF cleanup. Additional binary prepared-statement recovery, numeric rebinding and admission checks passed.

  • The initial diagnostic replay failed on a JDBC-specific error prefix. The corrected harness checked MySQL error 1690 and the server message, then passed.

  • Three base/head benchmark pairs covered 30 configurations. Median timing differences ranged from -4.95% to +8.21%; allocation counts were unchanged except one additional allocation in one configuration.

  • Reused frozen-head successful CI evidence for shared build, Linux UT, SCA, coverage and proxy/pessimistic multi-CN BVT.

  • Commands, source fingerprints, exit receipts and retained logs are reconciled in /home/xupeng/.local/state/mo-bot/jobs/c54ee92c0a06508b2b7b586e/attempt-1/validation-audit.json.

Limitations:

  • Local SQL replay checked values, column names and errors through the Go MySQL driver; JDBC type-width metadata relies on supplied BVT evidence.

  • Short microbenchmarks do not establish statistical equivalence or exclude modest timing regressions.

  • The separate linked issue body was not supplied; its committed SQL reproducer and stated PR contract were reviewed.

@aptend aptend left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Deep re-review of exact head 54f6cb40e41496b381e207e9bdb1bff788521897 against base b24d1b311555e0b6f3d56eb37f9a2e9617e9a5b7: APPROVE. No remaining blocking finding.

Read the complete nine-file delta, the increment since my previous reviewed 4af66792b3bf2a59fbaf16214543fd8c7806f219, all four historical reviews, all four conversation comments, both inline comments/author reply and the resolved/outdated thread. Also read the full linked issue #29902. The two previous UDF admission bypasses are closed by implementation and execution evidence, not just the author's reply or another approval.

This remains a focused SQL-compatibility bugfix reusing existing REPLACE lowering, with no new executor/catalog/wire format; it is design-document-exempt. The current body follows the repository template and distinguishes main from the reported release.

Key checks:

  • Query-form SQL UDFs and parsed expression-form bodies are rejected directly in INSERT VALUES before creating hidden relational branches. The guard is AST-based for the parsed expression, so uppercase/mixed-case SELECT, parentheses, COALESCE, IF/CASE and nested UDF calls cannot evade the policy. Deferred AST/argument cleanup remains in the UDF owner.
  • Explicit scalar subqueries still enter the shared lazy VALUES context through the actual subquery binder or numeric type analyzer. The 32-subquery-row check runs before subquery plan creation; success/error restore the borrowed binding scope. Ordinary literal, parameter, DEFAULT and expression VALUES do not acquire an unconditional AST preflight.
  • Reviewed assignment casts, IGNORE/default handling, literal batching, ordinal duplicate ordering, cardinality errors/rollback, prepared numeric rebinding and source privileges. The REPLACE branch and generalized diagnostic retain their existing contracts.
  • New state is statement-local, not concurrently shared; no new goroutine, synchronization, resource wait, retry or persisted plan ownership is introduced. No fresh race stress is warranted for this sequential binding increment.

Independent validation in detached exact-head/base worktrees, fresh native-owner builds and repository CGo wrapper:

  • Full planner suite -count=1 -vet=all: 3,769 root tests PASS, package 18.158s; two unrelated subtests skipped, not counted as passes.
  • A real MySQL-protocol probe passed 51 subtests in two rounds, package/cleanup 5.771s. Six actual SQL UDF bodies (lowercase query, uppercase parenthesized, mixed-case wrapper, nested UDF, IF and CASE) each reject direct 1/32/33-row INSERTs with zero persisted rows. Their explicitly admitted scalar-subquery controls succeed at 32 rows. Expression-only 33 rows succeed; direct 33-row subqueries reject; mixed explicit/UDF rejection remains atomic. A single binary-prepared INSERT survives empty/one/multiple-row cardinality and numeric/string parameter rebinding, then recovers without partial writes. Probe SHA-256: 81e2c303dbb19056b0d8cce6ff1b7604602302ea76aaa1bfea9132ddedf1e8ef.
  • Reused actual exact-head JDBC BVT evidence, not merely a green check: job 116821245068 checks out/builds 54f6cb40e4 and executes the added SQL case 91/91, including expected metadata/results/errors, duplicate ordering, atomic rollback, privileges and cleanup. Raw current UT logs also show that head, terminal planner/heavy stages status 0 and empty FAIL_UT_CASES. This replaces the prior head's red CI snapshot; it does not assert a newly proved root cause for that historical cancellation-harness failure.
  • Same benchmark function, byte-identical across candidate and base (function SHA-256 a42504d45f0dd90e6704b9aa22ca856c7d2fd94d06d894e31d10fc5f31be62b0), same Go/native build mode, GOMAXPROCS=6, -benchtime=100ms -count=3: all 30 ordinary VALUES configurations PASS. Median candidate/base timing differences range -4.25% to +6.24%, allocation-count differences -1 to +3. No material consistent regression was observed; these short sequential samples do not prove statistical equivalence. An earlier candidate sample overlapped other owned builds and was excluded from this comparison. The baseline harness initially missed a tree import; its corrected invocation passed, and that build-only harness error is not a product failure.
  • Full diff whitespace passes. No generated artifacts or production sources were changed. Temporary public-SQL and baseline-benchmark files are review-local and will be removed with both worktrees.

Exact-head CI run 38853201981 reports successful CI Required, build, UT, SCA, coverage and enabled BVT jobs. Skipped lanes are not executed passes. No forced distributed failure replay or broad application replay is claimed.

@mergify mergify Bot added the queued label Oct 16, 2026
@mergify

mergify Bot commented Oct 16, 2026 •

Copy link
Copy Markdown
Contributor

Merge Queue Status

  • ✅ Entered queue — 2026-10-16 08:51 UTC · Rule: main · triggered by rule Automatic queue on approval for main
  • 🟠 Checks running · in-place
  • 🚫 Left the queue — 2026-10-16 09:09 UTC · at d509f413d4d911b49c650ee2563f3f782f2b148e

This pull request spent 18 minutes in the queue, with no time running CI.

Reason

Pull request #30220 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.

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.

Waiting for any of
  • check-neutral = CI Required
  • check-skipped = CI Required
  • check-success = CI Required
All conditions

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

  • Requeue this pull request

Copy link
Copy Markdown
Contributor

最近24小时合并项复核:main aa4b6eddfdad54d11be6fd75a5675eb9801f6690 的计划回归和原始 MySQL 协议嵌套 INSERT 场景通过。但 #29902 报告的版本分支仍有缺口:4.2-dev c914080bba57dd17fb86be300c22b9be43cc2b61 对同一 SQL 实测仍返回 20102(subquery in JOIN condition is not yet implemented)。本轮未将 main 通过解释为 v4.2 分支已修复;结果已写回 #29902,不创建重复 issue。

This branch was previously deployed

1 inactive deployment
ci — d509f413 Deployed Oct 16, 2026 by mergify[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

dequeued kind/bug Something isn't working kind/test-ci size/L Denotes a PR that changes [500,999] lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants