Skip to content

fix(plan): reuse scalar CTEs under non-truncating limits - #32522

Merged
XuPeng-SH merged 5 commits into
matrixorigin:mainfrom
ck89119:issue-21333-main
Nov 11, 2026
Merged

XuPeng-SH merged 5 commits into
matrixorigin:mainfrom
ck89119:issue-21333-main

Conversation

@ck89119

@ck89119 ck89119 commented Nov 11, 2026

Copy link
Copy Markdown
Contributor

What type of PR is this?

  • API-change
  • BUG
  • Improvement
  • Documentation
  • Feature
  • Test and CI
  • Code Refactoring

Which issue(s) this PR fixes:

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 ALL branches. On main, an outer LIMIT 4 prevents 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:

  • A scalar aggregate contributes at most one row; projection, filter, ordinary window and sort preserve the bound; UNION ALL adds child bounds with overflow checks.
  • A positive literal limit covering the complete bound is non-truncating. Estimates, filters and limits themselves never tighten the structural bound, and OFFSET is not used to compensate for a smaller limit.
  • Unknown shapes retain the inline plan. Existing inner/zero/dynamic/session limit, conditional-join, evaluation-domain, output-demand, profitability and materialization-budget protections remain in place.

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:

  • The new 2/4/8-branch boundary regression fails on the unfixed planner for non-truncating limits and passes after the fix; smaller limits remain inline.
  • 110 focused CTE/grouping-set tests and the complete pkg/sql/plan package pass through mo-cgo-test with -count=1.
  • New structural-bound helper coverage is 100%; all 35 changed lines mapped to coverage blocks are covered.
  • go vet, incremental golangci-lint 2.14.0, formatting, and the service build pass.
  • The new SQL regression passes twice on the same isolated instance: 29/29 checks each time, with teardown verified. Related CTE regressions pass 124/124 checks. Coverage includes CTAS metadata, NULL/empty input, duplicate rows, OFFSET, dynamic/zero limits and observable overflow errors.

Using both complete incident SQL statements and the original table schema with 12 synthetic rows:

Source SELECT Main before Patched main
Four-row metrics comparison 4 base-table scans 1 base-table scan
Eight-row chart 1 base-table scan 1 base-table scan

EXPLAIN ANALYZE confirms the patched scan counts. Both actual local CTAS statements succeed, and their business values and SHOW CREATE TABLE output match the clean-main baseline. Assignment of unordered ROW_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.

@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 11, 2026 •

Copy link
Copy Markdown
Contributor

Queue requested — the merge queue status continues in this comment ↓.

@XuPeng-SH

XuPeng-SH commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor

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

Commit: 8eb50c2a0d5ef66df07aa6a277a46ecd63bf077b

Review completed. Read the assessment.

@XuPeng-SH XuPeng-SH left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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

Commit: 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.

@mergify mergify Bot added the queued label Nov 11, 2026
@mergify

mergify Bot commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor

🚫 Left the queue · pull request dequeued

1 h in the queue, with no time running CI.

So far

  • ✅ Entered the queue Wed 11 Nov, 16:41 · rule main · triggered by rule Automatic queue on approval for main
  • ⏹️ Testing stopped · in place
  • 🚫 Left the queue 17:40 · 3e89c06

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.

The author needs to enable "Allow edits from maintainers" on this pull request.

To get back in the queue

  • Push a change if one is needed: the pull request is queued again once its queue conditions match.
  • If no change is needed, tick the box below to queue it again as it is.

Merge conditions not met when it left the queue

  • any of · required by GitHub branch protection:
    • check-neutral = CI Required
    • check-skipped = CI Required
    • check-success = CI Required

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

  • Requeue this pull request
2 merge conditions met
  • #review-threads-unresolved = 0 · required by GitHub branch protection
  • github-review-approved · required by GitHub branch protection

Times in UTC · dashboard · how the merge queue works

@XuPeng-SH
XuPeng-SH merged commit 75b1ad8 into matrixorigin:main Nov 11, 2026
@mergify mergify Bot added dequeued and removed queued labels Nov 11, 2026
@ck89119
ck89119 deleted the issue-21333-main branch November 12, 2026 03:04
XuPeng-SH added a commit that referenced this pull request Nov 12, 2026
## 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]>
XuPeng-SH pushed a commit that referenced this pull request Nov 12, 2026
…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.

This branch was successfully deployed

No deployments
ci — 3e89c067 Deployed Nov 11, 2026 by mergify[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

dequeued kind/bug Something isn't working size/M Denotes a PR that changes [100,499] lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants