Repository navigation
fix(plan): reuse scalar CTEs under non-truncating limits - #32522
Conversation
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? |
|
Queue requested — the merge queue status continues in this comment ↓. |
|
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: 8eb50c2a0d5ef66df07aa6a277a46ecd63bf077b
Assessment: approve
The memoized structural bound narrowly extends the existing CTE drain proof. Retained evaluation, join and materialization guards preserve safety; boundary controls and public CTAS tests validate the intended reuse and scan reduction.
Model: gpt-6.1-sol / max
Session: 01a1a004-9884-72c0-ad39-f096c4209c4a · slot 1 · generation 0
Validation:
-
Reviewed the full delta, affected owners/consumers, all three discussion entries and the linked issue body/comment; discussion-assessment.json covers every indexed key.
-
Go 1.27.1/Linux amd64: pkg/sql/plan passed with -mod=readonly -count=1, including all three new test groups: 4,935 top-level and 19,361 subtests passed, with two existing unrelated skips. Receipt checks/1794414536672081083-3.json and planner-package.jsonl.
-
Explicit go vet ./pkg/sql/plan passed. Receipt checks/1794414760332748219-3.json.
-
Baseline behavioral control reproduced the intended optimization gap: six covering-limit cases failed for absent reuse, while three truncating-limit controls passed. Baseline source/probe hashes retained; receipt checks/1794414888750695169-3.json and baseline-boundary.jsonl.
-
Exact scalar_union_limit.sql passed normal mo-tester comparison twice on the same isolated instance: 29/29 each, document-level metadata comparison enabled, ISCP readiness observed and database teardown verified. Receipt checks/1794414911071621731-3.json, bvt.jsonl and bvt-run-{0,1}/report/report.txt.
-
Independent public EXPLAIN of the exact CTAS source SELECT showed one base scan versus four with the existing reuse-disable hint. scan-count-control.txt and validation-audit.json reconcile this result with frozen inputs and execution receipts.
Limitations:
- This validates the main-only planner change on a small fixture. The supplied evidence omits the linked production SQL attachment; production-scale latency, deployment and hotfix/backport outcomes were not verified.
🚫 Left the queue · pull request dequeued1 h in the queue, with no time running CI. So far
Reason Pull request #32522 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.
To get back in the queue
Merge conditions not met when it left the queue
Tick the box to put this pull request back in the merge queue (same as
2 merge conditions met
Times in UTC · dashboard · how the merge queue works |
## What type of PR is this? - [ ] API-change - [x] BUG - [ ] Improvement - [ ] Documentation - [ ] Feature - [ ] Test and CI - [ ] Code Refactoring ## Which issue(s) this PR fixes: Related to matrixorigin/matrixflow#21333. Branch-specific adaptation of #32522 for `4.2-dev`, **not a mechanical cherry-pick**. The mainline nested-CTE consumer-proof dependencies are intentionally not imported. ## What this PR does / why we need it: The two reported CTAS queries repeat an expensive aggregate through nested CTEs and scalar UNION ALL branches. On this branch, nested references and any consumer LIMIT prevent reuse; moreover, the existing reuse pass only runs at the SELECT entry point, not for CTAS's internal INSERT SELECT. - Admit one fixed-width scalar-aggregate producer only when its bound occurrences have identical semantics, every consumer executes, all published columns are genuinely demanded, and literal limits cannot truncate the structural row bound. - Preserve internal expression types and scan snapshots when comparing producers. Keep computed outer CTEs inline; reject joins, existing shared sources, unsupported windows, local filters, internal pagination, and uncertain evaluation domains in the new proof. - Trace live projection positions rather than counting references in dead/conditional expressions. Recognize the non-NULL numeric-literal-to-VARCHAR cast inserted by FORMAT without evaluating arbitrary constants. - Apply this restricted reuse to ordinary INSERT SELECT sources before adding target conversions or write nodes. Leave IGNORE, ODKU, REPLACE, RETURNING, and legacy fallback behavior unchanged. Preserve CTAS's HaveDDL/single-CN behavior, existing profitability/memory checks, and the materialized runtime. ### Validation - Go 1.26.4, native libraries built in the target worktree; full `pkg/sql/plan` tests and 18 targeted compiler/materialized-source tests pass. - Public planner regressions cover 2/4/8 branches, N−1/N/N+1 limits, live/dead column demand, unsafe shapes, producer identity, formatted metrics, and the **exact CreateAsSelectSql emitted by CTAS**. - New helper statement coverage: **80.75%**; changed profile-line coverage: **75.38%**. Matching-toolchain gofmt/vet and incremental golangci-lint 2.6.2 pass. - mo-tester-generated results were checked against the clean branch baseline: values, metadata, and expected errors are identical. New BVT passes twice (**35/35** each); the CTE directory passes **86/86**, with teardown checked. - Using the complete original SQL/DDL and 12 local synthetic rows: | Query | Baseline base-table scans | Patched base-table scans | | --- | ---: | ---: | | Eight-row chart | 8 | **1** | | Four-row comparison | 4 | **1** | Both source SELECT and executing CTAS-shaped INSERT SELECT plans have these counts. Actual CTAS outputs remain 8/4 rows, with business values and table metadata matching the branch baseline. Unordered row-number-to-metric assignment is not treated as deterministic. No production deployment or production-scale CTAS latency measurement was performed. This PR does not claim that the production incident is already resolved. Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com> Co-authored-by: XuPeng-SH <[email protected]>
…32550) ## What type of PR is this? - [ ] API-change - [x] BUG - [x] Improvement - [ ] Documentation - [ ] Feature - [ ] Test and CI - [ ] Code Refactoring ## Which issue(s) this PR fixes: Related to matrixorigin/matrixflow#21333 ## What this PR does / why we need it: Adapt two complementary optimizations to `4.1.6-hotfix`: reduce repeated scalar CTE computation, and admit safe ZoneMap pruning independently of estimated block selectivity. This is **a target-branch adaptation, not a pure cherry-pick**. The branch lacks the CTE-sharing prerequisite used by #32522. This PR supplies a deliberately restricted prerequisite and adapts its non-truncating LIMIT proof, rather than importing main's general CTE materialization/spill subsystem. The ZoneMap portion adapts the admission work from #32012/#32419, preserves the existing #32431 protections, and does not import partition behavior changes. ### Two separate commits 1. **Safe ZoneMap admission and reader protections** (`ce71f6e3bf`) - Admit stable direct-column comparisons/ranges even with unhelpful or missing statistics; preserve residual predicates and `blockFilter=2` disabling. - Normalize constant-on-left comparisons without mutating shared expressions. Fail open for missing summaries and avoid unsafe floating-key seek, early-stop, and raw-byte filtering paths. - Retain the previous admission policy for partition tables. 2. **Bounded scalar CTE sharing and LIMIT proof** (`9f19e6fb7c`) - Match the same CTE declaration and actual bound source, including snapshots, types, and column mappings. Require deterministic, data-error-free producers with structurally at most one fixed-width row. - Bound each query to one shared producer, 64 readers, 256 output columns, and 64 KiB of fixed-width output. Unsupported, correlated/recursive, volatile, early-stop, or otherwise unsafe shapes remain inline. - Admit a positive literal LIMIT only when it covers a structural scalar/UNION ALL row bound. Statistics, OFFSET, and LIMIT itself do not tighten that bound. - Gather the final scalar result on the coordinator, project the compact published schema, and remap each reader after pruning. Give each reader a private copy through existing connector/spool machinery before evaluating expressions: decimal casts can mutate input vector metadata. - Preserve CTAS `HaveDDL=true` and same-transaction visibility. Do not force CTAS onto multiple CNs, change terminal protocols, or add a materialized source, spill store, or cross-query cache. ### Validation Local validation used **Go 1.26.4**, worktree-built native libraries, the CGo test wrapper, and golangci-lint 2.14.0 built with Go 1.26.4. - Both complete incident queries, with their original schema and **12 synthetic rows**: base-table scans changed from **8/4 to 1/1**. Actual CTAS produced 8/4 rows; business values and `SHOW CREATE TABLE` matched the optimization-disabled controls. Unordered row-number assignments were not used as an equality oracle. - Two independent local CN processes: both complete source SELECTs returned matching results from either coordinator. Actual remote contribution was verified by zero local scan rows on one coordinator, nonempty producer merge input, and matching business results—not merely an `AP_MULTICN` label or a remote placeholder in EXPLAIN. - ZoneMap fixture: clustered ranges read **1 block / 2 rows**, versus **3 blocks / 6 rows** with filtering disabled. Interleaved ranges correctly retained all three blocks. Commuted comparisons preserved results. - New BVT results were generated with mo-tester and verified twice: **41/41** for scalar CTEs and **60/60** for ZoneMaps. Adjacent ordinary/recursive CTE, recursive INSERT, and legacy NaN cases also passed (**54 + 124 + 31 checks**, including the new CTE case in the first group; none ignored). - Planner tests cover 2/4/8-branch LIMIT boundaries, structural unknown/overflow/cycle controls, source identity, pruning, and unsafe-inline cases. Compiler/operator tests cover local/remote-shaped producers, reader vector isolation, success/error/cancellation, partial preparation/publication, and zero residual mpool usage. Targeted race checks passed. - `go vet`, incremental lint, gofmt, and diff checks passed. Changed-line coverage mapped through Go coverage blocks is **519/616 = 84.25%**; affected-block statement coverage is **434/505 = 85.94%**. **Known baseline test failures:** the initial related-package run hit these three Parquet tests. The same failures were reproduced on a clean `54feca6423` worktree with matching Go/native inputs. The subsequent related-package run passed while explicitly excluding only these tests; no test was disabled or weakened in the committed code: - `TestCompileExternScanParquetLoadUsesRowGroupFanoutWithEmptyFiles` - `TestCompileExternScanParquetRowGroupFanoutValidatesEmptyFileColumnCount` - `TestCompileExternScanParquetLoadUsesFileFanoutMainPath` The package selection covered planner, compiler, readutil, TAE index, dispatch, merge, connector, pSpool, and process. This is not a claim that the unfiltered full suite or CI is green. ### Limits of the evidence No production deployment, production CTAS/DML, or production-scale latency/throughput/memory acceptance was performed. The small local fixtures establish plan, result, metadata, and lifecycle behavior; they do not establish a production wall-clock speedup. Customer SQL, local evidence, credentials, and build/data artifacts are not included in this PR. ### P2 review follow-up: concurrent copying of a broadcast batch Addressed in [`c8e4f588b7`](c8e4f58), after merging latest target `bf18d10904` (nullability inference). - Confirmed the review finding: `GetCopiedBatch` moved `ExtraBuf` out of its source, so multiple reader connectors copying a broadcast batch raced even with nil metadata. Both a minimal spool regression and the real compiler/connector path failed under `-race -count=1`. This proves a data race, not an observed wrong SQL result or crash. - Fix the common copy owner with `slices.Clone(src.ExtraBuf)`. Source metadata is read-only; destinations own independent backing. No reader serialization, if-nil workaround, or terminal-protocol change. Nonempty metadata copying costs O(metadata bytes); the scalar fixed-width output bound is not a general bound on serialized metadata. - Regressions now run the **copy phase concurrently** rather than only modifying completed copies concurrently. Cover nil/empty/nonempty metadata, source preservation, non-aliasing, cache reuse, 4/8 real readers, error/cancellation/partial preparation/publication, and zero residual mpool usage. Each exact concurrency test passed **100 race repetitions**. - Spool/compiler owning normal/race checks passed with the same three previously disclosed unrelated Parquet failures explicitly excluded from compiler selection. Unfiltered runs retain those failures; no repository test was disabled or weakened. Connector/dispatch/process race, merged plan/function/group normal tests, vet and incremental lint passed. Changed-production line coverage against the latest base is **520/617 = 84.28%**; the copy fix is **1/1 = 100%**. - On a fresh local service, complete scalar CTE, ZoneMap and CTAS fixtures passed twice: **41**, **60**, and **1,284** successful checks respectively per round, with **30 pre-existing CTAS ignores** and zero failures. An initial CTAS run with an inappropriate private default database was excluded; the final runs used no JDBC default database, preserving privilege/no-database assertions without changing SQL/results. - Rebuilt and revalidated both complete incident queries on the merged base: one base scan each, actual CTAS 8/4 rows, matching business values and table metadata versus disabled-optimization controls, plus two-CN remote contribution/result checks. No production access or production-scale performance acceptance. Post-push CI and maintainer design approval are not claimed. ### Versioned design and approval status - **Repository design document:** [v3-public.3 — scalar CTE sharing and safe ZoneMap admission](https://github.com/matrixorigin/matrixone/blob/c8e4f588b798984c2068802a1d20c2f682972e1e/docs/design/CLAUDE_32550_scalar_cte_zonemap_design.md) (`docs/design/CLAUDE_32550_scalar_cte_zonemap_design.md`). This commit-pinned repository file is the authoritative design; the earlier v3-public.1 PR comment is historical, not the formal document location. - The document binds base `54feca6423`, implementation `9f19e6fb7c`, and expectation-only fix `35edb87c48`. Revision v3-public.2 moved the document into the repository; v3-public.3 adds the source-immutable metadata-copy contract, review regression, and merged-base validation in section 10. - Approval provenance: the requester approved local v3 with “go ahead” before implementation and authorized delivery with “go on”. These are private-session scope/implementation authorizations, **not a maintainer design approval**; no public link to that private exchange is claimed. - **Maintainer design approval: pending.** XuPeng-SH is requested as reviewer. Please review **v3-public.3 at the pinned repository revision** and record approval/requested changes on GitHub. Publishing the document does not itself close the design-gate blocker. - Review item 1 (EXPLAIN expectations) was addressed in `35edb87c48`: the 10 affected cases passed twice locally, each with 999 successes, zero failures, and eight unchanged pre-existing decimal ignores.
What type of PR is this?
Which issue(s) this PR fixes:
Related to https://github.com/matrixorigin/matrixflow/issues/21333.
What this PR does / why we need it:
The four-row metrics query in the linked incident repeats an expensive common aggregation across
UNION ALLbranches. On main, an outerLIMIT 4prevents CTE reuse even though the four scalar branches cannot produce more than four rows. The existing full-consumption proof conservatively treats this limit as potentially truncating the input.Extend that proof with a narrow structural row bound:
UNION ALLadds child bounds with overflow checks.This changes only planner admission. It does not introduce a new SQL rewrite, shared runtime, configuration or CTAS placement behavior.
Validation
On macOS arm64 with Go 1.27.1 and matching native artifacts:
pkg/sql/planpackage pass throughmo-cgo-testwith-count=1.go vet, incremental golangci-lint 2.14.0, formatting, and the service build pass.Using both complete incident SQL statements and the original table schema with 12 synthetic rows:
EXPLAIN ANALYZEconfirms the patched scan counts. Both actual local CTAS statements succeed, and their business values andSHOW CREATE TABLEoutput match the clean-main baseline. Assignment of unorderedROW_NUMBER()values to individual business rows is not treated as deterministic.This PR targets main only. It does not deploy or backport a production fix, and the small-data validation is not a production-scale latency benchmark.