Skip to content

refactor: narrow the public API of MaterializedCte - #27725

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

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

Conversation

@adriangb

@adriangb adriangb commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

Note

This PR is an alternative to #27570. It includes the change of #27570 (private fields), then replaces its generic mutation hooks with checked methods. MaterializedCte is new in 57.0.0 and is not released, so this PR does not break a released API.

Which issue does this PR close?

Rationale for this change

Each MaterializedCteScan reads the columns of its CTE body by position, so a change to the body needs a matching change to every scan. On main, the public API lets a rule change the body alone:

// Body: SELECT a, b FROM t. A scan in the continuation reads column 1 (`b`).
cte.cte = Arc::new(project_away_column_a(&cte.cte)?); // public field; body is now (b)
// No check runs. The scan still reads column 1 of a 1-column body.

#27570 makes the fields private, but it keeps generic hooks (try_map_inputs_mut, with_new_inputs, into_parts + try_new) that do not check the scans. To do a body change right, each rule (type coercion, OptimizeProjections, the physical planner) repeats the same loop by hand: find every scan of this id, also in subqueries, skip a nested CTE with the same id, remap the scan, rebuild the node. The public MaterializedCteScan::new and MaterializedCteId::next also let a caller bind a scan to the wrong CTE.

What changes are included in this PR?

MaterializedCte owns each coupled body-and-scan operation. The fields and the raw constructors are crate-private.

Use case API Checks the scans
Plan a WITH ... AS MATERIALIZED MaterializedCteBuilder::new(name, body), .scan(), .build(continuation) In build
Rewrite the body map_body(f) Yes
Rewrite the continuation map_continuation(f) Yes
Coerce the body types with_coerced_body(body) Remaps the scans
Remove unread body columns prune_body_columns() Remaps the scans
Optimizer driver, in place map_inputs_mut(f) After both calls
Fresh ids for a cloned plan renumber_materialized_ctes(plan) Not needed
with_new_exprs, map_children No. check_invariants is the backstop

Planning: the scan comes from the builder, so it has the right id.

let builder = MaterializedCteBuilder::new("c", body);
planner_context.insert_cte("c", builder.scan().into());
let plan: LogicalPlan = builder.build(plan_the_rest()?)?.into();

A rule picks the method that names its change:

// OptimizeProjections
cte.map_continuation(|c| optimize(c, required))?
    .transform_data(|cte| cte.prune_body_columns())?
    .transform_data(|cte| cte.map_body(|b| optimize(b, all_columns)))

The optimizer runs check_invariants before and after the rules (and after each rule in debug builds), so a rule that bypasses these methods still fails with an error.

The public API is the minimum that the callers in this repository need. For comparison, DuckDB and Polars use the same model (each consumer prunes its own columns, the body keeps their union), and DuckDB also pushes the OR of the consumer filters into the body. map_body can express that rule without new API.

What is the testing strategy for this PR?

Existing datafusion-expr, datafusion-optimizer, datafusion-sql unit tests and the cte*.slt sqllogictests. New: the builder doctest, and tests that drop an unread body column (accepted) and change a read column's type (rejected) through both map_inputs_mut and map_children.

Are there any user-facing changes?

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

🤖 Generated with Claude Code

@github-actions github-actions Bot added documentation Improvements or additions to documentation sql SQL Planner logical-expr Logical plan and expressions optimizer Optimizer rules core Core DataFusion crate labels Nov 24, 2026
@kosiew

kosiew commented Nov 27, 2026

Copy link
Copy Markdown
Contributor

run benchmark sql_planner

env:
  BENCH_FILTER: physical_cte_

@adriangbot

Copy link
Copy Markdown

🤖 Benchmark running (GKE) | trigger
Instance: c4a-highmem-16 (12 vCPU / 65 GiB) | Linux bench-c7217909567-5796-mq9zk 6.12.105+ #1 SMP Sat Sep 19 07:55:25 UTC 2026 aarch64 GNU/Linux

CPU Details (lscpu)
Architecture:                            aarch64
CPU op-mode(s):                          64-bit
Byte Order:                              Little Endian
CPU(s):                                  16
On-line CPU(s) list:                     0-15
Vendor ID:                               ARM
Model name:                              Neoverse-V2
Model:                                   1
Thread(s) per core:                      1
Core(s) per cluster:                     16
Socket(s):                               -
Cluster(s):                              1
Stepping:                                r0p1
BogoMIPS:                                2000.00
Flags:                                   fp asimd evtstrm aes pmull sha1 sha2 crc32 atomics fphp asimdhp cpuid asimdrdm jscvt fcma lrcpc dcpop sha3 sm3 sm4 asimddp sha512 sve asimdfhm dit uscat ilrcpc flagm sb paca pacg dcpodp sve2 sveaes svepmull svebitperm svesha3 svesm4 flagm2 frint svei8mm svebf16 i8mm bf16 dgh rng bti
L1d cache:                               1 MiB (16 instances)
L1i cache:                               1 MiB (16 instances)
L2 cache:                                32 MiB (16 instances)
L3 cache:                                80 MiB (1 instance)
NUMA node(s):                            1
NUMA node0 CPU(s):                       0-15
Vulnerability Gather data sampling:      Not affected
Vulnerability Indirect target selection: Not affected
Vulnerability Itlb multihit:             Not affected
Vulnerability L1tf:                      Not affected
Vulnerability Mds:                       Not affected
Vulnerability Meltdown:                  Not affected
Vulnerability Mmio stale data:           Not affected
Vulnerability Reg file data sampling:    Not affected
Vulnerability Retbleed:                  Not affected
Vulnerability Spec rstack overflow:      Not affected
Vulnerability Spec store bypass:         Mitigation; Speculative Store Bypass disabled via prctl
Vulnerability Spectre v1:                Mitigation; __user pointer sanitization
Vulnerability Spectre v2:                Mitigation; CSV2, BHB
Vulnerability Srbds:                     Not affected
Vulnerability Tsa:                       Not affected
Vulnerability Tsx async abort:           Not affected
Vulnerability Vmscape:                   Not affected

Comparing mcte-narrow-api (527849a) to a72c60b (merge-base) diff

Run configuration
run benchmark sql_planner
env:
  BENCH_FILTER: "physical_cte_"
Trigger comment
run benchmark sql_planner

```yaml
env:
  BENCH_FILTER: physical_cte_
```

Results will be posted here when complete


File an issue against this benchmark runner

@kosiew kosiew left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This PR has a neater and more organized approach to ensuring body-scan compatibility.
There are also more clone operations and I wonder how it affects performance.

Comment on lines +260 to +267
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
))
})?;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Dropping an unread trailing column fails here but succeeds through the subquery-aware traversal.
Please preserve executable-invariant checks or validate bound scans after both callbacks, update the documentation, and test valid pruning and incompatible schema changes through both paths.

@adriangbot

Copy link
Copy Markdown

🤖 Benchmark completed (GKE) | trigger

Instance: c4a-highmem-16 (12 vCPU / 65 GiB)

Comparing mcte-narrow-api (527849a) to a72c60b (merge-base) diff

Run configuration
run benchmark sql_planner
env:
  BENCH_FILTER: "physical_cte_"
Trigger comment
run benchmark sql_planner

```yaml
env:
  BENCH_FILTER: physical_cte_
```
CPU Details (lscpu)
Architecture:                            aarch64
CPU op-mode(s):                          64-bit
Byte Order:                              Little Endian
CPU(s):                                  16
On-line CPU(s) list:                     0-15
Vendor ID:                               ARM
Model name:                              Neoverse-V2
Model:                                   1
Thread(s) per core:                      1
Core(s) per cluster:                     16
Socket(s):                               -
Cluster(s):                              1
Stepping:                                r0p1
BogoMIPS:                                2000.00
Flags:                                   fp asimd evtstrm aes pmull sha1 sha2 crc32 atomics fphp asimdhp cpuid asimdrdm jscvt fcma lrcpc dcpop sha3 sm3 sm4 asimddp sha512 sve asimdfhm dit uscat ilrcpc flagm sb paca pacg dcpodp sve2 sveaes svepmull svebitperm svesha3 svesm4 flagm2 frint svei8mm svebf16 i8mm bf16 dgh rng bti
L1d cache:                               1 MiB (16 instances)
L1i cache:                               1 MiB (16 instances)
L2 cache:                                32 MiB (16 instances)
L3 cache:                                80 MiB (1 instance)
NUMA node(s):                            1
NUMA node0 CPU(s):                       0-15
Vulnerability Gather data sampling:      Not affected
Vulnerability Indirect target selection: Not affected
Vulnerability Itlb multihit:             Not affected
Vulnerability L1tf:                      Not affected
Vulnerability Mds:                       Not affected
Vulnerability Meltdown:                  Not affected
Vulnerability Mmio stale data:           Not affected
Vulnerability Reg file data sampling:    Not affected
Vulnerability Retbleed:                  Not affected
Vulnerability Spec rstack overflow:      Not affected
Vulnerability Spec store bypass:         Mitigation; Speculative Store Bypass disabled via prctl
Vulnerability Spectre v1:                Mitigation; __user pointer sanitization
Vulnerability Spectre v2:                Mitigation; CSV2, BHB
Vulnerability Srbds:                     Not affected
Vulnerability Tsa:                       Not affected
Vulnerability Tsx async abort:           Not affected
Vulnerability Vmscape:                   Not affected
Details

group                                     HEAD                                   mcte-narrow-api
-----                                     ----                                   ---------------
physical_cte_materialized_chain_6         1.00      2.3±0.01ms        ? ?/sec    1.01      2.4±0.00ms        ? ?/sec
physical_cte_materialized_one_ref         1.00    722.7±2.19µs        ? ?/sec    1.02    739.0±1.83µs        ? ?/sec
physical_cte_materialized_two_refs        1.00    935.7±3.14µs        ? ?/sec    1.03    961.6±7.03µs        ? ?/sec
physical_cte_mixed                        1.00      3.0±0.01ms        ? ?/sec    1.00      3.0±0.01ms        ? ?/sec
physical_cte_not_materialized_chain_6     1.00     17.6±0.09ms        ? ?/sec    1.01     17.8±0.09ms        ? ?/sec
physical_cte_not_materialized_one_ref     1.00    658.4±2.38µs        ? ?/sec    1.03    677.8±4.67µs        ? ?/sec
physical_cte_not_materialized_two_refs    1.00   1203.4±3.41µs        ? ?/sec    1.00   1205.7±5.58µs        ? ?/sec
physical_cte_unmarked_chain_6             1.00     17.6±0.08ms        ? ?/sec    1.01     17.8±0.09ms        ? ?/sec
physical_cte_unmarked_one_ref             1.01    667.9±1.75µs        ? ?/sec    1.00    658.9±1.85µs        ? ?/sec
physical_cte_unmarked_two_refs            1.01   1218.7±6.77µs        ? ?/sec    1.00   1202.0±2.60µs        ? ?/sec

Resource Usage

sql_planner — base (merge-base)

Metric Value
Wall time 360.1s
Peak memory 129.6 MiB
Avg memory 39.8 MiB
CPU user 136.6s
CPU sys 0.1s
Peak spill 0 B

sql_planner — branch

Metric Value
Wall time 355.1s
Peak memory 121.0 MiB
Avg memory 36.9 MiB
CPU user 132.5s
CPU sys 0.1s
Peak spill 0 B

File an issue against this benchmark runner

@adriangb

Copy link
Copy Markdown
Contributor Author

run benchmark sql_planner

env:
  BENCH_FILTER: physical_cte_

@adriangbot

Copy link
Copy Markdown

🤖 Benchmark running (GKE) | trigger
Instance: c4a-highmem-16 (12 vCPU / 65 GiB) | Linux bench-c7234349932-5825-l8tn5 6.12.105+ #1 SMP Sat Sep 19 07:55:25 UTC 2026 aarch64 GNU/Linux

CPU Details (lscpu)
Architecture:                            aarch64
CPU op-mode(s):                          64-bit
Byte Order:                              Little Endian
CPU(s):                                  16
On-line CPU(s) list:                     0-15
Vendor ID:                               ARM
Model name:                              Neoverse-V2
Model:                                   1
Thread(s) per core:                      1
Core(s) per cluster:                     16
Socket(s):                               -
Cluster(s):                              1
Stepping:                                r0p1
BogoMIPS:                                2000.00
Flags:                                   fp asimd evtstrm aes pmull sha1 sha2 crc32 atomics fphp asimdhp cpuid asimdrdm jscvt fcma lrcpc dcpop sha3 sm3 sm4 asimddp sha512 sve asimdfhm dit uscat ilrcpc flagm sb paca pacg dcpodp sve2 sveaes svepmull svebitperm svesha3 svesm4 flagm2 frint svei8mm svebf16 i8mm bf16 dgh rng bti
L1d cache:                               1 MiB (16 instances)
L1i cache:                               1 MiB (16 instances)
L2 cache:                                32 MiB (16 instances)
L3 cache:                                80 MiB (1 instance)
NUMA node(s):                            1
NUMA node0 CPU(s):                       0-15
Vulnerability Gather data sampling:      Not affected
Vulnerability Indirect target selection: Not affected
Vulnerability Itlb multihit:             Not affected
Vulnerability L1tf:                      Not affected
Vulnerability Mds:                       Not affected
Vulnerability Meltdown:                  Not affected
Vulnerability Mmio stale data:           Not affected
Vulnerability Reg file data sampling:    Not affected
Vulnerability Retbleed:                  Not affected
Vulnerability Spec rstack overflow:      Not affected
Vulnerability Spec store bypass:         Mitigation; Speculative Store Bypass disabled via prctl
Vulnerability Spectre v1:                Mitigation; __user pointer sanitization
Vulnerability Spectre v2:                Mitigation; CSV2, BHB
Vulnerability Srbds:                     Not affected
Vulnerability Tsa:                       Not affected
Vulnerability Tsx async abort:           Not affected
Vulnerability Vmscape:                   Not affected

Comparing mcte-narrow-api (fd0a081) to a72c60b (merge-base) diff

Run configuration
run benchmark sql_planner
env:
  BENCH_FILTER: "physical_cte_"
Trigger comment
run benchmark sql_planner

```yaml
env:
  BENCH_FILTER: physical_cte_
```

Results will be posted here when complete


File an issue against this benchmark runner

@adriangbot

Copy link
Copy Markdown

🤖 Benchmark completed (GKE) | trigger

Instance: c4a-highmem-16 (12 vCPU / 65 GiB)

Comparing mcte-narrow-api (fd0a081) to a72c60b (merge-base) diff

Run configuration
run benchmark sql_planner
env:
  BENCH_FILTER: "physical_cte_"
Trigger comment
run benchmark sql_planner

```yaml
env:
  BENCH_FILTER: physical_cte_
```
CPU Details (lscpu)
Architecture:                            aarch64
CPU op-mode(s):                          64-bit
Byte Order:                              Little Endian
CPU(s):                                  16
On-line CPU(s) list:                     0-15
Vendor ID:                               ARM
Model name:                              Neoverse-V2
Model:                                   1
Thread(s) per core:                      1
Core(s) per cluster:                     16
Socket(s):                               -
Cluster(s):                              1
Stepping:                                r0p1
BogoMIPS:                                2000.00
Flags:                                   fp asimd evtstrm aes pmull sha1 sha2 crc32 atomics fphp asimdhp cpuid asimdrdm jscvt fcma lrcpc dcpop sha3 sm3 sm4 asimddp sha512 sve asimdfhm dit uscat ilrcpc flagm sb paca pacg dcpodp sve2 sveaes svepmull svebitperm svesha3 svesm4 flagm2 frint svei8mm svebf16 i8mm bf16 dgh rng bti
L1d cache:                               1 MiB (16 instances)
L1i cache:                               1 MiB (16 instances)
L2 cache:                                32 MiB (16 instances)
L3 cache:                                80 MiB (1 instance)
NUMA node(s):                            1
NUMA node0 CPU(s):                       0-15
Vulnerability Gather data sampling:      Not affected
Vulnerability Indirect target selection: Not affected
Vulnerability Itlb multihit:             Not affected
Vulnerability L1tf:                      Not affected
Vulnerability Mds:                       Not affected
Vulnerability Meltdown:                  Not affected
Vulnerability Mmio stale data:           Not affected
Vulnerability Reg file data sampling:    Not affected
Vulnerability Retbleed:                  Not affected
Vulnerability Spec rstack overflow:      Not affected
Vulnerability Spec store bypass:         Mitigation; Speculative Store Bypass disabled via prctl
Vulnerability Spectre v1:                Mitigation; __user pointer sanitization
Vulnerability Spectre v2:                Mitigation; CSV2, BHB
Vulnerability Srbds:                     Not affected
Vulnerability Tsa:                       Not affected
Vulnerability Tsx async abort:           Not affected
Vulnerability Vmscape:                   Not affected
Details

group                                     HEAD                                   mcte-narrow-api
-----                                     ----                                   ---------------
physical_cte_materialized_chain_6         1.00      2.3±0.02ms        ? ?/sec    1.02      2.4±0.02ms        ? ?/sec
physical_cte_materialized_one_ref         1.00    748.7±3.15µs        ? ?/sec    1.03    771.8±2.93µs        ? ?/sec
physical_cte_materialized_two_refs        1.00    926.2±2.69µs        ? ?/sec    1.03    951.7±2.10µs        ? ?/sec
physical_cte_mixed                        1.01      3.1±0.03ms        ? ?/sec    1.00      3.1±0.01ms        ? ?/sec
physical_cte_not_materialized_chain_6     1.03     18.2±0.04ms        ? ?/sec    1.00     17.5±0.05ms        ? ?/sec
physical_cte_not_materialized_one_ref     1.00    668.1±1.85µs        ? ?/sec    1.03    687.2±1.56µs        ? ?/sec
physical_cte_not_materialized_two_refs    1.00   1211.3±3.86µs        ? ?/sec    1.02   1235.3±3.01µs        ? ?/sec
physical_cte_unmarked_chain_6             1.00     17.5±0.13ms        ? ?/sec    1.03     18.0±0.10ms        ? ?/sec
physical_cte_unmarked_one_ref             1.00    672.6±2.06µs        ? ?/sec    1.02    685.6±2.73µs        ? ?/sec
physical_cte_unmarked_two_refs            1.00   1195.3±2.42µs        ? ?/sec    1.02   1216.0±3.56µs        ? ?/sec

Resource Usage

sql_planner — base (merge-base)

Metric Value
Wall time 240.1s
Peak memory 122.8 MiB
Avg memory 55.0 MiB
CPU user 135.4s
CPU sys 0.1s
Peak spill 0 B

sql_planner — branch

Metric Value
Wall time 330.1s
Peak memory 130.8 MiB
Avg memory 42.4 MiB
CPU user 136.6s
CPU sys 0.1s
Peak spill 0 B

File an issue against this benchmark runner

adriangb and others added 8 commits November 28, 2026 12:49
A rule that builds a MaterializedCte with a struct literal or struct update
skips the scan check in try_new. Private fields send every new node through
try_new.

The fields are pub(crate), so the tree-node and display code of
datafusion-expr is unchanged. try_map_inputs_mut and into_parts replace the
remaining direct field access in the optimizer and the physical planner.
Later commits in this PR replace these interim hooks with checked methods.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The SQL planner allocated the id of a materialized CTE, built its
scans and kept a pending node until the continuation was planned. Any
other producer of the node has to repeat these steps and can bind a
scan to the wrong id.

Add MaterializedCteBuilder in datafusion-expr. It allocates the id,
hands out a scan for each reference, and builds the node from the
continuation. It is not Clone, so two nodes cannot share its id. The
SQL planner uses it in place of its own pending type. Add From impls
that wrap a MaterializedCte or a MaterializedCteScan in a LogicalPlan.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Type coercion, OptimizeProjections and the physical planner each change
the body of a materialized CTE together with its scans. Each repeated
the walk over the scans of the CTE, which must skip a nested occurrence
of the same CTE, and rebuilt the node from its parts. OptimizeProjections
also worked out which body columns to keep from the scan positions,
which are a detail of the representation.

Add these to datafusion-expr. They share one private scan traversal:

- MaterializedCte::with_coerced_body gives the scans the new types of
  a coerced body.
- MaterializedCte::prune_body_columns removes the body columns that no
  scan reads, and keeps one column if no scan reads a column.
- renumber_materialized_ctes gives each CTE in a plan a new id. A new
  id does not change a schema, so it does not check the scans again.

Add map_continuation and map_body for the rules that rewrite one input
(decorrelation, filter push down, OptimizeProjections). They check the
scans of the new node. The callers use these in place of into_parts
and try_new.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The only caller of MaterializedCte::try_map_inputs_mut is
map_children_mut in the optimizer, which does not care which input is
the body and which is the continuation. The closure could also change
the columns of the body without an error, and the scans would then read
the wrong columns.

Replace it with map_inputs_mut, which calls one closure for the body
and then for the continuation. It returns an error if the body changes
the names or the types of its columns. It skips the check when the
schema of the body is the same Arc. It does not check the continuation,
because the optimizer recomputes the schema of the node afterwards.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
With the builder and the coupled methods in place, no caller outside
datafusion-expr needs to build a node or a scan from its parts. A
public constructor lets a caller bind a scan to the wrong id or give a
scan a projection that does not match the body.

Make these crate-private: MaterializedCte::try_new, scans,
MaterializedCteScan::new, with_body_columns, with_body_schema,
check_body_schema, find_in, MaterializedCteId::next, and the id and
name fields of MaterializedCteScan. Remove into_parts. Rename
with_new_inputs to with_new_inputs_unchecked, which returns Self and
is crate-private. Its only caller is LogicalPlan::with_new_exprs.

The physical planner needs to know whether a CTE is read, so add
MaterializedCte::is_read. The module documentation says which APIs do
not check the scans, and that check_invariants is the backstop. The
OptimizeProjections tests build their plans with the builder. The
57.0.0 upgrade guide describes the new API.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Mechanical change: build a LogicalPlan from a MaterializedCte or a
MaterializedCteScan with the From impls in place of the nested enum
constructors. No behavior changes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The checks in try_new, check_invariants, is_read and prune_body_columns
collected a clone of each scan. A visitor reads the scans in place.
with_coerced_body and prune_body_columns built the new scans from the
body, so they do not need a second traversal to check them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
map_inputs_mut rejected a body that removed an unread column, but
check_invariants accepted the same plan from map_children. After both
calls of the closure, map_inputs_mut checks the scans against the body
with the check that check_invariants uses. The tests change the body
through both paths.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

core Core DataFusion crate documentation Improvements or additions to documentation logical-expr Logical plan and expressions optimizer Optimizer rules sql SQL Planner

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants