Skip to content

fix: keep the output of a materialized CTE in TaskContext (per run) not the plan - #26270

Open
adriangb wants to merge 3 commits into
apache:mainfrom
adriangb:mcte-per-run-output
Open

adriangb wants to merge 3 commits into
apache:mainfrom
adriangb:mcte-per-run-output

Conversation

@adriangb

@adriangb adriangb commented Oct 13, 2026 •

Copy link
Copy Markdown
Contributor

Which issue does this PR close?

Rationale for this change

MaterializedCteExec::reset_state cleared its shared buffer in place and returned self. ExecutionPlan::reset_state must return a node with new state and leave the old node unchanged. Because the buffered output was in the plan, two runs of one physical plan also shared it.

Example with one physical plan for WITH c AS MATERIALIZED (SELECT random() AS x) SELECT * FROM c:

Before After
Run 1 and run 2 of the same plan, each with its own TaskContext Run 2 replays the buffer of run 1. Each run computes the body.
reset_plan_states(plan) while run 1 is open The buffer that run 1 uses is replaced. Run 1 is not changed.

No SQL query is known to give a wrong result on main.

What changes are included in this PR?

  • TaskContext has a new RunState. It holds state that operators keep for one run of a plan.
  • The output of a materialized CTE is now in the RunState, keyed by the CTE id. MaterializedCteBuffer holds plan-time data only.
  • MaterializedCteExec uses the default reset_state.
  • RecursiveQueryExec gives each iteration a child RunState, in which the CTEs that the recursive term declares are computed again. A CTE that is declared outside the recursive term keeps its output for the whole query.

Alternative that was not used: rebind the scans to a new buffer in reset_plan_states. That function cannot reach a scan in a scalar subquery, and it does not separate two runs when nothing calls reset.

Notes for reviewers:

  • A run is identified by its TaskContext. If each partition is executed with a different TaskContext, the body is computed one time for each context.
  • The output now lives until the TaskContext of the run and the replay streams are dropped. Release the buffer of a materialized CTE when the last scan finishes #26233 releases it earlier.
  • The body runs with a copy of the TaskContext whose RunState refers to the outputs of the run weakly (internal_context). The future that buffers the body is in the RunState, and a body stream can keep its context, so a strong reference would be a cycle. With the weak reference, a run that is abandoned while the body is buffering is dropped: the body tasks are aborted, and their reservations and spill files are released. A scan stream of the caller keeps the outputs strongly until it has the output, so the body still runs when the caller drops the TaskContext before it polls.
  • ScalarSubqueryExec::reset_state has the same in-place reset and is not changed here.

Comparison with PostgreSQL and DuckDB. This is what PostgreSQL does: the CTE output is a tuplestore in the executor state of the first CteScan, not in the plan, so each execution has its own (nodeCtescan.c).

Are these changes tested?

Yes. Unit tests: two overlapping runs of one plan have separate outputs, reset_plan_states leaves the old plan usable, a renewed context computes only the given CTEs again, an abandoned run with chained CTEs and a body stream that keeps its context is released and cancels the body (abandoned_run_cancels_the_body), and a test for RunState. The recursive cases in cte_materialized.slt pass with no change. There is no slt for nested recursion.

Are there any user-facing changes?

New public API: datafusion_execution::RunState, TaskContext::run_state, TaskContext::with_run_state, and TaskContext: Clone. No existing API changes.

@github-actions github-actions Bot added sql SQL Planner logical-expr Logical plan and expressions optimizer Optimizer rules core Core DataFusion crate sqllogictest SQL Logic Tests (.slt) execution Related to the execution crate physical-plan Changes to the physical-plan crate labels Oct 13, 2026
@codecov-commenter

codecov-commenter commented Oct 13, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 82.81938% with 39 lines in your changes missing coverage. Please review.
✅ Project coverage is 82.89%. Comparing base (484183d) to head (08f406f).

Files with missing lines Patch % Lines
datafusion/physical-plan/src/materialized_cte.rs 79.16% 12 Missing and 23 partials ⚠️
datafusion/execution/src/task.rs 94.11% 3 Missing ⚠️
datafusion/physical-plan/src/recursive_query.rs 87.50% 0 Missing and 1 partial ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main   #26270      +/-   ##
==========================================
- Coverage   82.89%   82.89%   -0.01%     
==========================================
  Files        1154     1154              
  Lines      457630   457845     +215     
  Branches   457630   457845     +215     
==========================================
+ Hits       379370   379531     +161     
- Misses      55256    55283      +27     
- Partials    23004    23031      +27     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@adriangb
adriangb force-pushed the mcte-per-run-output branch 2 times, most recently from 91d3f3d to 71f28c3 Compare October 16, 2026 03:46
@github-actions github-actions Bot removed sql SQL Planner logical-expr Logical plan and expressions optimizer Optimizer rules core Core DataFusion crate sqllogictest SQL Logic Tests (.slt) labels Oct 16, 2026
@adriangb
adriangb force-pushed the mcte-per-run-output branch from 71f28c3 to 07a4fbb Compare October 16, 2026 16:57
@adriangb
adriangb marked this pull request as ready for review October 16, 2026 16:57
@adriangb
adriangb force-pushed the mcte-per-run-output branch from 07a4fbb to 08f406f Compare October 17, 2026 21:58
@adriangb
adriangb force-pushed the mcte-per-run-output branch from 08f406f to c817ddb Compare October 24, 2026 16:08
@adriangb
adriangb force-pushed the mcte-per-run-output branch 2 times, most recently from a70d4c0 to 8d744f8 Compare October 28, 2026 05:36
Comment on lines +72 to +73
/// State that operators keep for one run of a plan
run_state: Arc<RunState>,

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

This would definitely need some discussion

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.

Specifically I think the high level idea would be to move all execution plan state to TaskContext over time

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.

If we went with an approach like this it seems to me like we would want some general way to associate a plan node with its "state" in some way that could be shared with other nodes

For example, in a dynamic filter, we would need some way for both the producer (e.g. topk) and cosumer (e.g. scan) to find the same state

(SortExec -- dynamic filter producer) 
  ...
    (Scan -- dynamic filter consumer)

One way could be something like a generic
NodeId or StateId field that was assigned at plan time (so the SortExec would have NodeId=100 say, and the scan would have NodeId=200, but also know that its dynamic filter came from NodeId=100

The actaul state I would imagine in an Arc<dyn Any + Send + Sync> type situation

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

The per-run state also covers recursive queries. RecursiveQueryExec gives each iteration a child state with new outputs for the CTEs that its recursive term declares. A CTE declared outside the recursive term keeps one output for the whole query. Plan nodes no longer hold the output, so this needs no in-place reset_state. 449f12cf0 adds tests for nested recursive queries and for UNION (DISTINCT) recursion.

On your StateId point: here the CTE id is that id. A producer and consumer pair such as TopK and a scan would fit the same pattern. The planner assigns the filter an id, the producer writes its bounds to the per-run state under that id, and the scan reads them in execute. I sketched this in #28003.

@@ -35,7 +51,7 @@ use std::{collections::HashMap, sync::Arc};
///
/// [`SessionContext`]: https://docs.rs/datafusion/latest/datafusion/execution/context/struct.SessionContext.html
/// [`ExecutionProps`]: datafusion_expr::execution_props::ExecutionProps
#[derive(Debug)]
#[derive(Debug, Clone)]

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.

why does it need to be clone?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

The recursive query needs it. Each iteration has to recompute the CTEs declared inside the recursive term, but keep the ones declared outside it. So each iteration gets the same context with a fresh layer of CTE state on top:

let iteration_ctx = context.clone().with_run_state(child_state);

I tried removing Clone and rebuilding the context with TaskContext::new(...), but then any field set through a builder method (like run_state itself) would be silently dropped. The clone happens once per iteration, so it is cheap.

run_state: Arc<RunState>,
}

/// State that the operators of a plan keep for one run of that plan.

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.

I think @askalt had a similar idea about separating out the per-plan state of the operators into a separate structure

@adriangb adriangb Dec 2, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Yes, I think this is similar to what @askalt proposed in #19351: keep per-execution state in the TaskContext instead of in the plan. IMO that stalled mostly because it tried to cover every operator at once (hash tables, metrics, dynamic filters), keyed by plan node pointer, which changes whenever the plan is rewritten.

This PR does the same thing for just one operator. The CTE has a stable id from the planner, so it can look up its buffered output like this:

let outputs = context.run_state().get_or_init::<MaterializedCteOutputs>();

The rule this PR follows is "one TaskContext = one execution". That fits both modes from in #19905 (comment):

  • Run the plan again with a new TaskContext: the CTE is recomputed, no reset_state needed.
  • Run it concurrently with separate TaskContexts: each run has its own buffer, no deep copy needed.

The one gotcha is reusing the same TaskContext for two executions: the second run would replay the first run's buffered output.

It does not help dynamic filters, since those are wired into the scan at planning time. The same pattern could work there eventually, but I think that discussion belongs in #19905. To avoid committing to anything here, I cam make RunState crate-private and document the one-context-per-execution rule. Would that make this change more palatable?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

@askalt any thoughts?

@adriangb
adriangb force-pushed the mcte-per-run-output branch 2 times, most recently from d341ad4 to bad1518 Compare December 2, 2026 07:02
Add `RunState`, a type-keyed map that `TaskContext` carries for one run of
a plan. All `execute` calls of one run share the same `TaskContext` and so
the same `RunState`; a different `TaskContext` is a different run.

Operators that must share the result of a run between plan nodes (for
example a materialized CTE and its scans) can keep that result here
instead of in the plan nodes, so that a plan can be executed again, or
twice at the same time, without the runs seeing each other's state.

`RunState::new_child` creates a state that replaces the value of one type
and reads all other types from its parent. An operator that executes part
of a plan more than once in a run (such as the recursive term of a
recursive query) uses it to give each execution fresh state for that part.

`TaskContext` now derives `Clone`; a clone shares the `RunState` and is
therefore the same run.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@adriangb
adriangb force-pushed the mcte-per-run-output branch from bad1518 to f4164c1 Compare December 3, 2026 20:28
@alamb alamb changed the title fix: keep the output of a materialized CTE per run, not in the plan fix: keep the output of a materialized CTE in TaskContext (per run) not the plan Dec 3, 2026
@alamb

alamb commented Dec 3, 2026

Copy link
Copy Markdown
Contributor

I filed a ticket I think explaining the high level idea here (moving state into the TaskContext)

`MaterializedCteExec::reset_state` cleared the shared buffer in place and returned `self`.
This did not follow the `ExecutionPlan::reset_state` contract, and two overlapping runs of one plan shared one buffer.

The buffered output is now in a new `RunState` of the `TaskContext`, keyed by the CTE id.
Each run of a plan has its own `TaskContext`, so each run has its own output.
The plan nodes keep no state of a run, so the default `reset_state` is correct for them.

`RecursiveQueryExec` gives each iteration a child `RunState` in which the CTEs that the recursive term declares have no output.
A CTE that is declared outside the recursive term keeps its output for the whole query.

The body runs with a copy of the `TaskContext` that refers to the outputs of the run weakly.
The future that buffers the body is in the outputs, and a body stream can keep its context.
A strong reference would be a cycle, so an abandoned run would never be dropped, and its body would run to completion and keep its memory and spill files.
A scan stream of the caller keeps the outputs strongly until it has the output, so the body runs even when the caller drops the `TaskContext` before it polls.

Closes apache#26229.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
RecursiveQueryExec gives each iteration new outputs for the materialized
CTEs that its recursive term declares. The existing tests cover a single
level of UNION ALL recursion only.

Add a test with a recursive query nested in the recursive term of another
recursive query, with a MATERIALIZED CTE at each level that reads the work
table of its own level. Add a test for UNION (DISTINCT) recursion with a
MATERIALIZED CTE in the recursive term.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@github-actions github-actions Bot added the sqllogictest SQL Logic Tests (.slt) label Dec 4, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

execution Related to the execution crate physical-plan Changes to the physical-plan crate sqllogictest SQL Logic Tests (.slt)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

MaterializedCteExec::reset_state clears its shared buffer in place

3 participants