Repository navigation
Conversation
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>
adriangb
force-pushed
the
mcte-narrow-api
branch
from
November 25, 2026 05:43
51b71ce to
527849a
Compare
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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,
MaterializedCtestill exposestry_newandinto_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,OptimizeProjectionsand the physical planner each repeat this loop. A caller can also bind a scan to the wrong id, becauseMaterializedCteScan::new,MaterializedCteId::nextand the scanidfield 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?
MaterializedCteBuilderMaterializedCteBuilder::new(name, body),scan(&self)andbuild(self, continuation). It is notClone, so two nodes cannot share its id. The SQL planner uses it in place of its private pending type. Also addsFrom<MaterializedCte>andFrom<MaterializedCteScan>forLogicalPlan.with_coerced_body(type coercion),prune_body_columns()(OptimizeProjections, including the "keep at least one column" rule), and the plan-levelrenumber_materialized_ctes(physical planner). They share one private scan traversal.map_continuation(decorrelation, filter push down) andmap_body(OptimizeProjections) rewrite one input.try_map_inputs_mutwithmap_inputs_mutFnMut(&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 schemaArcis unchanged.try_new,scans,MaterializedCteScan::new,with_body_columns,with_body_schema,check_body_schema,find_in,MaterializedCteId::next, and the scanidandnamefields. Removesinto_parts.with_new_inputsbecomes the crate-privatewith_new_inputs_unchecked -> Self. AddsMaterializedCte::is_readfor the physical planner. Documents thatwith_new_exprsandmap_childrendo not check the scans, and thatcheck_invariantsis the backstop. Moves theOptimizeProjectionstests to the builder and updates the 57.0.0 upgrade guide.FromFromimpls in place of the nested enum constructors.Validation rules:
map_body,map_continuation,with_coerced_body,prune_body_columnsandMaterializedCteBuilder::buildcheck that every scan has the names and types of the body columns that it reads.map_inputs_mutchecks only the body, by names and types. It does not check the continuation, because the optimizer recomputes the schema of the node.renumber_materialized_ctesdoes not check the scans again, because a new id does not change a schema.Notes for review:
scans()is now crate-private, so the planner calls a new publicMaterializedCte::is_read() -> Result<bool>.push_down_filterbuilds the pushed filter withFilter::try_new, where it usedFilter::new. The filter then goes throughmap_continuation, which checks the scans.OptimizeProjectionsclones a built node and rewrites the continuation of the clone, which is how a cloned plan gets two occurrences of one id.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-optimizeranddatafusion-sql, and thecte*.sltsqllogictests. New tests:MaterializedCteBuilderdoctest.map_inputs_mut_rejects_a_body_with_other_columns.cargo clippy --all-targets --all-features -- -D warningspasses.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