Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion datafusion/execution/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,4 +38,4 @@ pub use disk_manager::DiskManager;
pub use registry::FunctionRegistry;
pub use spill_file::{AsyncSpillWriter, SpillFile, SpillWriter, TempFileFactory};
pub use stream::{RecordBatchStream, SendableRecordBatchStream};
pub use task::{TaskContext, TaskContextProvider};
pub use task::{RunState, TaskContext, TaskContextProvider};
105 changes: 104 additions & 1 deletion datafusion/execution/src/task.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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,
Expand All @@ -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>,
Comment on lines +59 to +60

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.

}

/// 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?

///
/// 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 {
Expand All @@ -69,6 +137,7 @@ impl Default for TaskContext {
aggregate_functions: HashMap::new(),
window_functions: HashMap::new(),
runtime,
run_state: Arc::default(),
}
}
}
Expand Down Expand Up @@ -99,6 +168,7 @@ impl TaskContext {
aggregate_functions,
window_functions,
runtime,
run_state: Arc::default(),
}
}

Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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());
Expand Down
Loading