From ffb77b4d60804d7d820e47a053dd9b567dddbaae 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 1/8] 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, and every in-place change through inputs_mut or with_new_inputs.
The fields are pub(crate), so the tree-node and display code of
datafusion-expr is unchanged. inputs_mut and into_inputs replace the
remaining direct field access in the optimizer and the physical planner.
---
datafusion/core/src/physical_planner.rs | 22 ++++++++++---------
.../expr/src/logical_plan/materialized_cte.rs | 20 +++++++++++++----
datafusion/expr/src/logical_plan/plan.rs | 10 ++++-----
.../optimizer/src/analyzer/type_coercion.rs | 21 ++++++++++--------
datafusion/optimizer/src/decorrelate.rs | 17 ++++++++------
.../optimizer/src/optimize_projections/mod.rs | 10 +++------
datafusion/optimizer/src/optimizer.rs | 11 ++++------
datafusion/optimizer/src/push_down_filter.rs | 5 +++--
.../library-user-guide/upgrading/57.0.0.md | 7 ++++++
9 files changed, 71 insertions(+), 52 deletions(-)
diff --git a/datafusion/core/src/physical_planner.rs b/datafusion/core/src/physical_planner.rs
index a861a538d6b13..601f2e4a10746 100644
--- a/datafusion/core/src/physical_planner.rs
+++ b/datafusion/core/src/physical_planner.rs
@@ -274,15 +274,16 @@ 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 (old_id, name) = (cte.id(), cte.name().to_string());
let new_id = MaterializedCteId::next();
- let continuation = Arc::unwrap_or_clone(cte.continuation)
+ let (body, continuation) = cte.into_inputs();
+ 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 +298,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 +2046,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..bcde76056f3c4 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,6 +151,18 @@ impl MaterializedCte {
MaterializedCteScan::find_in(&self.continuation, self.id)
}
+ /// The body and the continuation, in this order, for a rule that changes
+ /// them in place. The schemas of the scans are not checked again.
+ pub fn inputs_mut(&mut self) -> (&mut Arc, &mut Arc) {
+ (&mut self.cte, &mut self.continuation)
+ }
+
+ /// The body and the continuation, in this order. Build a node again with
+ /// [`Self::try_new`].
+ pub fn into_inputs(self) -> (Arc, Arc) {
+ (self.cte, self.continuation)
+ }
+
/// Return a node with the same id and name, and new inputs. The schemas
/// of the scans are not checked again.
pub fn with_new_inputs(
diff --git a/datafusion/expr/src/logical_plan/plan.rs b/datafusion/expr/src/logical_plan/plan.rs
index d2467e2346c44..cd812eafa6aca 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),
diff --git a/datafusion/optimizer/src/analyzer/type_coercion.rs b/datafusion/optimizer/src/analyzer/type_coercion.rs
index 42e74b0d70437..d54e64587f43c 100644
--- a/datafusion/optimizer/src/analyzer/type_coercion.rs
+++ b/datafusion/optimizer/src/analyzer/type_coercion.rs
@@ -128,21 +128,24 @@ 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) = (cte.id(), cte.name().to_string());
+ let (body, continuation) = cte.into_inputs();
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 +176,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 3e6f141af5d9c..3f7e0bb2089f0 100644
--- a/datafusion/optimizer/src/decorrelate.rs
+++ b/datafusion/optimizer/src/decorrelate.rs
@@ -215,7 +215,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))
@@ -223,14 +223,17 @@ 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) = (cte.id(), cte.name().to_string());
+ let (body, continuation) = cte.into_inputs();
+ 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..59444c93f43f3 100644
--- a/datafusion/optimizer/src/optimize_projections/mod.rs
+++ b/datafusion/optimizer/src/optimize_projections/mod.rs
@@ -528,12 +528,8 @@ fn optimize_materialized_cte(
config: &dyn OptimizerConfig,
indices: RequiredIndices,
) -> Result> {
- let MaterializedCte {
- id,
- name,
- cte: body,
- continuation,
- } = cte;
+ let (id, name) = (cte.id(), cte.name().to_string());
+ let (body, continuation) = cte.into_inputs();
// The output is the output of the continuation, so the continuation
// needs what the parent needs.
let continuation =
@@ -578,7 +574,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..612a53964c512 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,11 +467,8 @@ fn map_children_mut Result>(
let r = f(Arc::make_mut(recursive_term))?;
s || r
}
- LogicalPlan::MaterializedCte(MaterializedCtePlan::Cte(MaterializedCte {
- cte,
- continuation,
- ..
- })) => {
+ LogicalPlan::MaterializedCte(MaterializedCtePlan::Cte(cte)) => {
+ let (cte, continuation) = cte.inputs_mut();
let b = f(Arc::make_mut(cte))?;
let c = f(Arc::make_mut(continuation))?;
b || c
diff --git a/datafusion/optimizer/src/push_down_filter.rs b/datafusion/optimizer/src/push_down_filter.rs
index efaea281a14e2..75344182f2ea4 100644
--- a/datafusion/optimizer/src/push_down_filter.rs
+++ b/datafusion/optimizer/src/push_down_filter.rs
@@ -1403,9 +1403,10 @@ 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(
+ let (_, continuation) = cte.inputs_mut();
+ *continuation = Arc::new(LogicalPlan::Filter(Filter::new(
filter.predicate,
- cte.continuation,
+ Arc::clone(continuation),
)));
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 438b0ed3b1a76..ef806290325f5 100644
--- a/docs/source/library-user-guide/upgrading/57.0.0.md
+++ b/docs/source/library-user-guide/upgrading/57.0.0.md
@@ -168,3 +168,10 @@ schema.
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.
+
+The fields of `MaterializedCte` are private. Read them with
+`MaterializedCte::id`, `name`, `body` and `continuation`. Build a node with
+`MaterializedCte::try_new`, which checks the scans of the CTE. A rule that
+changes the inputs in place can use `MaterializedCte::inputs_mut` or
+`MaterializedCte::with_new_inputs`, and `MaterializedCte::into_inputs` takes
+the inputs by value.
From d367c8ee89c0ca070c839f8608db29b0df695072 Mon Sep 17 00:00:00 2001
From: Adrian Garcia Badaracco <1755071+adriangb@users.noreply.github.com>
Date: Mon, 23 Nov 2026 23:35:04 -0600
Subject: [PATCH 2/8] refactor: make MaterializedCte input mutation APIs
fallible
Review asked that the unchecked mutation APIs keep room for future
validation. try_map_inputs_mut replaces inputs_mut and takes a fallible
closure, and with_new_inputs returns a Result. into_parts replaces
into_inputs and also returns the id and name, so that callers do not copy
the name before they consume the node.
Co-Authored-By: Claude Opus 5.5
---
datafusion/core/src/physical_planner.rs | 3 +-
.../expr/src/logical_plan/materialized_cte.rs | 51 ++++++++++++-------
datafusion/expr/src/logical_plan/plan.rs | 2 +-
.../optimizer/src/analyzer/type_coercion.rs | 3 +-
datafusion/optimizer/src/decorrelate.rs | 3 +-
.../optimizer/src/optimize_projections/mod.rs | 3 +-
datafusion/optimizer/src/optimizer.rs | 12 ++---
datafusion/optimizer/src/push_down_filter.rs | 12 +++--
.../library-user-guide/upgrading/57.0.0.md | 18 +++++--
9 files changed, 65 insertions(+), 42 deletions(-)
diff --git a/datafusion/core/src/physical_planner.rs b/datafusion/core/src/physical_planner.rs
index 601f2e4a10746..0fa6ea0195f87 100644
--- a/datafusion/core/src/physical_planner.rs
+++ b/datafusion/core/src/physical_planner.rs
@@ -274,9 +274,8 @@ fn renumber_materialized_ctes(plan: &LogicalPlan) -> Result>
let LogicalPlan::MaterializedCte(MaterializedCtePlan::Cte(cte)) = node else {
return Ok(Transformed::no(node));
};
- let (old_id, name) = (cte.id(), cte.name().to_string());
let new_id = MaterializedCteId::next();
- let (body, continuation) = cte.into_inputs();
+ 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
diff --git a/datafusion/expr/src/logical_plan/materialized_cte.rs b/datafusion/expr/src/logical_plan/materialized_cte.rs
index bcde76056f3c4..199651d0c50b9 100644
--- a/datafusion/expr/src/logical_plan/materialized_cte.rs
+++ b/datafusion/expr/src/logical_plan/materialized_cte.rs
@@ -151,31 +151,46 @@ impl MaterializedCte {
MaterializedCteScan::find_in(&self.continuation, self.id)
}
- /// The body and the continuation, in this order, for a rule that changes
- /// them in place. The schemas of the scans are not checked again.
- pub fn inputs_mut(&mut self) -> (&mut Arc, &mut Arc) {
- (&mut self.cte, &mut self.continuation)
- }
-
- /// The body and the continuation, in this order. Build a node again with
- /// [`Self::try_new`].
- pub fn into_inputs(self) -> (Arc, Arc) {
- (self.cte, self.continuation)
- }
-
- /// 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,
- }
+ })
}
}
@@ -758,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 cd812eafa6aca..956d31d0ed8d6 100644
--- a/datafusion/expr/src/logical_plan/plan.rs
+++ b/datafusion/expr/src/logical_plan/plan.rs
@@ -1232,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 d54e64587f43c..4f8843dbc83cb 100644
--- a/datafusion/optimizer/src/analyzer/type_coercion.rs
+++ b/datafusion/optimizer/src/analyzer/type_coercion.rs
@@ -128,8 +128,7 @@ 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) = (cte.id(), cte.name().to_string());
- let (body, continuation) = cte.into_inputs();
+ 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(
diff --git a/datafusion/optimizer/src/decorrelate.rs b/datafusion/optimizer/src/decorrelate.rs
index 3f7e0bb2089f0..25918d6f48071 100644
--- a/datafusion/optimizer/src/decorrelate.rs
+++ b/datafusion/optimizer/src/decorrelate.rs
@@ -223,8 +223,7 @@ 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) = (cte.id(), cte.name().to_string());
- let (body, continuation) = cte.into_inputs();
+ let (id, name, body, continuation) = cte.into_parts();
let continuation = Arc::unwrap_or_clone(continuation).rewrite(self)?;
Ok(Transformed::new(
LogicalPlan::MaterializedCte(MaterializedCtePlan::Cte(
diff --git a/datafusion/optimizer/src/optimize_projections/mod.rs b/datafusion/optimizer/src/optimize_projections/mod.rs
index 59444c93f43f3..6d1f550b77416 100644
--- a/datafusion/optimizer/src/optimize_projections/mod.rs
+++ b/datafusion/optimizer/src/optimize_projections/mod.rs
@@ -528,8 +528,7 @@ fn optimize_materialized_cte(
config: &dyn OptimizerConfig,
indices: RequiredIndices,
) -> Result> {
- let (id, name) = (cte.id(), cte.name().to_string());
- let (body, continuation) = cte.into_inputs();
+ 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 =
diff --git a/datafusion/optimizer/src/optimizer.rs b/datafusion/optimizer/src/optimizer.rs
index 612a53964c512..7e738809fac98 100644
--- a/datafusion/optimizer/src/optimizer.rs
+++ b/datafusion/optimizer/src/optimizer.rs
@@ -467,12 +467,12 @@ fn map_children_mut Result>(
let r = f(Arc::make_mut(recursive_term))?;
s || r
}
- LogicalPlan::MaterializedCte(MaterializedCtePlan::Cte(cte)) => {
- let (cte, continuation) = cte.inputs_mut();
- 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 75344182f2ea4..8b006ffb29f7c 100644
--- a/datafusion/optimizer/src/push_down_filter.rs
+++ b/datafusion/optimizer/src/push_down_filter.rs
@@ -1403,11 +1403,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.
- let (_, continuation) = cte.inputs_mut();
- *continuation = Arc::new(LogicalPlan::Filter(Filter::new(
- filter.predicate,
- Arc::clone(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 ef806290325f5..73707c3d7e2d9 100644
--- a/docs/source/library-user-guide/upgrading/57.0.0.md
+++ b/docs/source/library-user-guide/upgrading/57.0.0.md
@@ -171,7 +171,17 @@ that does not remap the scans now fails with an error that names the rule.
The fields of `MaterializedCte` are private. Read them with
`MaterializedCte::id`, `name`, `body` and `continuation`. Build a node with
-`MaterializedCte::try_new`, which checks the scans of the CTE. A rule that
-changes the inputs in place can use `MaterializedCte::inputs_mut` or
-`MaterializedCte::with_new_inputs`, and `MaterializedCte::into_inputs` takes
-the inputs by value.
+`MaterializedCte::try_new`, which checks the scans of the CTE.
+`MaterializedCte::into_parts` takes the id, name, body and continuation by
+value, so that a rule can rebuild the node with `try_new`.
+
+Two other APIs do not check the scans:
+
+| API | What it does |
+| ------------------------------------- | -------------------------------------------------------------------- |
+| `MaterializedCte::try_map_inputs_mut` | Calls a closure that changes the body and the continuation in place. |
+| `MaterializedCte::with_new_inputs` | Returns a new node with the same id and name, and new inputs. |
+
+Both return a `Result`, so that a later version can check the scans.
+`LogicalPlan::check_invariants` checks the scans of a plan that these APIs
+build.
From 6ac27dfeef8aca05c70ba399aaef8fe9fe63bf6a 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 3/8] 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 6df1dd18fb4fc53021be8825b24217bd47d4dc40 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 4/8] 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 0fa6ea0195f87..8b99dd304a9a1 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 4f8843dbc83cb..910b6fb66d683 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 25918d6f48071..2ea4bcf8bd204 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
@@ -223,18 +223,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 8b006ffb29f7c..f32df473655f8 100644
--- a/datafusion/optimizer/src/push_down_filter.rs
+++ b/datafusion/optimizer/src/push_down_filter.rs
@@ -1399,20 +1399,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 696ad04a507a1f26c25aa79cab8e4365735e8b83 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 5/8] 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 +--
.../library-user-guide/upgrading/57.0.0.md | 8 +--
3 files changed, 68 insertions(+), 18 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();
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 73707c3d7e2d9..67876275f0ceb 100644
--- a/docs/source/library-user-guide/upgrading/57.0.0.md
+++ b/docs/source/library-user-guide/upgrading/57.0.0.md
@@ -177,10 +177,10 @@ value, so that a rule can rebuild the node with `try_new`.
Two other APIs do not check the scans:
-| API | What it does |
-| ------------------------------------- | -------------------------------------------------------------------- |
-| `MaterializedCte::try_map_inputs_mut` | Calls a closure that changes the body and the continuation in place. |
-| `MaterializedCte::with_new_inputs` | Returns a new node with the same id and name, and new inputs. |
+| API | What it does |
+| ---------------------------------- | ----------------------------------------------------------------------- |
+| `MaterializedCte::map_inputs_mut` | Calls a closure that changes the body, then the continuation, in place. |
+| `MaterializedCte::with_new_inputs` | Returns a new node with the same id and name, and new inputs. |
Both return a `Result`, so that a later version can check the scans.
`LogicalPlan::check_invariants` checks the scans of a plan that these APIs
From af7545beb6728e7982fbbc7e4e595d1328a59c8d 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 6/8] 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 ++++++-------------
.../library-user-guide/upgrading/57.0.0.md | 61 ++++++++-----
5 files changed, 119 insertions(+), 127 deletions(-)
diff --git a/datafusion/core/src/physical_planner.rs b/datafusion/core/src/physical_planner.rs
index 8b99dd304a9a1..6add5010bb774 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 956d31d0ed8d6..3f15d6abfad44 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"
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 67876275f0ceb..822ec8ea6d540 100644
--- a/docs/source/library-user-guide/upgrading/57.0.0.md
+++ b/docs/source/library-user-guide/upgrading/57.0.0.md
@@ -151,37 +151,48 @@ 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.
+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`. Build a scan with `MaterializedCteScan::new`
-and `MaterializedCteScan::with_projection`. To build a physical scan with a
+`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.
-`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.
+The fields of `MaterializedCte` and `MaterializedCteScan` are private. Read
+them with `id`, `name`, `body` and `continuation`. Build a node with
+`MaterializedCteBuilder`, which allocates the id that binds the scans to the
+node:
-The fields of `MaterializedCte` are private. Read them with
-`MaterializedCte::id`, `name`, `body` and `continuation`. Build a node with
-`MaterializedCte::try_new`, which checks the scans of the CTE.
-`MaterializedCte::into_parts` takes the id, name, body and continuation by
-value, so that a rule can rebuild the node with `try_new`.
-
-Two other APIs do not check the scans:
-
-| API | What it does |
-| ---------------------------------- | ----------------------------------------------------------------------- |
-| `MaterializedCte::map_inputs_mut` | Calls a closure that changes the body, then the continuation, in place. |
-| `MaterializedCte::with_new_inputs` | Returns a new node with the same id and name, and new inputs. |
+```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)?);
+```
-Both return a `Result`, so that a later version can check the scans.
-`LogicalPlan::check_invariants` checks the scans of a plan that these APIs
-build.
+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::with_coerced_body` | Replaces the body with one that has new column types. The scans get the types. |
+| `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 `map_inputs_mut` and `renumber_materialized_ctes` checks
+that the scans have the names and types of the columns that they read from
+the body. `map_inputs_mut` checks that the body keeps the names and types of
+its columns. 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.
From 527849afaf2c8d4fe322c7cc2fb19b3f90972264 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 7/8] 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 106714a91600f877c7aa46ac30e0b88b21bbc1f6 Mon Sep 17 00:00:00 2001
From: Adrian Garcia Badaracco <1755071+adriangb@users.noreply.github.com>
Date: Tue, 24 Nov 2026 23:46:42 -0600
Subject: [PATCH 8/8] fix: reject a materialized CTE scan outside the
continuation of its CTE
The invariant check only validated the scans that `MaterializedCte::scans`
finds in the continuation of their CTE. A scan of the same id in the body of
its CTE, beside the CTE, or in a subquery above it was never checked, and
`prune_body_columns` does not remap it. The physical binder binds scans by
id over the whole plan, so such a scan could read the wrong columns.
The check now walks the plan with a scope stack. The id of a CTE is in scope
only in its continuation, and the innermost CTE with an id owns its scans.
A scan of a CTE that is in the plan must be in scope and match that body. A
scan whose CTE is not in the plan is still allowed, so that a check on a
part of a plan keeps working.
Co-Authored-By: Claude Opus 5.5
---
.../expr/src/logical_plan/invariants.rs | 87 ++++++++++++---
.../expr/src/logical_plan/materialized_cte.rs | 105 +++++++++++++++++-
2 files changed, 177 insertions(+), 15 deletions(-)
diff --git a/datafusion/expr/src/logical_plan/invariants.rs b/datafusion/expr/src/logical_plan/invariants.rs
index 18b8193835127..00771b948bb56 100644
--- a/datafusion/expr/src/logical_plan/invariants.rs
+++ b/datafusion/expr/src/logical_plan/invariants.rs
@@ -2,9 +2,12 @@
// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership
// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements
-use crate::logical_plan::MaterializedCtePlan;
+use std::collections::HashSet;
+use std::sync::Arc;
+
+use crate::logical_plan::{MaterializedCteId, MaterializedCtePlan};
use datafusion_common::{
- DFSchemaRef, Result, assert_or_internal_err, plan_err,
+ DFSchemaRef, Result, assert_or_internal_err, internal_err, plan_err,
tree_node::{TreeNode, TreeNodeRecursion},
};
@@ -98,26 +101,82 @@ fn assert_valid_semantic_plan(plan: &LogicalPlan) -> Result<()> {
Ok(())
}
-/// Returns an error if a scan of a materialized CTE does not have the names
-/// and types of the columns that it reads from the body of the CTE.
+/// Returns an error if a scan of a materialized CTE is not in the
+/// continuation of its CTE, or does not have the names and types of the
+/// columns that it reads from the body of the CTE.
+///
+/// The id of a CTE is in scope only in its continuation, also in subquery
+/// expressions there. It is not in scope in the body of the CTE or above the
+/// CTE. A nested CTE with the same id owns the scans below it.
///
/// A scan whose CTE is not in `plan` is not checked, because `plan` can be a
/// part of a larger plan.
fn assert_materialized_cte_scans_are_valid(plan: &LogicalPlan) -> Result<()> {
+ let mut ids = HashSet::new();
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()
- ))
- })?;
- }
+ ids.insert(cte.id());
}
Ok(TreeNodeRecursion::Continue)
- })
- .map(|_| ())
+ })?;
+ if ids.is_empty() {
+ return Ok(());
+ }
+ check_materialized_cte_scope(plan, &ids, &mut vec![])
+}
+
+/// The id and body schema of each CTE whose continuation contains the
+/// current node, innermost last. It holds owned values because
+/// `apply_subqueries` hands out temporary plans.
+type MaterializedCteScope = Vec<(MaterializedCteId, DFSchemaRef)>;
+
+#[cfg_attr(feature = "recursive_protection", recursive::recursive)]
+fn check_materialized_cte_scope(
+ plan: &LogicalPlan,
+ ids: &HashSet,
+ scope: &mut MaterializedCteScope,
+) -> Result<()> {
+ match plan {
+ LogicalPlan::MaterializedCte(MaterializedCtePlan::Cte(cte)) => {
+ check_materialized_cte_scope(cte.body(), ids, scope)?;
+ scope.push((cte.id(), Arc::clone(cte.body().schema())));
+ let result = check_materialized_cte_scope(cte.continuation(), ids, scope);
+ scope.pop();
+ return result;
+ }
+ LogicalPlan::MaterializedCte(MaterializedCtePlan::Scan(scan))
+ if ids.contains(&scan.id()) =>
+ {
+ let Some((_, body_schema)) =
+ scope.iter().rev().find(|(id, _)| *id == scan.id())
+ else {
+ return internal_err!(
+ "A scan of the materialized CTE {} is not in the continuation of the CTE",
+ scan.name()
+ );
+ };
+ return scan.check_body_schema(body_schema).map_err(|e| {
+ e.context(format!(
+ "A scan of the materialized CTE {} does not match the CTE",
+ scan.name()
+ ))
+ });
+ }
+ _ => {}
+ }
+ for input in plan.inputs() {
+ check_materialized_cte_scope(input, ids, scope)?;
+ }
+ let mut result = Ok(());
+ plan.apply_subqueries(|subquery| {
+ result = check_materialized_cte_scope(subquery, ids, scope);
+ Ok(if result.is_ok() {
+ TreeNodeRecursion::Jump
+ } else {
+ TreeNodeRecursion::Stop
+ })
+ })?;
+ result
}
/// Returns an error if the plan does not have the expected schema.
diff --git a/datafusion/expr/src/logical_plan/materialized_cte.rs b/datafusion/expr/src/logical_plan/materialized_cte.rs
index 2f502bdcca64e..f15a6759bda56 100644
--- a/datafusion/expr/src/logical_plan/materialized_cte.rs
+++ b/datafusion/expr/src/logical_plan/materialized_cte.rs
@@ -739,7 +739,7 @@ impl PartialOrd for MaterializedCteScan {
mod tests {
use super::*;
use crate::logical_plan::builder::LogicalPlanBuilder;
- use crate::{EmptyRelation, exists};
+ use crate::{EmptyRelation, Filter, exists};
use arrow::datatypes::{DataType, Field, Schema};
use datafusion_common::{Constraint, Constraints, DFSchema, FunctionalDependencies};
use std::collections::HashMap;
@@ -1101,6 +1101,109 @@ mod tests {
Ok(())
}
+ /// Build a node without the checks of `try_new`.
+ fn unchecked(
+ id: MaterializedCteId,
+ cte: LogicalPlan,
+ continuation: LogicalPlan,
+ ) -> LogicalPlan {
+ LogicalPlan::MaterializedCte(MaterializedCtePlan::Cte(MaterializedCte {
+ id,
+ name: "c".to_string(),
+ cte: Arc::new(cte),
+ continuation: Arc::new(continuation),
+ }))
+ }
+
+ fn assert_out_of_scope(plan: &LogicalPlan) {
+ use crate::logical_plan::InvariantLevel;
+ let err = plan
+ .check_invariants(InvariantLevel::Executable)
+ .unwrap_err();
+ assert!(
+ err.to_string().contains(
+ "A scan of the materialized CTE c is not in the continuation of the CTE"
+ ),
+ "{err}"
+ );
+ }
+
+ #[test]
+ fn check_invariants_rejects_a_scan_outside_the_continuation() -> Result<()> {
+ use crate::logical_plan::InvariantLevel;
+ let id = MaterializedCteId::next();
+ let valid = || {
+ unchecked(
+ id,
+ (*body(DataType::Int32)).clone(),
+ scan(id, DataType::Int32),
+ )
+ };
+ valid().check_invariants(InvariantLevel::Executable)?;
+
+ // In the body of its own CTE.
+ assert_out_of_scope(&unchecked(
+ id,
+ scan(id, DataType::Int32),
+ scan(id, DataType::Int32),
+ ));
+
+ // Beside its CTE.
+ let beside = LogicalPlanBuilder::from(valid())
+ .union(scan(id, DataType::Int32))?
+ .build()?;
+ assert_out_of_scope(&beside);
+
+ // In a subquery expression above its CTE.
+ let above = LogicalPlan::Filter(Filter::try_new(
+ exists(Arc::new(scan(id, DataType::Int32))),
+ Arc::new(valid()),
+ )?);
+ assert_out_of_scope(&above);
+
+ // In a subquery expression in the continuation, the scan is in scope.
+ let in_subquery = unchecked(
+ id,
+ (*body(DataType::Int32)).clone(),
+ LogicalPlan::Filter(Filter::try_new(
+ exists(Arc::new(scan(id, DataType::Int32))),
+ Arc::new(scan(id, DataType::Int32)),
+ )?),
+ );
+ in_subquery.check_invariants(InvariantLevel::Executable)?;
+ Ok(())
+ }
+
+ #[test]
+ fn check_invariants_binds_a_scan_to_the_innermost_cte_with_its_id() -> Result<()> {
+ use crate::logical_plan::InvariantLevel;
+ let id = MaterializedCteId::next();
+ // Two copies of one CTE, with different body types. Each scan must
+ // match the body of the copy whose continuation holds it.
+ let inner = unchecked(
+ id,
+ (*body(DataType::Utf8)).clone(),
+ scan(id, DataType::Utf8),
+ );
+ unchecked(id, (*body(DataType::Int32)).clone(), inner.clone())
+ .check_invariants(InvariantLevel::Executable)?;
+
+ let wrong = unchecked(
+ id,
+ (*body(DataType::Utf8)).clone(),
+ scan(id, DataType::Int32),
+ );
+ let err = unchecked(id, (*body(DataType::Int32)).clone(), wrong)
+ .check_invariants(InvariantLevel::Executable)
+ .unwrap_err();
+ assert!(
+ err.to_string()
+ .contains("A scan of the materialized CTE c does not match the CTE"),
+ "{err}"
+ );
+ Ok(())
+ }
+
#[test]
fn try_new_checks_the_projection_of_the_scans() -> Result<()> {
let id = MaterializedCteId::next();