Repository navigation
fix: keep the output of a materialized CTE in TaskContext (per run) not the plan
#26270
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -9,7 +9,10 @@ use crate::{ | |
| use datafusion_common::{Result, internal_datafusion_err, plan_datafusion_err}; | ||
| use datafusion_expr::planner::ExprPlanner; | ||
| use datafusion_expr::{AggregateUDF, HigherOrderUDF, ScalarUDF, WindowUDF}; | ||
| use parking_lot::Mutex; | ||
| use std::any::{Any, TypeId}; | ||
| use std::collections::HashSet; | ||
| use std::fmt; | ||
| use std::{collections::HashMap, sync::Arc}; | ||
|
|
||
| /// Task Execution Context | ||
|
|
@@ -35,7 +38,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)] | ||
| pub struct TaskContext { | ||
| /// Session Id | ||
| session_id: String, | ||
|
|
@@ -53,6 +56,71 @@ pub struct TaskContext { | |
| window_functions: HashMap<String, Arc<WindowUDF>>, | ||
| /// Runtime environment associated with this task context | ||
| runtime: Arc<RuntimeEnv>, | ||
| /// State that operators keep for one run of a plan | ||
| run_state: Arc<RunState>, | ||
| } | ||
|
|
||
| /// State that the operators of a plan keep for one run of that plan. | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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 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
The one gotcha is reusing the same 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
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. @askalt any thoughts? |
||
| /// | ||
| /// An operator must not keep the result of a run in its plan node when another | ||
| /// node reads that result, because the plan can be executed again, or two | ||
| /// times at the same time. Such an operator keeps the result here. All | ||
| /// `execute` calls of one run get the same [`TaskContext`], so they share one | ||
| /// [`RunState`]. A different [`TaskContext`] is a different run. | ||
| /// | ||
| /// A [`RunState`] holds at most one value of each type. An operator defines | ||
| /// its own type, for example a map from an operator id to a result. | ||
| /// | ||
| /// An operator that executes a part of the plan more than one time in a run | ||
| /// (such as the recursive term of a recursive query) can give each execution a | ||
| /// child state. See [`RunState::new_child`]. | ||
| #[derive(Default)] | ||
| pub struct RunState { | ||
| /// Types that are not in `values` are read from the parent. | ||
| parent: Option<Arc<RunState>>, | ||
| values: Mutex<HashMap<TypeId, Arc<dyn Any + Send + Sync>>>, | ||
| } | ||
|
|
||
| impl fmt::Debug for RunState { | ||
| fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { | ||
| f.debug_struct("RunState") | ||
| .field("parent", &self.parent) | ||
| .finish_non_exhaustive() | ||
| } | ||
| } | ||
|
|
||
| impl RunState { | ||
| /// Create an empty state. | ||
| pub fn new() -> Self { | ||
| Self::default() | ||
| } | ||
|
|
||
| /// Create a state in which `value` replaces the value of type `T` of | ||
| /// `parent`. The values of all other types are those of `parent`. | ||
| pub fn new_child<T: Send + Sync + 'static>( | ||
| parent: Arc<RunState>, | ||
| value: Arc<T>, | ||
| ) -> Self { | ||
| let value = value as Arc<dyn Any + Send + Sync>; | ||
| Self { | ||
| parent: Some(parent), | ||
| values: Mutex::new(HashMap::from([(TypeId::of::<T>(), value)])), | ||
| } | ||
| } | ||
|
|
||
| /// Return the value of type `T`. The first call creates it. | ||
| pub fn get_or_init<T: Default + Send + Sync + 'static>(&self) -> Arc<T> { | ||
| let mut values = self.values.lock(); | ||
| let id = TypeId::of::<T>(); | ||
| let value = match (values.get(&id), &self.parent) { | ||
| (Some(value), _) => Arc::clone(value), | ||
| (None, Some(parent)) => return parent.get_or_init(), | ||
| (None, None) => { | ||
| Arc::clone(values.entry(id).or_insert_with(|| Arc::new(T::default()))) | ||
| } | ||
| }; | ||
| value.downcast().expect("the value has the type of its key") | ||
| } | ||
| } | ||
|
|
||
| impl Default for TaskContext { | ||
|
|
@@ -69,6 +137,7 @@ impl Default for TaskContext { | |
| aggregate_functions: HashMap::new(), | ||
| window_functions: HashMap::new(), | ||
| runtime, | ||
| run_state: Arc::default(), | ||
| } | ||
| } | ||
| } | ||
|
|
@@ -99,6 +168,7 @@ impl TaskContext { | |
| aggregate_functions, | ||
| window_functions, | ||
| runtime, | ||
| run_state: Arc::default(), | ||
| } | ||
| } | ||
|
|
||
|
|
@@ -155,6 +225,17 @@ impl TaskContext { | |
| self | ||
| } | ||
|
|
||
| /// Return the [`RunState`] of the run that this [`TaskContext`] is for | ||
| pub fn run_state(&self) -> &Arc<RunState> { | ||
| &self.run_state | ||
| } | ||
|
|
||
| /// Update the [`RunState`] | ||
| pub fn with_run_state(mut self, run_state: Arc<RunState>) -> Self { | ||
| self.run_state = run_state; | ||
| self | ||
| } | ||
|
|
||
| /// Update the `task_id` | ||
| pub fn with_task_id(mut self, task_id: String) -> Self { | ||
| self.task_id = Some(task_id); | ||
|
|
@@ -281,6 +362,28 @@ mod tests { | |
| const PREFIX: &'static str = "test"; | ||
| } | ||
|
|
||
| #[test] | ||
| fn run_state_child_replaces_one_type() { | ||
| let context = TaskContext::default(); | ||
| let state = context.run_state(); | ||
| let number: Arc<Mutex<usize>> = state.get_or_init(); | ||
| *number.lock() = 1; | ||
| // A copy of the context is the same run. | ||
| let copy = context.clone(); | ||
| assert_eq!(*copy.run_state().get_or_init::<Mutex<usize>>().lock(), 1); | ||
|
|
||
| let child = RunState::new_child(Arc::clone(state), Arc::new(Mutex::new(2_usize))); | ||
| assert_eq!(*child.get_or_init::<Mutex<usize>>().lock(), 2); | ||
| assert_eq!(*state.get_or_init::<Mutex<usize>>().lock(), 1); | ||
| // The child reads all other types from the parent. | ||
| *child.get_or_init::<Mutex<String>>().lock() = "a".to_string(); | ||
| assert_eq!(*state.get_or_init::<Mutex<String>>().lock(), "a"); | ||
|
|
||
| // A new context is a new run. | ||
| let other = TaskContext::default(); | ||
| assert_eq!(*other.run_state().get_or_init::<Mutex<usize>>().lock(), 0); | ||
| } | ||
|
|
||
| #[test] | ||
| fn task_context_extensions() -> Result<()> { | ||
| let runtime = Arc::new(RuntimeEnv::default()); | ||
|
|
||
There was a problem hiding this comment.
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
There was a problem hiding this comment.
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
ExecutionPlans / concurrently running plans by moving all state to TaskContext #28002There was a problem hiding this comment.
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
One way could be something like a generic
NodeIdorStateIdfield 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=100The actaul state I would imagine in an
Arc<dyn Any + Send + Sync>type situationThere was a problem hiding this comment.
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.
RecursiveQueryExecgives 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-placereset_state. 449f12cf0 adds tests for nested recursive queries and forUNION(DISTINCT) recursion.On your
StateIdpoint: 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 inexecute. I sketched this in #28003.