Skip to content

refactor: narrow the public API of MaterializedCte - #27725

Draft
adriangb wants to merge 7 commits into
apache:mainfrom
adriangb:mcte-narrow-api
Draft

adriangb wants to merge 7 commits into
apache:mainfrom
adriangb:mcte-narrow-api

Conversation

@adriangb

@adriangb adriangb commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

Note

This PR stacks on #27570. Review only the last five commits. The earlier commits belong to #27570.

Which issue does this PR close?

Rationale for this change

After #27570, MaterializedCte still exposes try_new and into_parts. Every caller that changes the body has to walk the scans of the CTE in the continuation, skip a nested CTE with the same id, and rebuild the node. Type coercion, OptimizeProjections and the physical planner each repeat this loop. A caller can also bind a scan to the wrong id, because MaterializedCteScan::new, MaterializedCteId::next and the scan id field are public.

This PR moves the coupled body-and-scan operations onto MaterializedCte, so that the traversal lives in one place. It then makes the constructors crate-private.

What changes are included in this PR?

Commit Change
1. Add MaterializedCteBuilder MaterializedCteBuilder::new(name, body), scan(&self) and build(self, continuation). It is not Clone, so two nodes cannot share its id. The SQL planner uses it in place of its private pending type. Also adds From<MaterializedCte> and From<MaterializedCteScan> for LogicalPlan.
2. Own the coupled body and scan operations with_coerced_body (type coercion), prune_body_columns() (OptimizeProjections, including the "keep at least one column" rule), and the plan-level renumber_materialized_ctes (physical planner). They share one private scan traversal. map_continuation (decorrelation, filter push down) and map_body (OptimizeProjections) rewrite one input.
3. Replace try_map_inputs_mut with map_inputs_mut One FnMut(&mut LogicalPlan) closure, called for the body and then the continuation. It returns an error if the body changes the names or types of its columns, and skips the check when the schema Arc is unchanged.
4. Narrow the public API Makes these crate-private: try_new, scans, MaterializedCteScan::new, with_body_columns, with_body_schema, check_body_schema, find_in, MaterializedCteId::next, and the scan id and name fields. Removes into_parts. with_new_inputs becomes the crate-private with_new_inputs_unchecked -> Self. Adds MaterializedCte::is_read for the physical planner. Documents that with_new_exprs and map_children do not check the scans, and that check_invariants is the backstop. Moves the OptimizeProjections tests to the builder and updates the 57.0.0 upgrade guide.
5. Wrap nodes with From Mechanical: uses the From impls in place of the nested enum constructors.

Validation rules:

  • map_body, map_continuation, with_coerced_body, prune_body_columns and MaterializedCteBuilder::build check that every scan has the names and types of the body columns that it reads.
  • map_inputs_mut checks only the body, by names and types. It does not check the continuation, because the optimizer recomputes the schema of the node.
  • renumber_materialized_ctes does not check the scans again, because a new id does not change a schema.

Notes for review:

  • The physical planner skips a CTE that nothing reads. scans() is now crate-private, so the planner calls a new public MaterializedCte::is_read() -> Result<bool>.
  • push_down_filter builds the pushed filter with Filter::try_new, where it used Filter::new. The filter then goes through map_continuation, which checks the scans.
  • The nested same-id test in OptimizeProjections clones a built node and rewrites the continuation of the clone, which is how a cloned plan gets two occurrences of one id.
  • This PR does not check scans that are outside the continuation of their CTE. That is a separate follow-up.

What is the testing strategy for this PR?

This is a refactor, so the existing tests cover it. That means the unit tests of datafusion-expr, datafusion-optimizer and datafusion-sql, and the cte*.slt sqllogictests. New tests:

  • The MaterializedCteBuilder doctest.
  • map_inputs_mut_rejects_a_body_with_other_columns.

cargo clippy --all-targets --all-features -- -D warnings passes.

Are there any user-facing changes?

Yes, an API change to MaterializedCte, which is new in 57.0.0 and not released yet. The upgrade guide describes the new API.

🤖 Generated with Claude Code

adriangb and others added 2 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>
@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 24, 2026
adriangb and others added 5 commits November 24, 2026 23:30
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>
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