Skip to main content

datafusion_execution/
task.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership
3// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements
4
5use crate::{
6    config::SessionConfig, memory_pool::MemoryPool, registry::FunctionRegistry,
7    runtime_env::RuntimeEnv,
8};
9use datafusion_common::{Result, internal_datafusion_err, plan_datafusion_err};
10use datafusion_expr::planner::ExprPlanner;
11use datafusion_expr::{AggregateUDF, HigherOrderUDF, ScalarUDF, WindowUDF};
12use std::collections::HashSet;
13use std::{collections::HashMap, sync::Arc};
14
15/// Task Execution Context
16///
17/// A [`TaskContext`] contains the state required during a single query's
18/// execution. Please see the documentation on [`SessionContext`] for more
19/// information.
20///
21/// # Relationship with [`ExecutionProps`]
22///
23/// [`TaskContext`] is intentionally distinct from [`ExecutionProps`].
24/// [`ExecutionProps`] is state used while optimizing a logical
25/// plan and constructing a physical plan.
26///
27/// [`TaskContext`] is the runtime context passed to physical operators when
28/// executing a physical plan. It carries runtime services and session state
29/// needed at that stage, such as [`RuntimeEnv`], memory-pool access, session
30/// configuration, and function lookup.
31///
32/// Keeping these structures separate avoids threading execution/runtime state
33/// through planning APIs, and avoids making execution depend on planner-only
34/// scratch state.
35///
36/// [`SessionContext`]: https://docs.rs/datafusion/latest/datafusion/execution/context/struct.SessionContext.html
37/// [`ExecutionProps`]: datafusion_expr::execution_props::ExecutionProps
38#[derive(Debug)]
39pub struct TaskContext {
40    /// Session Id
41    session_id: String,
42    /// Optional task identity
43    task_id: Option<String>,
44    /// Session configuration
45    session_config: SessionConfig,
46    /// Scalar functions associated with this task context
47    scalar_functions: HashMap<String, Arc<ScalarUDF>>,
48    /// Higher order functions associated with this task context
49    higher_order_functions: HashMap<String, Arc<HigherOrderUDF>>,
50    /// Aggregate functions associated with this task context
51    aggregate_functions: HashMap<String, Arc<AggregateUDF>>,
52    /// Window functions associated with this task context
53    window_functions: HashMap<String, Arc<WindowUDF>>,
54    /// Runtime environment associated with this task context
55    runtime: Arc<RuntimeEnv>,
56}
57
58impl Default for TaskContext {
59    fn default() -> Self {
60        let runtime = Arc::new(RuntimeEnv::default());
61
62        // Create a default task context, mostly useful for testing
63        Self {
64            session_id: "DEFAULT".to_string(),
65            task_id: None,
66            session_config: SessionConfig::new(),
67            scalar_functions: HashMap::new(),
68            higher_order_functions: HashMap::new(),
69            aggregate_functions: HashMap::new(),
70            window_functions: HashMap::new(),
71            runtime,
72        }
73    }
74}
75
76impl TaskContext {
77    /// Create a new [`TaskContext`] instance.
78    ///
79    /// Most users will use [`SessionContext::task_ctx`] to create [`TaskContext`]s
80    ///
81    /// [`SessionContext::task_ctx`]: https://docs.rs/datafusion/latest/datafusion/execution/context/struct.SessionContext.html#method.task_ctx
82    #[expect(clippy::too_many_arguments)]
83    pub fn new(
84        task_id: Option<String>,
85        session_id: String,
86        session_config: SessionConfig,
87        scalar_functions: HashMap<String, Arc<ScalarUDF>>,
88        higher_order_functions: HashMap<String, Arc<HigherOrderUDF>>,
89        aggregate_functions: HashMap<String, Arc<AggregateUDF>>,
90        window_functions: HashMap<String, Arc<WindowUDF>>,
91        runtime: Arc<RuntimeEnv>,
92    ) -> Self {
93        Self {
94            session_id,
95            task_id,
96            session_config,
97            scalar_functions,
98            higher_order_functions,
99            aggregate_functions,
100            window_functions,
101            runtime,
102        }
103    }
104
105    /// Return the SessionConfig associated with this [TaskContext]
106    pub fn session_config(&self) -> &SessionConfig {
107        &self.session_config
108    }
109
110    /// Return the `session_id` of this [TaskContext]
111    pub fn session_id(&self) -> String {
112        self.session_id.clone()
113    }
114
115    /// Return the `task_id` of this [TaskContext]
116    pub fn task_id(&self) -> Option<String> {
117        self.task_id.clone()
118    }
119
120    /// Return the [`MemoryPool`] associated with this [TaskContext]
121    pub fn memory_pool(&self) -> &Arc<dyn MemoryPool> {
122        &self.runtime.memory_pool
123    }
124
125    /// Return the [RuntimeEnv] associated with this [TaskContext]
126    pub fn runtime_env(&self) -> Arc<RuntimeEnv> {
127        Arc::clone(&self.runtime)
128    }
129
130    pub fn scalar_functions(&self) -> &HashMap<String, Arc<ScalarUDF>> {
131        &self.scalar_functions
132    }
133
134    pub fn higher_order_functions(&self) -> &HashMap<String, Arc<HigherOrderUDF>> {
135        &self.higher_order_functions
136    }
137
138    pub fn aggregate_functions(&self) -> &HashMap<String, Arc<AggregateUDF>> {
139        &self.aggregate_functions
140    }
141
142    pub fn window_functions(&self) -> &HashMap<String, Arc<WindowUDF>> {
143        &self.window_functions
144    }
145
146    /// Update the [`SessionConfig`]
147    pub fn with_session_config(mut self, session_config: SessionConfig) -> Self {
148        self.session_config = session_config;
149        self
150    }
151
152    /// Update the [`RuntimeEnv`]
153    pub fn with_runtime(mut self, runtime: Arc<RuntimeEnv>) -> Self {
154        self.runtime = runtime;
155        self
156    }
157
158    /// Update the `task_id`
159    pub fn with_task_id(mut self, task_id: String) -> Self {
160        self.task_id = Some(task_id);
161        self
162    }
163}
164
165impl FunctionRegistry for TaskContext {
166    fn udfs(&self) -> HashSet<String> {
167        self.scalar_functions.keys().cloned().collect()
168    }
169
170    fn udf(&self, name: &str) -> Result<Arc<ScalarUDF>> {
171        let result = self.scalar_functions.get(name);
172
173        result.cloned().ok_or_else(|| {
174            plan_datafusion_err!("There is no UDF named \"{name}\" in the TaskContext")
175        })
176    }
177
178    fn higher_order_function(&self, name: &str) -> Result<Arc<HigherOrderUDF>> {
179        let result = self.higher_order_functions.get(name);
180
181        result.cloned().ok_or_else(|| {
182            plan_datafusion_err!(
183                "There is no higher-order function named \"{name}\" in the TaskContext"
184            )
185        })
186    }
187
188    fn udaf(&self, name: &str) -> Result<Arc<AggregateUDF>> {
189        let result = self.aggregate_functions.get(name);
190
191        result.cloned().ok_or_else(|| {
192            plan_datafusion_err!("There is no UDAF named \"{name}\" in the TaskContext")
193        })
194    }
195
196    fn udwf(&self, name: &str) -> Result<Arc<WindowUDF>> {
197        let result = self.window_functions.get(name);
198
199        result.cloned().ok_or_else(|| {
200            internal_datafusion_err!(
201                "There is no UDWF named \"{name}\" in the TaskContext"
202            )
203        })
204    }
205    fn register_udaf(
206        &mut self,
207        udaf: Arc<AggregateUDF>,
208    ) -> Result<Option<Arc<AggregateUDF>>> {
209        udaf.aliases().iter().for_each(|alias| {
210            self.aggregate_functions
211                .insert(alias.clone(), Arc::clone(&udaf));
212        });
213        Ok(self.aggregate_functions.insert(udaf.name().into(), udaf))
214    }
215    fn register_udwf(&mut self, udwf: Arc<WindowUDF>) -> Result<Option<Arc<WindowUDF>>> {
216        udwf.aliases().iter().for_each(|alias| {
217            self.window_functions
218                .insert(alias.clone(), Arc::clone(&udwf));
219        });
220        Ok(self.window_functions.insert(udwf.name().into(), udwf))
221    }
222    fn register_udf(&mut self, udf: Arc<ScalarUDF>) -> Result<Option<Arc<ScalarUDF>>> {
223        udf.aliases().iter().for_each(|alias| {
224            self.scalar_functions
225                .insert(alias.clone(), Arc::clone(&udf));
226        });
227        Ok(self.scalar_functions.insert(udf.name().into(), udf))
228    }
229
230    fn register_higher_order_function(
231        &mut self,
232        function: Arc<HigherOrderUDF>,
233    ) -> Result<Option<Arc<HigherOrderUDF>>> {
234        function.aliases().iter().for_each(|alias| {
235            self.higher_order_functions
236                .insert(alias.clone(), Arc::clone(&function));
237        });
238        Ok(self
239            .higher_order_functions
240            .insert(function.name().into(), function))
241    }
242
243    fn expr_planners(&self) -> Vec<Arc<dyn ExprPlanner>> {
244        vec![]
245    }
246
247    fn higher_order_function_names(&self) -> HashSet<String> {
248        self.higher_order_functions.keys().cloned().collect()
249    }
250
251    fn udafs(&self) -> HashSet<String> {
252        self.aggregate_functions.keys().cloned().collect()
253    }
254
255    fn udwfs(&self) -> HashSet<String> {
256        self.window_functions.keys().cloned().collect()
257    }
258}
259
260/// Produce the [`TaskContext`].
261pub trait TaskContextProvider {
262    fn task_ctx(&self) -> Arc<TaskContext>;
263}
264
265#[cfg(test)]
266mod tests {
267    use super::*;
268    use datafusion_common::{
269        config::{ConfigExtension, ConfigOptions, Extensions},
270        extensions_options,
271    };
272
273    extensions_options! {
274        struct TestExtension {
275            value: usize, default = 42
276            option_value: Option<usize>, default = None
277        }
278    }
279
280    impl ConfigExtension for TestExtension {
281        const PREFIX: &'static str = "test";
282    }
283
284    #[test]
285    fn task_context_extensions() -> Result<()> {
286        let runtime = Arc::new(RuntimeEnv::default());
287        let mut extensions = Extensions::new();
288        extensions.insert(TestExtension::default());
289
290        let mut config = ConfigOptions::new().with_extensions(extensions);
291        config.set("test.value", "24")?;
292        config.set("test.option_value", "42")?;
293        let session_config = SessionConfig::from(config);
294
295        let task_context = TaskContext::new(
296            Some("task_id".to_string()),
297            "session_id".to_string(),
298            session_config,
299            HashMap::default(),
300            HashMap::default(),
301            HashMap::default(),
302            HashMap::default(),
303            runtime,
304        );
305
306        let test = task_context
307            .session_config()
308            .options()
309            .extensions
310            .get::<TestExtension>();
311        assert!(test.is_some());
312
313        assert_eq!(test.unwrap().value, 24);
314        assert_eq!(test.unwrap().option_value, Some(42));
315
316        Ok(())
317    }
318
319    #[test]
320    fn task_context_extensions_default() -> Result<()> {
321        let runtime = Arc::new(RuntimeEnv::default());
322        let mut extensions = Extensions::new();
323        extensions.insert(TestExtension::default());
324
325        let config = ConfigOptions::new().with_extensions(extensions);
326        let session_config = SessionConfig::from(config);
327
328        let task_context = TaskContext::new(
329            Some("task_id".to_string()),
330            "session_id".to_string(),
331            session_config,
332            HashMap::default(),
333            HashMap::default(),
334            HashMap::default(),
335            HashMap::default(),
336            runtime,
337        );
338
339        let test = task_context
340            .session_config()
341            .options()
342            .extensions
343            .get::<TestExtension>();
344        assert!(test.is_some());
345
346        assert_eq!(test.unwrap().value, 42);
347        assert_eq!(test.unwrap().option_value, None);
348
349        Ok(())
350    }
351}