Repository navigation
fix(plan): keep correlation depth for ENUM/SET outer columns - #32271
Conversation
The ENUM/SET display-value wrapper in baseBinder.baseBindColRef built a plain Expr_Col for the wrapped column regardless of binding depth. When a correlated subquery resolved an outer ENUM/SET key through its outer binder at depth>0, the wrapper dropped the correlation depth and left an unresolvable plain column reference inside the subquery scope, so plan building failed with "Column remapping failed: cannot find column reference" for legal EXISTS/NOT EXISTS (and comparison/IN variants) whose association key is an ENUM/SET column. Emit an Expr_Corr carrying the binding depth in that branch, mirroring the ordinary column path (including the full-group-by aggregate position adjustment); depth==0 keeps the previous Expr_Col shape, so non-correlated plans are unchanged. Root cause, red/green proof on base 0384130, BVT result-file generation and residual risks are detailed in the PR description. Related to matrixorigin#31568
Qodo reviews are paused for this user.Troubleshooting steps vary by plan Learn more → On a Teams plan? Using GitHub Enterprise Server, GitLab Self-Managed, or Bitbucket Data Center? |
|
mo-bot review · Commit: Review completed. Read the assessment. |
XuPeng-SH
left a comment
There was a problem hiding this comment.
mo-bot review · mo-bot-local · review
Commit: 73cab4f3c4ab06e5a10da838594cecf971ad95b0
Assessment: request_changes
Preserving correlation depth inside the existing ENUM/SET display wrapper is an appropriate narrow fix, and the previous grouped-HAVING finding is resolved. One consumer remains incomplete: direct outer-column aggregate arguments bypass their existing binder guard and produce plans whose arguments cannot be evaluated.
Model: gpt-6.1-sol / max
Session: 01a1a004-9884-72c0-ad39-f096c4209c4a · slot 1 · generation 0
- P2
pkg/sql/plan/base_binder.go:957: With an ENUM or SET outer key, SELECT l.id, (SELECT MAX(l.k) FROM enum_r r) FROM enum_l l reaches HavingBinder.BindColRef's insideAgg branch with the new display-wrapped Expr_Corr. COUNT and grouped-HAVING MAX arguments have the same problem.
Impact: The branch at having_binder.go:220-250 recognizes only a top-level Expr_Corr, so these expressions bypass its correlated-aggregate admission checks. Planning succeeds with reachable correlations in an ordinary aggregate's arguments, but aggregate-argument executor construction returns an unsupported-expression NYI. Equivalent INT inputs are rejected by the binder.
Evidence: candidate-executor.jsonl records six ENUM/SET failures and three INT bind-rejection controls on this head; candidate-planner-recovered.jsonl and baseline-planner.jsonl show that the candidate admits these plans whereas the merge-base rejects them. constructGroup (pkg/sql/compile/operator.go:1989) passes these arguments to group argument evaluation (pkg/sql/colexec/group/exec2.go:304), whose expression executor has no Expr_Corr implementation (pkg/sql/colexec/evalExpression.go:571). Apply displayWrappedCorrColRef in the insideAgg/bindingProjectedAlias branch as well, preserving its existing permitted-scope exceptions and rejection policy, and add paired ENUM/SET/INT aggregate-argument regression coverage. These forms already failed on the merge-base; the demonstrated defect is invalid-plan admission, not loss of previously supported results.
Validation:
-
Read all six changed files, relevant binder/remapping/execution consumers, closing issue #31568 and its expanded reproduction, and all six discussion entries. discussion-assessment.json covers every discussion key exactly once; the prior grouped-HAVING concern is resolved.
-
Exact-head local Go execution passed all five maintained correlation regression tests, including their 30 subtests. A diagnostic-only overlay classified 66 SQL cases on the candidate and the merge-base production overlay; planner-comparison.json retains the paired outcomes.
-
The focused aggregate-argument executor probe exited 1 with six confirmed ENUM/SET failures; its three INT controls rejected the unsupported forms during binding. Logs, overlay inputs and command/source/exit receipts are retained and reconciled in validation-ledger.json.
-
relational-oracle.log independently checks all 26 SELECT result groups across the 44-statement distributed fixture using label/NULL semantics. The fixture's save/default/restore sequence was also checked under two modeled inherited SQL modes.
-
Reused source-pinned author evidence for the full owning planner package and public SQL/BVT runs, and the successful substantive CI snapshot at this exact head. Earlier failed CI states are retained as historical evidence, not passes.
-
Runtime preflight passed. Native reuse was verified against 196 current input hashes, seven native outputs and 27 generated headers. Initial incomplete native staging caused a pre-test build failure; after setup recovery, the recorded focused tests ran using the assigned task caches and test-exec.
-
final-evidence-audit.log and its exit-0 receipt verify the frozen head, unchanged tracked source, discussion coverage, overlay provenance and matching retained validation receipts.
Limitations:
-
No local MatrixOne SQL service or multi-CN execution was run. The finding is established by finalized planner arguments, the real expression-executor constructor and the traced execution consumer.
-
The SQLite oracle validates relational expected rows; it does not exercise MatrixOne ENUM/SET physical representation, protocol metadata or actual session-mode restoration. Public service evidence is reused from the supplied snapshot.
-
Archived author proof files and raw external CI logs were not locally available. The assessment uses the supplied evidence snapshot and retained local checks; historical unrelated CI failure explanations were not independently reproduced.
…e guard HavingBinder's insideAgg/bindingProjectedAlias branch type-asserted only a bare top-level Expr_Corr, so an outer ENUM/SET key - kept as a correlated reference inside the display wrapper by matrixorigin#31568's repair - bypassed its correlated-aggregate admission checks when used directly as an aggregate argument (for example SELECT l.id, (SELECT MAX(l.k) FROM enum_r r) FROM enum_l l, plus the COUNT and grouped-HAVING MAX variants). Planning admitted the plan with the correlation intact in ordinary aggregate arguments, whose expression executor the group evaluation cannot construct, while equivalent INT keys were rejected at bind time. The branch now extracts the wrapped reference with the existing displayWrappedCorrColRef helper and runs the unchanged admission sequence on it - the aggregate-argument-subquery exception, the rebound-alias exception and the grouped-HAVING target-scope exceptions, then the same correlated-columns NYI - so a wrapped ENUM/SET key gets the identical verdict as its INT twin for every shape.
|
@XuPeng-SH valid finding — fixed in Diagnosis confirmed: with the correlation kept inside the display wrapper, an outer ENUM/SET key binds as Fix ( Paired aggregate-argument regression coverage:
Residual limit (pre-existing, unchanged by this commit): |
|
mo-bot review · Commit: Review completed. Read the assessment. |
XuPeng-SH
left a comment
There was a problem hiding this comment.
mo-bot review · mo-bot-local · review
Commit: b029266f557bcfbaf05510dd4beac859d862225e
Assessment: approve
Both prior findings are resolved. Wrapped ENUM/SET references retain correlation depth and follow existing HAVING and aggregate scope checks. The fix reuses established remapping and validation owners without adding execution state.
Model: gpt-6.1-sol / max
Session: 01a1a004-9884-72c0-ad39-f096c4209c4a · slot 1 · generation 0
Validation:
-
Reviewed the complete six-file delta, closing issue #31568 and all nine discussion entries; discussion-assessment.json covers every key.
-
Full vet-enabled planner suite passed: 4,865 top-level tests, including all six new groups and the existing INT rejection control; two unrelated subtests skipped. Receipt: checks/1794236403075877452-2.json; log: plan-normal.jsonl.
-
All 24 additional planner cases passed for scalar aggregates, ORDER BY/LIMIT, nested correlation, aliases and aggregate-input scope. Receipt: checks/1794236640670881511-2.json.
-
Independent label/NULL oracle matched 29 value SELECTs in the 59-statement fixture; 12 NYI expectations match source and paired planner controls. Receipt: checks/1794236078754281848-2.json. An earlier oracle count assertion was corrected; its script, failed receipt and log remain retained.
-
Isolation preflight passed; reused native artifacts matched 196 current inputs, seven outputs and 27 headers. Final audit confirmed clean source, matching frozen delta, gofmt and receipt/log consistency; validation-summary.json.
-
Frozen-head CI reports successful UT, SCA, coverage, PROXY/PESSIMISTIC BVT and CI Required.
Limitations:
-
No local MatrixOne service or multi-CN execution. Author service results and CI statuses were assessed from supplied evidence; raw external logs were unavailable. SQLite validates logical values; session restoration was modeled.
-
Bare wrapped-correlated scalar projection remains an unsupported decorrelation case outside this repair.
❌ Left the queue ·
|
What type of PR is this?
Which issue(s) this PR fixes:
issue #31568
Related to #31568.
What this PR does / why we need it:
A legal correlated EXISTS / NOT EXISTS (or comparison, IN / NOT IN variant) whose association key is an ENUM or SET column was rejected during planning with
SQL parser error: Column remapping failed: cannot find column reference, while the same fixture worked for ordinary joins, LEFT-JOIN anti-join and integer-key correlations. MySQL 8.4 accepts the queries.Root cause (WHERE/clause shape): in
baseBindColRefthe ENUM/SET display-value wrapper bound its wrapped column as a plainExpr_Colregardless of the binding depth. A correlated outer ENUM/SET key is resolved by the outer binder at depth>0 and must be emitted asExpr_Corrso subquery flattening can pull it across scopes; the depth-blind wrapper leaked an unresolvable outer column reference (for examplel.kwith the outer tag) into the subquery's filter list and column remapping failed.Change 1 (pkg/sql/plan/base_binder.go): the ENUM/SET display wrapper now emits
Expr_Corrcarrying the binding depth, mirroring the ordinary column path (including the full-group-by aggregate position adjustment);depth == 0keeps the previousExpr_Colshape so non-correlated plans are unchanged.Review follow-up: wrapped correlations in grouped-subquery HAVING
The first commit repaired the WHERE positions, but the ONLY_FULL_GROUP_BY HAVING variants of the issue still failed (review finding on the
... GROUP BY r.k HAVING r.k=l.kshapes): with the correlation kept on the wrapped reference,HavingBinder.BindColRefonly recognized bare top-levelExpr_Corrreferences, andmysqlFullGroupByAllowsExprColumnswalks only plain column/function nodes, so the nested correlation was invisible and legal outer keys were rejected withcolumn ... must appear in the GROUP BY clausewhile the same shape with an INT key planned.Change 2 (pkg/sql/plan/having_binder.go + mysql_full_group_by.go): the HAVING validation now extracts the wrapped correlation with a narrow helper (
displayWrappedCorrColRef, which only unwraps the exactcast_index_to_value(<members>, <reference>)shape produced bybaseBindColRef, withisEnumOrSetDisplayValueExpr) and passes it through the same target-scope checks as a bare correlated reference; when none applies, the rejection and its error stay unchanged. An outer ENUM/SET key in a grouped subquery's HAVING therefore gets the identical accept/reject decision as an outer INT key, dependent references keep working (grouped outer key, grouped outer primary key through the any_value remap) and ungrouped cases keep failing exactly like their INT equivalents.Issue-to-test proof and commands
All commands ran with the repository wrapper (CGo mode). Parent/base for the red proof is the PR parent
6cb85576(fix reverted) and the pre-merge base70d39334e1; both fail identically, the INT/VARCHAR controls pass on both, so the delta is the wrapped ENUM/SET reference alone. The mo-bot review's frozen-head probes independently reproduce the same HAVING failures on6cb85576.pkg/sql/plan/mysql_special_correlated_test.go(three tests, all executed in the commands below):TestCorrelatedExistsOnEnumSetKeysPlans/TestCorrelatedEnumSetWrapperKeepsOuterReference: correlated EXISTS/NOT EXISTS/plain/CAST probes and the flattened-join wrapper check (red/green on70d39334e1).TestCorrelatedGroupedHavingOnEnumSetKeysPlans: the reported grouped-subquery HAVING shapes — ENUM/SET EXISTS/NOT EXISTS withGROUP BY r.k HAVING r.k=l.k, and grouped-outer blocks where the grouped primary key makes the ungrouped outer key functionally dependent. Red (exit 1, 6 failing subtests) on the fix-reverted head, green with the fix:.agents/skills/mo-dev/scripts/mo-cgo-test -count=1 -run 'TestCorrelatedGroupedHaving|TestCorrelatedExistsOnEnumSetKeysPlans|TestCorrelatedEnumSetWrapperKeepsOuterReference' ./pkg/sql/plan-> ok.TestCorrelatedGroupedHavingMatchesIntKeyPolicy: decision parity between special-typed and INT outer keys across four shapes, including two rejection pairs (no primary key, key not grouped; inner local key not grouped) proving the target-scope checks stay enforced for wrapped correlations..agents/skills/mo-dev/scripts/mo-cgo-test -count=1 -timeout 2400s ./pkg/sql/plan->ok, exit 0, zero failures.CGO_CFLAGS="-I$PWD/cgo -I$PWD/thirdparties/install/include" go vet ./pkg/sql/plan-> clean;golangci-lint run --new-from-rev <merge-base>-> 0 issues.test/distributed/cases/dtype/issue_31568_enum_set_correlated_exists.{test,result}(result generated with mo-testergenrsagainst the fixed binary and inspected statement-by-statement against MySQL semantic derivations): covers ENUM and SET correlated EXISTS/NOT EXISTS, explicit casts, same/reversed member definitions, NULL keys, NULL-augmented correlation, IN/NOT IN, LEFT-JOIN anti-join control, integer-key control, plus nine grouped-HAVING statements (ENUM/SET EXISTS/NOT EXISTS/IN, grouped-outer-by-PK, same-member and INT controls, health checks). In comparison mode with the CI-path flags it passes 44/44 statements at 100% against the same clean instance, with the created database verified absent from the catalog after each run (real teardown, not masked by entry-timeDROP IF EXISTS).CI follow-up: compose-PROXY BVT failures from session sql_mode inheritance
CI run 42128708082 (attempt 1) failed
multi cn e2e bvt test docker compose(PROXY)with 9 failures, all in this PR's own BVT file:unsupported expression executor for typ:<... enum_l/set_l ...> corr:<...>,SQL parser error: Column remapping failed: cannot find column reference, andcorrelated columns in aggregate function. The multi-CN/proxy topology was not the differential. mo-tester reuses one connection across the wholerun_bvt_group.shexecution anddtype/enum.sqlends withset session sql_mode = ''without restoring it, so every later dtype file - including this PR's - executed with a relaxed sql_mode. Under that mode the query builder selects themysqlCompatibleHAVING path instead of themysqlFullGroupByCompatpath the fix targeted; the wrapped correlated ENUM/SET reference was not recognized as a correlation there and was folded intoany_value, which then either leaked a rawExpr_Corrinto the executed plan, died in column remapping, or surfaced the pre-existing correlated-aggregate NYI (the same verdict the INT control gets in that mode). The 9 statements were reproduced byte-for-byte on a local single-process instance of head3fc67ae33aafterset session sql_mode=''and passed again afterset session sql_mode=default, isolating the trigger to the session mode rather than the deployment.Change 3 (pkg/sql/plan/having_binder.go): the relaxed-mode HAVING binder now rejects a wrapped correlated ENUM/SET reference at bind time with the same
correlated columns in aggregate functionNYI a bare correlated column gets in that mode, instead of building the doomedany_value-wrapped plans. In ONLY_FULL_GROUP_BY mode the Change 2 correlation planning is unchanged; free local keys keep the existingany_valuebehavior.Change 4 (test/distributed/cases/dtype/issue_31568_enum_set_correlated_exists.test): the BVT pair now pins the semantics it asserts, following the dtype convention already used by
order_by_clause.sql/update_text_coalesce_cast.sql: save@@session.sql_mode,set session sql_mode = default, execute the contract under MySQL's default mode, then restore the inherited value and guard the restore with an equality check. The file is now independent of the session state earlier files leave behind on the shared mo-tester connection, and later files observe exactly the state they observed before (including the enum.sql pollution).Follow-up proof:
TestLooseGroupByHavingCorrelatedKeyRejected(in the same UT file): under a relaxed sql_mode every special-typed correlated grouped-HAVING shape - EXISTS/NOT EXISTS/IN with ENUM and SET keys, plus grouped-outer variants - fails binding with the same NYI as its INT control, while a free local ENUM key without correlation keeps planning (theany_valuepath stays intact). Red on head3fc67ae33awith Change 3 stashed: the seven special-typed subtests fail (the plan-level shapes build broken plans or hit the remapping error); green with Change 3..agents/skills/mo-dev/scripts/mo-cgo-test -count=1 -timeout=300s -run 'TestCorrelatedExistsOnEnumSetKeysPlans|TestCorrelatedEnumSetWrapperKeepsOuterReference|TestCorrelatedGroupedHavingOnEnumSetKeysPlans|TestCorrelatedGroupedHavingMatchesIntKeyPolicy|TestLooseGroupByHavingCorrelatedKeyRejected' ./pkg/sql/plan-> ok.genrson a fresh session produces a result file byte-identical to the committed one for all pre-existing statements, andrunmode passes 44/44. A CI-order simulation (one connection: polluteset session sql_mode=''-> pinned file -> restore check) regenerates a byte-identical result for the pinned file, passes 46/46 at 100%, and verifies the inherited loose mode is restored afterwards, so downstream dtype files keep their current behavior.sql_mode=''now fail binding with the cleancorrelated columns in aggregate functionNYI (matching their INT controls) instead of the three internal-error classes, and the same suite undersql_mode=defaultstill returns the committed MySQL-checked results.Review follow-up 2: direct outer-column aggregate arguments
The mo-bot review of
73cab4f3c4found one remaining incomplete consumer of the kept correlation:HavingBinder.BindColRef's insideAgg/bindingProjectedAlias branch still recognized only a bare top-levelExpr_Corr, so an outer ENUM/SET key bound ascast_index_to_value(<members>, Expr_Corr)bypassed its correlated-aggregate admission checks when it appeared directly in an aggregate's arguments — for exampleSELECT l.id, (SELECT MAX(l.k) FROM enum_r r) FROM enum_l l, theCOUNTvariant, and the grouped-subqueryHAVING MAX(l.k)form. Planning admitted the plan with the correlation reachable inside ordinary AGG node arguments, aggregate-argument evaluation then failed with an unsupported-expression NYI (pkg/sql/colexec/evalExpression.gohas noExpr_Corrcase), while the identical query with an INT key was rejected during binding.Change 5 (pkg/sql/plan/having_binder.go): the insideAgg/bindingProjectedAlias branch now extracts the wrapped correlation with the existing
displayWrappedCorrColRefhelper and runs the identical admission sequence on that reference — the aggregate-argument-subquery exception, the rebound-alias/current-query-input exception, and the grouped-HAVING target-scope exceptions — before the samecorrelated columns in aggregate functionNYI. A wrapped ENUM/SET key therefore gets exactly the bare-INT verdict for every shape: rejected when the correlation would stay live inside an ordinary aggregate's arguments, admitted where an existing exception already permits the same correlation for INT.Follow-up proof:
73cab4f3c4: the six ENUM/SET direct-aggregate-argument shapes admitted plans whose AGG nodes carried the nestedExpr_Corrinside the aggregate arguments (the executor construction dead end), while all INT twins failed binding with the correlated-aggregate NYI.TestCorrelatedAggregateArgsOnEnumSetKeysMatchIntPolicy(new UT inmysql_special_correlated_test.go): four paired families with ENUM/SET + INT twins — MAX scalar subquery, COUNT scalar subquery, grouped-subquery HAVING MAX, grouped-outer-PK HAVING EXISTS — assert both decision parity and the concrete NYI; three positive controls prove the aggregate-argument-subquery exception still admits wrapped WHERE-position correlations end-to-end so enum/set/int all plan.73cab4f3c4withspecial-typed key accepted while the INT key is rejected: "select l.id, (select max(l.k) from enum_r r) from enum_l l"and passes with the fix; the five maintained correlation tests and the INT-pinningTestOnlyFullGroupByPreservesCorrelatedAggregateNYIstay green..agents/skills/mo-dev/scripts/mo-cgo-test -count=1 -timeout=3600s ./pkg/sql/plan→ok(exit 0);go vet ./pkg/sql/planandgolangci-lint run --new-from-rev <merge-base>→ clean.issue_31568_enum_set_correlated_exists.testgained fifteen statements — eight ENUM/SET rejections, four INT-twin rejections, and three end-to-end positive controls; the.resultwas regenerated against the fixed binary with mo-testergenrs(all pre-existing statement entries byte-identical) and the updated pair passes in comparison mode at 100%.Residual limit (pre-existing, unchanged by this round):
select max((select l.k from ...))— a wrapped correlated reference in a scalar subquery's bare projection used as an aggregate argument — still fails with the pre-existingwrapped correlated scalar projection cannot be safely decorrelatedNYI, identical before and after this change, while its INT twin plans. That is a separate decorrelation capability, not an invalid-plan admission, so it stays out of this fix.Residual risks and limits
depth == 0paths are unchanged and the complete owning-package suite passes in normal mode on the final head.Base synchronization (2026-11-09)
Scheduled
ci_base_refresh:mainhad advanced 42 commits past this PR's merge-base. Mergedorigin/main@e2459cc55finto this branch (merge commit73cab4f3c4, no conflicts; the PR's own files are byte-identical to the pre-merge head). Re-validated on the merged head with the repository CGo wrapper:.agents/skills/mo-dev/scripts/mo-cgo-test -count=1 -run 'TestCorrelatedExistsOnEnumSetKeysPlans|TestCorrelatedEnumSetWrapperKeepsOuterReference|TestCorrelatedGroupedHavingOnEnumSetKeysPlans|TestCorrelatedGroupedHavingMatchesIntKeyPolicy|TestLooseGroupByHavingCorrelatedKeyRejected' ./pkg/sql/plan(exact five-test regression selection) →ok, 5/5 tests + 30 subtests PASS, 0 FAIL..agents/skills/mo-dev/scripts/mo-cgo-test -count=1 -timeout=3600s ./pkg/sql/plan(complete owning package, unfiltered) →ok(133.99s), including upstream's newly merged planner tests for the 42 commits — no semantic drift.GOWORK=off go vet -mod=readonly ./pkg/sql/plan(repo CGo environment) → clean.The previously recorded red/green proofs are unchanged: the fix commits and their tests are byte-identical across this merge. Fresh CI runs on the new head.