Skip to content

fix: reject a materialized CTE scan outside the continuation of its CTE - #27739

Draft
adriangb wants to merge 8 commits into
apache:mainfrom
adriangb:mcte-scan-scope
Draft

adriangb wants to merge 8 commits into
apache:mainfrom
adriangb:mcte-scan-scope

Conversation

@adriangb

Copy link
Copy Markdown
Contributor

Stacked on #27725 (which stacks on #27570). Only the last commit, 106714a91, belongs to this PR.

Which issue does this PR close?

Rationale for this change

A MaterializedCteScan reads the body of the MaterializedCte with its id by column position. The invariant check only validated the scans inside the continuation of their CTE. A scan in the body of its own CTE, beside the CTE, or in a subquery above it was never checked. prune_body_columns does not remap such a scan either. The physical binder binds scans by id over the whole plan, so such a scan could read the wrong columns.

No SQL query that we tried reaches this state today. The check makes a future optimizer rule that moves a scan out of scope fail loudly instead of returning wrong results.

What changes are included in this PR?

assert_materialized_cte_scans_are_valid now walks the plan with a scope stack:

Position of a scan of CTE N Result
In the continuation of N, also in a subquery expression Checked against the body of the innermost N
In the body of N, beside N, or above N Error: "is not in the continuation of the CTE"
N is not in the plan Allowed, so that a check on a part of a plan keeps working

The physical binder needs no change. MaterializedCteBinder::bind already calls check_body_schema before it binds a scan.

What is the testing strategy for this PR?

New unit tests in materialized_cte.rs build invalid plans by hand and assert the exact error:

  • check_invariants_rejects_a_scan_outside_the_continuation: a scan in its own body, beside its CTE, and in a subquery above its CTE. A scan in a subquery inside the continuation stays valid.
  • check_invariants_binds_a_scan_to_the_innermost_cte_with_its_id: two nested copies of a CTE with the same id and different body types.

The existing CTE sqllogictests pass.

Are there any user-facing changes?

No. Valid plans are unchanged. A plan with an out-of-scope scan now fails check_invariants at InvariantLevel::Executable.

🤖 Generated with Claude Code

adriangb and others added 8 commits November 20, 2026 00:13
A rule that builds a MaterializedCte with a struct literal or struct update
skips the scan check in try_new. Private fields send every new node through
try_new, and every in-place change through inputs_mut or with_new_inputs.

The fields are pub(crate), so the tree-node and display code of
datafusion-expr is unchanged. inputs_mut and into_inputs replace the
remaining direct field access in the optimizer and the physical planner.
Review asked that the unchecked mutation APIs keep room for future
validation. try_map_inputs_mut replaces inputs_mut and takes a fallible
closure, and with_new_inputs returns a Result. into_parts replaces
into_inputs and also returns the id and name, so that callers do not copy
the name before they consume the node.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The SQL planner allocated the id of a materialized CTE, built its
scans and kept a pending node until the continuation was planned. Any
other producer of the node has to repeat these steps and can bind a
scan to the wrong id.

Add MaterializedCteBuilder in datafusion-expr. It allocates the id,
hands out a scan for each reference, and builds the node from the
continuation. It is not Clone, so two nodes cannot share its id. The
SQL planner uses it in place of its own pending type. Add From impls
that wrap a MaterializedCte or a MaterializedCteScan in a LogicalPlan.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Type coercion, OptimizeProjections and the physical planner each change
the body of a materialized CTE together with its scans. Each repeated
the walk over the scans of the CTE, which must skip a nested occurrence
of the same CTE, and rebuilt the node from its parts. OptimizeProjections
also worked out which body columns to keep from the scan positions,
which are a detail of the representation.

Add these to datafusion-expr. They share one private scan traversal:

- MaterializedCte::with_coerced_body gives the scans the new types of
  a coerced body.
- MaterializedCte::prune_body_columns removes the body columns that no
  scan reads, and keeps one column if no scan reads a column.
- renumber_materialized_ctes gives each CTE in a plan a new id. A new
  id does not change a schema, so it does not check the scans again.

Add map_continuation and map_body for the rules that rewrite one input
(decorrelation, filter push down, OptimizeProjections). They check the
scans of the new node. The callers use these in place of into_parts
and try_new.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The only caller of MaterializedCte::try_map_inputs_mut is
map_children_mut in the optimizer, which does not care which input is
the body and which is the continuation. The closure could also change
the columns of the body without an error, and the scans would then read
the wrong columns.

Replace it with map_inputs_mut, which calls one closure for the body
and then for the continuation. It returns an error if the body changes
the names or the types of its columns. It skips the check when the
schema of the body is the same Arc. It does not check the continuation,
because the optimizer recomputes the schema of the node afterwards.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
With the builder and the coupled methods in place, no caller outside
datafusion-expr needs to build a node or a scan from its parts. A
public constructor lets a caller bind a scan to the wrong id or give a
scan a projection that does not match the body.

Make these crate-private: MaterializedCte::try_new, scans,
MaterializedCteScan::new, with_body_columns, with_body_schema,
check_body_schema, find_in, MaterializedCteId::next, and the id and
name fields of MaterializedCteScan. Remove into_parts. Rename
with_new_inputs to with_new_inputs_unchecked, which returns Self and
is crate-private. Its only caller is LogicalPlan::with_new_exprs.

The physical planner needs to know whether a CTE is read, so add
MaterializedCte::is_read. The module documentation says which APIs do
not check the scans, and that check_invariants is the backstop. The
OptimizeProjections tests build their plans with the builder. The
57.0.0 upgrade guide describes the new API.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Mechanical change: build a LogicalPlan from a MaterializedCte or a
MaterializedCteScan with the From impls in place of the nested enum
constructors. No behavior changes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The invariant check only validated the scans that `MaterializedCte::scans`
finds in the continuation of their CTE. A scan of the same id in the body of
its CTE, beside the CTE, or in a subquery above it was never checked, and
`prune_body_columns` does not remap it. The physical binder binds scans by
id over the whole plan, so such a scan could read the wrong columns.

The check now walks the plan with a scope stack. The id of a CTE is in scope
only in its continuation, and the innermost CTE with an id owns its scans.
A scan of a CTE that is in the plan must be in scope and match that body. A
scan whose CTE is not in the plan is still allowed, so that a check on a
part of a plan keeps working.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@github-actions github-actions Bot added documentation Improvements or additions to documentation sql SQL Planner logical-expr Logical plan and expressions optimizer Optimizer rules core Core DataFusion crate labels Nov 25, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

core Core DataFusion crate documentation Improvements or additions to documentation logical-expr Logical plan and expressions optimizer Optimizer rules sql SQL Planner

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant