Repository navigation
Conversation
Codecov Report❌ Patch coverage is 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. 🚀 New features to boost your workflow:
|
91d3f3d to
71f28c3
Compare
71f28c3 to
07a4fbb
Compare
07a4fbb to
08f406f
Compare
08f406f to
c817ddb
Compare
a70d4c0 to
8d744f8
Compare
| /// State that operators keep for one run of a plan | ||
| run_state: Arc<RunState>, |
There was a problem hiding this comment.
This would definitely need some discussion
There was a problem hiding this comment.
Specifically I think the high level idea would be to move all execution plan state to TaskContext over time
There was a problem hiding this comment.
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
There was a problem hiding this comment.
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)] | |||
There was a problem hiding this comment.
why does it need to be clone?
There was a problem hiding this comment.
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. |
There was a problem hiding this comment.
I think @askalt had a similar idea about separating out the per-plan state of the operators into a separate structure
There was a problem hiding this comment.
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, noreset_stateneeded. - 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?
d341ad4 to
bad1518
Compare
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>
bad1518 to
f4164c1
Compare
TaskContext (per run) not the plan
|
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>
f4164c1 to
1523191
Compare
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>
Which issue does this PR close?
MaterializedCteExec::reset_stateclears its shared buffer in place #26229.Rationale for this change
MaterializedCteExec::reset_statecleared its shared buffer in place and returnedself.ExecutionPlan::reset_statemust 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:TaskContextreset_plan_states(plan)while run 1 is openNo SQL query is known to give a wrong result on
main.What changes are included in this PR?
TaskContexthas a newRunState. It holds state that operators keep for one run of a plan.RunState, keyed by the CTE id.MaterializedCteBufferholds plan-time data only.MaterializedCteExecuses the defaultreset_state.RecursiveQueryExecgives each iteration a childRunState, 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:
TaskContext. If each partition is executed with a differentTaskContext, the body is computed one time for each context.TaskContextof the run and the replay streams are dropped. Release the buffer of a materialized CTE when the last scan finishes #26233 releases it earlier.TaskContextwhoseRunStaterefers to the outputs of the run weakly (internal_context). The future that buffers the body is in theRunState, 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 theTaskContextbefore it polls.ScalarSubqueryExec::reset_statehas 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_statesleaves 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 forRunState. The recursive cases incte_materialized.sltpass 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, andTaskContext: Clone. No existing API changes.