Repository navigation
feat: make the materialized CTE nodes a first-class LogicalPlan variant - #26269
Conversation
Codecov Report❌ Patch coverage is Additional details and impacted files@@ Coverage Diff @@
## main #26269 +/- ##
==========================================
- Coverage 82.89% 82.88% -0.02%
==========================================
Files 1154 1154
Lines 457630 457707 +77
Branches 457630 457707 +77
==========================================
+ Hits 379370 379378 +8
- Misses 55256 55308 +52
- Partials 23004 23021 +17 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
|
Thank you for opening this pull request! Reviewer note: cargo-semver-checks reported the current version number is not SemVer-compatible with the changes in this pull request (compared against the base branch). Details |
1ca8c39 to
e408875
Compare
0356f37 to
37c5b98
Compare
Replace the `MaterializedCte` and `MaterializedCteScan` extension nodes with the variants `LogicalPlan::MaterializedCte` and `LogicalPlan::MaterializedCteScan`. Each rule now states what it does with the nodes in its `match`, and the downcasts are removed from `PushDownFilter`, `PullUpCorrelatedExpr`, `head_output_expr` and the physical planner. `MaterializedCte::try_new` checks that the scans have the schema of the body, and `MaterializedCteScan::find_in` finds the scans of one CTE, also in subquery expressions. The unparser, the Substrait producer and the protobuf serializer return a "not implemented" error for the two variants. Plans and results do not change. Closes apache#26238. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
37c5b98 to
14c4e73
Compare
| pub cte: LogicalPlan, | ||
| pub continuation: LogicalPlan, | ||
| /// The body of the CTE | ||
| pub cte: Arc<LogicalPlan>, |
There was a problem hiding this comment.
nit: the field is cte but the accessor is body(), so call sites end up reading cte.cte (e.g. in decorrelate.rs and optimize_projections). Since #25580 hasn't shipped in a release yet, renaming the field to body now would be free:
- pub cte: Arc<LogicalPlan>,
+ pub body: Arc<LogicalPlan>,|
Thanks @adriangb! This is ready to go once the conflicts are resolved. |
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
# Conflicts: # datafusion/expr/src/logical_plan/display.rs
|
I merged up to resolve conflicts |
…e#26274) ## Which issue does this PR close? - Closes apache#26240. Stacked on apache#26269. Only the last commit is new. ## Rationale for this change The body of a materialized CTE kept all its columns, also when no reference read them. ```sql CREATE TABLE wide(a INT, b INT, c INT, d INT, e INT) AS VALUES (1, 10, 100, 1000, 10000); EXPLAIN WITH w AS MATERIALIZED (SELECT * FROM wide) SELECT a FROM w UNION ALL SELECT b FROM w; ``` Before, all five columns were read and buffered: ```text MaterializedCte: name=w SubqueryAlias: w TableScan: wide projection=[a, b, c, d, e] Union Projection: w.a MaterializedCteScan: name=w Projection: w.b AS a MaterializedCteScan: name=w ``` After, only `a` and `b` are read and buffered: ```text MaterializedCte: name=w SubqueryAlias: w TableScan: wide projection=[a, b] Union MaterializedCteScan: name=w projection=[a] Projection: w.b AS a MaterializedCteScan: name=w projection=[b] ``` ## What changes are included in this PR? - `MaterializedCteScan` has a new field `projection: Option<Vec<usize>>`: the indexes of the columns of the CTE body that the scan outputs. - `OptimizeProjections` narrows each `MaterializedCteScan` to the columns that its parent needs, as it does for a `TableScan`. - At a `MaterializedCte`, `OptimizeProjections` optimizes the continuation first. It then computes the union of the columns of all the scans of the CTE, projects the body to this union, and gives each scan the new positions of its columns. Scans in subquery expressions and in the bodies of other CTEs are counted. - `MaterializedCteScanExec` applies the projection to the shared buffered batches. - The physical planner checks that each scan agrees with the physical schema of its body when it binds the scan, and returns an internal error if it does not. The projection in the scan makes the intermediate state (a narrow scan and a wide body) a valid plan, so no separate rule is necessary. Notes: - A reference that reads no column (`SELECT count(*) FROM c`) gets `projection=[]`. If no reference reads a column, the body keeps its first column. - The projection is put above the body. A volatile column can be removed, but the number of rows does not change. Columns below a `DISTINCT` or a recursive query are not removed. - A scan in a correlated subquery that is not decorrelated is not narrowed. The CTE then keeps all its columns. - The pgjson display does not show the projection. **Comparison with PostgreSQL and DuckDB.** This is what DuckDB does: `RemoveUnusedColumns` prunes the body to the columns that its references read ([remove_unused_columns.cpp](https://github.com/duckdb/duckdb/blob/1b4c3e54ba3625bac56ad184f0ce642a8d2bfbd5/src/optimizer/remove_unused_columns.cpp#L844)). PostgreSQL plans a CTE for full retrieval and does not prune ([subselect.c](https://github.com/postgres/postgres/blob/af090508018be5ace443ba6e2814500c10842a4d/src/backend/optimizer/plan/subselect.c#L986)). ## Are these changes tested? Yes. `cte_materialized.slt`: `EXPLAIN` and result checks for the example above, a column that only a filter reads, `count(*)`, a CTE that another CTE reads, references in subqueries, a volatile body, a `DISTINCT` body, aliased columns, a self join, a recursive body and a CTE that nothing reads. Unit tests for the scan projection, nested CTEs, idempotence and the zero-column case. ## Are there any user-facing changes? `EXPLAIN` shows `projection=[...]` on `MaterializedCteScan` and `MaterializedCteScanExec` when the scan does not read all the columns. `MaterializedCteScan` has the new public field `projection`. The upgrade guide for 56.0.0 says this. --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Which issue does this PR close?
LogicalPlanvariants #26238.Rationale for this change
#25580 plans
WITH x AS MATERIALIZED (...)with two built-inUserDefinedLogicalNodes insideLogicalPlan::Extension. Rules that must know about the nodes find them with a downcast, and code outside DataFusion sees an unknown extension node.For users of SQL nothing changes. Plans and results are the same. For library users, the nodes are now visible in a
match:It is easier to do this before more rules are written against the extension nodes.
What changes are included in this PR?
LogicalPlan::MaterializedCte(MaterializedCtePlan).MaterializedCtePlanhas two cases:Cte, which computes the body once and evaluates the continuation, andScan, a leaf that reads the buffered output. This keeps the number of top-level variants low, in the same way asLogicalPlan::StatementandLogicalPlan::Ddl. Amatcharm that treats both cases the same way isLogicalPlan::MaterializedCte(_).Scancase and not aTableScanover aTableSource. ATableScanwould need a downcast of the source to read the CTE id, andOptimizeProjectionswould write a projection into it, which changes the plans.MaterializedCte::try_newchecks that each scan of the CTE in the continuation has the column names and types of the body.with_new_exprsand theTreeNoderewrites do not run this check again.MaterializedCteScan::find_inreturns the scans of one CTE in a plan, also in subquery expressions.PushDownFilter,PullUpCorrelatedExpr,LogicalPlan::head_output_exprand the physical planner. Eachmatchnow states the behaviour, and the behaviour is the same as before.Comparison with PostgreSQL and DuckDB. PostgreSQL plans a CTE as a separate subplan that
CteScannodes read. DuckDB uses aLOGICAL_MATERIALIZED_CTEnode andLOGICAL_CTE_REFleaves. This PR uses the same two-part shape.Are these changes tested?
Yes.
cte_materialized.sltpasses without changes, so no plan changed. There are new unit tests for the constructor check and forfind_in. The "not implemented" arms have no tests.Are there any user-facing changes?
Yes, this is a public API change. An exhaustive
matchonLogicalPlanin downstream code needs one new arm.MaterializedCte::cteandMaterializedCte::continuationare nowArc<LogicalPlan>. There is an entry in the 56.0.0 upgrade guide.