From 6b0743fec28a9cf18319fde31cb693acf3237248 Mon Sep 17 00:00:00 2001 From: Adrian Garcia Badaracco <1755071+adriangb@users.noreply.github.com> Date: Wed, 18 Nov 2026 14:29:49 -0600 Subject: [PATCH 01/12] refactor: make the fields of MaterializedCte private 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. The fields are pub(crate), so the tree-node and display code of datafusion-expr is unchanged. try_map_inputs_mut and into_parts replace the remaining direct field access in the optimizer and the physical planner. Later commits in this PR replace these interim hooks with checked methods. Co-Authored-By: Claude Opus 5.5 --- datafusion/core/src/physical_planner.rs | 21 +++++---- .../expr/src/logical_plan/materialized_cte.rs | 47 +++++++++++++++---- datafusion/expr/src/logical_plan/plan.rs | 12 ++--- .../optimizer/src/analyzer/type_coercion.rs | 20 ++++---- datafusion/optimizer/src/decorrelate.rs | 16 ++++--- .../optimizer/src/optimize_projections/mod.rs | 9 +--- datafusion/optimizer/src/optimizer.rs | 19 ++++---- datafusion/optimizer/src/push_down_filter.rs | 11 +++-- .../library-user-guide/upgrading/57.0.0.md | 27 ----------- 9 files changed, 90 insertions(+), 92 deletions(-) diff --git a/datafusion/core/src/physical_planner.rs b/datafusion/core/src/physical_planner.rs index 946962e2a95f8..f04498c1ac0c1 100644 --- a/datafusion/core/src/physical_planner.rs +++ b/datafusion/core/src/physical_planner.rs @@ -274,15 +274,15 @@ fn renumber_materialized_ctes(plan: &LogicalPlan) -> Result> let LogicalPlan::MaterializedCte(MaterializedCtePlan::Cte(cte)) = node else { return Ok(Transformed::no(node)); }; - let old_id = cte.id; let new_id = MaterializedCteId::next(); - let continuation = Arc::unwrap_or_clone(cte.continuation) + let (old_id, name, body, continuation) = cte.into_parts(); + let continuation = Arc::unwrap_or_clone(continuation) .transform_down_with_subqueries(|node| match node { // A nested occurrence of the same CTE owns the scans below // it, and is renumbered on its own. LogicalPlan::MaterializedCte(MaterializedCtePlan::Cte( ref nested, - )) if nested.id == old_id => { + )) if nested.id() == old_id => { Ok(Transformed::new(node, false, TreeNodeRecursion::Jump)) } LogicalPlan::MaterializedCte(MaterializedCtePlan::Scan(mut scan)) @@ -297,11 +297,12 @@ fn renumber_materialized_ctes(plan: &LogicalPlan) -> Result> })? .data; Ok(Transformed::yes(LogicalPlan::MaterializedCte( - MaterializedCtePlan::Cte(MaterializedCte { - id: new_id, - continuation: Arc::new(continuation), - ..cte - }), + MaterializedCtePlan::Cte(MaterializedCte::try_new( + new_id, + name, + body, + Arc::new(continuation), + )?), ))) }) .map(|t| Some(t.data)) @@ -2044,11 +2045,11 @@ impl DefaultPhysicalPlanner { if body.boundedness().is_unbounded() { return plan_err!( "MATERIALIZED CTE {} reads an unbounded source, which cannot be materialized", - cte.name + cte.name() ); } let buffer = - Arc::new(MaterializedCteBuffer::new(cte.id.as_u64(), &cte.name)); + Arc::new(MaterializedCteBuffer::new(cte.id().as_u64(), cte.name())); Arc::new(MaterializedCteExec::new(body, continuation, buffer)) } diff --git a/datafusion/expr/src/logical_plan/materialized_cte.rs b/datafusion/expr/src/logical_plan/materialized_cte.rs index 4df766bae5eb8..199651d0c50b9 100644 --- a/datafusion/expr/src/logical_plan/materialized_cte.rs +++ b/datafusion/expr/src/logical_plan/materialized_cte.rs @@ -82,13 +82,13 @@ pub enum MaterializedCtePlan { #[derive(Debug, Clone, PartialEq, Eq, Hash)] pub struct MaterializedCte { /// Binds the scans in `continuation` to this node - pub id: MaterializedCteId, + pub(crate) id: MaterializedCteId, /// Name of the CTE, used for display and error messages only - pub name: String, + pub(crate) name: String, /// The body of the CTE - pub cte: Arc, + pub(crate) cte: Arc, /// The query that declared the CTE and reads it - pub continuation: Arc, + pub(crate) continuation: Arc, } impl MaterializedCte { @@ -151,19 +151,46 @@ impl MaterializedCte { MaterializedCteScan::find_in(&self.continuation, self.id) } - /// Return a node with the same id and name, and new inputs. The schemas - /// of the scans are not checked again. + /// Call `f` with the body and the continuation, in this order, so that a + /// rule can change them in place. Return the result of `f`. + /// + /// The schemas of the scans are not checked again. The signature lets a + /// later version validate the new inputs and return an error. + pub fn try_map_inputs_mut( + &mut self, + f: impl FnOnce(&mut Arc, &mut Arc) -> Result, + ) -> Result { + f(&mut self.cte, &mut self.continuation) + } + + /// The id, the name, the body and the continuation, in this order. Build + /// a node again with [`Self::try_new`]. + pub fn into_parts( + self, + ) -> ( + MaterializedCteId, + String, + Arc, + Arc, + ) { + (self.id, self.name, self.cte, self.continuation) + } + + /// Return a new node with the same id and name, and new inputs. + /// + /// The schemas of the scans are not checked again. The signature lets a + /// later version validate the new inputs and return an error. pub fn with_new_inputs( &self, cte: Arc, continuation: Arc, - ) -> Self { - Self { + ) -> Result { + Ok(Self { id: self.id, name: self.name.clone(), cte, continuation, - } + }) } } @@ -746,7 +773,7 @@ mod tests { // `with_new_inputs` does not check the scans, so a rule can build // this plan. The invariant check rejects it. let invalid = cte - .with_new_inputs(body(DataType::Int32), Arc::new(scan(id, DataType::Utf8))); + .with_new_inputs(body(DataType::Int32), Arc::new(scan(id, DataType::Utf8)))?; let invalid = LogicalPlan::MaterializedCte(MaterializedCtePlan::Cte(invalid)); let err = invalid .check_invariants(InvariantLevel::Executable) diff --git a/datafusion/expr/src/logical_plan/plan.rs b/datafusion/expr/src/logical_plan/plan.rs index 8bc9be1227b49..3f48a0c9f67c0 100644 --- a/datafusion/expr/src/logical_plan/plan.rs +++ b/datafusion/expr/src/logical_plan/plan.rs @@ -530,11 +530,9 @@ impl LogicalPlan { LogicalPlan::Subquery(Subquery { subquery, .. }) => vec![subquery], LogicalPlan::SubqueryAlias(SubqueryAlias { input, .. }) => vec![input], LogicalPlan::Extension(extension) => extension.node.inputs(), - LogicalPlan::MaterializedCte(MaterializedCtePlan::Cte(MaterializedCte { - cte, - continuation, - .. - })) => vec![cte, continuation], + LogicalPlan::MaterializedCte(MaterializedCtePlan::Cte(cte)) => { + vec![cte.body(), cte.continuation()] + } LogicalPlan::MaterializedCte(MaterializedCtePlan::Scan(_)) => vec![], LogicalPlan::Union(Union { inputs, .. }) => { inputs.iter().map(|arc| arc.as_ref()).collect() @@ -673,7 +671,7 @@ impl LogicalPlan { } // A materialized CTE outputs the output of its continuation. LogicalPlan::MaterializedCte(MaterializedCtePlan::Cte(cte)) => { - cte.continuation.head_output_expr() + cte.continuation().head_output_expr() } LogicalPlan::Extension(_) | LogicalPlan::MaterializedCte(MaterializedCtePlan::Scan(_)) => Ok(None), @@ -1234,7 +1232,7 @@ impl LogicalPlan { self.assert_no_expressions(expr)?; let (body, continuation) = self.only_two_inputs(inputs)?; Ok(LogicalPlan::MaterializedCte(MaterializedCtePlan::Cte( - cte.with_new_inputs(Arc::new(body), Arc::new(continuation)), + cte.with_new_inputs(Arc::new(body), Arc::new(continuation))?, ))) } LogicalPlan::MaterializedCte(MaterializedCtePlan::Scan(_)) => { diff --git a/datafusion/optimizer/src/analyzer/type_coercion.rs b/datafusion/optimizer/src/analyzer/type_coercion.rs index faf7531496291..aa4b5124c48b7 100644 --- a/datafusion/optimizer/src/analyzer/type_coercion.rs +++ b/datafusion/optimizer/src/analyzer/type_coercion.rs @@ -128,21 +128,23 @@ fn coerce_plan_and_subqueries( // of a `NULL` column of a `UNION`. Coerce the body first, and give // its new schema to the scans before the continuation is coerced. LogicalPlan::MaterializedCte(MaterializedCtePlan::Cte(cte)) => { + let (id, name, body, continuation) = cte.into_parts(); let body = - coerce_plan_and_subqueries(Arc::unwrap_or_clone(cte.cte), config)?; + coerce_plan_and_subqueries(Arc::unwrap_or_clone(body), config)?; let continuation = with_materialized_cte_scan_schema( - Arc::unwrap_or_clone(cte.continuation), - cte.id, + Arc::unwrap_or_clone(continuation), + id, body.schema(), )?; let continuation = coerce_plan_and_subqueries(continuation, config)?; Ok(Transformed::new( LogicalPlan::MaterializedCte(MaterializedCtePlan::Cte( - MaterializedCte { - cte: Arc::new(body), - continuation: Arc::new(continuation), - ..cte - }, + MaterializedCte::try_new( + id, + name, + Arc::new(body), + Arc::new(continuation), + )?, )), true, TreeNodeRecursion::Jump, @@ -173,7 +175,7 @@ fn with_materialized_cte_scan_schema( .transform_down_with_subqueries(|node| match node { // A nested occurrence of the same CTE owns the scans below it. LogicalPlan::MaterializedCte(MaterializedCtePlan::Cte(ref nested)) - if nested.id == id => + if nested.id() == id => { Ok(Transformed::new(node, false, TreeNodeRecursion::Jump)) } diff --git a/datafusion/optimizer/src/decorrelate.rs b/datafusion/optimizer/src/decorrelate.rs index efbfa00776743..27af421812e54 100644 --- a/datafusion/optimizer/src/decorrelate.rs +++ b/datafusion/optimizer/src/decorrelate.rs @@ -238,7 +238,7 @@ impl TreeNodeRewriter for PullUpCorrelatedExpr { Ok(Transformed::new(plan, false, TreeNodeRecursion::Jump)) } LogicalPlan::MaterializedCte(MaterializedCtePlan::Cte(ref cte)) - if !cte.cte.all_out_ref_exprs().is_empty() => + if !cte.body().all_out_ref_exprs().is_empty() => { // A correlated body would have to run once per outer row. Ok(self.stop_pull_up(plan)) @@ -246,14 +246,16 @@ impl TreeNodeRewriter for PullUpCorrelatedExpr { LogicalPlan::MaterializedCte(MaterializedCtePlan::Cte(cte)) => { // Only the continuation can hold correlated expressions. Rewrite // it alone, so that the body shared by every scan keeps its schema. - let continuation = - Arc::unwrap_or_clone(cte.continuation).rewrite(self)?; + let (id, name, body, continuation) = cte.into_parts(); + let continuation = Arc::unwrap_or_clone(continuation).rewrite(self)?; Ok(Transformed::new( LogicalPlan::MaterializedCte(MaterializedCtePlan::Cte( - MaterializedCte { - continuation: Arc::new(continuation.data), - ..cte - }, + MaterializedCte::try_new( + id, + name, + body, + Arc::new(continuation.data), + )?, )), continuation.transformed, TreeNodeRecursion::Jump, diff --git a/datafusion/optimizer/src/optimize_projections/mod.rs b/datafusion/optimizer/src/optimize_projections/mod.rs index f8b997f82b964..6d1f550b77416 100644 --- a/datafusion/optimizer/src/optimize_projections/mod.rs +++ b/datafusion/optimizer/src/optimize_projections/mod.rs @@ -528,12 +528,7 @@ fn optimize_materialized_cte( config: &dyn OptimizerConfig, indices: RequiredIndices, ) -> Result> { - let MaterializedCte { - id, - name, - cte: body, - continuation, - } = cte; + let (id, name, body, continuation) = cte.into_parts(); // The output is the output of the continuation, so the continuation // needs what the parent needs. let continuation = @@ -578,7 +573,7 @@ fn optimize_materialized_cte( // A nested occurrence of the same CTE has its own body and // owns the scans below it. LogicalPlan::MaterializedCte(MaterializedCtePlan::Cte(ref nested)) - if nested.id == id => + if nested.id() == id => { Ok(Transformed::new(node, false, TreeNodeRecursion::Jump)) } diff --git a/datafusion/optimizer/src/optimizer.rs b/datafusion/optimizer/src/optimizer.rs index fdf5e5bbb1bf8..7e738809fac98 100644 --- a/datafusion/optimizer/src/optimizer.rs +++ b/datafusion/optimizer/src/optimizer.rs @@ -24,8 +24,8 @@ use datafusion_expr::logical_plan::LogicalPlan; use datafusion_expr::{ Aggregate, Analyze, CreateMemoryTable, CreateView, DdlStatement, Distinct, DistinctOn, DmlStatement, Explain, Expr, Extension, Filter, Join, Limit, - MaterializedCte, MaterializedCtePlan, Projection, RecursiveQuery, Repartition, Sort, - Statement, Subquery, SubqueryAlias, Union, Unnest, Window, + MaterializedCtePlan, Projection, RecursiveQuery, Repartition, Sort, Statement, + Subquery, SubqueryAlias, Union, Unnest, Window, }; use crate::common_subexpr_eliminate::CommonSubexprEliminate; @@ -467,15 +467,12 @@ fn map_children_mut Result>( let r = f(Arc::make_mut(recursive_term))?; s || r } - LogicalPlan::MaterializedCte(MaterializedCtePlan::Cte(MaterializedCte { - cte, - continuation, - .. - })) => { - let b = f(Arc::make_mut(cte))?; - let c = f(Arc::make_mut(continuation))?; - b || c - } + LogicalPlan::MaterializedCte(MaterializedCtePlan::Cte(cte)) => cte + .try_map_inputs_mut(|cte, continuation| { + let b = f(Arc::make_mut(cte))?; + let c = f(Arc::make_mut(continuation))?; + Ok(b || c) + })?, LogicalPlan::Statement(Statement::Prepare(p)) => f(Arc::make_mut(&mut p.input))?, LogicalPlan::Extension(Extension { node }) => { let inputs = node.inputs(); diff --git a/datafusion/optimizer/src/push_down_filter.rs b/datafusion/optimizer/src/push_down_filter.rs index 892941d66d6b8..63637a41261a3 100644 --- a/datafusion/optimizer/src/push_down_filter.rs +++ b/datafusion/optimizer/src/push_down_filter.rs @@ -1414,10 +1414,13 @@ impl OptimizerRule for PushDownFilter { // The output is the output of the continuation, so the filter // moves onto the continuation. The body is shared by every scan // of the CTE and is never filtered for one of them. - cte.continuation = Arc::new(LogicalPlan::Filter(Filter::new( - filter.predicate, - cte.continuation, - ))); + cte.try_map_inputs_mut(|_, continuation| { + *continuation = Arc::new(LogicalPlan::Filter(Filter::new( + filter.predicate, + Arc::clone(continuation), + ))); + Ok(()) + })?; Ok(Transformed::yes(LogicalPlan::MaterializedCte( MaterializedCtePlan::Cte(cte), ))) diff --git a/docs/source/library-user-guide/upgrading/57.0.0.md b/docs/source/library-user-guide/upgrading/57.0.0.md index 7b90380a3cb9b..8e5a74ba250f3 100644 --- a/docs/source/library-user-guide/upgrading/57.0.0.md +++ b/docs/source/library-user-guide/upgrading/57.0.0.md @@ -228,33 +228,6 @@ let statistics = Statistics::new_unknown(&self.schema()) .with_num_rows(Precision::Exact(num_rows)); ``` -### Materialized CTE scans have a projection - -`MaterializedCteScan` and `MaterializedCteScanExec` have a `projection`. It gives -the indexes of the columns of the CTE body that the scan outputs. `None` means all -the columns. `OptimizeProjections` uses it to remove from the body the columns -that no scan reads. - -A custom optimizer rule that changes the schema of the body of a -`MaterializedCte` must also change the `projection` of every scan of that CTE, -because a scan reads the columns of the body by position. Use -`MaterializedCteScan::with_body_columns` to remap a scan, and -`MaterializedCteScan::with_body_schema` to give a scan the new types of the -columns that it reads. - -The `schema` and `projection` fields of `MaterializedCteScan` are private, so -that the two always match. Read them with `MaterializedCteScan::schema` and -`MaterializedCteScan::projection`. Build a scan with `MaterializedCteScan::new` -and `MaterializedCteScan::with_projection`. To build a physical scan with a -projection, use `MaterializedCteScanExec::with_body_projection`. It returns an -error if the projection does not have one index for each column of the scan -schema. - -`LogicalPlan::check_invariants` checks that each scan of a `MaterializedCte` -has the names and types of the columns that it reads from the body. The -optimizer runs this check after each rule in debug builds, so a custom rule -that does not remap the scans now fails with an error that names the rule. - ### Null-aware sort-merge joins add a protobuf field `SortMergeJoinExec` now supports null-aware (`NOT IN`) semantics for From f42f5e83922bbfbcb97c2f62a03d6731e739d2b1 Mon Sep 17 00:00:00 2001 From: Adrian Garcia Badaracco <1755071+adriangb@users.noreply.github.com> Date: Tue, 24 Nov 2026 23:30:24 -0600 Subject: [PATCH 02/12] refactor: add MaterializedCteBuilder 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 --- .../expr/src/logical_plan/materialized_cte.rs | 72 +++++++++++++++++++ datafusion/expr/src/logical_plan/mod.rs | 3 +- datafusion/sql/src/cte.rs | 43 ++--------- datafusion/sql/src/query.rs | 2 +- 4 files changed, 80 insertions(+), 40 deletions(-) diff --git a/datafusion/expr/src/logical_plan/materialized_cte.rs b/datafusion/expr/src/logical_plan/materialized_cte.rs index 199651d0c50b9..5338df00777c2 100644 --- a/datafusion/expr/src/logical_plan/materialized_cte.rs +++ b/datafusion/expr/src/logical_plan/materialized_cte.rs @@ -91,6 +91,78 @@ pub struct MaterializedCte { pub(crate) continuation: Arc, } +/// Builds a [`MaterializedCte`]: the body first, then one +/// [`MaterializedCteScan`] for each reference to the CTE, then the +/// continuation that holds the references. +/// +/// The builder allocates the id that binds the scans to the node. It is not +/// `Clone`, so two nodes built from it cannot share an id. +/// +/// ``` +/// # use std::sync::Arc; +/// # use datafusion_common::{DFSchema, Result}; +/// # use datafusion_expr::{EmptyRelation, LogicalPlan, MaterializedCteBuilder}; +/// # fn main() -> Result<()> { +/// let body = LogicalPlan::EmptyRelation(EmptyRelation { +/// produce_one_row: true, +/// schema: Arc::new(DFSchema::empty()), +/// }); +/// let builder = MaterializedCteBuilder::new("c", body); +/// let continuation = LogicalPlan::from(builder.scan()); +/// let cte = builder.build(continuation)?; +/// assert_eq!(cte.name(), "c"); +/// # Ok(()) +/// # } +/// ``` +#[derive(Debug)] +pub struct MaterializedCteBuilder { + id: MaterializedCteId, + name: String, + body: Arc, +} + +impl MaterializedCteBuilder { + /// Start a materialized CTE with the name `name` and the body `body`. + pub fn new(name: impl Into, body: LogicalPlan) -> Self { + Self { + id: MaterializedCteId::next(), + name: name.into(), + body: Arc::new(body), + } + } + + /// A scan of all the columns of the body. Call this once for each + /// reference to the CTE in the continuation. + pub fn scan(&self) -> MaterializedCteScan { + MaterializedCteScan::new( + self.id, + self.name.clone(), + Arc::clone(self.body.schema()), + ) + } + + /// Build the node that computes the body once and evaluates + /// `continuation`. + /// + /// Returns an error if a scan of this CTE in `continuation` does not have + /// the names and types of the columns of the body that it reads. + pub fn build(self, continuation: LogicalPlan) -> Result { + MaterializedCte::try_new(self.id, self.name, self.body, Arc::new(continuation)) + } +} + +impl From for LogicalPlan { + fn from(cte: MaterializedCte) -> Self { + LogicalPlan::MaterializedCte(MaterializedCtePlan::Cte(cte)) + } +} + +impl From for LogicalPlan { + fn from(scan: MaterializedCteScan) -> Self { + LogicalPlan::MaterializedCte(MaterializedCtePlan::Scan(scan)) + } +} + impl MaterializedCte { /// Create a new node. /// diff --git a/datafusion/expr/src/logical_plan/mod.rs b/datafusion/expr/src/logical_plan/mod.rs index 5191b78392778..3f2ff110f8265 100644 --- a/datafusion/expr/src/logical_plan/mod.rs +++ b/datafusion/expr/src/logical_plan/mod.rs @@ -50,5 +50,6 @@ pub use display::display_schema; pub use extension::{UserDefinedLogicalNode, UserDefinedLogicalNodeCore}; pub use materialized_cte::{ - MaterializedCte, MaterializedCteId, MaterializedCtePlan, MaterializedCteScan, + MaterializedCte, MaterializedCteBuilder, MaterializedCteId, MaterializedCtePlan, + MaterializedCteScan, }; diff --git a/datafusion/sql/src/cte.rs b/datafusion/sql/src/cte.rs index bc36cf0203b96..9a8a913dd5065 100644 --- a/datafusion/sql/src/cte.rs +++ b/datafusion/sql/src/cte.rs @@ -12,38 +12,16 @@ use datafusion_common::{ tree_node::{TreeNode, TreeNodeRecursion}, }; use datafusion_expr::{ - LogicalPlan, LogicalPlanBuilder, MaterializedCte, MaterializedCteId, - MaterializedCtePlan, MaterializedCteScan, TableSource, + LogicalPlan, LogicalPlanBuilder, MaterializedCteBuilder, TableSource, }; use sqlparser::ast::{CteAsMaterialized, Ident, Query, SetExpr, SetOperator, With}; -/// A `WITH x AS MATERIALIZED (...)` CTE whose body must wrap the query that -/// declared it. See [`MaterializedCte`]. -pub(crate) struct PendingMaterializedCte { - id: MaterializedCteId, - name: String, - cte: LogicalPlan, -} - -impl PendingMaterializedCte { - /// Wrap `continuation` so that its scans of this CTE read one shared result. - pub(crate) fn wrap(self, continuation: LogicalPlan) -> Result { - MaterializedCte::try_new( - self.id, - self.name, - Arc::new(self.cte), - Arc::new(continuation), - ) - .map(|cte| LogicalPlan::MaterializedCte(MaterializedCtePlan::Cte(cte))) - } -} - impl SqlToRel<'_, S> { pub(super) fn plan_with_clause( &self, with: With, planner_context: &mut PlannerContext, - ) -> Result> { + ) -> Result> { let is_recursive = with.recursive; let mut materialized = vec![]; // Process CTEs from top to bottom @@ -86,20 +64,9 @@ impl SqlToRel<'_, S> { // Every reference reads the shared result instead of a copy // of the body. The body is already planned, so a reference // of a recursive CTE to itself stays a work table scan. - let id = MaterializedCteId::next(); - let scan = LogicalPlan::MaterializedCte(MaterializedCtePlan::Scan( - MaterializedCteScan::new( - id, - cte_name.clone(), - Arc::clone(final_plan.schema()), - ), - )); - materialized.push(PendingMaterializedCte { - id, - name: cte_name.clone(), - cte: final_plan, - }); - planner_context.insert_cte(cte_name, scan); + let builder = MaterializedCteBuilder::new(cte_name.clone(), final_plan); + planner_context.insert_cte(cte_name, builder.scan().into()); + materialized.push(builder); continue; } // Export the CTE to the outer query diff --git a/datafusion/sql/src/query.rs b/datafusion/sql/src/query.rs index d68e8b80cf76a..e825dd23766cc 100644 --- a/datafusion/sql/src/query.rs +++ b/datafusion/sql/src/query.rs @@ -92,7 +92,7 @@ impl SqlToRel<'_, S> { materialized_ctes .into_iter() .rev() - .try_fold(plan, |plan, cte| cte.wrap(plan)) + .try_fold(plan, |plan, cte| cte.build(plan).map(LogicalPlan::from)) } /// Apply pipe operators to a plan From 5bcd662fa5e49e53cae7b0c23ce2d49036d43406 Mon Sep 17 00:00:00 2001 From: Adrian Garcia Badaracco <1755071+adriangb@users.noreply.github.com> Date: Tue, 24 Nov 2026 23:35:30 -0600 Subject: [PATCH 03/12] refactor: own the coupled body and scan operations of MaterializedCte 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 --- datafusion/core/src/physical_planner.rs | 84 +------- .../expr/src/logical_plan/materialized_cte.rs | 188 +++++++++++++++++- datafusion/expr/src/logical_plan/mod.rs | 2 +- .../optimizer/src/analyzer/type_coercion.rs | 70 ++----- datafusion/optimizer/src/decorrelate.rs | 19 +- .../optimizer/src/optimize_projections/mod.rs | 88 ++------ datafusion/optimizer/src/push_down_filter.rs | 15 +- 7 files changed, 229 insertions(+), 237 deletions(-) diff --git a/datafusion/core/src/physical_planner.rs b/datafusion/core/src/physical_planner.rs index f04498c1ac0c1..d20cbc173192b 100644 --- a/datafusion/core/src/physical_planner.rs +++ b/datafusion/core/src/physical_planner.rs @@ -83,9 +83,9 @@ use datafusion_expr::physical_planning_context::{ use datafusion_expr::utils::{expr_to_columns, split_conjunction}; use datafusion_expr::{ Analyze, BinaryExpr, DmlStatement, Explain, ExplainFormat, Extension, FetchType, - Filter, JoinType, MaterializedCte, MaterializedCteId, MaterializedCtePlan, Operator, - RecursiveQuery, Show, ShowKind, SkipType, StringifiedPlan, WindowFrame, - WindowFrameBound, WriteOp, + Filter, JoinType, MaterializedCtePlan, Operator, RecursiveQuery, Show, ShowKind, + SkipType, StringifiedPlan, WindowFrame, WindowFrameBound, WriteOp, + renumber_materialized_ctes, }; use datafusion_physical_expr::aggregate::{ AggregateFunctionExpr, LoweredAggregate, LoweredAggregateBuilder, @@ -227,8 +227,10 @@ impl DefaultPhysicalPlanner { { return Ok(plan); } - let renumbered = renumber_materialized_ctes(logical_plan)?; - let logical_plan = renumbered.as_ref().unwrap_or(logical_plan); + // The ids must be new for each planning run. See + // `renumber_materialized_ctes`. + let logical_plan = renumber_materialized_ctes(logical_plan.clone())?.data; + let logical_plan = &logical_plan; let plan = self .create_initial_plan(logical_plan, session_state) .await?; @@ -236,78 +238,6 @@ impl DefaultPhysicalPlanner { } } -/// Give each occurrence of a [`MaterializedCte`] in `plan` a new id, and -/// update the scans in its continuation, including the scans in subqueries. -/// -/// The id is copied when a logical plan is cloned, so one CTE can occur more -/// than once, for example when a view that declares it is referenced two -/// times, or when a DataFrame is joined to itself. Each occurrence is a -/// separate CTE, as in PostgreSQL. -/// -/// The ids must also be new for each planning run, not only unique within -/// `plan`. A table provider can plan a saved logical plan in its `scan`, as a -/// [`ViewTable`] that is not inlined does. Each such scan is a separate -/// planning run of the same saved plan, and its CTEs end up in the same -/// physical plan as the CTEs of the outer run. -/// -/// Returns `None` when `plan` has no materialized CTE. -/// -/// [`ViewTable`]: crate::datasource::ViewTable -fn renumber_materialized_ctes(plan: &LogicalPlan) -> Result> { - let mut has_cte = false; - plan.apply_with_subqueries(|node| { - if matches!( - node, - LogicalPlan::MaterializedCte(MaterializedCtePlan::Cte(_)) - ) { - has_cte = true; - return Ok(TreeNodeRecursion::Stop); - } - Ok(TreeNodeRecursion::Continue) - })?; - if !has_cte { - return Ok(None); - } - - plan.clone() - .transform_down_with_subqueries(|node| { - let LogicalPlan::MaterializedCte(MaterializedCtePlan::Cte(cte)) = node else { - return Ok(Transformed::no(node)); - }; - let new_id = MaterializedCteId::next(); - let (old_id, name, body, continuation) = cte.into_parts(); - let continuation = Arc::unwrap_or_clone(continuation) - .transform_down_with_subqueries(|node| match node { - // A nested occurrence of the same CTE owns the scans below - // it, and is renumbered on its own. - LogicalPlan::MaterializedCte(MaterializedCtePlan::Cte( - ref nested, - )) if nested.id() == old_id => { - Ok(Transformed::new(node, false, TreeNodeRecursion::Jump)) - } - LogicalPlan::MaterializedCte(MaterializedCtePlan::Scan(mut scan)) - if scan.id == old_id => - { - scan.id = new_id; - Ok(Transformed::yes(LogicalPlan::MaterializedCte( - MaterializedCtePlan::Scan(scan), - ))) - } - _ => Ok(Transformed::no(node)), - })? - .data; - Ok(Transformed::yes(LogicalPlan::MaterializedCte( - MaterializedCtePlan::Cte(MaterializedCte::try_new( - new_id, - name, - body, - Arc::new(continuation), - )?), - ))) - }) - .map(|t| Some(t.data)) -} - /// Points every [`MaterializedCteScanExec`] at the buffer of the /// [`MaterializedCteExec`] with the same id, and gives it the statistics of /// the CTE body. diff --git a/datafusion/expr/src/logical_plan/materialized_cte.rs b/datafusion/expr/src/logical_plan/materialized_cte.rs index 5338df00777c2..f12caf991b9f7 100644 --- a/datafusion/expr/src/logical_plan/materialized_cte.rs +++ b/datafusion/expr/src/logical_plan/materialized_cte.rs @@ -25,12 +25,12 @@ use std::hash::Hash; use std::sync::Arc; use std::sync::atomic::{AtomicU64, Ordering as AtomicOrdering}; -use datafusion_common::tree_node::TreeNodeRecursion; +use datafusion_common::tree_node::{Transformed, TreeNodeRecursion}; use datafusion_common::{ - DFSchema, DFSchemaRef, Result, internal_datafusion_err, internal_err, + Column, DFSchema, DFSchemaRef, Result, internal_datafusion_err, internal_err, }; -use crate::LogicalPlan; +use crate::{Expr, LogicalPlan, Projection}; /// Identifies one materialized CTE and binds its scans to it. /// @@ -248,6 +248,142 @@ impl MaterializedCte { (self.id, self.name, self.cte, self.continuation) } + /// Replace the continuation with the result of `f`. + /// + /// Returns an error if a scan of this CTE in the new continuation does + /// not have the names and types of the columns of the body that it reads. + pub fn map_continuation( + self, + f: impl FnOnce(LogicalPlan) -> Result>, + ) -> Result> { + let Self { + id, + name, + cte, + continuation, + } = self; + f(Arc::unwrap_or_clone(continuation))? + .map_data(|continuation| Self::try_new(id, name, cte, Arc::new(continuation))) + } + + /// Replace the body with the result of `f`. The scans do not change. + /// + /// Returns an error if a scan of this CTE does not have the names and + /// types of the columns of the new body that it reads. + pub fn map_body( + self, + f: impl FnOnce(LogicalPlan) -> Result>, + ) -> Result> { + let Self { + id, + name, + cte, + continuation, + } = self; + f(Arc::unwrap_or_clone(cte))? + .map_data(|cte| Self::try_new(id, name, Arc::new(cte), continuation)) + } + + /// Replace the body with `body`, which has the column names of the + /// current body and maybe other types, for example after type coercion. + /// Each scan gets the new types of the columns that it reads, and keeps + /// its qualifiers. + /// + /// Returns an error if `body` does not have the column names of the + /// current body that the scans read. + pub fn with_coerced_body(self, body: LogicalPlan) -> Result { + let body_schema = Arc::clone(body.schema()); + let continuation = Self::map_scans(self.id, self.continuation, |scan| { + let new_scan = scan.with_body_schema(&body_schema)?; + Ok(if new_scan.schema().inner() == scan.schema().inner() { + Transformed::no(scan) + } else { + Transformed::yes(new_scan) + }) + })?; + Self::try_new(self.id, self.name, Arc::new(body), continuation) + } + + /// Remove from the body the columns that no scan of this CTE reads. The + /// body becomes a [`Projection`] of the other columns, and each scan + /// reads the new positions of its columns. The output of each scan does + /// not change. + /// + /// The body keeps one column if no scan reads a column, as + /// `SELECT count(*) FROM c` does, so that it still has its rows. The node + /// does not change if nothing reads the CTE or if every column is read. + pub fn prune_body_columns(self) -> Result> { + let body_len = self.cte.schema().fields().len(); + let scans = self.scans()?; + let mut is_read = vec![false; body_len]; + for scan in &scans { + match scan.projection() { + None => is_read.fill(true), + Some(projection) => { + for index in projection { + let Some(is_read) = is_read.get_mut(*index) else { + return internal_err!( + "A scan of the materialized CTE {} reads the column {index}, but the CTE has {body_len} columns", + self.name + ); + }; + *is_read = true; + } + } + } + } + if !is_read.contains(&true) + && let Some(first) = is_read.first_mut() + { + *first = true; + } + let kept: Vec = (0..body_len).filter(|index| is_read[*index]).collect(); + // A CTE that nothing reads is not planned, so its body is left as it is. + if scans.is_empty() || kept.len() == body_len { + return Ok(Transformed::no(self)); + } + + let schema = self.cte.schema(); + let exprs = kept + .iter() + .map(|index| Expr::Column(Column::from(schema.qualified_field(*index)))) + .collect(); + let body = Projection::try_new(exprs, Arc::clone(&self.cte)) + .map(LogicalPlan::Projection)?; + let continuation = Self::map_scans(self.id, self.continuation, |scan| { + scan.with_body_columns(&kept).map(Transformed::yes) + })?; + Self::try_new(self.id, self.name, Arc::new(body), continuation) + .map(Transformed::yes) + } + + /// Apply `f` to each scan of the CTE `id` in `continuation`, also in + /// subquery expressions, and return the new continuation. + /// + /// The traversal does not go below a [`MaterializedCte`] with the same id. + /// Such a node is a separate occurrence of the CTE and owns its scans. + fn map_scans( + id: MaterializedCteId, + continuation: Arc, + mut f: impl FnMut(MaterializedCteScan) -> Result>, + ) -> Result> { + Arc::unwrap_or_clone(continuation) + .transform_down_with_subqueries(|node| match node { + LogicalPlan::MaterializedCte(MaterializedCtePlan::Cte(ref nested)) + if nested.id == id => + { + Ok(Transformed::new(node, false, TreeNodeRecursion::Jump)) + } + LogicalPlan::MaterializedCte(MaterializedCtePlan::Scan(scan)) + if scan.id == id => + { + f(scan).map(|scan| scan.update_data(LogicalPlan::from)) + } + _ => Ok(Transformed::no(node)), + }) + .map(|t| Arc::new(t.data)) + } + /// Return a new node with the same id and name, and new inputs. /// /// The schemas of the scans are not checked again. The signature lets a @@ -282,6 +418,52 @@ impl PartialOrd for MaterializedCte { } } +/// Give each occurrence of a [`MaterializedCte`] in `plan` a new id, and +/// update the scans in its continuation, including the scans in subqueries. +/// +/// The id is copied when a logical plan is cloned, so one CTE can occur more +/// than once, for example when a view that declares it is referenced two +/// times, or when a DataFrame is joined to itself. Each occurrence is a +/// separate CTE, as in PostgreSQL. +/// +/// The new ids are also unique across calls. A physical planner can thus +/// call this function for each planning run of the same saved plan, and put +/// the results in one physical plan. +/// +/// A new id does not change a schema, so the scans are not checked again. +pub fn renumber_materialized_ctes(plan: LogicalPlan) -> Result> { + let mut has_cte = false; + plan.apply_with_subqueries(|node| { + if matches!( + node, + LogicalPlan::MaterializedCte(MaterializedCtePlan::Cte(_)) + ) { + has_cte = true; + return Ok(TreeNodeRecursion::Stop); + } + Ok(TreeNodeRecursion::Continue) + })?; + if !has_cte { + return Ok(Transformed::no(plan)); + } + plan.transform_down_with_subqueries(|node| { + let LogicalPlan::MaterializedCte(MaterializedCtePlan::Cte(cte)) = node else { + return Ok(Transformed::no(node)); + }; + let id = MaterializedCteId::next(); + let continuation = + MaterializedCte::map_scans(cte.id, cte.continuation, |mut scan| { + scan.id = id; + Ok(Transformed::yes(scan)) + })?; + Ok(Transformed::yes(LogicalPlan::from(MaterializedCte { + id, + continuation, + ..cte + }))) + }) +} + /// Reads the buffered output of the [`MaterializedCte`] with the same `id`. /// /// This is a leaf. It outputs all the columns of the CTE body, or the columns diff --git a/datafusion/expr/src/logical_plan/mod.rs b/datafusion/expr/src/logical_plan/mod.rs index 3f2ff110f8265..cab4b55e23af1 100644 --- a/datafusion/expr/src/logical_plan/mod.rs +++ b/datafusion/expr/src/logical_plan/mod.rs @@ -51,5 +51,5 @@ pub use display::display_schema; pub use extension::{UserDefinedLogicalNode, UserDefinedLogicalNodeCore}; pub use materialized_cte::{ MaterializedCte, MaterializedCteBuilder, MaterializedCteId, MaterializedCtePlan, - MaterializedCteScan, + MaterializedCteScan, renumber_materialized_ctes, }; diff --git a/datafusion/optimizer/src/analyzer/type_coercion.rs b/datafusion/optimizer/src/analyzer/type_coercion.rs index aa4b5124c48b7..195f7f7c0e00d 100644 --- a/datafusion/optimizer/src/analyzer/type_coercion.rs +++ b/datafusion/optimizer/src/analyzer/type_coercion.rs @@ -47,10 +47,9 @@ use datafusion_expr::type_coercion::{ use datafusion_expr::utils::merge_schema; use datafusion_expr::{ AsOfJoin, AsOfMatch, Cast, DmlStatement, Expr, ExprSchemable, Join, Limit, - LogicalPlan, MaterializedCte, MaterializedCteId, MaterializedCtePlan, Operator, - Projection, Union, ValueOrLambda, WindowFrame, WindowFrameBound, WindowFrameUnits, - WriteOp, is_false, is_not_false, is_not_true, is_not_unknown, is_true, is_unknown, - lit, not, + LogicalPlan, MaterializedCtePlan, Operator, Projection, Union, ValueOrLambda, + WindowFrame, WindowFrameBound, WindowFrameUnits, WriteOp, is_false, is_not_false, + is_not_true, is_not_unknown, is_true, is_unknown, lit, not, }; /// Performs type coercion by determining the schema @@ -128,27 +127,16 @@ fn coerce_plan_and_subqueries( // of a `NULL` column of a `UNION`. Coerce the body first, and give // its new schema to the scans before the continuation is coerced. LogicalPlan::MaterializedCte(MaterializedCtePlan::Cte(cte)) => { - let (id, name, body, continuation) = cte.into_parts(); let body = - coerce_plan_and_subqueries(Arc::unwrap_or_clone(body), config)?; - let continuation = with_materialized_cte_scan_schema( - Arc::unwrap_or_clone(continuation), - id, - body.schema(), - )?; - let continuation = coerce_plan_and_subqueries(continuation, config)?; - Ok(Transformed::new( - LogicalPlan::MaterializedCte(MaterializedCtePlan::Cte( - MaterializedCte::try_new( - id, - name, - Arc::new(body), - Arc::new(continuation), - )?, - )), - true, - TreeNodeRecursion::Jump, - )) + coerce_plan_and_subqueries(LogicalPlan::clone(cte.body()), config)?; + let cte = cte + .with_coerced_body(body)? + .map_continuation(|continuation| { + coerce_plan_and_subqueries(continuation, config) + .map(Transformed::yes) + })? + .data; + Ok(Transformed::new(cte.into(), true, TreeNodeRecursion::Jump)) } _ => Ok(Transformed::no(plan)), }, @@ -163,40 +151,6 @@ fn coerce_plan_and_subqueries( .map(|t| t.data) } -/// Give the fields of `body_schema` to each scan of the materialized CTE `id` -/// in `continuation`, also in subquery expressions. A scan keeps its -/// qualifiers and reads only the fields of its projection. -fn with_materialized_cte_scan_schema( - continuation: LogicalPlan, - id: MaterializedCteId, - body_schema: &DFSchemaRef, -) -> Result { - continuation - .transform_down_with_subqueries(|node| match node { - // A nested occurrence of the same CTE owns the scans below it. - LogicalPlan::MaterializedCte(MaterializedCtePlan::Cte(ref nested)) - if nested.id() == id => - { - Ok(Transformed::new(node, false, TreeNodeRecursion::Jump)) - } - LogicalPlan::MaterializedCte(MaterializedCtePlan::Scan(scan)) - if scan.id == id => - { - let new_scan = scan.with_body_schema(body_schema)?; - if new_scan.schema().inner() == scan.schema().inner() { - return Ok(Transformed::no(LogicalPlan::MaterializedCte( - MaterializedCtePlan::Scan(scan), - ))); - } - Ok(Transformed::yes(LogicalPlan::MaterializedCte( - MaterializedCtePlan::Scan(new_scan), - ))) - } - _ => Ok(Transformed::no(node)), - }) - .map(|t| t.data) -} - /// use the external schema to handle the correlated subqueries case /// /// Assumes that children have already been optimized diff --git a/datafusion/optimizer/src/decorrelate.rs b/datafusion/optimizer/src/decorrelate.rs index 27af421812e54..67aec73c49313 100644 --- a/datafusion/optimizer/src/decorrelate.rs +++ b/datafusion/optimizer/src/decorrelate.rs @@ -28,8 +28,8 @@ use datafusion_expr::simplify::SimplifyContext; use datafusion_expr::utils::{collect_subquery_cols, conjunction, split_conjunction}; use datafusion_expr::{ Aggregate, BinaryExpr, Cast, Distinct, EmptyRelation, Expr, ExprSchemable, FetchType, - LogicalPlan, LogicalPlanBuilder, MaterializedCte, MaterializedCtePlan, Operator, - SkipType, Window, expr, lit, + LogicalPlan, LogicalPlanBuilder, MaterializedCtePlan, Operator, SkipType, Window, + expr, lit, }; /// This struct rewrite the sub query plan by pull up the correlated @@ -246,18 +246,11 @@ impl TreeNodeRewriter for PullUpCorrelatedExpr { LogicalPlan::MaterializedCte(MaterializedCtePlan::Cte(cte)) => { // Only the continuation can hold correlated expressions. Rewrite // it alone, so that the body shared by every scan keeps its schema. - let (id, name, body, continuation) = cte.into_parts(); - let continuation = Arc::unwrap_or_clone(continuation).rewrite(self)?; + let cte = + cte.map_continuation(|continuation| continuation.rewrite(self))?; Ok(Transformed::new( - LogicalPlan::MaterializedCte(MaterializedCtePlan::Cte( - MaterializedCte::try_new( - id, - name, - body, - Arc::new(continuation.data), - )?, - )), - continuation.transformed, + cte.data.into(), + cte.transformed, TreeNodeRecursion::Jump, )) } diff --git a/datafusion/optimizer/src/optimize_projections/mod.rs b/datafusion/optimizer/src/optimize_projections/mod.rs index 6d1f550b77416..8df9d951409a2 100644 --- a/datafusion/optimizer/src/optimize_projections/mod.rs +++ b/datafusion/optimizer/src/optimize_projections/mod.rs @@ -29,15 +29,13 @@ use datafusion_common::{ use datafusion_expr::expr::Alias; use datafusion_expr::utils::passthrough_field_index; use datafusion_expr::{ - Aggregate, Distinct, EmptyRelation, Expr, MaterializedCte, MaterializedCteScan, - Projection, TableScanBuilder, Unnest, Window, logical_plan::LogicalPlan, + Aggregate, Distinct, EmptyRelation, Expr, MaterializedCte, Projection, + TableScanBuilder, Unnest, Window, logical_plan::LogicalPlan, }; use crate::optimize_projections::required_indices::RequiredIndices; use crate::utils::NamePreserver; -use datafusion_common::tree_node::{ - Transformed, TreeNode, TreeNodeContainer, TreeNodeRecursion, -}; +use datafusion_common::tree_node::{Transformed, TreeNode, TreeNodeContainer}; /// Optimizer rule to prune unnecessary columns from intermediate schemas /// inside the [`LogicalPlan`]. This rule: @@ -528,80 +526,20 @@ fn optimize_materialized_cte( config: &dyn OptimizerConfig, indices: RequiredIndices, ) -> Result> { - let (id, name, body, continuation) = cte.into_parts(); // The output is the output of the continuation, so the continuation // needs what the parent needs. - let continuation = - optimize_projections(Arc::unwrap_or_clone(continuation), config, indices)?; - let mut transformed = continuation.transformed; - let mut continuation = continuation.data; - let mut body = Arc::unwrap_or_clone(body); - - let body_len = body.schema().fields().len(); - let scans = MaterializedCteScan::find_in(&continuation, id)?; - let mut is_read = vec![false; body_len]; - for scan in &scans { - match scan.projection() { - None => is_read.fill(true), - Some(projection) => { - for index in projection { - let Some(is_read) = is_read.get_mut(*index) else { - return internal_err!( - "A scan of the materialized CTE {name} reads the column {index}, but the CTE has {body_len} columns" - ); - }; - *is_read = true; - } - } - } - } - // A reference such as `SELECT count(*) FROM c` reads no column. Keep one - // column then, so that the body is never a projection without columns. - if !is_read.contains(&true) - && let Some(first) = is_read.first_mut() - { - *first = true; - } - let kept: Vec = (0..body_len).filter(|index| is_read[*index]).collect(); - // A CTE that nothing reads is not planned, so its body is left as it is. - if !scans.is_empty() && kept.len() < body_len { - let exprs = RequiredIndices::new_from_indices(kept.clone()) - .get_required_exprs(body.schema()); - body = Projection::try_new(exprs, Arc::new(body)).map(LogicalPlan::Projection)?; - continuation = continuation - .transform_down_with_subqueries(|node| match node { - // A nested occurrence of the same CTE has its own body and - // owns the scans below it. - LogicalPlan::MaterializedCte(MaterializedCtePlan::Cte(ref nested)) - if nested.id() == id => - { - Ok(Transformed::new(node, false, TreeNodeRecursion::Jump)) - } - LogicalPlan::MaterializedCte(MaterializedCtePlan::Scan(scan)) - if scan.id == id => - { - Ok(Transformed::yes(LogicalPlan::MaterializedCte( - MaterializedCtePlan::Scan(scan.with_body_columns(&kept)?), - ))) - } - _ => Ok(Transformed::no(node)), - })? - .data; - transformed = true; - } - + let continuation = cte.map_continuation(|continuation| { + optimize_projections(continuation, config, indices) + })?; + let pruned = continuation.data.prune_body_columns()?; // All the columns that the body has now are necessary. - let body_indices = RequiredIndices::new_for_all_exprs(&body); - let body = optimize_projections(body, config, body_indices)?; - transformed |= body.transformed; + let body = pruned.data.map_body(|body| { + let indices = RequiredIndices::new_for_all_exprs(&body); + optimize_projections(body, config, indices) + })?; Ok(Transformed::new_transformed( - LogicalPlan::MaterializedCte(MaterializedCtePlan::Cte(MaterializedCte::try_new( - id, - name, - Arc::new(body.data), - Arc::new(continuation), - )?)), - transformed, + body.data.into(), + continuation.transformed || pruned.transformed || body.transformed, )) } diff --git a/datafusion/optimizer/src/push_down_filter.rs b/datafusion/optimizer/src/push_down_filter.rs index 63637a41261a3..2167bb2545276 100644 --- a/datafusion/optimizer/src/push_down_filter.rs +++ b/datafusion/optimizer/src/push_down_filter.rs @@ -1410,20 +1410,15 @@ impl OptimizerRule for PushDownFilter { LogicalPlan::TableScan(scan), ))) } - LogicalPlan::MaterializedCte(MaterializedCtePlan::Cte(mut cte)) => { + LogicalPlan::MaterializedCte(MaterializedCtePlan::Cte(cte)) => { // The output is the output of the continuation, so the filter // moves onto the continuation. The body is shared by every scan // of the CTE and is never filtered for one of them. - cte.try_map_inputs_mut(|_, continuation| { - *continuation = Arc::new(LogicalPlan::Filter(Filter::new( - filter.predicate, - Arc::clone(continuation), - ))); - Ok(()) + let cte = cte.map_continuation(|continuation| { + Filter::try_new(filter.predicate, Arc::new(continuation)) + .map(|filter| Transformed::yes(LogicalPlan::Filter(filter))) })?; - Ok(Transformed::yes(LogicalPlan::MaterializedCte( - MaterializedCtePlan::Cte(cte), - ))) + Ok(Transformed::yes(cte.data.into())) } // A scan reads the shared body, so the filter stays above it. scan @ LogicalPlan::MaterializedCte(MaterializedCtePlan::Scan(_)) => { From 738933d55c86d7bf48d16d2bb2316408058d1b4f Mon Sep 17 00:00:00 2001 From: Adrian Garcia Badaracco <1755071+adriangb@users.noreply.github.com> Date: Tue, 24 Nov 2026 23:36:44 -0600 Subject: [PATCH 04/12] refactor: replace try_map_inputs_mut with map_inputs_mut 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 --- .../expr/src/logical_plan/materialized_cte.rs | 69 ++++++++++++++++--- datafusion/optimizer/src/optimizer.rs | 9 +-- 2 files changed, 64 insertions(+), 14 deletions(-) diff --git a/datafusion/expr/src/logical_plan/materialized_cte.rs b/datafusion/expr/src/logical_plan/materialized_cte.rs index f12caf991b9f7..c0c8ad307e03d 100644 --- a/datafusion/expr/src/logical_plan/materialized_cte.rs +++ b/datafusion/expr/src/logical_plan/materialized_cte.rs @@ -223,16 +223,31 @@ impl MaterializedCte { MaterializedCteScan::find_in(&self.continuation, self.id) } - /// Call `f` with the body and the continuation, in this order, so that a - /// rule can change them in place. Return the result of `f`. + /// Call `f` with the body, then with the continuation, so that a rule can + /// change them in place. Return `true` if a call of `f` returns `true`. /// - /// The schemas of the scans are not checked again. The signature lets a - /// later version validate the new inputs and return an error. - pub fn try_map_inputs_mut( + /// Returns an error if `f` changes the names or the types of the columns + /// of the body, because the scans read them by position. The continuation + /// is not checked: its schema can change, and the optimizer then + /// recomputes the schema of this node. + pub fn map_inputs_mut( &mut self, - f: impl FnOnce(&mut Arc, &mut Arc) -> Result, - ) -> Result { - f(&mut self.cte, &mut self.continuation) + mut f: impl FnMut(&mut LogicalPlan) -> Result, + ) -> Result { + let schema = Arc::clone(self.cte.schema()); + let body = f(Arc::make_mut(&mut self.cte))?; + if !Arc::ptr_eq(&schema, self.cte.schema()) { + schema + .has_equivalent_names_and_types(self.cte.schema()) + .map_err(|e| { + e.context(format!( + "The body of the materialized CTE {} changed its columns", + self.name + )) + })?; + } + let continuation = f(Arc::make_mut(&mut self.continuation))?; + Ok(body || continuation) } /// The id, the name, the body and the continuation, in this order. Build @@ -1011,6 +1026,44 @@ mod tests { Ok(()) } + #[test] + fn map_inputs_mut_rejects_a_body_with_other_columns() -> Result<()> { + let id = MaterializedCteId::next(); + let mut cte = MaterializedCte::try_new( + id, + "c", + body(DataType::Int32), + Arc::new(scan(id, DataType::Int32)), + )?; + assert!(!cte.map_inputs_mut(|_| Ok(false))?); + + // A new body with the same names and types is accepted. + let mut visited = 0; + assert!(cte.map_inputs_mut(|input| { + visited += 1; + if visited == 1 { + *input = LogicalPlan::clone(&body(DataType::Int32)); + } + Ok(visited == 1) + })?); + assert_eq!(visited, 2); + + let err = cte + .map_inputs_mut(|input| { + if matches!(input, LogicalPlan::EmptyRelation(_)) { + *input = LogicalPlan::clone(&body(DataType::Utf8)); + } + Ok(true) + }) + .unwrap_err(); + assert!( + err.to_string() + .contains("The body of the materialized CTE c changed its columns"), + "{err}" + ); + Ok(()) + } + #[test] fn check_invariants_rejects_a_scan_that_does_not_match_the_body() -> Result<()> { use crate::logical_plan::InvariantLevel; diff --git a/datafusion/optimizer/src/optimizer.rs b/datafusion/optimizer/src/optimizer.rs index 7e738809fac98..1f53923fdff58 100644 --- a/datafusion/optimizer/src/optimizer.rs +++ b/datafusion/optimizer/src/optimizer.rs @@ -467,12 +467,9 @@ fn map_children_mut Result>( let r = f(Arc::make_mut(recursive_term))?; s || r } - LogicalPlan::MaterializedCte(MaterializedCtePlan::Cte(cte)) => cte - .try_map_inputs_mut(|cte, continuation| { - let b = f(Arc::make_mut(cte))?; - let c = f(Arc::make_mut(continuation))?; - Ok(b || c) - })?, + LogicalPlan::MaterializedCte(MaterializedCtePlan::Cte(cte)) => { + cte.map_inputs_mut(f)? + } LogicalPlan::Statement(Statement::Prepare(p)) => f(Arc::make_mut(&mut p.input))?, LogicalPlan::Extension(Extension { node }) => { let inputs = node.inputs(); From dd1b91f642d8d1d9e406db4ba449b07a3f38b8f6 Mon Sep 17 00:00:00 2001 From: Adrian Garcia Badaracco <1755071+adriangb@users.noreply.github.com> Date: Tue, 24 Nov 2026 23:42:05 -0600 Subject: [PATCH 05/12] refactor: narrow the public API of MaterializedCte 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 --- datafusion/core/src/physical_planner.rs | 6 +- .../expr/src/logical_plan/materialized_cte.rs | 80 +++++++++------- datafusion/expr/src/logical_plan/plan.rs | 8 +- .../optimizer/src/optimize_projections/mod.rs | 91 ++++++------------- 4 files changed, 83 insertions(+), 102 deletions(-) diff --git a/datafusion/core/src/physical_planner.rs b/datafusion/core/src/physical_planner.rs index d20cbc173192b..e97d75be3efc6 100644 --- a/datafusion/core/src/physical_planner.rs +++ b/datafusion/core/src/physical_planner.rs @@ -878,8 +878,8 @@ impl DefaultPhysicalPlanner { LogicalPlan::MaterializedCte(MaterializedCtePlan::Scan(scan)) => { // Unbound until `bind_materialized_cte_scans` runs on the whole plan. let exec = MaterializedCteScanExec::new( - scan.id.as_u64(), - &scan.name, + scan.id().as_u64(), + scan.name(), Arc::clone(scan.schema().inner()), session.config().target_partitions(), ); @@ -1967,7 +1967,7 @@ impl DefaultPhysicalPlanner { LogicalPlan::MaterializedCte(MaterializedCtePlan::Cte(cte)) => { let [body, continuation] = children.two()?; // A CTE that nothing reads is never evaluated. - if cte.scans()?.is_empty() { + if !cte.is_read()? { return Ok(continuation); } // The body is fully buffered before a scan yields a row, so an diff --git a/datafusion/expr/src/logical_plan/materialized_cte.rs b/datafusion/expr/src/logical_plan/materialized_cte.rs index c0c8ad307e03d..c618eeafa6a0b 100644 --- a/datafusion/expr/src/logical_plan/materialized_cte.rs +++ b/datafusion/expr/src/logical_plan/materialized_cte.rs @@ -18,6 +18,20 @@ //! A scan can read a subset of the columns of the body (see //! [`MaterializedCteScan::projection`]). The optimizer removes from the body //! the columns that no scan reads. +//! +//! # Checks +//! +//! A scan reads the columns of the body by position, so the scans must +//! match the body. [`MaterializedCteBuilder::build`] and the methods of +//! [`MaterializedCte`] that change an input check this. +//! +//! The generic tree APIs do not check it: [`LogicalPlan::with_new_exprs`] +//! and [`TreeNode::map_children`] replace the inputs as they are given. +//! [`LogicalPlan::check_invariants`] checks the scans of every +//! [`MaterializedCte`] in a plan. The optimizer runs it before and after +//! the rules. +//! +//! [`TreeNode::map_children`]: datafusion_common::tree_node::TreeNode::map_children use std::cmp::Ordering; use std::fmt; @@ -41,7 +55,7 @@ pub struct MaterializedCteId(u64); impl MaterializedCteId { /// Allocate a new unique id. - pub fn next() -> Self { + pub(crate) fn next() -> Self { static NEXT: AtomicU64 = AtomicU64::new(0); Self(NEXT.fetch_add(1, AtomicOrdering::Relaxed)) } @@ -169,7 +183,7 @@ impl MaterializedCte { /// Returns an error if a scan of this CTE in `continuation` (also in a /// subquery expression) does not have the names and types of the columns /// of `cte` that it reads. - pub fn try_new( + pub(crate) fn try_new( id: MaterializedCteId, name: impl Into, cte: Arc, @@ -217,9 +231,15 @@ impl MaterializedCte { self.continuation.schema() } + /// Whether a scan in the continuation reads this CTE, also in a subquery + /// expression. A CTE that nothing reads does not need to be computed. + pub fn is_read(&self) -> Result { + self.scans().map(|scans| !scans.is_empty()) + } + /// The scans in the continuation that read this CTE, also in subquery /// expressions. See [`MaterializedCteScan::find_in`]. - pub fn scans(&self) -> Result> { + pub(crate) fn scans(&self) -> Result> { MaterializedCteScan::find_in(&self.continuation, self.id) } @@ -250,19 +270,6 @@ impl MaterializedCte { Ok(body || continuation) } - /// The id, the name, the body and the continuation, in this order. Build - /// a node again with [`Self::try_new`]. - pub fn into_parts( - self, - ) -> ( - MaterializedCteId, - String, - Arc, - Arc, - ) { - (self.id, self.name, self.cte, self.continuation) - } - /// Replace the continuation with the result of `f`. /// /// Returns an error if a scan of this CTE in the new continuation does @@ -399,21 +406,19 @@ impl MaterializedCte { .map(|t| Arc::new(t.data)) } - /// Return a new node with the same id and name, and new inputs. - /// - /// The schemas of the scans are not checked again. The signature lets a - /// later version validate the new inputs and return an error. - pub fn with_new_inputs( + /// Return a new node with the same id and name, and new inputs. The + /// scans are not checked. See the [module documentation](self). + pub(crate) fn with_new_inputs_unchecked( &self, cte: Arc, continuation: Arc, - ) -> Result { - Ok(Self { + ) -> Self { + Self { id: self.id, name: self.name.clone(), cte, continuation, - }) + } } } @@ -486,9 +491,9 @@ pub fn renumber_materialized_ctes(plan: LogicalPlan) -> Result, schema: DFSchemaRef, @@ -568,7 +573,7 @@ impl MaterializedCteScan { /// columns `kept`, in this order. /// /// Returns an error if this scan reads a column that is not in `kept`. - pub fn with_body_columns(&self, kept: &[usize]) -> Result { + pub(crate) fn with_body_columns(&self, kept: &[usize]) -> Result { let old: Vec = match &self.projection { Some(projection) => projection.clone(), // The scan reads all the columns, so `kept` must be all of them. @@ -598,7 +603,7 @@ impl MaterializedCteScan { /// Return this scan with the fields that it reads from a CTE body with /// the schema `body`. The scan keeps its qualifiers and its projection. - pub fn with_body_schema(&self, body: &DFSchema) -> Result { + pub(crate) fn with_body_schema(&self, body: &DFSchema) -> Result { // The analyzer can change the types of the body, so only the indexes // and the names are checked here. self.check_body_names(body)?; @@ -653,7 +658,7 @@ impl MaterializedCteScan { /// Check that this scan has the names and types of the columns that it /// reads from a CTE body with the schema `body`. - pub fn check_body_schema(&self, body: &DFSchema) -> Result<()> { + pub(crate) fn check_body_schema(&self, body: &DFSchema) -> Result<()> { match &self.projection { None => self.schema.has_equivalent_names_and_types(body), Some(projection) => { @@ -676,7 +681,10 @@ impl MaterializedCteScan { /// The search does not go below a [`MaterializedCte`] with the same `id` /// in `plan`. Such a node is a separate occurrence of the CTE (the id is /// copied when a plan is cloned) and owns the scans below it. - pub fn find_in(plan: &LogicalPlan, id: MaterializedCteId) -> Result> { + pub(crate) fn find_in( + plan: &LogicalPlan, + id: MaterializedCteId, + ) -> Result> { let mut scans = vec![]; plan.apply_with_subqueries(|node| match node { LogicalPlan::MaterializedCte(MaterializedCtePlan::Cte(cte)) @@ -1077,10 +1085,12 @@ mod tests { LogicalPlan::MaterializedCte(MaterializedCtePlan::Cte(cte.clone())) .check_invariants(InvariantLevel::Executable)?; - // `with_new_inputs` does not check the scans, so a rule can build + // `with_new_exprs` does not check the scans, so a rule can build // this plan. The invariant check rejects it. - let invalid = cte - .with_new_inputs(body(DataType::Int32), Arc::new(scan(id, DataType::Utf8)))?; + let invalid = cte.with_new_inputs_unchecked( + body(DataType::Int32), + Arc::new(scan(id, DataType::Utf8)), + ); let invalid = LogicalPlan::MaterializedCte(MaterializedCtePlan::Cte(invalid)); let err = invalid .check_invariants(InvariantLevel::Executable) diff --git a/datafusion/expr/src/logical_plan/plan.rs b/datafusion/expr/src/logical_plan/plan.rs index 3f48a0c9f67c0..b4eabb45dd4be 100644 --- a/datafusion/expr/src/logical_plan/plan.rs +++ b/datafusion/expr/src/logical_plan/plan.rs @@ -1231,9 +1231,11 @@ impl LogicalPlan { LogicalPlan::MaterializedCte(MaterializedCtePlan::Cte(cte)) => { self.assert_no_expressions(expr)?; let (body, continuation) = self.only_two_inputs(inputs)?; - Ok(LogicalPlan::MaterializedCte(MaterializedCtePlan::Cte( - cte.with_new_inputs(Arc::new(body), Arc::new(continuation))?, - ))) + // The scans are not checked. See the documentation of + // `materialized_cte`. + Ok(cte + .with_new_inputs_unchecked(Arc::new(body), Arc::new(continuation)) + .into()) } LogicalPlan::MaterializedCte(MaterializedCtePlan::Scan(_)) => { self.assert_no_expressions(expr)?; diff --git a/datafusion/optimizer/src/optimize_projections/mod.rs b/datafusion/optimizer/src/optimize_projections/mod.rs index 8df9d951409a2..18747f7d74273 100644 --- a/datafusion/optimizer/src/optimize_projections/mod.rs +++ b/datafusion/optimizer/src/optimize_projections/mod.rs @@ -1067,9 +1067,9 @@ mod tests { Column, DFSchema, DFSchemaRef, JoinType, Result, ScalarValue, TableReference, }; use datafusion_expr::ExprFunctionExt; + use datafusion_expr::logical_plan::InvariantLevel; use datafusion_expr::{ - BinaryExpr, Expr, Extension, Like, LogicalPlan, MaterializedCte, - MaterializedCteId, MaterializedCtePlan, MaterializedCteScan, Operator, + BinaryExpr, Expr, Extension, Like, LogicalPlan, MaterializedCteBuilder, Operator, Projection, UserDefinedLogicalNodeCore, WindowFunctionDefinition, binary_expr, build_join_schema, builder::table_scan_with_filters, @@ -2969,32 +2969,21 @@ mod tests { /// `WITH w AS MATERIALIZED (test), x AS MATERIALIZED (SELECT a, b FROM w) /// SELECT a FROM x UNION ALL SELECT c FROM w` fn nested_materialized_ctes() -> Result { - let w = MaterializedCteId::next(); - let x = MaterializedCteId::next(); - let body_w = test_table_scan()?; - let scan_w = LogicalPlan::MaterializedCte(MaterializedCtePlan::Scan( - MaterializedCteScan::new(w, "w", Arc::clone(body_w.schema())), - )); - let body_x = LogicalPlanBuilder::from(scan_w.clone()) + let w = MaterializedCteBuilder::new("w", test_table_scan()?); + let body_x = LogicalPlanBuilder::from(LogicalPlan::from(w.scan())) .project(vec![col("a"), col("b")])? .build()?; - let scan_x = LogicalPlan::MaterializedCte(MaterializedCtePlan::Scan( - MaterializedCteScan::new(x, "x", Arc::clone(body_x.schema())), - )); - let continuation = LogicalPlanBuilder::from(scan_x) + let x = MaterializedCteBuilder::new("x", body_x); + let continuation = LogicalPlanBuilder::from(LogicalPlan::from(x.scan())) .project(vec![col("a")])? .union( - LogicalPlanBuilder::from(scan_w) + LogicalPlanBuilder::from(LogicalPlan::from(w.scan())) .project(vec![col("c")])? .build()?, )? .build()?; - let inner = LogicalPlan::MaterializedCte(MaterializedCtePlan::Cte( - MaterializedCte::try_new(x, "x", Arc::new(body_x), Arc::new(continuation))?, - )); - Ok(LogicalPlan::MaterializedCte(MaterializedCtePlan::Cte( - MaterializedCte::try_new(w, "w", Arc::new(body_w), Arc::new(inner))?, - ))) + let inner = LogicalPlan::from(x.build(continuation)?); + Ok(w.build(inner)?.into()) } /// The body of `w` keeps the columns that its scan in the body of `x` and @@ -3022,16 +3011,8 @@ mod tests { let once = optimize(nested_materialized_ctes()?)?; let twice = optimize(once.clone())?; assert_eq!(once, twice); - // The checks of `try_new` pass for the pruned plan. - let LogicalPlan::MaterializedCte(MaterializedCtePlan::Cte(cte)) = &twice else { - panic!("expected a MaterializedCte, got {twice}"); - }; - MaterializedCte::try_new( - cte.id(), - cte.name(), - Arc::clone(cte.body()), - Arc::clone(cte.continuation()), - )?; + // The scans of the pruned plan match the bodies. + twice.check_invariants(InvariantLevel::Executable)?; Ok(()) } @@ -3039,17 +3020,11 @@ mod tests { /// first column. #[test] fn materialized_cte_scan_without_columns() -> Result<()> { - let id = MaterializedCteId::next(); - let body = test_table_scan()?; - let scan = LogicalPlan::MaterializedCte(MaterializedCtePlan::Scan( - MaterializedCteScan::new(id, "w", Arc::clone(body.schema())), - )); - let continuation = LogicalPlanBuilder::from(scan) + let w = MaterializedCteBuilder::new("w", test_table_scan()?); + let continuation = LogicalPlanBuilder::from(LogicalPlan::from(w.scan())) .aggregate(Vec::::new(), vec![count(lit(1))])? .build()?; - let plan = LogicalPlan::MaterializedCte(MaterializedCtePlan::Cte( - MaterializedCte::try_new(id, "w", Arc::new(body), Arc::new(continuation))?, - )); + let plan = LogicalPlan::from(w.build(continuation)?); assert_optimized_plan_equal!( plan, @r" @@ -3067,28 +3042,22 @@ mod tests { /// body from its own scans. #[test] fn materialized_cte_nested_occurrence_with_the_same_id() -> Result<()> { - let id = MaterializedCteId::next(); - let occurrence = - |column: &str, rest: Option| -> Result { - let body = test_table_scan()?; - let scan = LogicalPlan::MaterializedCte(MaterializedCtePlan::Scan( - MaterializedCteScan::new(id, "w", Arc::clone(body.schema())), - )); - let mut continuation = - LogicalPlanBuilder::from(scan).project(vec![col(column)])?; - if let Some(rest) = rest { - continuation = continuation.union(rest)?; - } - Ok(LogicalPlan::MaterializedCte(MaterializedCtePlan::Cte( - MaterializedCte::try_new( - id, - "w", - Arc::new(body), - Arc::new(continuation.build()?), - )?, - ))) - }; - let plan = occurrence("c", Some(occurrence("b", None)?))?; + // The inner occurrence is a clone of a plan that declares `w`. The + // outer occurrence rewrites the continuation of another clone. + let w = MaterializedCteBuilder::new("w", test_table_scan()?); + let outer_scan = LogicalPlan::from(w.scan()); + let inner_continuation = LogicalPlanBuilder::from(LogicalPlan::from(w.scan())) + .project(vec![col("b")])? + .build()?; + let inner = w.build(inner_continuation)?; + let outer = inner.clone().map_continuation(|_| { + LogicalPlanBuilder::from(outer_scan) + .project(vec![col("c")])? + .union(LogicalPlan::from(inner))? + .build() + .map(Transformed::yes) + })?; + let plan = LogicalPlan::from(outer.data); assert_optimized_plan_equal!( plan, @r" From 0ca0c540db7a5d497adcbbac0b359a2b685a84f8 Mon Sep 17 00:00:00 2001 From: Adrian Garcia Badaracco <1755071+adriangb@users.noreply.github.com> Date: Tue, 24 Nov 2026 23:43:44 -0600 Subject: [PATCH 06/12] refactor: wrap MaterializedCte nodes with From 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 --- .../expr/src/logical_plan/materialized_cte.rs | 34 ++++++------------- datafusion/expr/src/logical_plan/tree_node.rs | 14 ++++---- .../optimizer/src/optimize_projections/mod.rs | 5 +-- 3 files changed, 18 insertions(+), 35 deletions(-) diff --git a/datafusion/expr/src/logical_plan/materialized_cte.rs b/datafusion/expr/src/logical_plan/materialized_cte.rs index c618eeafa6a0b..2f502bdcca64e 100644 --- a/datafusion/expr/src/logical_plan/materialized_cte.rs +++ b/datafusion/expr/src/logical_plan/materialized_cte.rs @@ -764,11 +764,7 @@ mod tests { } fn scan(id: MaterializedCteId, data_type: DataType) -> LogicalPlan { - LogicalPlan::MaterializedCte(MaterializedCtePlan::Scan(MaterializedCteScan::new( - id, - "c", - schema(data_type), - ))) + MaterializedCteScan::new(id, "c", schema(data_type)).into() } #[test] @@ -1082,8 +1078,7 @@ mod tests { body(DataType::Int32), Arc::new(scan(id, DataType::Int32)), )?; - LogicalPlan::MaterializedCte(MaterializedCtePlan::Cte(cte.clone())) - .check_invariants(InvariantLevel::Executable)?; + LogicalPlan::from(cte.clone()).check_invariants(InvariantLevel::Executable)?; // `with_new_exprs` does not check the scans, so a rule can build // this plan. The invariant check rejects it. @@ -1115,8 +1110,7 @@ mod tests { })); let scan = MaterializedCteScan::new(id, "c", wide_schema()); let narrow = scan.with_projection(&[1, 3])?; - let plan = - LogicalPlan::MaterializedCte(MaterializedCtePlan::Scan(narrow.clone())); + let plan = LogicalPlan::from(narrow.clone()); assert_eq!( plan.display_indent().to_string(), "MaterializedCteScan: name=c projection=[b, d]" @@ -1128,18 +1122,14 @@ mod tests { projection: Some(vec![0, 1]), ..narrow.clone() }; - let plan = Arc::new(LogicalPlan::MaterializedCte(MaterializedCtePlan::Scan( - wrong, - ))); + let plan = Arc::new(LogicalPlan::from(wrong)); assert!(MaterializedCte::try_new(id, "c", Arc::clone(&body), plan).is_err()); let out_of_range = MaterializedCteScan { projection: Some(vec![1, 9]), ..narrow }; - let plan = Arc::new(LogicalPlan::MaterializedCte(MaterializedCtePlan::Scan( - out_of_range, - ))); + let plan = Arc::new(LogicalPlan::from(out_of_range)); assert!(MaterializedCte::try_new(id, "c", body, plan).is_err()); Ok(()) } @@ -1154,14 +1144,12 @@ mod tests { let plan = LogicalPlanBuilder::from(scan(id, DataType::Int32)) .filter(exists(Arc::new(scan(id, DataType::Int32))))? .union(scan(other, DataType::Int32))? - .union(LogicalPlan::MaterializedCte(MaterializedCtePlan::Cte( - MaterializedCte::try_new( - id, - "c", - body(DataType::Int32), - Arc::new(scan(id, DataType::Int32)), - )?, - )))? + .union(LogicalPlan::from(MaterializedCte::try_new( + id, + "c", + body(DataType::Int32), + Arc::new(scan(id, DataType::Int32)), + )?))? .build()?; assert_eq!(MaterializedCteScan::find_in(&plan, id)?.len(), 2); assert_eq!(MaterializedCteScan::find_in(&plan, other)?.len(), 1); diff --git a/datafusion/expr/src/logical_plan/tree_node.rs b/datafusion/expr/src/logical_plan/tree_node.rs index 7b9c4586bc4d1..c9895d8607521 100644 --- a/datafusion/expr/src/logical_plan/tree_node.rs +++ b/datafusion/expr/src/logical_plan/tree_node.rs @@ -373,14 +373,12 @@ impl TreeNode for LogicalPlan { (cte, continuation) .map_elements(f)? .update_data(|(cte, continuation)| { - LogicalPlan::MaterializedCte(MaterializedCtePlan::Cte( - MaterializedCte { - id, - name, - cte, - continuation, - }, - )) + LogicalPlan::from(MaterializedCte { + id, + name, + cte, + continuation, + }) }) } LogicalPlan::Statement(stmt) => match stmt { diff --git a/datafusion/optimizer/src/optimize_projections/mod.rs b/datafusion/optimizer/src/optimize_projections/mod.rs index 18747f7d74273..b5d62a1632955 100644 --- a/datafusion/optimizer/src/optimize_projections/mod.rs +++ b/datafusion/optimizer/src/optimize_projections/mod.rs @@ -284,10 +284,7 @@ fn optimize_projections( // scan reads. let new_scan = scan.with_projection(indices.indices())?; let transformed = new_scan.projection() != scan.projection(); - return Ok(Transformed::new_transformed( - LogicalPlan::MaterializedCte(MaterializedCtePlan::Scan(new_scan)), - transformed, - )); + return Ok(Transformed::new_transformed(new_scan.into(), transformed)); } LogicalPlan::MaterializedCte(MaterializedCtePlan::Cte(cte)) => { return optimize_materialized_cte(cte, config, indices); From da8d02cfa97150423a4b062fdb68c1129bb2d3f2 Mon Sep 17 00:00:00 2001 From: Adrian Garcia Badaracco <1755071+adriangb@users.noreply.github.com> Date: Fri, 27 Nov 2026 20:53:31 -0800 Subject: [PATCH 07/12] refactor: check the scans of a MaterializedCte without cloning them The checks in try_new, check_invariants, is_read and prune_body_columns collected a clone of each scan. A visitor reads the scans in place. with_coerced_body and prune_body_columns built the new scans from the body, so they do not need a second traversal to check them. Co-Authored-By: Claude Opus 5.5 --- .../expr/src/logical_plan/invariants.rs | 9 +- .../expr/src/logical_plan/materialized_cte.rs | 123 ++++++++++++------ 2 files changed, 87 insertions(+), 45 deletions(-) diff --git a/datafusion/expr/src/logical_plan/invariants.rs b/datafusion/expr/src/logical_plan/invariants.rs index 18b8193835127..18b8641b9cef5 100644 --- a/datafusion/expr/src/logical_plan/invariants.rs +++ b/datafusion/expr/src/logical_plan/invariants.rs @@ -106,14 +106,7 @@ fn assert_valid_semantic_plan(plan: &LogicalPlan) -> Result<()> { fn assert_materialized_cte_scans_are_valid(plan: &LogicalPlan) -> Result<()> { plan.apply_with_subqueries(|node| { if let LogicalPlan::MaterializedCte(MaterializedCtePlan::Cte(cte)) = node { - for scan in cte.scans()? { - scan.check_body_schema(cte.body().schema()).map_err(|e| { - e.context(format!( - "A scan of the materialized CTE {} does not match the CTE", - cte.name() - )) - })?; - } + cte.check_scans()?; } Ok(TreeNodeRecursion::Continue) }) diff --git a/datafusion/expr/src/logical_plan/materialized_cte.rs b/datafusion/expr/src/logical_plan/materialized_cte.rs index 2f502bdcca64e..91fc4bebe5780 100644 --- a/datafusion/expr/src/logical_plan/materialized_cte.rs +++ b/datafusion/expr/src/logical_plan/materialized_cte.rs @@ -190,14 +190,7 @@ impl MaterializedCte { continuation: Arc, ) -> Result { let name = name.into(); - for scan in MaterializedCteScan::find_in(&continuation, id)? { - scan.check_body_schema(cte.schema()) - .map_err(|e| { - e.context(format!( - "A scan of the materialized CTE {name} does not have the schema of the CTE" - )) - })?; - } + check_scans(id, &name, cte.schema(), &continuation)?; Ok(Self { id, name, @@ -234,12 +227,24 @@ impl MaterializedCte { /// Whether a scan in the continuation reads this CTE, also in a subquery /// expression. A CTE that nothing reads does not need to be computed. pub fn is_read(&self) -> Result { - self.scans().map(|scans| !scans.is_empty()) + let mut is_read = false; + visit_scans(&self.continuation, self.id, |_| { + is_read = true; + Ok(TreeNodeRecursion::Stop) + })?; + Ok(is_read) + } + + /// Returns an error if a scan of this CTE in the continuation does not + /// have the names and types of the columns of the body that it reads. + pub(crate) fn check_scans(&self) -> Result<()> { + check_scans(self.id, &self.name, self.cte.schema(), &self.continuation) } /// The scans in the continuation that read this CTE, also in subquery /// expressions. See [`MaterializedCteScan::find_in`]. - pub(crate) fn scans(&self) -> Result> { + #[cfg(test)] + fn scans(&self) -> Result> { MaterializedCteScan::find_in(&self.continuation, self.id) } @@ -323,7 +328,13 @@ impl MaterializedCte { Transformed::yes(new_scan) }) })?; - Self::try_new(self.id, self.name, Arc::new(body), continuation) + // `with_body_schema` checked the names, and the scans have the types + // of `body`. + Ok(Self { + cte: Arc::new(body), + continuation, + ..self + }) } /// Remove from the body the columns that no scan of this CTE reads. The @@ -336,9 +347,10 @@ impl MaterializedCte { /// does not change if nothing reads the CTE or if every column is read. pub fn prune_body_columns(self) -> Result> { let body_len = self.cte.schema().fields().len(); - let scans = self.scans()?; + let mut has_scans = false; let mut is_read = vec![false; body_len]; - for scan in &scans { + visit_scans(&self.continuation, self.id, |scan| { + has_scans = true; match scan.projection() { None => is_read.fill(true), Some(projection) => { @@ -353,7 +365,8 @@ impl MaterializedCte { } } } - } + Ok(TreeNodeRecursion::Continue) + })?; if !is_read.contains(&true) && let Some(first) = is_read.first_mut() { @@ -361,7 +374,7 @@ impl MaterializedCte { } let kept: Vec = (0..body_len).filter(|index| is_read[*index]).collect(); // A CTE that nothing reads is not planned, so its body is left as it is. - if scans.is_empty() || kept.len() == body_len { + if !has_scans || kept.len() == body_len { return Ok(Transformed::no(self)); } @@ -375,8 +388,12 @@ impl MaterializedCte { let continuation = Self::map_scans(self.id, self.continuation, |scan| { scan.with_body_columns(&kept).map(Transformed::yes) })?; - Self::try_new(self.id, self.name, Arc::new(body), continuation) - .map(Transformed::yes) + // `with_body_columns` checked that each scan reads a kept column. + Ok(Transformed::yes(Self { + cte: Arc::new(body), + continuation, + ..self + })) } /// Apply `f` to each scan of the CTE `id` in `continuation`, also in @@ -681,30 +698,61 @@ impl MaterializedCteScan { /// The search does not go below a [`MaterializedCte`] with the same `id` /// in `plan`. Such a node is a separate occurrence of the CTE (the id is /// copied when a plan is cloned) and owns the scans below it. - pub(crate) fn find_in( - plan: &LogicalPlan, - id: MaterializedCteId, - ) -> Result> { + #[cfg(test)] + fn find_in(plan: &LogicalPlan, id: MaterializedCteId) -> Result> { let mut scans = vec![]; - plan.apply_with_subqueries(|node| match node { - LogicalPlan::MaterializedCte(MaterializedCtePlan::Cte(cte)) - if cte.id == id => - { - Ok(TreeNodeRecursion::Jump) - } - LogicalPlan::MaterializedCte(MaterializedCtePlan::Scan(scan)) - if scan.id == id => - { - scans.push(scan.clone()); - Ok(TreeNodeRecursion::Continue) - } - _ => Ok(TreeNodeRecursion::Continue), + visit_scans(plan, id, |scan| { + scans.push(scan.clone()); + Ok(TreeNodeRecursion::Continue) })?; Ok(scans) } } /// The columns `indices` of `schema`, with their qualifiers. +/// Call `f` with each scan of the CTE `id` in `plan`, also in subquery +/// expressions, until `f` returns [`TreeNodeRecursion::Stop`]. +/// +/// The traversal does not go below a [`MaterializedCte`] with the same `id`. +/// Such a node is a separate occurrence of the CTE (the id is copied when a +/// plan is cloned) and owns the scans below it. +fn visit_scans( + plan: &LogicalPlan, + id: MaterializedCteId, + mut f: impl FnMut(&MaterializedCteScan) -> Result, +) -> Result<()> { + plan.apply_with_subqueries(|node| match node { + LogicalPlan::MaterializedCte(MaterializedCtePlan::Cte(cte)) if cte.id == id => { + Ok(TreeNodeRecursion::Jump) + } + LogicalPlan::MaterializedCte(MaterializedCtePlan::Scan(scan)) + if scan.id == id => + { + f(scan) + } + _ => Ok(TreeNodeRecursion::Continue), + }) + .map(|_| ()) +} + +/// Returns an error if a scan of the CTE `id` in `continuation` does not have +/// the names and types of the columns of `body` that it reads. +fn check_scans( + id: MaterializedCteId, + name: &str, + body: &DFSchema, + continuation: &LogicalPlan, +) -> Result<()> { + visit_scans(continuation, id, |scan| { + scan.check_body_schema(body).map_err(|e| { + e.context(format!( + "A scan of the materialized CTE {name} does not have the schema of the CTE" + )) + })?; + Ok(TreeNodeRecursion::Continue) + }) +} + fn project_schema(schema: &DFSchema, indices: &[usize]) -> Result { let fields = indices .iter() @@ -738,6 +786,7 @@ impl PartialOrd for MaterializedCteScan { #[cfg(test)] mod tests { use super::*; + use crate::logical_plan::InvariantLevel; use crate::logical_plan::builder::LogicalPlanBuilder; use crate::{EmptyRelation, exists}; use arrow::datatypes::{DataType, Field, Schema}; @@ -1070,7 +1119,6 @@ mod tests { #[test] fn check_invariants_rejects_a_scan_that_does_not_match_the_body() -> Result<()> { - use crate::logical_plan::InvariantLevel; let id = MaterializedCteId::next(); let cte = MaterializedCte::try_new( id, @@ -1091,8 +1139,9 @@ mod tests { .check_invariants(InvariantLevel::Executable) .unwrap_err(); assert!( - err.to_string() - .contains("A scan of the materialized CTE c does not match the CTE"), + err.to_string().contains( + "A scan of the materialized CTE c does not have the schema of the CTE" + ), "{err}" ); From c5d915f2f8eaa36582683e2da301a76401c85764 Mon Sep 17 00:00:00 2001 From: Adrian Garcia Badaracco <1755071+adriangb@users.noreply.github.com> Date: Fri, 27 Nov 2026 20:53:31 -0800 Subject: [PATCH 08/12] fix: check the scans after both calls in map_inputs_mut map_inputs_mut rejected a body that removed an unread column, but check_invariants accepted the same plan from map_children. After both calls of the closure, map_inputs_mut checks the scans against the body with the check that check_invariants uses. The tests change the body through both paths. Co-Authored-By: Claude Opus 5.5 --- .../expr/src/logical_plan/materialized_cte.rs | 130 +++++++++++++----- 1 file changed, 97 insertions(+), 33 deletions(-) diff --git a/datafusion/expr/src/logical_plan/materialized_cte.rs b/datafusion/expr/src/logical_plan/materialized_cte.rs index 91fc4bebe5780..047e98a5e2e65 100644 --- a/datafusion/expr/src/logical_plan/materialized_cte.rs +++ b/datafusion/expr/src/logical_plan/materialized_cte.rs @@ -251,27 +251,22 @@ impl MaterializedCte { /// Call `f` with the body, then with the continuation, so that a rule can /// change them in place. Return `true` if a call of `f` returns `true`. /// - /// Returns an error if `f` changes the names or the types of the columns - /// of the body, because the scans read them by position. The continuation - /// is not checked: its schema can change, and the optimizer then - /// recomputes the schema of this node. + /// After both calls, if an input changed, check the scans of this CTE in + /// the continuation against the body, as [`LogicalPlan::check_invariants`] + /// does. Returns an error if a scan does not have the names and types of + /// the columns of the body that it reads. A rule can remove a column of + /// the body that no scan reads. The continuation can change its schema, + /// and the optimizer then recomputes the schema of this node. pub fn map_inputs_mut( &mut self, mut f: impl FnMut(&mut LogicalPlan) -> Result, ) -> Result { let schema = Arc::clone(self.cte.schema()); let body = f(Arc::make_mut(&mut self.cte))?; - if !Arc::ptr_eq(&schema, self.cte.schema()) { - schema - .has_equivalent_names_and_types(self.cte.schema()) - .map_err(|e| { - e.context(format!( - "The body of the materialized CTE {} changed its columns", - self.name - )) - })?; - } let continuation = f(Arc::make_mut(&mut self.continuation))?; + if body || continuation || !Arc::ptr_eq(&schema, self.cte.schema()) { + self.check_scans()?; + } Ok(body || continuation) } @@ -1079,39 +1074,108 @@ mod tests { Ok(()) } - #[test] - fn map_inputs_mut_rejects_a_body_with_other_columns() -> Result<()> { + /// A body with the columns `a` and `b`, and a scan that reads only `a`. + fn cte_that_reads_a() -> Result { let id = MaterializedCteId::next(); - let mut cte = MaterializedCte::try_new( - id, - "c", - body(DataType::Int32), - Arc::new(scan(id, DataType::Int32)), - )?; - assert!(!cte.map_inputs_mut(|_| Ok(false))?); + let body = Arc::new(LogicalPlan::EmptyRelation(EmptyRelation { + produce_one_row: false, + schema: wide_schema(), + })); + let scan = + MaterializedCteScan::new(id, "c", wide_schema()).with_projection(&[0])?; + MaterializedCte::try_new(id, "c", body, Arc::new(scan.into())) + } - // A new body with the same names and types is accepted. + /// The body with only the first `n` columns of [`wide_schema`]. + fn narrow_body( + cte: &MaterializedCte, + n: usize, + data_type: DataType, + ) -> Result { + let fields = cte.body().schema().fields()[..n] + .iter() + .map(|f| Field::new(f.name(), data_type.clone(), true)) + .collect::>(); + Ok(LogicalPlan::EmptyRelation(EmptyRelation { + produce_one_row: false, + schema: Arc::new(DFSchema::try_from_qualified_schema( + "c", + &Schema::new(fields), + )?), + })) + } + + #[test] + fn map_inputs_mut_checks_the_scans_after_both_calls() -> Result<()> { + let mut cte = cte_that_reads_a()?; let mut visited = 0; - assert!(cte.map_inputs_mut(|input| { + assert!(!cte.map_inputs_mut(|_| { visited += 1; - if visited == 1 { - *input = LogicalPlan::clone(&body(DataType::Int32)); - } - Ok(visited == 1) + Ok(false) })?); assert_eq!(visited, 2); + // A rule can remove the column `b`, because no scan reads it. + let mut pruned = cte.clone(); + let new_body = narrow_body(&pruned, 1, DataType::Int32)?; + let mut new_body = Some(new_body); + assert!(pruned.map_inputs_mut(|input| { + if let Some(body) = new_body.take() { + *input = body; + return Ok(true); + } + Ok(false) + })?); + assert_eq!(pruned.body().schema().fields().len(), 1); + LogicalPlan::from(pruned).check_invariants(InvariantLevel::Executable)?; + + // A rule cannot change the type of the column `a`, because a scan + // reads it. + let mut new_body = Some(narrow_body(&cte, 1, DataType::Utf8)?); let err = cte .map_inputs_mut(|input| { - if matches!(input, LogicalPlan::EmptyRelation(_)) { - *input = LogicalPlan::clone(&body(DataType::Utf8)); + if let Some(body) = new_body.take() { + *input = body; } Ok(true) }) .unwrap_err(); assert!( - err.to_string() - .contains("The body of the materialized CTE c changed its columns"), + err.to_string().contains( + "A scan of the materialized CTE c does not have the schema of the CTE" + ), + "{err}" + ); + Ok(()) + } + + /// The same body changes through [`TreeNode::map_children`], which does + /// not check the scans. [`LogicalPlan::check_invariants`] gives the + /// result of [`MaterializedCte::map_inputs_mut`]. + #[test] + fn check_invariants_agrees_with_map_inputs_mut() -> Result<()> { + use datafusion_common::tree_node::TreeNode; + let cte = cte_that_reads_a()?; + let replace_body = |data_type: DataType| -> Result { + let new_body = narrow_body(&cte, 1, data_type)?; + let mut new_body = Some(new_body); + LogicalPlan::from(cte.clone()) + .map_children(|child| { + Ok(match new_body.take() { + Some(body) => Transformed::yes(body), + None => Transformed::no(child), + }) + }) + .map(|t| t.data) + }; + replace_body(DataType::Int32)?.check_invariants(InvariantLevel::Executable)?; + let err = replace_body(DataType::Utf8)? + .check_invariants(InvariantLevel::Executable) + .unwrap_err(); + assert!( + err.to_string().contains( + "A scan of the materialized CTE c does not have the schema of the CTE" + ), "{err}" ); Ok(()) From 4660df9208f169f1669f3b169868a75abfb94545 Mon Sep 17 00:00:00 2001 From: Adrian Garcia Badaracco <1755071+adriangb@users.noreply.github.com> Date: Mon, 30 Nov 2026 23:55:26 -0800 Subject: [PATCH 09/12] perf: do not clone a plan that has no materialized CTE The physical planner cloned every plan before the renumbering looked for a CTE. Borrow the plan, and clone it only when it has one. Co-Authored-By: Claude Opus 5.5 --- datafusion/core/src/physical_planner.rs | 4 +- .../expr/src/logical_plan/materialized_cte.rs | 40 ++++++++++--------- 2 files changed, 24 insertions(+), 20 deletions(-) diff --git a/datafusion/core/src/physical_planner.rs b/datafusion/core/src/physical_planner.rs index e97d75be3efc6..9bbcb8125295c 100644 --- a/datafusion/core/src/physical_planner.rs +++ b/datafusion/core/src/physical_planner.rs @@ -229,8 +229,8 @@ impl DefaultPhysicalPlanner { } // The ids must be new for each planning run. See // `renumber_materialized_ctes`. - let logical_plan = renumber_materialized_ctes(logical_plan.clone())?.data; - let logical_plan = &logical_plan; + let renumbered = renumber_materialized_ctes(logical_plan)?; + let logical_plan = renumbered.as_ref().unwrap_or(logical_plan); let plan = self .create_initial_plan(logical_plan, session_state) .await?; diff --git a/datafusion/expr/src/logical_plan/materialized_cte.rs b/datafusion/expr/src/logical_plan/materialized_cte.rs index 047e98a5e2e65..fbd27644a9257 100644 --- a/datafusion/expr/src/logical_plan/materialized_cte.rs +++ b/datafusion/expr/src/logical_plan/materialized_cte.rs @@ -463,7 +463,9 @@ impl PartialOrd for MaterializedCte { /// the results in one physical plan. /// /// A new id does not change a schema, so the scans are not checked again. -pub fn renumber_materialized_ctes(plan: LogicalPlan) -> Result> { +/// +/// Returns `None`, and does not clone `plan`, if it has no materialized CTE. +pub fn renumber_materialized_ctes(plan: &LogicalPlan) -> Result> { let mut has_cte = false; plan.apply_with_subqueries(|node| { if matches!( @@ -476,24 +478,26 @@ pub fn renumber_materialized_ctes(plan: LogicalPlan) -> Result Date: Mon, 30 Nov 2026 23:55:36 -0800 Subject: [PATCH 10/12] fix: coerce the body and the continuation in one operation with_coerced_body returned a node whose continuation could have stale schemas, and its caller had to clone the body. coerce_inputs consumes both inputs, and checks the scans after the continuation is coerced. Co-Authored-By: Claude Opus 5.5 --- .../expr/src/logical_plan/materialized_cte.rs | 101 +++++++++++++++--- .../optimizer/src/analyzer/type_coercion.rs | 11 +- 2 files changed, 86 insertions(+), 26 deletions(-) diff --git a/datafusion/expr/src/logical_plan/materialized_cte.rs b/datafusion/expr/src/logical_plan/materialized_cte.rs index fbd27644a9257..86f5cebe08208 100644 --- a/datafusion/expr/src/logical_plan/materialized_cte.rs +++ b/datafusion/expr/src/logical_plan/materialized_cte.rs @@ -306,30 +306,36 @@ impl MaterializedCte { .map_data(|cte| Self::try_new(id, name, Arc::new(cte), continuation)) } - /// Replace the body with `body`, which has the column names of the - /// current body and maybe other types, for example after type coercion. - /// Each scan gets the new types of the columns that it reads, and keeps - /// its qualifiers. + /// Replace the body with the result of `f`, give each scan the new types + /// of the columns that it reads, then replace the continuation with the + /// result of `f`. A scan keeps its qualifiers. Type coercion uses this. /// - /// Returns an error if `body` does not have the column names of the - /// current body that the scans read. - pub fn with_coerced_body(self, body: LogicalPlan) -> Result { - let body_schema = Arc::clone(body.schema()); - let continuation = Self::map_scans(self.id, self.continuation, |scan| { - let new_scan = scan.with_body_schema(&body_schema)?; + /// `f` must recompute the schemas of the continuation from its leaves, + /// because the new types of the scans can change the schemas above them. + /// + /// Returns an error if `f` changes a column name that a scan reads, or if + /// a scan in the new continuation does not match the new body. + pub fn coerce_inputs( + self, + mut f: impl FnMut(LogicalPlan) -> Result, + ) -> Result { + let Self { + id, + name, + cte, + continuation, + } = self; + let body = f(Arc::unwrap_or_clone(cte))?; + let continuation = Self::map_scans(id, continuation, |scan| { + let new_scan = scan.with_body_schema(body.schema())?; Ok(if new_scan.schema().inner() == scan.schema().inner() { Transformed::no(scan) } else { Transformed::yes(new_scan) }) })?; - // `with_body_schema` checked the names, and the scans have the types - // of `body`. - Ok(Self { - cte: Arc::new(body), - continuation, - ..self - }) + let continuation = f(Arc::unwrap_or_clone(continuation))?; + Self::try_new(id, name, Arc::new(body), Arc::new(continuation)) } /// Remove from the body the columns that no scan of this CTE reads. The @@ -1185,6 +1191,67 @@ mod tests { Ok(()) } + #[test] + fn coerce_inputs_updates_the_continuation_and_dependent_ctes() -> Result<()> { + use datafusion_common::tree_node::{TransformedResult, TreeNode}; + // c AS (a Int32), d AS (SELECT * FROM c) SELECT a FROM d + let c = + MaterializedCteBuilder::new("c", LogicalPlan::clone(&body(DataType::Int32))); + let d = MaterializedCteBuilder::new("d", c.scan().into()); + let project = LogicalPlanBuilder::from(LogicalPlan::from(d.scan())) + .project(vec![Expr::Column(Column::from( + d.scan().schema().qualified_field(0), + ))])? + .build()?; + let cte = c.build(d.build(project)?.into())?; + + fn coerce(plan: LogicalPlan) -> Result { + plan.transform_down_up( + |node| match node { + LogicalPlan::MaterializedCte(MaterializedCtePlan::Cte(cte)) => { + Ok(Transformed::new( + cte.coerce_inputs(coerce)?.into(), + true, + TreeNodeRecursion::Jump, + )) + } + LogicalPlan::EmptyRelation(_) => { + Ok(Transformed::yes(LogicalPlan::clone(&body(DataType::Int64)))) + } + node => Ok(Transformed::no(node)), + }, + |node| node.recompute_schema().map(Transformed::yes), + ) + .data() + } + let plan = LogicalPlan::from(cte.coerce_inputs(coerce)?); + plan.check_invariants(InvariantLevel::Executable)?; + assert_eq!(plan.schema().field(0).data_type(), &DataType::Int64); + Ok(()) + } + + #[test] + fn coerce_inputs_consumes_a_uniquely_owned_body() -> Result<()> { + let c = MaterializedCteBuilder::new( + "c", + LogicalPlanBuilder::from(LogicalPlan::clone(&body(DataType::Int32))) + .limit(0, Some(1))? + .build()?, + ); + let scan = c.scan(); + let mut is_body = true; + c.build(scan.into())?.coerce_inputs(|plan| { + if std::mem::take(&mut is_body) { + let LogicalPlan::Limit(limit) = &plan else { + panic!("expected a limit: {plan}") + }; + assert_eq!(Arc::strong_count(&limit.input), 1); + } + Ok(plan) + })?; + Ok(()) + } + #[test] fn check_invariants_rejects_a_scan_that_does_not_match_the_body() -> Result<()> { let id = MaterializedCteId::next(); diff --git a/datafusion/optimizer/src/analyzer/type_coercion.rs b/datafusion/optimizer/src/analyzer/type_coercion.rs index 195f7f7c0e00d..fa8d9f27cebaf 100644 --- a/datafusion/optimizer/src/analyzer/type_coercion.rs +++ b/datafusion/optimizer/src/analyzer/type_coercion.rs @@ -127,15 +127,8 @@ fn coerce_plan_and_subqueries( // of a `NULL` column of a `UNION`. Coerce the body first, and give // its new schema to the scans before the continuation is coerced. LogicalPlan::MaterializedCte(MaterializedCtePlan::Cte(cte)) => { - let body = - coerce_plan_and_subqueries(LogicalPlan::clone(cte.body()), config)?; - let cte = cte - .with_coerced_body(body)? - .map_continuation(|continuation| { - coerce_plan_and_subqueries(continuation, config) - .map(Transformed::yes) - })? - .data; + let cte = + cte.coerce_inputs(|plan| coerce_plan_and_subqueries(plan, config))?; Ok(Transformed::new(cte.into(), true, TreeNodeRecursion::Jump)) } _ => Ok(Transformed::no(plan)), From 5f8280457e8a4145111e077a3e2ab70ae9aea7b1 Mon Sep 17 00:00:00 2001 From: Adrian Garcia Badaracco <1755071+adriangb@users.noreply.github.com> Date: Mon, 30 Nov 2026 23:55:46 -0800 Subject: [PATCH 11/12] refactor: keep the scan accessors of MaterializedCte public 56.0.0 released scans and find_in. They only read the plan, so hiding them is a break without a benefit. They also replace the new is_read. Co-Authored-By: Claude Opus 5.5 --- datafusion/core/src/physical_planner.rs | 2 +- .../expr/src/logical_plan/materialized_cte.rs | 17 ++--------------- 2 files changed, 3 insertions(+), 16 deletions(-) diff --git a/datafusion/core/src/physical_planner.rs b/datafusion/core/src/physical_planner.rs index 9bbcb8125295c..35c1304d566df 100644 --- a/datafusion/core/src/physical_planner.rs +++ b/datafusion/core/src/physical_planner.rs @@ -1967,7 +1967,7 @@ impl DefaultPhysicalPlanner { LogicalPlan::MaterializedCte(MaterializedCtePlan::Cte(cte)) => { let [body, continuation] = children.two()?; // A CTE that nothing reads is never evaluated. - if !cte.is_read()? { + if cte.scans()?.is_empty() { return Ok(continuation); } // The body is fully buffered before a scan yields a row, so an diff --git a/datafusion/expr/src/logical_plan/materialized_cte.rs b/datafusion/expr/src/logical_plan/materialized_cte.rs index 86f5cebe08208..afa2a7258e444 100644 --- a/datafusion/expr/src/logical_plan/materialized_cte.rs +++ b/datafusion/expr/src/logical_plan/materialized_cte.rs @@ -224,17 +224,6 @@ impl MaterializedCte { self.continuation.schema() } - /// Whether a scan in the continuation reads this CTE, also in a subquery - /// expression. A CTE that nothing reads does not need to be computed. - pub fn is_read(&self) -> Result { - let mut is_read = false; - visit_scans(&self.continuation, self.id, |_| { - is_read = true; - Ok(TreeNodeRecursion::Stop) - })?; - Ok(is_read) - } - /// Returns an error if a scan of this CTE in the continuation does not /// have the names and types of the columns of the body that it reads. pub(crate) fn check_scans(&self) -> Result<()> { @@ -243,8 +232,7 @@ impl MaterializedCte { /// The scans in the continuation that read this CTE, also in subquery /// expressions. See [`MaterializedCteScan::find_in`]. - #[cfg(test)] - fn scans(&self) -> Result> { + pub fn scans(&self) -> Result> { MaterializedCteScan::find_in(&self.continuation, self.id) } @@ -703,8 +691,7 @@ impl MaterializedCteScan { /// The search does not go below a [`MaterializedCte`] with the same `id` /// in `plan`. Such a node is a separate occurrence of the CTE (the id is /// copied when a plan is cloned) and owns the scans below it. - #[cfg(test)] - fn find_in(plan: &LogicalPlan, id: MaterializedCteId) -> Result> { + pub fn find_in(plan: &LogicalPlan, id: MaterializedCteId) -> Result> { let mut scans = vec![]; visit_scans(plan, id, |scan| { scans.push(scan.clone()); From 1f6553cdb1325cebd0d81b2033120909700a46ff Mon Sep 17 00:00:00 2001 From: Adrian Garcia Badaracco <1755071+adriangb@users.noreply.github.com> Date: Mon, 30 Nov 2026 23:55:58 -0800 Subject: [PATCH 12/12] docs: restore the materialized CTE upgrade guide A rebase removed the section. Restore it, and give the replacement for each public item of 56.0.0. Co-Authored-By: Claude Opus 5.5 --- .../library-user-guide/upgrading/57.0.0.md | 67 +++++++++++++++++++ 1 file changed, 67 insertions(+) diff --git a/docs/source/library-user-guide/upgrading/57.0.0.md b/docs/source/library-user-guide/upgrading/57.0.0.md index 8e5a74ba250f3..2b6503be6119d 100644 --- a/docs/source/library-user-guide/upgrading/57.0.0.md +++ b/docs/source/library-user-guide/upgrading/57.0.0.md @@ -228,6 +228,73 @@ let statistics = Statistics::new_unknown(&self.schema()) .with_num_rows(Precision::Exact(num_rows)); ``` +### Materialized CTE scans have a projection + +`MaterializedCteScan` and `MaterializedCteScanExec` have a `projection`. It gives +the indexes of the columns of the CTE body that the scan outputs. `None` means all +the columns. `OptimizeProjections` uses it to remove from the body the columns +that no scan reads. + +A custom optimizer rule that changes the schema of the body of a +`MaterializedCte` must also change the `projection` of every scan of that CTE, +because a scan reads the columns of the body by position. Use the methods of +`MaterializedCte` below, which change the body and the scans together. + +The `schema` and `projection` fields of `MaterializedCteScan` are private, so +that the two always match. Read them with `MaterializedCteScan::schema` and +`MaterializedCteScan::projection`. Narrow a scan with +`MaterializedCteScan::with_projection`. To build a physical scan with a +projection, use `MaterializedCteScanExec::with_body_projection`. It returns an +error if the projection does not have one index for each column of the scan +schema. + +The fields of `MaterializedCte` and `MaterializedCteScan`, which were public in +56.0.0, are private. Replace the 56.0.0 API as follows: + +| 56.0.0 | 57.0.0 | +| --------------------------------------------------------------------------------- | ---------------------------------------------- | +| Read a field of `MaterializedCte` | `id()`, `name()`, `body()`, `continuation()` | +| Read a field of `MaterializedCteScan` | `id()`, `name()`, `schema()` | +| `MaterializedCteId::next`, `MaterializedCteScan::new`, `MaterializedCte::try_new` | `MaterializedCteBuilder::new`, `scan`, `build` | +| `MaterializedCte::with_new_inputs`, struct update | A method in the table below | + +`MaterializedCte::scans` and `MaterializedCteScan::find_in` do not change. + +Build a node with +`MaterializedCteBuilder`, which allocates the id that binds the scans to the +node: + +```rust,ignore +let builder = MaterializedCteBuilder::new("c", body); +// One scan for each reference to the CTE. +let continuation = LogicalPlan::from(builder.scan()); +let plan = LogicalPlan::from(builder.build(continuation)?); +``` + +Use these methods to change a node: + +| API | What it does | +| ------------------------------------- | ------------------------------------------------------------------------------------ | +| `MaterializedCte::map_continuation` | Replaces the continuation with the result of a closure. | +| `MaterializedCte::map_body` | Replaces the body with the result of a closure. The scans do not change. | +| `MaterializedCte::coerce_inputs` | Replaces the body, gives its new types to the scans, then replaces the continuation. | +| `MaterializedCte::prune_body_columns` | Removes the body columns that no scan reads. The scans read the new positions. | +| `MaterializedCte::map_inputs_mut` | Calls a closure that changes the body, then the continuation, in place. | +| `renumber_materialized_ctes` | Gives each `MaterializedCte` in a plan, and its scans, a new id. | + +Each method except `renumber_materialized_ctes` checks that the scans have +the names and types of the columns that they read from the body. +`map_inputs_mut` does this check after both calls of the closure, so a rule +can remove a column of the body that no scan reads. A new id does not change +a schema. + +`LogicalPlan::with_new_exprs` and `TreeNode::map_children` replace the inputs +of a `MaterializedCte` without these checks. `LogicalPlan::check_invariants` +checks that each scan of a `MaterializedCte` has the names and types of the +columns that it reads from the body. The optimizer runs this check before and +after the rules, and after each rule in debug builds, so a custom rule that does not remap the scans fails with an +error. + ### Null-aware sort-merge joins add a protobuf field `SortMergeJoinExec` now supports null-aware (`NOT IN`) semantics for