Skip to content

Fix correlated scalar subquery with LIMIT 0 - #32871

Merged
XuPeng-SH merged 15 commits into
matrixorigin:mainfrom
XuPeng-SH:codex/issue-32869-main
Nov 22, 2026
Merged

XuPeng-SH merged 15 commits into
matrixorigin:mainfrom
XuPeng-SH:codex/issue-32869-main

Conversation

@XuPeng-SH

@XuPeng-SH XuPeng-SH commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

What type of PR is this?

  • BUG
  • Improvement
  • Test and CI

Which issue(s) this PR fixes

Fixes #32869

What this PR does / why we need it

A correlated scalar subquery with a semantic-root LIMIT 0 returns a typed NULL for each outer row and retains source authorization and catalog dependencies. The same dependency rules apply when SQL UDF argument folding removes the enclosing scalar from the expression. CREATE VIEW and unused named windows obtain those sources from the bound query they already validate. The unused window plan keeps its table checks without executing the discarded branches.

The dependent executor can copy an untyped NULL when reading a view. It uses the shared vector setter, which also replaces the time-window-specific implementation.

Prepared SET evaluates the original expression with its normal authorization and lazy branch evaluation. The replay preserves parameter order, NULL and decimal types, and prepared binary-literal provenance. When a SQL UDF discards a subquery and returns X'31', numeric use of the result yields 49. A scalar subquery that materializes the same bytes retains its computed-value behavior.

Control-function validation now follows the existing correlated-scalar rewrite and source-retention boundary. Ordinary LIMIT 0 scalar and EXISTS subqueries keep their original frontend authorization and return NULL and false for the administrator. If an affected wrapper loses its control-function check, planning rejects it.

Validation

Rebased on main at 7431a275e907. All 14 patches remained equivalent in the final git range-diff. The upstream commit touched storage, and the planner, frontend and SQL fixture were identical across this rebase.

  • Go 1.27.1 on darwin/arm64. The affected planner, frontend, parser tree, vector, colexec and time-window short suites passed. Focused race tests covered correlated scalars, prepared SET, result metadata, dependent execution and NULL vector copies.
  • Native SQL A/B verified the old CREATE VIEW and WINDOW binding errors, the pre-fix view column-copy failure and the binary-literal regression. The fixed view reads NULL without a cast. Prepared SET preserved literal, user-variable, parameter and NULL behavior. Binary-protocol prepare and execute also returned the expected byte value and SQL NULL.
  • The isolated two-CN issue BVT passed all 150 statements with the committed expected results on the preceding base a77c55b6d627. The frontend short suite passed on that base. The focused planner tests were rerun after the final rebase. The expected results include the actual view column, named-window behavior, denied table privileges, rejection of an unsafe saved-result source in the named window, and distinct binary-literal versus scalar results.
  • The control-function follow-up was reproduced on the previous head and retested on a two-CN service. Administrator results and ordinary-role denials matched the legacy behavior. A rewritten wrapper retained authorization when its bound control call survived and failed closed when binding discarded the call. The planner short suite and final focused regressions passed.
  • Formatting, git diff --check, vet, incremental golangci-lint, molint and make err-check passed.

The existing vector shuffle limitation for sorting results that include an untyped arithmetic NULL is reproducible on the previous PR head. A typed NULL control succeeds.

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

@mergify

mergify Bot commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

This pull request is merged.

@XuPeng-SH

XuPeng-SH commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor Author

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

Commit: 78de1ccfa8563cee07b6f12ae030794f59210fdd

Review completed. Read the assessment.

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

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

Commit: 78de1ccfa8563cee07b6f12ae030794f59210fdd

Assessment: request_changes

The existing dependent executor handles the reported LIMIT 0 shape and retains its source scan. The admission checks still reject equivalent ordinary-table queries, and the UDF guard rejects calls that retain the argument.

Model: gpt-6.2-sol / xhigh

Session: 01a1a004-9884-72c0-ad39-f096c4209c4a · slot 1 · generation 0

  • P2 pkg/sql/plan/correlation_binding.go:64: Add an alias to the sole inner projection, or order the inner query by a local table column, in the reported correlated scalar LIMIT 0 shape.
    Impact: Both forms still raise the original decorrelation error. They should return a typed NULL for each outer row while retaining the source scan.
    Evidence: planner-probe.log shows the plain form succeeds and both variants fail. Line 64 rejects the alias. Line 274 counts the hidden sort projection added by order_binder.go:448 as an additional result. Check visible scalar arity separately from internal sort inputs and preserve source validation for both forms.

  • P2 pkg/sql/plan/base_binder.go:5656: A SQL identity function consumes a nested scalar argument containing the new LIMIT 0 plan.
    Impact: The binder rejects the call before expansion even though the body uses the argument and retains its source.
    Evidence: planner-identity-udf.log shows the plain control binds two dependent programs and the identity call raises the new NYI. The program directory already retains registered roots through finalization and compaction. Use the bound dependency graph to check which sources survive expansion, and fail closed when a required source cannot be accounted for.

Validation:

  • Isolation preflight and the repository native build passed. The focused planner tests and full normal planner package passed with 5,085 passing test roots and two unrelated subtest skips.

  • The exact-base overlay reproduced the original planner error. Head probes confirmed the two ordinary-table gaps and the identity UDF rejection.

  • Reviewed the seven changed paths, linked issue and all three discussion entries. Commands, source fingerprints, terminal exits and logs are matched in receipt-reconciliation.json.

Limitations:

  • The fresh probes exercised the planner. Public SQL and race results were author-reported without raw logs, and the supplied CI snapshot had UT and BVT still in progress.

@XuPeng-SH

Copy link
Copy Markdown
Contributor Author

Thanks for the review. I updated this PR at 2a399c3c38e335614d908a8f6c91e8592bf94c18, based on the latest main head 517e1695388cbaf1135238d5ab0c19a4556fb551.

  • The correlated scalar rewrite now uses visible result arity, so a projection alias and hidden local ORDER BY input do not reject an otherwise valid scalar result.
  • SQL UDF validation snapshots authorization sources before expansion and checks the returned expression plus retained plan roots afterward. Identity expression-body UDFs pass when their source survives. Query-body and repeated-argument forms that currently break dependent-plan remapping fail with an explicit NYI.
  • Named WINDOW validation scans now survive both ordinary node pruning and dependent-plan compaction as unreachable authorization carriers. An isolated reader BVT confirmed the unused WINDOW reference to an ungranted table is denied; the carrier is not an execution root.
  • Authorization source tracking covers table scans, MongoDB external scans, and table_changes function scans. Publication-view UDF rejection keeps its typed error precedence.

Validation on this head: pkg/sql/plan passed at 86.1% statement coverage, planner race passed (216.5s, with GOEXPERIMENT=), go vet passed, and the exact BVT passed 43/43. Normal planner tests passed with GOEXPERIMENT=simd. gofmt and git diff --check are clean. New GitHub CI checks are running.

@XuPeng-SH

XuPeng-SH commented Nov 21, 2026 •

Copy link
Copy Markdown
Contributor Author

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

Commit: 83a2c9a8a10ddeafb6ae15f554e9a93b205931ac

Review completed. Read the assessment.

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

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

Commit: 83a2c9a8a10ddeafb6ae15f554e9a93b205931ac

Assessment: request_changes

The existing dependent scalar executor and compact validation carriers fit the fix. Three planner issues remain. Prepared SET rejects a previously accepted expression, SQL UDF binding rejects a folded wrapper whose table checks are already retained, and the new control-function check can forget a match.

Model: gpt-6.2-sol / xhigh

Session: 01a1f0a0-5126-78f3-9ab8-ef4e87f2f119 · slot 0 · generation 3

  • P2 pkg/sql/plan/build_dcl.go:776: Prepare a SET assignment whose RHS is 1 + (SELECT ...) and whose scalar SELECT contains NULL + a correlated scalar with root LIMIT 0.
    Impact: PREPARE rejects an assignment that the pinned base accepted. The same scalar still binds on this head when it is the entire RHS.
    Evidence: probe-set-baseline.log accepts the arithmetic wrapper. probe-set-candidate.log rejects it while the direct RHS and predicate-only controls pass. The new policy applies only to a bare scalar RHS, although the existing frontend evaluator handles scalar subqueries inside expressions at pkg/frontend/util.go:577. Preserve the nested scalar's catalog dependencies through that existing path.

  • P2 pkg/sql/plan/base_binder.go:5994: Pass NULL + a scalar wrapper containing an eligible correlated LIMIT 0 to an identity SQL UDF.
    Impact: The UDF rejects the argument even though binding the wrapper already retained both table dependencies. The folded argument should reach the UDF as NULL.
    Evidence: probe-candidate.log reports an untracked source while the directly folded argument control passes. Binding the wrapper records its sources at line 1278. The rewrite counter then triggers UDF validation, which rejects the empty source set obtained from the folded literal. Carry forward the proof that the wrapper's dependencies were retained.

  • P2 pkg/sql/plan/correlation_binding.go:57: The AST walker visits a control function and then an ordinary function in a later sibling expression of a LIMIT 0 subquery.
    Impact: The pre-bind check can miss a control function it already found. Its result depends on sibling visitation order.
    Evidence: walkGroupingSetOrderByExpr at pkg/sql/plan/query_builder.go:11432 stops descending the current expression when the callback returns false and continues visiting siblings. The next ordinary function overwrites found with false. Keep the match latched for the entire walk.

Validation:

  • Verified the frozen head, merge base, complete diff, clean checkout, and whitespace. Also verified the baseline overlay inputs against Git. See scope-and-overlays-verified.log and receipt 1795237254666861923-2.json.

  • Isolation preflight and the native prerequisite build passed. Focused planner and frontend tests passed, including a separate SQL UDF selection. See focused-tests.log, udf-tests.log, and receipts 1795237163020007938-2.json and 1795237329434562026-2.json.

  • Isolated planner probes reproduced the UDF rejection and the prepared SET regression. The prepared SET witness passed with the pinned base inputs, and the candidate controls passed. See probe-candidate.log, probe-set-candidate.log, probe-set-baseline.log, and receipts 1795237150820386502-3.json, 1795237223836052306-4.json, and 1795237243093690341-2.json.

  • Recorded dispositions for all 19 discussion entries in discussion-assessment.json.

Limitations:

  • The probes exercise planner entry points with mock catalog fixtures. The control-function finding is based on source inspection.

  • The author reports 104 of 104 isolated single-CN SQL checks passing on this head. The review did not rerun that suite. The shared build, unit-test, and coverage jobs were pending in the frozen CI snapshot.

@XuPeng-SH

XuPeng-SH commented Nov 21, 2026 •

Copy link
Copy Markdown
Contributor Author

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

Commit: e387847724f598774c98023c2758c444d20f26e5

Review completed. Read the assessment.

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

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

Commit: e387847724f598774c98023c2758c444d20f26e5

Assessment: request_changes

The LIMIT 0 fix reuses the existing dependent executor and named-window authorization carriers. The prior live SET wrapper, executable UDF fold, and control-function latch cases are covered. Prepared SET still rejects valid expression shapes, and result-type recovery can fail after the same expression binds successfully for execution.

Model: gpt-6.2-sol / xhigh

Session: 01a1f0a0-5126-78f3-9ab8-ef4e87f2f119 · slot 0 · generation 3

  • P2 pkg/sql/plan/build_dcl.go:794: Prepare a SET assignment whose right-hand side contains a scalar SELECT wrapping the eligible correlated LIMIT 0 expression. Put NULL + outside that scalar SELECT, or use the SELECT as the operand of a simple CASE with two WHEN clauses.
    Impact: PREPARE rejects both forms with an unsupported-feature error. The pinned base planner accepts both.
    Evidence: The replay validator requires one surviving plan reference per AST subquery in the same order. NULL arithmetic removes the reference, while simple CASE binds the same AST operand once per WHEN. The paired probe reproduced both rejections and accepted the live arithmetic wrapper on both revisions. Preserve catalog dependencies for folded operands and allow legitimate repeated bindings.

  • P2 pkg/sql/plan/base_binder.go:1274: Execute a prepared SET whose scalar SELECT returns the result of a SQL identity UDF applied to NULL plus a scalar wrapper containing the eligible correlated LIMIT 0 expression.
    Impact: The NULL assignment can fail after the synthetic SELECT evaluates it. The frontend propagates an unsupported-feature error from the result-type binder before assigning the value.
    Evidence: The planner probe passed PREPARE and the executable SELECT bind, then reproduced the untracked-source error in BindSetVariableResultType. The validation-only binder skips recording the folded wrapper at line 1274, so UDF source collection sees an empty argument after folding. Carry the wrapper's source information through type recovery or reuse the logical result type from the authorized SELECT.

Validation:

  • Verified the frozen head, merge base, complete patch, pinned policy, whitespace and clean checkout. Isolation preflight passed and native inputs matched the retained build. See verify-inputs.log and checks/1795255848773163722-3.json.

  • Focused planner and frontend tests passed, including source retention, named-window diagnostics, flat NULL output and prepared SET controls. See focused.log and focused-metadata.log with receipts 1795255679341661336-2.json and 1795255868600008282-2.json.

  • The paired PREPARE probe accepted all three cases with the pinned base overlay. The candidate accepted the live wrapper and rejected the folded and simple CASE forms. The separate type-recovery probe passed both binding controls before reproducing the recovery error. See prepared-fold-base.log, prepared-fold-candidate.log and prepared-type-recovery.log with receipts 1795255811552272877-2.json, 1795255740158055817-2.json and 1795255847887105607-2.json.

Limitations:

  • The counterexamples exercised planner entry points with mock catalogs. The failed EXECUTE assignment follows from the frontend call path and was not independently reproduced through a SQL client.

  • The 126-statement SQL BVT and full normal and race suites are author-reported. The relevant CI jobs were pending in the frozen snapshot.

@XuPeng-SH

XuPeng-SH commented Nov 21, 2026 •

Copy link
Copy Markdown
Contributor Author

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

Commit: be79869f384e55c185f64c22e5c3de0edd1834f3

Review completed. Read the assessment.

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

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

Commit: be79869f384e55c185f64c22e5c3de0edd1834f3

Assessment: request_changes

The fix reuses the dependent executor to return typed NULL and extends the existing authorization carriers to preserve sources removed by folding. The latest revision addresses the prepared SET findings. View inference and unused named-window validation still lose the same wrapper provenance during SQL UDF binding.

Model: gpt-6.2-sol / xhigh

Session: 01a1f0a0-5126-78f3-9ab8-ef4e87f2f119 · slot 0 · generation 3

  • P2 pkg/sql/plan/base_binder.go:1274: Create a view or declare an unused named window whose expression passes NULL plus a scalar wrapper to an expression-body SQL identity UDF. The wrapper projects a correlated scalar with root LIMIT 0 over an ordinary table.
    Impact: CREATE VIEW or the enclosing SELECT fails with “SQL UDF with an untracked correlated scalar LIMIT 0 source”. The equivalent standalone projection can bind successfully.
    Evidence: View inference and unused named windows select zeroScalarValidateOnly in build_ddl.go:291 and window_binder.go:674. The inner rewrite activates UDF source validation, but the validation-only branch skips recording the wrapper at base_binder.go:1283. NULL folding then removes its bound reference, leaving the source check at base_binder.go:6006 empty. Carry the wrapper provenance through the existing validation owners and keep their special-source checks.

Validation:

  • The checkout matched the assigned head and merge base. Isolation preflight, native input hash verification, git diff --check, and gofmt passed. Receipts and logs are indexed in review-evidence.md.

  • Verified that discussion-assessment.json accounts for all 23 discussion keys.

Limitations:

  • Both local Go checks timed out during dependency downloads before any test ran. The view and window finding is based on source analysis. The focused probe is retained in review32871_view_fold_test.go.

  • The author reported passing normal and short race package suites and 134 SQL fixture statements. The frozen evidence contains no logs for those runs, and the build and unit CI checks were pending.

@XuPeng-SH

XuPeng-SH commented Nov 22, 2026 •

Copy link
Copy Markdown
Contributor Author

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

Commit: 97837e81af542cf9973bf354430a9a6c546c4750

Review completed. Read the assessment.

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

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

Commit: 97837e81af542cf9973bf354430a9a6c546c4750

Assessment: request_changes

The fix reuses the dependent executor to return typed NULL and preserves table checks when expressions fold. The latest revision resolves the folded UDF cases in views and unused named windows. One regression remains in the scope of the new control-function guard.

Model: gpt-6.2-sol / xhigh

Session: 01a1f0a0-5126-78f3-9ab8-ef4e87f2f119 · slot 0 · generation 3

  • P2 pkg/sql/plan/base_binder.go:1218: A system administrator uses a read-only control function in an uncorrelated scalar or EXISTS subquery with LIMIT 0.
    Impact: The query now fails during binding with error 20102. The pinned base returned NULL for the scalar and false for EXISTS.
    Evidence: Paired planner and single-CN MySQL probes reproduced the difference. The ordinary scalar control without a control function passed on both revisions. The guard runs before the binder establishes correlation or rewrite eligibility. Scope the rejection to rewrites or folds that would lose a required authorization check, and preserve the existing path and frontend privilege checks for unrelated subqueries.

Validation:

  • Verified the frozen head, merge base, complete patch, pinned policy, clean checkout, isolation preflight, and native artifact provenance. Matched commands, source fingerprints, exits, and logs in review-evidence.json.

  • Passed 241 focused race test roots across planner, frontend, vector, and time-window packages. The parser-tree selector matched no tests. The frontend suite exercised the shared AST collector.

  • A single-CN MySQL probe passed the correlated LIMIT 0 and positive LIMIT controls, folded UDF view and unused-window cases, binary prepared SET parameter ordering and NULL assignment, and binary-literal conversion.

  • The pinned-base planner and MySQL probes passed both legacy control-function cases. The head probes reproduced both failures. The SQL logs and receipts are listed in review-evidence.json.

  • Reconciled all 25 discussion entries in discussion-assessment.json.

Limitations:

  • Independent SQL validation used one CN. The two-CN BVT result is author-reported. Unit, static analysis, coverage, and both multi-CN BVT checks were in progress in the frozen CI snapshot.

@XuPeng-SH

XuPeng-SH commented Nov 22, 2026 •

Copy link
Copy Markdown
Contributor Author

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

Commit: fcdb62f61954d40228d4c3716fca71382944dd07

Review completed. Read the assessment.

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

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

Commit: fcdb62f61954d40228d4c3716fca71382944dd07

Assessment: approve

The fix returns a typed SQL NULL for each outer row in the affected correlated scalar queries. It reuses dependent execution and preserves catalog and authorization checks when expressions fold. The latest revision resolves the prior control-function regression by scoping the planner guard to affected rewrites and preserving the existing role checks for ordinary scalar and EXISTS queries.

Model: gpt-6.2-sol / xhigh

Session: 01a1f0a0-5126-78f3-9ab8-ef4e87f2f119 · slot 0 · generation 3

Validation:

  • Verified the frozen head, merge base, patch, pinned review policy, and native build inputs. Matched all seven completed check receipts to their retained logs in validation-ledger.json.

  • The planner short suite passed 5,144 top-level tests with two unrelated subtests skipped. Focused frontend, vector, and time-window tests also passed.

  • Single-CN MySQL tests passed for correlated scalar NULL results, positive-limit controls, folded view and named-window dependencies, and binary prepared SET. Administrator queries returned the expected values, restricted roles were denied, and planning rejected an affected wrapper whose authorization check was lost.

  • Reconciled all 27 discussion entries in discussion-assessment.json.

Limitations:

  • Independent SQL execution used one CN. The two-CN results are author-reported.

This branch was successfully deployed

No deployments
ci — 6f199d83 Deployed Nov 22, 2026 by XuPeng-SH
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 kind/enhancement kind/test-ci size/XXL Denotes a PR that changes 2000+ lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: correlated scalar projection with outer reference fails on LIMIT 0

2 participants