Skip to content

feat(plan): add opt-in derived view query planning - #30551

Merged
mergify[bot] merged 20 commits into
matrixorigin:mainfrom
ck89119:issue-29438-main
Oct 21, 2026
Merged

mergify[bot] merged 20 commits into
matrixorigin:mainfrom
ck89119:issue-29438-main

Conversation

@ck89119

@ck89119 ck89119 commented Oct 19, 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:

Refs #29438 (S3 of #29433; builds on S1/S2).

What this PR does / why we need it:

Add an explicit, opt-in derived-View planning entry for SELECT, CTAS, and supported text/typed PREPARE statements. Persisted View columns no longer determine admission, binding, or CTAS metadata/default provenance in this path.

  • Bind real executable base-table subtrees; never reuse Describe's synthetic metadata-only memo scans for execution. Share the binder's placeholder classification with early numeric source collection, so unqualified DUAL is a value-only source while qualified db.dual remains a protected physical root.
  • Preserve explicit names, null-extension, existing CTAS default policy, publisher/snapshot identity, and transitive dependencies in CatalogDependencies / Prepare.Schemas. CTAS source binding inherits the caller's effective snapshot, while target existence checks and existing DDL invalidation rules remain unchanged. Reuse existing cache/reprepare validators rather than introducing durable invalidation.
  • Authorize root visibility before catalog probes, including PREPARE's pre-binding numeric metadata lookups. Authorization and resolution share the binding context's actual snapshot; skip optional probes when the context or a source/CTE time hint is unresolved. Preserve the first denial through optional inference without caching successful grants or exposing the private derivation marker to authorization SQL; keep final statement/plan execution authorization with the caller.
  • Deep-copy publisher identity in DeepCopyObjectRef and attach the effective publisher account to executable physical-table references and dependency copies; preserve request/plan ownership across cancellation and Close.
  • Keep ordinary cross-database intermediate Views distinct from resolved subscription entries: preserve dependency account evidence without inventing a View entry alias. Scope PREPARE's metadata-name probes to the View/CTE binding database, not the statement owner's default database. Numeric CTE references retain their declaration namespace; recursive projection/scalar probes and the propagation queue use the normal binder's findCTE, including ancestor declaration masks, instead of bypassing visibility through a flat numeric index. Normal and numeric registration share declaration-order construction, and target keys respect the binding comparison mode rather than unconditionally folding case.
  • Isolate trusted planner and subscription-metadata SQL from the outer derivation marker, including cloned historical transactions, so these catalog reads do not become user roots. Preserve cancellation, transaction/snapshot identity, and direct user-query authorization. Restore borrowed compiler snapshots on success/error/panic at both the CTE binding phase and request boundary; propagate the original panic without contaminating subsequent planning.
  • Extend unit and existing native fixtures for stale physical columns, nested views, CTAS, PREPARE/cache identity changes, subscriptions/history/RBAC, and upstream correlated-query main-output compatibility.

Implementation and consumer audit: S3 design.

Scope / rollout

Default SQL, PREPARE, and cursor routing is unchanged. The opt-in helper is not a replacement for frontend parameter normalization, retry/reprepare routing, stats/trace, final authorization, or protocol sending. This PR does not claim default binary/cursor activation or completion of S5/S6/S8/S9 validation and rollout gates. No background refresh, persistent freshness mechanism, cross-request cache, or independent CTAS semantics are added.

Validation

Validated after merging upstream main@76e152a1dd02b7875829027117a6f6344d1f8d33, using Go 1.27.1, darwin/arm64, and the repository CGo wrapper:

  • Focused View-schema/metadata/description UTs; complete pkg/sql/plan and pkg/frontend owning packages in normal mode; affected View-schema and snapshot/internal-SQL tests with -race.
  • CI run 39399062579 failed in TestCheckConstraintNamespace/repeatable_read_rejects_a_catalog_commit_after_its_snapshot: the old SI rejection succeeded, but the subsequent fresh-SI positive assertion encountered another valid namespace abort. Merged upstream test: fix transaction, context and resource ownership in UT fixtures #30670 rather than maintaining a duplicate fix. The exact failing subtest and complete CHECK namespace/recovery group pass locally with CI's matrixone_test, -short, and -race flags. The original fixed-snapshot rejection and terminal-error checks remain intact; local darwin/arm64 evidence is not a claim that a new full Linux CI run has passed.
  • Pseudo-table matrix: 32 cases across ordinary/direct/text/typed planning, no-FROM, DUAL case/quoting/aliases/CTE shadowing and qualified physical controls. Native coverage actually executes all eight no-FROM/DUAL mode combinations, returns one constant row, and rejects all four qualified-DUAL controls without weakening the authorizer.
  • Snapshot authorization/resolution matrix: 80 cases across ordinary/direct/text/typed entry points, historical-only/current-only policies, SELECT/CTAS, CTE SUM/AVG/chains and time hints; unknown binding scope performs no probe. Historical source dependencies are checked for current-domain contamination; CTAS target/catalog checks and its existing account-wide DDL marker explicitly retain their original semantics. Three additional CTE-scope cases verify inherited/declaration namespaces and explicit snapshot precedence. Native historical-only authorization covers SELECT, CTE SUM and CTAS planning in all four modes, retaining the pre-ALTER one-column schema rather than the current two-column schema.
  • CTE lexical-scope matrix: 44 cases across four modes, including later declarations, ancestor masks, shadowing, qualified controls, chains, body-local WITH and scalar consumers. No unused View may be authorized, resolved or captured as a dependency. Eight native executions cover shadowing and declaration order, producing SUM(id)=3 while permitting only the actually referenced View.
  • Case-sensitive roots: 28 cases across four modes, physical/quoted/qualified/scalar roots, actual CTE/parser-alias controls and lower_case_table_names=1 rejection controls. Eight duplicate-CTE cases reject without authorization/catalog probes.
  • Snapshot unwind/reuse: 16 cases across four modes, error/panic and nil/non-nil caller snapshots. Inject failure only after CTE binding publishes the historical domain, verify exact restoration and panic propagation, then authorize/resolve/plan the next root on the same request in the caller's original domain with no retained leases.
  • Explicit correlated-View main-output/deep-copy regression. Ordinary SELECT, direct prepared planning, text PREPARE, and typed PREPARE all reject with zero relation/database/subscription probes, preserve a one-shot denial, recover on a later planning call, and never enter a blocking catalog resolver. Denial/barrier, cancellation/Close, declaration/case and snapshot-unwind/reuse race cases repeated 100 times.
  • Two existing native integration fixtures, normal and -race: own-DDL/history/shared reads and subscription/history/role denial. Includes CTAS with an authorizer allowing only its source View, direct system-table user-query denial, and 18 actual ordinary/prepared-template executions across direct/nested/cross-database-intermediate/historical publisher sources, distinguished from subscriber rows/types; also validates ordinary and prepared CTAS planning through the cross-database intermediate View.
  • TestViewDescriptionPublicSQL: existing public SQL/binary PREPARE and empty-result metadata controls. These are compatibility controls, not proof that default binary routing uses S3.
  • Go 1.27.1 gofmt/vet; golangci-lint 2.14.0 built with Go 1.27.1, normal and integration-tagged scopes.
  • Modified-block statement coverage on the merged base: 312/331 = 94.26% (>75%). This CI follow-up adds no separate kernel/test patch beyond the upstream merge.
  • An earlier validation round hit the unrelated physical-write elapsed > 0 assertion. Restoring every local Go change to the pre-fix merged baseline through a verified Go overlay reproduced the same zero-duration failure; one subsequent complete owning-package run passed. The original failure and baseline evidence are retained, with no test skips or unrelated product changes.

No new BVT golden files: the new entry is internal/opt-in; native fixtures exercise it directly, and the existing public protocol regression checks the unchanged default path.

QA decision

QA is required before activation: tenant/snapshot isolation, CTAS provenance, and reusable-plan metadata are correctness-sensitive. Full cursor, multi-CN, mixed-version, performance, and rollout coverage remain separate gates; this PR does not waive them.

@XuPeng-SH

XuPeng-SH commented Oct 20, 2026 •

Copy link
Copy Markdown
Contributor

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

Commit: ab76739f6f15b52813b5f32ff45b37bc276e33a0

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: ab76739f6f15b52813b5f32ff45b37bc276e33a0

Assessment: request_changes

Reviewed the complete 14-file delta and surrounding owners. The opt-in design reasonably reuses the binder, request lifecycle and dependency validators. Current-head validation closes the historical snapshot concern, but confirms that prepared DUAL queries still receive incorrect physical-table authorization.

Model: gpt-6-astra / xhigh

Session: 01a13dcf-1517-7f90-b3f9-c5f9f9e7031b · slot 0 · generation 1

  • P2 pkg/sql/plan/query_builder.go:7247: Plan SELECT 1 AS one FROM dual through direct prepared planning, text PREPARE or typed PREPARE with a root authorizer that rejects physical-table access.
    Impact: A valid constant query fails authorization despite accessing no physical table. Classify unqualified DUAL before this optional metadata probe and skip its authorization/Resolve calls; preserve authorization for qualified db.dual and add regression controls for all entry modes.
    Evidence: buildTable classifies unqualified DUAL as a placeholder at line 12941, but this earlier probe invokes authorizeRoot and preserves its denial. Current-head planner and native frontend probes each reproduced failures in all three prepared modes. Ordinary DUAL and every no-FROM control passed with zero authorization calls; qualified-DUAL planner controls remained protected. See planner-focused.log/checks/1792474449941846879-5.json and native-focused.log/checks/1792474668506039562-3.json in the diagnostic directory.

Validation:

  • Evidence directory: /home/xupeng/.local/state/mo-bot/jobs/25361509bf0b50d1c13fb8af/attempt-1. review-evidence-audit.json reconciles commands, source fingerprints, native provenance, overlay hashes, logs and exit receipts. Source remained unchanged.

  • Isolation preflight and repository-owned native build passed. Tests used the supplied test-exec and assigned task caches.

  • Complete pkg/sql/plan and pkg/frontend suites passed with existing skips: owning-normal.log; receipt 1792474719170885978-3.json, exit 0.

  • Focused race tests passed, including planning cancellation, Close/BUSY, provider ownership and dependency invalidation: focused-race.log; receipt 1792474903656452737-3.json, exit 0.

  • Planner snapshot authorization tests and additional historical dependency probes passed across ordinary/direct/text/typed modes. The only failures in planner-focused.log were the three DUAL reproductions.

  • Both existing native fixtures passed, including own-DDL/history, publisher/subscriber execution, CTAS and role denial. Child ownership and cache invalidation tests also passed. The native command exited 1 solely because of the three DUAL reproductions.

  • Design, ownership, compatibility, test quality and performance analysis are retained in review-scope-notes.json.

Limitations:

  • local_validation contained no retained worker gates. Linked issue bodies were absent; requirements were assessed from the frozen PR evidence and versioned design contracts.

  • Native fixtures ran in normal mode; race validation covered focused planner/provider tests. Default activation, cursor, multi-CN and mixed-version rollout remain outside this opt-in scope.

  • No comparative performance benchmark was run. Opt-in rebinding and owned dependency copies add work; no speedup or comprehensive absence of regressions is claimed.

@XuPeng-SH

XuPeng-SH commented Oct 20, 2026 •

Copy link
Copy Markdown
Contributor

mo-bot review · mo-bot-xupeng · superseded

Commit: e25177d820ea73f79951ef6f28f540d2bb689862

"interrupted"

@XuPeng-SH

XuPeng-SH commented Oct 20, 2026 •

Copy link
Copy Markdown
Contributor

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

Commit: e25177d820ea73f79951ef6f28f540d2bb689862

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: e25177d820ea73f79951ef6f28f540d2bb689862

Assessment: request_changes

Reviewed the complete 14-file delta and surrounding owners. Reusing the existing binder, request lifecycle and dependency validators is sound. Current-head tests close the earlier DUAL and snapshot-probe concerns, but one reproducible panic/reuse defect remains.

Model: gpt-6-astra / xhigh

Session: 01a13dcf-1517-7f90-b3f9-c5f9f9e7031b · slot 0 · generation 1

  • P2 pkg/sql/plan/view_schema_planning.go:73: Reuse a ViewSchemaRequest after recovering a catalog panic while planning a historical View whose body contains a CTE.
    Impact: The compiler retains the historical snapshot. A subsequent query without a snapshot hint is authorized and planned in that historical domain, violating the documented recovery contract. Defer restoration of the compiler snapshot around BuildPlan, or make the temporary CTE snapshot change panic-safe.
    Evidence: bindNoRecursiveCte changes the compiler snapshot and restores it only on normal return; state.close restores context and leases, not snapshot. TestReviewViewSchemaPanicRestoresSnapshot reproduces historical authorization and CatalogDependencies on the next current query. Direct-source and existing Describe controls pass. See snapshot-reuse-controls.log and checks/1792482964607735872-4.json (exit 1).

Validation:

  • Artifacts: /home/xupeng/.local/state/mo-bot/jobs/118b37f03111da3a6cc2041e/attempt-1. validation-audit.json reconciles commands, fingerprints, logs, exits and probe hashes; review-scope-notes.json records design, ownership, performance and test analysis.

  • Isolation preflight, repository-owned native build and provenance verification passed. Tests used Go 1.27.1, Linux amd64, assigned caches and test-exec.

  • Complete pkg/sql/plan and pkg/frontend suites passed in normal and race modes, with existing skips. Receipts: 1792482840482793803-3.json and 1792483405223628918-3.json.

  • Cancellation/Close and denial-before-catalog tests each passed 100 race repetitions. Both native View-schema fixtures and TestViewDescriptionPublicSQL passed, covering publisher execution, history, CTAS, authorization and default-route compatibility.

  • Changed-file gofmt and whitespace checks passed. Final audit verified 11,617 tracked files and 190 native inputs; source remained unchanged. Audit receipt: 1792483450914463844-4.json, exit 0.

Limitations:

  • The finding concerns the reusable opt-in API and was demonstrated with an injected catalog panic; default SQL routing remains unchanged.

  • local_validation was empty and linked issue bodies were absent. Available contracts came from frozen PR evidence and versioned design documents.

  • No comparative performance benchmark or independent changed-code coverage percentage is claimed. Cursor, multi-CN, mixed-version and default-activation qualification remain separate rollout gates.

@XuPeng-SH

XuPeng-SH commented Oct 20, 2026 •

Copy link
Copy Markdown
Contributor

mo-bot review · mo-bot-xupeng · superseded

Commit: 6b518c7395ac842ec603c5ea1411b53b2c53229d

"interrupted"

@XuPeng-SH

XuPeng-SH commented Oct 20, 2026 •

Copy link
Copy Markdown
Contributor

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

Commit: 6b518c7395ac842ec603c5ea1411b53b2c53229d

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: 6b518c7395ac842ec603c5ea1411b53b2c53229d

Assessment: approve

Reviewed the complete 16-file delta and affected callers. The bounded opt-in design appropriately reuses the existing binder, request lifecycle and dependency validators. Validation closes the earlier DUAL authorization, historical snapshot and panic/reuse findings. No actionable blocker remains.

Model: gpt-6-astra / xhigh

Session: 01a13dcf-1517-7f90-b3f9-c5f9f9e7031b · slot 0 · generation 1

Validation:

  • Full planner and frontend suites passed normally and under race, with existing unrelated skips. The initial planner race run exceeded 300 seconds; its complete rerun passed in 483.6 seconds.

  • All 35 focused race tests passed. Denial-before-blocking-catalog and cancellation/Close tests each passed 100 race repetitions.

  • Both native integration fixtures passed, covering executable plans, publisher/subscriber identity, historical snapshots, CTAS and role denial. Separately selected TestViewDescriptionPublicSQL passed. Integration-tagged go vet passed.

  • Base/head benchmarks measured modest bookkeeping costs: one-CTE planning added approximately 1.4 KB and 7% median time; 32 CTEs added 10.6 KB and 3%. The 128-CTE case was approximately 17% faster. The no-CTE control added 32 bytes and one allocation.

  • Final audit verified 11,655 tracked files unchanged, 198 matching native build inputs and 46 native artifacts. Commands, overlays, logs and exit receipts are reconciled in /home/xupeng/.local/state/mo-bot/jobs/55ed4ec441040226da452b90/attempt-1/validation-audit.json; audit receipt checks/1792515978365042725-4.json exited zero.

Limitations:

  • Approval covers the explicit opt-in API. Default activation, cursor, multi-CN, mixed-version and comprehensive performance qualification remain separate rollout gates.

  • Native integration fixtures ran in normal mode; race evidence covers owning packages and focused lifecycle stress. Benchmarks measure narrow parser/planner workloads.

  • local_validation was empty and linked issue bodies were absent. Requirements were assessed from frozen PR evidence and versioned design contracts; author-reported raw validation was not treated as independently verified.

@mergify

mergify Bot commented Oct 21, 2026 •

Copy link
Copy Markdown
Contributor

Merge Queue Status

  • ✅ Entered queue — 2026-10-21 00:36 UTC · Rule: main · triggered by rule Automatic queue on approval for main
  • ✅ Checks passed · in-place
  • ✅ Merged — 2026-10-21 03:25 UTC · at a648b13e53cf0a07ff19211203a69e37b2d1dd93 · squash

This pull request spent 2 hours 49 minutes 16 seconds in the queue, including 54 minutes 30 seconds running CI.

Required conditions to merge

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

Independent deep re-review of exact head f59f8fe34652e4d795377336a6328b3a68c9126b, declared base/merge-base 63a964a82fbaae4759cfabb45655e0185bc0979c, against my prior reviewed head 9c5be2d0dc064b4b07345fdd80cbe3f781dcb62c.

Read every current changed hunk (16 files), all six historical reviews, all discussion/inline comments and both resolved threads. Re-reviewed the current S3 design amendment as a distinct phase and retained acceptance for the explicit bounded opt-in API only. No remaining blocking finding.

Both issues from my previous REQUEST_CHANGES are closed by implementation and independently executed current-head evidence: optional probes use the binding context's effective snapshot for authorization AND resolution/dependency capture, deferring unresolved time hints; unqualified DUAL shares the binder's placeholder classifier before physical authorization, while qualified DUAL remains protected. The ordinary/direct/text/typed matrix checks historical-only dependencies and nearest negative controls. The native fixtures actually execute all four DUAL modes and validate historical schema selection.

Also traced declaration-order/ancestor CTE masks, case-sensitive names, numeric propagation/scalar consumers, CTAS source-versus-target snapshot rules, trusted catalog SQL isolation, publisher execution/dependency identities, real executable subtrees versus description memo, and panic/error snapshot restoration before same-request reuse. Q1/Q2/Q3 remain closed: request owns child/leases, caller retains parent transaction and independent returned plan; Close cancels before waiting on its gate; per-request work/memo bounds remain, with no new global cache/background owner.

Fresh independent validation in detached exact-head worktree (Linux amd64, Go1.27.1, CGO enabled, own provenance-stamped make -j4 cgo, repository test wrapper):

  • Full pkg/sql/plan and pkg/frontend normal: PASS, 49.318s / 14.362s.
  • Full owning packages once under race: PASS, 199.914s / 25.725s.
  • Denial-before-blocking-catalog and cancel/Close: each exact root separately race PASS x100; measured T=.01s / below resolution, B=30s, capped N=100. No package-wide repeated stress.
  • Both integration-tagged native fixtures: PASS, 6.82s / 6.48s, covering actual publisher-specific values/types, subscription/history/RBAC, CTAS and request/parent ownership.
  • Separate actual pkg/tests/upgrade/TestViewDescriptionPublicSQL: PASS, 5.65s, default-route compatibility control only.
  • Integration-tagged owning-package -vet=all and git diff --check: PASS.

No source patches or temporary adversarial tests were needed this round. Full GitHub CI/coverage jobs were still pending at the final check, not counted as passing local evidence; no independently measured changed-code coverage or comparative performance claim. Approval does not activate default SQL/PREPARE/cursor routing or waive the separate multi-CN, mixed-version, performance and rollout gates.

This branch was previously deployed

1 inactive deployment
ci — f59f8fe3 Deployed Oct 21, 2026 by mergify[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

kind/bug Something isn't working kind/documentation Improvements or additions to documentation kind/feature kind/test-ci size/XXL Denotes a PR that changes 2000+ lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants