Repository navigation
[4.1.6-hotfix] fix(plan): infer result nullability from explicit proofs - #32519
Conversation
Share audited function/overload proofs across binding, casts, remapping and windows. Preserve safe constraints while retaining legal NULL results in grouping, DISTINCT and CTAS. Fixes matrixorigin#32264. Nullable NOT IN release validation with matrixorigin#32263 remains required.
Apply null extension to binding output types after ON/USING binding, before parent expressions can establish non-null proofs. Keep source/catalog types intact and preserve safe ANTI controls. Cover nullable build/probe expressions, LEFT/RIGHT/FULL joins, derived and nested joins, and actual NOT IN results.
Treat scalar results as nullable at binding and through SINGLE/LEFT lowering, then refresh parent proofs after argument substitution. Preserve EXISTS, literal and non-null fallback controls without changing evaluation or scalar errors. Cover correlated and uncorrelated empty scalar subqueries with early binding, typed plan and SQL result regressions.
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? |
|
This pull request is merged. |
Regenerate the affected information_schema and JSON_EXTRACT descriptors without changing inference. Preserve strong CASE output contracts and add matched/missing-path view value controls.
|
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: 2f6f19508ca564403aa150f786ede2ac181e231e
Assessment: approve
Shared registry proofs and early NULL extension correctly align binding, remapping, windows and CTAS without a second inference rule set. Safe constraints and three-valued membership behavior are preserved.
Model: gpt-6.1-sol / max
Session: 01a1a004-90c3-73b1-acc9-3d4636452003 · slot 0 · generation 0
Validation:
-
Read all 16 changed paths and affected owners/consumers, complete discussion and linked issue requirements; saved the three-key discussion ledger.
-
Frozen exact-head CI: build, UT, SCA, coverage, active multi-CN BVT and CI Required succeeded (12 successful, 13 skipped, 2 neutral).
-
Reused qualified author reports of full owning/consumer tests, 23 SQL groups, the CTAS fixture twice and three metadata fixtures twice.
-
Local bounded source/format/evidence audit passed; receipt checks/1794407866788237610-4.json matches retained stdout/stderr and clean-source fingerprint.
Limitations:
-
No fresh local Go/native/SQL/BVT execution; raw author and CI logs were not supplied.
-
The expression/DOUBLE MARK fallback retains the measured performance risk tracked in #32263. This approval does not close the explicitly separate release decision; restoring incorrect ANTI inference would lose SQL semantics.
-
Diff-check reports intentional trailing spaces in regenerated result-format rows; Go formatting is clean.
## What type of PR is this? - [ ] API-change - [x] BUG - [ ] Improvement - [ ] Documentation - [ ] Feature - [x] Test and CI - [ ] Code Refactoring ## Which issue(s) this PR fixes: Related to matrixorigin/matrixflow#21396. ## What this PR does / why we need it: ### Root cause and branch-specific fix A distributed shuffle aggregate creates multiple receiver buckets per CN. A Dispatch attached to one bucket can target local receivers owned by sibling buckets. A following global Window uses `newMergeScope`, which previously split those buckets into independent RemoteRun trees. The old runtime then moved a non-standalone tree onto the coordinator without changing the compile-time notification addresses, causing remote Dispatch registration timeouts. Adapt the common ownership fix from #26603 to `4.1.6-hotfix`: - Extract a pure receiver-ownership detector and reuse it during compilation and the existing runtime check. Preserve the root output retained on the caller. - Before constructing a common merge's receivers, group dependent inputs by their actual CN. Preserve every input, including nodes outside `cnList`, along with operator chains, receiver identities, UUIDs and `FromAddr`. - Keep independent remote inputs and local-only dependencies on the existing path. - Add Dispatch/Connector ownership controls and actual Range/Hash Shuffle GROUP → Window topology tests. - Extend the existing shuffle BVT fixture with ranked top-five rows, COUNT wrapping and a UNION ALL total; add no new large-data setup. This is a focused adaptation, not a wholesale cherry-pick of the newer scheduler. It does not change the existing RemoteRun fallback/error protocol, registration timeout, or wire/catalog/storage formats. ### Validation Validated on darwin/arm64 with Go 1.26.4 and branch-matched native libraries. The delivered source hashes at `a30a0368f0` match the validated sources. - New counterexamples fail before the fix for missing ownership grouping; the same assertions and directly affected existing tests pass afterward. - Five focused topology/lifecycle tests each pass 100 repetitions under `-race`, including merge cancellation, blocked remote forwarding cancellation and empty Dispatch completion. - Service build, matching gofmt, `go vet`, and incremental repository-pinned golangci-lint 2.6.2 pass. - New grouping function coverage: 100%; extracted detector: 89.7%; other directly modified functions: 100%. - Full `optimizer/shuffle.test` passes twice on an isolated two-CN cluster: **75 successful, 0 failed, 9 pre-existing ignored cases** each, in 20.473s / 19.250s. All three new cases execute. The original case on the same binary takes 15.746s. - Each CN separately executes all three new SQL shapes with independently checked results. Plans show MULTICN + range shuffle + Window; the physical execution plan contains both CN addresses. - Test databases are removed and the owned cluster exits with code 0. No production SQL replay or deployment was performed. ### Known baseline failures Full `pkg/sql/compile` is **not green** in this local environment. Both normal and race runs fail the following tests; clean `54feca6423` worktree runs with the same modes reproduce the identical assertion failures: - `TestCompileExternScanParquetLoadUsesRowGroupFanoutWithEmptyFiles`: expected two scopes, got one. - `TestCompileExternScanParquetRowGroupFanoutValidatesEmptyFileColumnCount`: expected an error, got nil. - `TestCompileExternScanParquetLoadUsesFileFanoutMainPath`: expected two scopes, got one. These failures are not introduced by this change; the tests were neither skipped nor weakened. No race detector finding was reported. Local commands, terminal logs, source hashes and the detailed report are retained under the task worktree's `CLAUDE_VALIDATION/` and are intentionally not committed. ### CI follow-up (2026-11-12) Merged current upstream `4.1.6-hotfix` (`bf18d10904`, #32519) without conflicts; updated head: `089cb315ae2de0d85ff55b3188b37eee036ded63`. The PR remains the original five-file receiver-ownership change; no unrelated fixture, assertion, timeout or CI-harness changes are included. The preceding Ubuntu race attempt was not green. Its failures are tracked separately: - DML's shared branch-diff deadline: existing #32544. - `TestPreparedParams` / `TestCalculateObjectCount` bootstrap failures in the serialized embedded stage: #32614. - S3 merge-count assertion recurrence: #32615 (historical closed #25550). - Attempt 1's `TestReplay1` fixed-port collision matches historical #26165 and did not recur in attempt 2. On the merged head, an explicitly selected local run with Go 1.26.4, matching native libraries, `-race -short -tags matrixone_test -count=1 -p 1` passes all selected original failed tests, the preceding `Test_TxnExecutorExec`, remote-ownership regressions, and `TestWindowResultNullability` across six packages (exit 0). This is Darwin/arm64 evidence, not a reproduction or repair guarantee for the Linux runner failures. No root-cause equivalence with historical issues or full CI success is claimed. The push starts a new CI generation; its outcome remains pending.
…#32520) ## What type of PR is this? - [ ] API-change - [x] BUG - [ ] Improvement - [x] Documentation - [ ] Feature - [ ] Test and CI - [x] Code Refactoring ## Which issue(s) this PR fixes: Fixes #32265 ## What this PR does / why we need it: Restore consistent grouping-extension results and nullability across SELECT, views, CTAS, and repeated planning on `4.1.6-hotfix`. **Design documentation — maintainer approval pending.** This is now a grouping-planner ownership restructuring, not just a localized CTAS/formatter fix. The current hand-written production Go diff is 655 additions + 38 deletions (693 lines), plus five grammar lines; generated parser and tests are excluded. Before this follow-up it was 686 lines; the earlier 786-line estimate was incorrect. - [Versioned design v3 at `0e711ba98e`](https://github.com/matrixorigin/matrixone/blob/0e711ba98e4005b868b94af4305c02bbe2091a16/docs/design/CLAUDE_32265_grouping_ownership.md): compares scope reduction, outer-AST normalization, typed internal transport, and native grouping aggregation; defines ownership, expression identity, branch/union nullability proofs, lineage, SAMPLE/windows/subqueries, cost, release compatibility and counterexample validation. This edition refines the public summary while retaining the technical design contracts. - [Design-review record at `0e711ba98e`](https://github.com/matrixorigin/matrixone/blob/0e711ba98e4005b868b94af4305c02bbe2091a16/docs/design/CLAUDE_32265_grouping_design_review.md): records the exact historical v1 REQUEST_CHANGES and v2 design-only PASS revisions. No new independent review was performed for this editorial v3 update. This is retrospective design documentation, **not** evidence of pre-implementation approval, current implementation acceptance or GitHub maintainer approval. Maintainer approval of the exact design revision is pending. - The latest merge incorporates target `9937f1b74a` (#32609/#32596/#32591) without conflicts. This follow-up implements the two contracts requested in [review 5887871372](#32520 (review)): branch-output proof publication before HAVING consumers (§4.6/D8), and uniform DISTINCT GROUPING admission (§4.7/D7). The versioned v3 design/review documents are unchanged. Fresh validation for the listed affected boundaries appears below; historical results are not automatically promoted to this target. Actual multi-CN and release-source compatibility validation remain unverified. - No new GitHub review request/comment, CI monitoring, or `mo-self-review` was performed. The following implementation/evidence history does not substitute for maintainer review. - Format ROLLUP, CUBE, and GROUPING SETS as reparsable SQL, preserving explicit empty and duplicate sets rather than flattening or deduplicating them. - Keep ROLLUP/CUBE expansion and the derived HAVING marker local to each planning invocation. Rebinding a source AST no longer adds subtotal levels or loses CUBE keys; CTAS retains the original grouping syntax for its generated INSERT. - Publish omitted-key nullability when HavingBinder/ProjectionBinder first bind grouping output references, before branch HAVING subquery flattening can consume the proof. Reuse the same output-type rule in remapping/transport; preserve the evaluated AGG inputs and raw SAMPLE value types. Parent functions and quantified operands bind bottom-up from the correct child proof; retain the post-UNION refresh as a separate boundary. Ordinary/common keys, COUNT and proven COALESCE fallbacks retain NOT NULL. MARK/ANTI algorithms are unchanged. - Accept qualified column names in GROUPING so that binding-generated `GROUPING(table.column)` survives the CTAS format/reparse boundary. Regenerate the MySQL parser through the repository Makefile; the large generated diff is parser tables and line directives, with only the corresponding GROUPING semantic action changed. Repeated generation produces identical output. - Apply SELECT DISTINCT to the combined grouping-set result, not separately to its UNION ALL branches. Deduplicate before hidden ORDER BY expressions and LIMIT/offset are introduced; ordinary grouping sets still preserve duplicate rows. - Mark grouping-set membership only for complete root grouping expressions with a successful key lookup. Recursive operands of arithmetic/function keys must not accidentally mark key zero present. - Retain subtotal aggregates when any key is omitted, even if the evaluated input contains a primary key. Ordinary PK grouping retains its existing effectless-aggregate optimization. - Give an explicit empty grouping set a hidden COUNT when neither an aggregate nor SAMPLE owns its cardinality, so each set produces one global row on populated or empty input. Preserve its HAVING boundary, reject ungrouped source columns, and leave ordinary constant scans unchanged. - Preserve predicates on omitted grouping keys above the aggregate instead of replacing output NULLs with input values. Keep output predicates above keyless global aggregates as well: filtering their input to zero rows still produces a global aggregate row. Predicates on present/common grouping keys retain safe pushdown. - Split expanded grouping queries into a branch-local grouping stage and a single combined-result stage. Carry only grouping/aggregate inputs consumed by the final/window/order/post-window-HAVING expressions through UNION ALL; evaluate windows and final projection once over that complete result, then DISTINCT, ORDER BY and LIMIT. Rebind through a private slot map rather than assuming all group keys are present. Internal homogeneous transport bypasses SQL common-type coercion, preserving BINARY/VARBINARY grouping bitmaps; public set-operation coercion is unchanged. This also supports windows used only in ORDER BY, partitioning, ranking, aggregate-over-aggregate windows, and reused CTAS/prepared ASTs without text rewriting. - Rebind quantified subqueries' outer operands, including `SubqueryRef.Child`, to the combined grouping output. Flatten scalar and quantified subqueries before constructing the DISTINCT key projection, not only in the ordinary final projection; preserve the existing unsupported-left-subquery rejection. - Keep SAMPLE branch-local and materialize its selected post-sample outputs, including already-supported input passthrough. Omitted keys become independently typed NULL grouping expressions, so subtotal branches really sample the correct group; branch-local GROUPING masks distinguish omitted keys from actual NULLs. Preserve physical group-column ordinals when unused group outputs are pruned. Reconstruct legal hidden ORDER BY expressions (including `chosen+1`) from selected results after DISTINCT, without transporting unused computed sort columns or sampling again. Serialize the complete SAMPLE call for CTAS, retaining columns/star, percentage precision, row count, and row/block unit. - Refresh WINDOW arguments/results from their actual remapped child types before publishing their nullable proofs. FIRST/LAST_VALUE now see synthesized grouping NULLs, including view/CTAS consumers; partition-only keys retain their upstream PARTITION coordinate ownership. COUNT/ranking and proven literal fallbacks retain their non-null guarantees. - Validate every DISTINCT sort dependency recursively, including expression lists/tuples. Match exact selected slots or safe complete selected expressions first; reject any remaining GROUPING invocation with error 1149, uniformly for AGG and SAMPLE. Do not reconstruct lineage from deduplicated key values or add hidden markers to DISTINCT keys. Selected GROUPING aliases/complete expressions and ordinary value expressions remain supported; admission does not depend on primary keys, NOT NULL, current data or whether a particular grouping set omits a key. Unselected dependencies fail before SELECT execution or CTAS target creation. - Preserve SAMPLE sort dependencies before branch-local GROUPING folding. A detail-arm zero must not be promoted into a global constant or confused with a literal zero. For non-DISTINCT SAMPLE sorting, hidden GROUPING (including when its key is selected) stays in the branch payload unless the complete GROUPING result is already selected/materialized; ordinary value expressions still reconstruct from selected outputs. This fixes subtotal-first LIMIT selection and the corresponding silent CTAS writes while retaining legal `chosen+1` sorting. - Recompute composite expression proofs bottom-up immediately after rebinding to merged grouping outputs, before quantified-subquery flattening/MARK optimization. A nullable `g+0` must not retain its old NOT NULL promise and become a NULL-unaware ANTI filter; explicit non-null COALESCE controls retain their guarantee. - Bind grouping DISTINCT/SAMPLE ORDER BY aliases to exact selected-output references, not copies of their expression trees, retaining alias names in the source AST for CTAS/repeated planning. Map the selected tag and ordinal explicitly across projection boundaries; independent structurally identical volatile outputs `a`/`b` retain their own identity in nested sorting expressions. Structural fallback reuse rejects volatile/real-time calls, including under deterministic wrappers. Resolve DISTINCT sort dependencies before subquery flattening replaces expression identity with join tags. Independent selected subqueries are not merged by SQL text, aliases are not re-executed for sorting, and unselected dependencies still raise syntax errors. - Split mixed SAMPLE sort dependencies recursively rather than falling back to an entire branch PROJECT expression. Selected aliases consume their already-materialized outputs; branch-only GROUPING/column dependencies are transported separately and folded only at their branch owner. Evaluate the combined arithmetic/CASE/list expression after UNION; keep scalar and quantified subqueries at that global consumer boundary, including their selected outer operands. This prevents future-output/self references in SELECT and CTAS without copying/re-executing volatile selected expressions, and preserves DISTINCT dependency rejection. - Resolve GROUPING's alias arguments to their bound projection origins during initial function-argument binding. Unlike ordinary ORDER BY value functions, GROUPING describes grouping-key lineage and must not consume future selected-output slots. Preserve the source alias AST for CTAS/rebinding; ordinary volatile aliases retain exact output references, and actual NULL values are not used to infer subtotal membership. - Keep transport-column type/provenance separate from the user projection. A literal NULL in a user output slot must not cause an unrelated transport aggregate at the same slot to be retyped as text; restore bare-NULL provenance for enclosing set operations. - Add focused parser/planner regressions and a small SQL case covering rows, schema, NULL insertion constraints, empty inputs, actual versus synthesized NULLs, duplicate sets, views, CTE reuse, prepared execution, HAVING, and projection pruning. Correct only the five duplicate subtotal/grand-total expectations in the existing hint CTE fixture after independently verifying its ten correct rows. **Latest review-follow-up validation** (implementation `28da04af7e`; local darwin/arm64, Go 1.26.4, matching native/module inputs, target `9937f1b74a`): - Frozen pre-fix `0e711ba98e` reproduces the extra `(NULL,10)` in SAMPLE HAVING SELECT and administrator CTAS readback, and wrongly accepts hidden-GROUPING DISTINCT SELECT/CTAS. New typed planner tests fail before repair and pass afterward; they check real binding/MARK consumers, immutable input proofs, and BuildPlan admission for both SELECT and CTAS. - Fresh full planner/function/loopjoin/sample/window/group runs: **4,875 test/subtest passes**, three unchanged planner skips. Fresh tree/MySQL parser/readutil/pSpool packages add 1,060 passes; selected compiler grouping/window/receiver/scalar-CTE boundaries add 44 passes, not a full compile-package claim. - Independent SQL/value/metadata/CTAS/error-cleanup checks pass twice, including ordinary AGG, common keys, CUBE, CAST/ANY/ALL, empty/NULL/matching RHS, COALESCE, actual NULL, PK/NOT NULL admission, selected markers/composites/aliases, and normal SAMPLE value sorting. All nine earlier review oracles and the original multiset/constraint oracle pass again. - Grouping CTAS BVT: **345/345 twice**, metadata enabled, no ignores. Generated results append 45 statements without changing the previous 300 expectations. Existing SAMPLE suites pass 78/78 and 51/51; ROLLUP 107 with two unchanged ignores, hint CTE 65/65, scalar CTE 41/41, non-primary ZoneMap 60/60. - Matching build/gofmt/vet, pinned molint and golangci-lint 2.6.2, and err-check pass. Changed production statements in this increment: **27/29 (93.10%)**; full PR: **375/388 (96.65%)**, reusing only the unchanged tree coverage. The initial validation-command/setup errors remain in local evidence and are not counted as passes. - Only these listed current checks are claimed; the historical results below retain their original revision scope. No re-review request, GitHub comment, CI monitoring, `mo-self-review`, multi-CN acceptance or release-upgrade approval is claimed. **Historical implementation validation** (recorded at `0a88c1d8cd`, not a fresh validation of the documentation/new-target head; local darwin/arm64, Go 1.26.4, matching worktree-built native libraries; validated target base `af531771cc`, merged without rebasing; previous result-proof base `bf18d10904`; original reproduction base `cbb7da471a`): - Baseline regressions reproduce CTAS error 3819, CUBE rebinding errors, lost duplicate empty sets, and repeated expansion. Qualified GROUPING parser tests fail before the grammar correction. - The first review's four defects and the second review's three operator-boundary defects fail focused planner tests before their respective repairs and pass afterward. Controls cover safe common-key pushdown, hidden sort keys, PK optimization retention, constant HAVING, projection provenance, and plain scans. - Third-review quantified and SAMPLE binding failures are recorded before repair. A single-owner revert reproduces residual subqueries in published DISTINCT projections and the missing flattener rejection; the strengthened UT checks executable IR rather than only successful binding. SAMPLE format/reparse tests also fail with the original formatter. - Fourth-review typed tests and SQL witnesses fail on the frozen `512f10f324` source/binary, covering binary markers, SAMPLE subtotal grouping, stale window metadata, tuple-order acceptance, unnecessary transport columns, and rejected computed sample ordering. The exact `54feca6423` Go source was independently built via an audited overlay with unchanged module/native inputs; the same computed SAMPLE ordering SELECT completes there. Its known old duplicate-DISTINCT rows are not used as the new result oracle. - At `0a88c1d8cd`, the full `pkg/sql/plan`, `pkg/sql/plan/function`, `pkg/sql/colexec/sample`, `pkg/sql/colexec/loopjoin`, `pkg/sql/colexec/group`, and `pkg/sql/colexec/window` tests pass (4,753 test/subtest pass events; three existing planner skips, no new skipped regression). That planner evidence was refreshed after the `af531771cc` base merge and includes GROUPING-alias key origins, mixed SAMPLE branch/global dependencies, exact volatile alias output slots, independent-call structural fallback, compound-operand proofs, selected-subquery identity and repeated-CTAS regressions; the five unchanged owning/consumer package runs reuse sixth-review evidence. The unchanged tree/MySQL parser suites reuse third-review evidence. Build, matching gofmt, vet, and affected-package golangci-lint 2.6.2 pass. - Changed handwritten production statements across the PR: 373/384 covered (97.14%); the latest review-fix increment covers 3/3 (100%). Unchanged tree coverage is explicitly reused; current planner coverage is newly collected. Generated parser tables are excluded from that denominator and validated through parser and SQL consumers. - Independent manual-multiset SQL checks pass for the original controls and all four review witnesses: arithmetic-key CUBE has eight rows, PK ROLLUP/CUBE has `(NULL),(1),(2)`, DISTINCT removes only result duplicates, and each explicit empty set contributes one constant row on either empty or populated input. SELECT and CTAS agree, including LIMIT/offset and nullability/insertion constraints; original explicit INSERT and literal fallback controls remain green. - Independent second-review checks verify that outer `g=1` excludes synthesized NULL, an outer false predicate over an explicit empty set returns zero rows, and COUNT OVER sees all three grouped rows in both SELECT and CTAS. Ranking, partitioning, nested aggregates, HAVING/window ordering, DISTINCT/LIMIT, empty/duplicate sets, actual/synthesized NULLs and view consumers have additional value controls. The separate generic ordered-SUM write failure is explicitly excluded below, not recorded as a pass. - Independent third-review SELECT/CTAS checks verify IN/NOT IN/ANY/ALL, expression/tuple operands, synthesized NULL and empty/NULL-containing RHS three-valued logic, scalar/functional/DISTINCT/window combinations, multirow-scalar error propagation and CTAS rollback, and complete deterministic SAMPLE output. SAMPLE checks use 100 percent or a budget exceeding the fixture, with duplicate/empty sets, empty input, zero percent, multiple columns, supported passthrough, DISTINCT, and enclosing bare-NULL numeric UNION controls. These pass twice; prior-review and original value/constraint oracles also pass again. - Independent fourth-review SELECT/CTAS/view checks pass twice: binary actual/subtotal NULL markers, SAMPLE ROLLUP/CUBE/mixed sets and nullable keys, non-prefix group outputs, FIRST/LAST_VALUE and partition-only keys, COUNT/literal-fallback metadata, tuple-order syntax rejection and CTAS rollback, and computed SAMPLE ordering. All earlier review/original value and constraint oracles pass again. - Transport-pruning UT and EXPLAIN verify count-only AGG/UNION output without unused keys. A separate 20,000-row/two-2-KiB-key local check returns 60,000 on both base and candidate; five alternating warm runs have medians 50.2 ms / 51.2 ms respectively (client-inclusive local sanity measurements, not a performance threshold or cluster claim). Large data is not added to BVT. - Fifth-review frozen-head SQL reproduces the wrong `5,5,7` LIMIT result and identical CTAS rows. Old-owner overlay UT rejects the same hidden-marker transport loss and literal-to-flag dependency substitution. Final independent ordered-result/CTAS checks pass twice for hidden, selected and wrapped markers, actual NULL, mixed sets, int/bigint samples, literal zero, DISTINCT, and computed-order controls. - Sixth-review frozen `a2103870aa` reproduces a NULL row from `NOT flag` over `g+0 IN (...)`, including the same incorrect CTAS write, plus 1149 for the legal scalar-subquery alias ordering SELECT/CTAS. Exact `bf18d10904` independently confirms the alias SELECT/CTAS control succeeds. Final ordered/value oracles pass twice for IN/NOT IN/ANY/ALL, compound/cast operands, empty/NULL RHS, non-null fallback, scalar/count/wrapped aliases, multiple independent aliases, repeated source binding and CTAS cleanup. All earlier review/original oracles pass again. - Seventh-review frozen `bcec0af15d` fails deterministic typed slot-ownership tests and six public nested-`b` ordering witnesses (plain DISTINCT, DISTINCT SAMPLE and ordinary SAMPLE); three `a` controls remain ordered. Exact `bf18d10904` passes all nine SELECT ordering controls. The candidate passes all nine SELECT/CTAS checks twice, comparing actual returned values rather than fixed random strings. CTAS records row ordinals before storage and verifies them when read back; nested wrappers, reverse order and SAMPLE LIMIT are covered. All six earlier review/original result oracles pass again. The exact base's volatile-alias CTAS has a separate 1149 format/rebind limitation, so it is not claimed as a successful CTAS oracle. - Eighth-review frozen `7674e4e2c4` reproduces 1064 column-remapping failures for mixed selected-alias/branch-marker sorting, in both SELECT and CTAS; typed tests directly reject the branch PROJECT's reference to its own future output. Frozen `bcec0af15d` passes the same eight deterministic SELECT/CTAS controls. The candidate passes them twice (arithmetic, reverse direction, CASE, multiple CUBE masks, literal zero, scalar/quantified subqueries), plus mixed volatile alias/hidden GROUPING ordering, selected-marker DISTINCT and unselected-marker rejection/CTAS rollback. All earlier review/original oracles pass again. - Ninth-review frozen `f0b27a96ed` fails GROUPING-alias key-origin assertions and the public alias SELECT/CTAS controls; frozen `bcec0af15d` passes the same deterministic controls. The candidate passes eight SELECT/CTAS shapes twice: aliases, source-name shadowing, quoted names, nested CASE/arithmetic, multiple CUBE arguments, qualified sources, selected-marker SAMPLE DISTINCT and ordinary aggregate DISTINCT. Additional checks cover actual NULL versus subtotal lineage, GROUPING(alias) mixed with independently selected volatile `b`, and unselected-marker 1149/CTAS rollback. All earlier review/original oracles pass again. - Expanded grouping CTAS BVT passes twice on the same isolated single-CN instance: 300/300 each, no skips, including metadata comparison. The prior 289 results are unchanged; eleven statements add hand-computed GROUPING-alias lineage/order results, CTAS, shadowing, CUBE and DISTINCT controls. Its only pre-existing expectation changes are two SUM nullability rows (`NO` to `YES`) required by #32519; the same metadata is independently verified on exact `bf18d10904` and candidate controls. Existing SAMPLE BVT passes unchanged: 78/78 and 51/51. Existing hint CTE passes: 65/65. Existing ROLLUP passes with 107 successes and two unchanged skips; existing CTAS passes with 1,284 successes and 30 unchanged skips (including the new target-base cases). Generated results were reviewed against independent expected values before normal comparison runs. - CI run `43223581993` at `f14f314d58`: arm64 SCA failed because its self-hosted runner lost communication (check annotation), not because of a reported lint finding. Ubuntu race UT reports twelve failed roots across checkpoint quiescence, ISCP watermarks and embedded bootstrap/RPC paths. The target update brings #32629 fixture/endpoint corrections and #32550 scalar-CTE/ZoneMap changes; these are merged, not reimplemented in this PR. - After the new-base merge, all twelve original failed roots pass locally in Go 1.26.4 `-race -short -tags matrixone_test` mode; an audited exact-`af531771cc` Go-source overlay passes the same twelve roots. These Darwin/arm64 focused checks do not reproduce the concurrent Linux lane or establish that its causes are fixed/pre-existing/harmless. Snapshot checkpoint waiting is tracked separately in #32640; the ten-root bootstrap/RPC episode in #32641; ISCP watermark timing already has #32636/#32639. No assertions, timeouts or test-body retries are weakened here. - New-base planner, pSpool and readutil packages pass. The full compile package has three Parquet fanout-fixture failures, identically reproduced at exact target source; its new scalar-CTE tests pass. These are not masked or claimed as a whole-package pass (related historical CPU-capacity tracker #29637). Matching build, affected-package vet, pinned molint, incremental golangci-lint and `make err-check` pass. The initial local embedded run exceeded Darwin's Unix-socket path limit before SQL; a short task-owned TMPDIR fixes that precondition, and only the subsequent completed runs are counted. - Grouping BVT is rerun twice after this merge: 300/300 each, metadata enabled and no skips. All nine review/original result oracles pass again. No remote CI recovery is claimed; pushing this merged head schedules fresh CI rather than treating an isolated local pass as approval. - Test database cleanup is verified, and all task-owned services are stopped. **Review coordination:** Per request, the previous re-review request was withdrawn. This update does not request another review. Historical AI design review of v2 is recorded above; the editorial v3 update adds no approval claim. Maintainer design approval and independent acceptance remain pending. **Previously tracked limitation:** #32531 recorded the generic ordered-SUM CTAS failure on the earlier source baseline. After merging #32519, the exact `bf18d10904` and candidate controls both write the correct `(NULL,21,21),(1,12,33),(2,9,42)` rows. This improvement comes from the target base, not an extra generic SUM repair in this PR; the historical failing probes remain retained. **Separate known limitation:** #32549 tracks the pre-existing grouped SAMPLE passthrough-column execution panic. `SELECT g,h,SAMPLE(v,100 PERCENT) FROM src GROUP BY g` fails without any grouping extension on the original source baseline; the generic passthrough-input offset remains outside this repair (the required group-output ordinal correction does not repair that separate path). This is not counted as a passing test, nor fixed through a generic SAMPLE runtime/remapping change. Already-supported nongrouped passthrough is covered through repeated empty sets. **Separate known limitation:** #32595 tracks the generic binder selecting the wrong expression after SAMPLE (`SELECT SAMPLE(v,100 PERCENT),7 ...` repeats `v`). It independently reproduces without grouping on exact `bf18d10904`; the reversed projection order is a successful control. It is not repaired here. New literal/marker regressions place SAMPLE last so they test this PR's sort-origin boundary rather than that separate binder defect. **Scope and limits:** The PR diff does not include #32263's MARK optimization or #32264's general function/aggregate/window nullability redesign. The latest base includes #32315 and #32519; merge conflict resolution retains upstream's explicit nullability proofs plus the grouping/window consumer boundary, with no additional MARK changes here. Empty-input ROLLUP retains the existing zero-row behavior, cross-checked against MySQL 8.4.11. No operator lifecycle, wire/catalog format, or distributed-protocol changes are introduced. Validation is single-CN/local; no production replay, multi-CN/race claim, or remote CI result is claimed.
What type of PR is this?
Which issue(s) this PR fixes:
Fixes #32264.
Related to #32263. Its implementation from #32315 is now inherited from the updated
4.1.6-hotfixbase, not duplicated in this PR's diff.What this PR does / why we need it:
Non-NULL arguments do not prove that a function result is non-NULL. On the verified
4.1.6-hotfixbaseline (cbb7da471a495f21361fcfdc8fa715f6bdd346a0), division can lose its NULL group in GROUP BY/DISTINCT, while division, empty MAX, LAG/LEAD, REGEXP_SUBSTR, invalid UNHEX and missing-path JSON_EXTRACT can fail CTAS with error 3819.Validation
All reported checks used Go/gofmt 1.26.4 and matching local native artifacts. Follow-up validation was repeated after merging target commit
54feca6423(#32315); the PR diff remains limited to nullability inference and its regressions../pkg/sql/plan/function ./pkg/sql/plan, via the repository-supported CGo wrapper,-p=1 -count=1 -timeout=300s, with coverage../pkg/sql/colexec/group ./pkg/sql/colexec/window ./pkg/sql/colexec/aggexec, via the same wrapper, including-vet=all../pkg/sql/colexec/loopjoin ./pkg/vm/message ./pkg/common/malloc ./pkg/common/mpoolwith coverage: all passed.go vetand full configured golangci-lint v2.6.2, built with Go 1.26.4: passed, 0 lint issues. Formatting andgit diff --check: passed.test/distributed/cases/ddl/create_table_as_select.sql: results generated with mo-tester, inspected, and the full fixture compared twice: 1,284 successful, 0 failed, 30 pre-existing ignored statements on each run; no new skips. Only relevant generated checkpoints were retained, preserving unrelated legacy formatting and regex expectations. The owned service was stopped afterward.An initial mo-tester generation run used the wrong local instance and is excluded from this evidence. Reported BVT results were regenerated and verified after adding actual JDBC-address and owned-listener-PID checks. No claim of all-green CI is made; observed CI status and checkpoint synchronization are recorded below.
P1 review follow-up: bind outer-join output nullability before optimization
The original PR revision (
557103baa9) incorrectly inferredcoalesce(l.x,r.y)as non-NULL whenr.ywas a NOT NULL base column on the null-extended side of a LEFT JOIN. That allowed MARK-to-ANTI before final remapping corrected the output type. The subquery returned NULL, but NOT IN incorrectly returned42; the same query on the hotfix baseline retained MARK and returned no rows.The fix applies null extension at the binding-output ownership boundary, after binding the join's own ON/USING expressions and before building parent expressions. It does not special-case COALESCE/NOT IN or disable safe non-NULL proofs. Evidence:
42on the owned service; the corrected binary uses MARK and returns the empty result. Matched and empty-subquery controls return42as expected.test/distributed/cases/join/mark_membership.sql, the full loopjoin/message/allocator/mpool UTs, the P1 public witness, and the 23 compatibility check groups. The owned service was stopped and test databases were verified removed.P1 review follow-up: empty scalar-subquery results
On reviewed head
12da23a4fd, an empty scalar subquery inherited a NOT NULL projection type, although SQL returns NULL when the scalar subquery has zero rows.coalesce(x,(select y ...))could therefore trigger MARK-to-ANTI before remapping: both uncorrelated and correlated witnesses projected NULL but incorrectly returnedcount(*) = 1instead of 0. CTAS output metadata alone did not detect this optimization-time defect.hasSingleRow/LIMIT 1 proves at most one row, not existence. EXISTS keeps its separate non-NULL Boolean contract.(select 7)and truly non-NULL fallback can still retain the safe ANTI optimization. No expression is evaluated for a proof, and multi-row scalar errors remain unchanged.CI follow-up: synchronize existing metadata checkpoints
At
b1997fac1b, run 42986548206 passed the full UT, SCA and UT-coverage jobs, but both BVT jobs found four outdated DESC/SHOW assertions across three fixtures:information_schema.COLUMNS.IS_NULLABLEandCOLUMN_KEY, plusTABLES.TABLE_TYPE, are CASE expressions with non-NULL string results in every branch; their metadata now correctly reportsNO.YES, consistent with its missing-path NULL behavior. Added matched-value and missing-path-view value/metadata controls rather than weakening function inference to satisfy the old result.Only test inputs/results changed in this follow-up. Relevant checkpoints were regenerated with guarded mo-tester and independently reviewed; unrelated checkpoints, regex expectations and ignores were preserved. Each complete fixture passed twice on a fresh owned single-CN service:
database/system_table.sqlfunction/func_json_extract.testsystem_variable/system_variables.sqlCleanup left only built-in databases and the system account, and the owned service was stopped. Product/Go inputs did not change, so the exact-head UT/SCA evidence and existing changed-production coverage remain valid. The observed Coverage job was blocked at its BVT-success prerequisite, not a calculated coverage-threshold failure; the shared workflow explicitly permits UT-only profiles for this legacy non-main branch. Post-push CI still needs to recompute its verdict.
Release gate: nullable NOT IN / MARK
Correct nullable metadata changes the affected NOT IN plan from an incorrect ANTI path to MARK. The candidate correctly returns no rows when the subquery contains a generated NULL, but exposes the performance issue tracked by #32263.
Historical probe before merging #32315:
select count(*) from lhs where v not in (select 1/n from rhs), five warmed end-to-end measurements per size:These are local probes, not general benchmark claims. Historical candidate runtime grows approximately 3.86x when input size doubles. #32315 has since landed on the target branch and is included by merge for combined validation.
On the merged candidate (
12da23a4fd), the same warmed division/DOUBLE probe remains MARK and correct, with medians 92.759 ms / 350.500 ms for 3,000 / 6,000 rows. #32315 accelerates direct, same-type integer/Boolean column equality; this expression/DOUBLE query is outside its supported domain. Combined functional validation passed, but this measured performance risk still requires resolution or an explicit release decision before release; merging #32315 does not eliminate it. This PR does not restore unsound metadata to avoid MARK costs or expand the membership index's supported domain. ROLLUP/CUBE work remains excluded.