diff --git a/datafusion/execution/src/lib.rs b/datafusion/execution/src/lib.rs index 4f3ce798c21ae..6a3f2cc090401 100644 --- a/datafusion/execution/src/lib.rs +++ b/datafusion/execution/src/lib.rs @@ -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}; diff --git a/datafusion/execution/src/task.rs b/datafusion/execution/src/task.rs index bc4d38689e79a..4148890281937 100644 --- a/datafusion/execution/src/task.rs +++ b/datafusion/execution/src/task.rs @@ -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>, /// Runtime environment associated with this task context runtime: Arc, + /// State that operators keep for one run of a plan + run_state: Arc, +} + +/// State that the operators of a plan keep for one run of that plan. +/// +/// 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>, + values: Mutex>>, +} + +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( + parent: Arc, + value: Arc, + ) -> Self { + let value = value as Arc; + Self { + parent: Some(parent), + values: Mutex::new(HashMap::from([(TypeId::of::(), value)])), + } + } + + /// Return the value of type `T`. The first call creates it. + pub fn get_or_init(&self) -> Arc { + let mut values = self.values.lock(); + let id = TypeId::of::(); + 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 { + &self.run_state + } + + /// Update the [`RunState`] + pub fn with_run_state(mut self, run_state: Arc) -> 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> = 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::>().lock(), 1); + + let child = RunState::new_child(Arc::clone(state), Arc::new(Mutex::new(2_usize))); + assert_eq!(*child.get_or_init::>().lock(), 2); + assert_eq!(*state.get_or_init::>().lock(), 1); + // The child reads all other types from the parent. + *child.get_or_init::>().lock() = "a".to_string(); + assert_eq!(*state.get_or_init::>().lock(), "a"); + + // A new context is a new run. + let other = TaskContext::default(); + assert_eq!(*other.run_state().get_or_init::>().lock(), 0); + } + #[test] fn task_context_extensions() -> Result<()> { let runtime = Arc::new(RuntimeEnv::default()); diff --git a/datafusion/physical-plan/src/materialized_cte.rs b/datafusion/physical-plan/src/materialized_cte.rs index 45588fd0ba078..f1039343a0b77 100644 --- a/datafusion/physical-plan/src/materialized_cte.rs +++ b/datafusion/physical-plan/src/materialized_cte.rs @@ -10,6 +10,27 @@ //! partition of the body to completion and buffers the output; every scan then //! replays that buffer. //! +//! The buffered output is not kept in the plan. It is kept in the +//! [`RunState`] of the [`TaskContext`], so each run of a plan has its own +//! output, and two runs of one plan that overlap do not share it. All +//! `execute` calls of one run must get the same [`TaskContext`]. With a +//! different [`TaskContext`] for each call, each call computes the body again. +//! +//! The body runs with a copy of the [`TaskContext`] that refers to the +//! outputs of the run weakly. See `internal_context`. The future that +//! buffers the body is in the outputs, and the body streams can keep their +//! context. A strong reference would keep the run alive after the caller +//! dropped its streams and its context, and the body would run to completion. +//! +//! The plan nodes keep no state of a run, so the default +//! [`ExecutionPlan::reset_state`] is correct for them: it returns a new node +//! and the old node stays usable. +//! +//! `RecursiveQueryExec` executes its recursive term one time for each +//! iteration, with the same [`TaskContext`]. It gives each iteration new +//! outputs for the CTEs that the recursive term declares. See +//! `with_new_materialized_cte_outputs`. +//! //! The body is fully materialized before any scan yields a row. This is a //! pipeline break, but it cannot deadlock when two consumers of the same CTE //! are read at different rates (for example the build and probe side of one @@ -31,19 +52,20 @@ //! the statistics of the body. The planner copies them to the scan with //! [`MaterializedCteScanExec::with_body_statistics`]. +use std::collections::{HashMap, HashSet}; use std::fmt; use std::pin::Pin; -use std::sync::Arc; +use std::sync::{Arc, Weak}; use std::task::{Context, Poll}; use arrow::datatypes::{Schema, SchemaRef}; use arrow::record_batch::RecordBatch; use datafusion_common::config::ConfigOptions; -use datafusion_common::tree_node::TreeNodeRecursion; +use datafusion_common::tree_node::{TreeNode, TreeNodeRecursion}; use datafusion_common::{Result, Statistics, internal_err}; use datafusion_common_runtime::JoinSet; use datafusion_execution::memory_pool::{MemoryConsumer, MemoryReservation}; -use datafusion_execution::{SendableRecordBatchStream, SpillFile, TaskContext}; +use datafusion_execution::{RunState, SendableRecordBatchStream, SpillFile, TaskContext}; use datafusion_physical_expr::{EquivalenceProperties, Partitioning, PhysicalExpr}; use futures::stream::BoxStream; use futures::{Stream, StreamExt, TryStreamExt}; @@ -250,8 +272,102 @@ fn reserve_replay_memory( } } -/// State shared by one [`MaterializedCteExec`] and all its -/// [`MaterializedCteScanExec`]s. +/// The outputs of the materialized CTEs in one run of a plan, by CTE id. +/// +/// The [`RunState`] of the [`TaskContext`] holds it, and so does a scan stream +/// of the caller until it has the output. An output lives until the last of +/// these and the last replay of the output are dropped. +#[derive(Default)] +struct MaterializedCteOutputs { + /// The outputs of the enclosing execution. `None` for a whole run. + parent: Option>, + /// The outputs of the run, for the context of a CTE body. Weak, so that + /// the body does not keep the run alive. See [`internal_context`]. + weak_parent: Option>, + /// The CTEs that have their own output here when `parent` is set. The + /// output of every other CTE is the output in `parent`. + renewed: HashSet, + outputs: Mutex>>>, +} + +impl MaterializedCteOutputs { + /// Return the output of the CTE `id`. The first call creates it, empty. + fn get(&self, id: u64) -> Result>> { + if let Some(parent) = &self.weak_parent { + let Some(parent) = parent.upgrade() else { + return internal_err!("MaterializedCte: the run of the CTE {id} ended"); + }; + return parent.get(id); + } + match &self.parent { + Some(parent) if !self.renewed.contains(&id) => parent.get(id), + _ => Ok(Arc::clone(self.outputs.lock().entry(id).or_default())), + } + } +} + +/// Return a copy of `context` for the body of a CTE. Its scans read the +/// outputs of the run of `context` through a weak reference. +/// +/// The future that buffers the body is in the outputs of the run, and it owns +/// the body streams, which can keep their context. With a strong reference, +/// the run would keep itself alive: when the caller drops every stream and +/// context, the body would not be cancelled, and its memory reservations and +/// spill files would live until the body completes. +fn internal_context(context: &Arc) -> Arc { + let run = context.run_state().get_or_init::(); + let weak_parent = match &run.weak_parent { + Some(weak_parent) => Weak::clone(weak_parent), + None => Arc::downgrade(&run), + }; + let outputs = MaterializedCteOutputs { + weak_parent: Some(weak_parent), + ..Default::default() + }; + // A new `RunState`, not a child of the state of the run, because a child + // keeps its parent. Only materialized CTEs keep state in a `RunState`. + let run_state = RunState::new_child(Arc::new(RunState::new()), Arc::new(outputs)); + Arc::new(context.as_ref().clone().with_run_state(Arc::new(run_state))) +} + +/// Return the ids of the materialized CTEs that `plan` declares. +pub(crate) fn materialized_cte_ids(plan: &Arc) -> HashSet { + let mut ids = HashSet::new(); + plan.apply(|node| { + if let Some(cte) = node.downcast_ref::() { + ids.insert(cte.buffer.id); + } + Ok(TreeNodeRecursion::Continue) + }) + .expect("the closure does not fail"); + ids +} + +/// Return a copy of `context` in which the materialized CTEs `ids` have no +/// output, so that they are computed again. All other CTEs keep the output +/// that they have in `context`. +/// +/// `RecursiveQueryExec` calls this for each iteration with the CTEs that its +/// recursive term declares. A CTE that is declared outside the recursive term +/// and read inside it is not in `ids`, so it is computed one time for the +/// whole query. +pub(crate) fn with_new_materialized_cte_outputs( + context: &TaskContext, + ids: &HashSet, +) -> TaskContext { + let run_state = context.run_state(); + let outputs = MaterializedCteOutputs { + parent: Some(run_state.get_or_init()), + renewed: ids.clone(), + ..Default::default() + }; + let run_state = RunState::new_child(Arc::clone(run_state), Arc::new(outputs)); + context.clone().with_run_state(Arc::new(run_state)) +} + +/// The plan-time state shared by one [`MaterializedCteExec`] and all its +/// [`MaterializedCteScanExec`]s. It holds no output: the output of a run is in +/// the [`RunState`] of the [`TaskContext`] of that run. pub struct MaterializedCteBuffer { id: u64, name: String, @@ -260,7 +376,6 @@ pub struct MaterializedCteBuffer { /// the final plan. A scan can run the body before the owning /// `MaterializedCteExec` executes, for example from a scalar subquery. body: Mutex>>, - output: Mutex>>, /// The partition count of every scan bound to this buffer. scan_partitions: Mutex>, metrics: ExecutionPlanMetricsSet, @@ -280,7 +395,6 @@ impl MaterializedCteBuffer { id, name: name.into(), body: Mutex::new(None), - output: Mutex::new(Arc::default()), scan_partitions: Mutex::new(vec![]), metrics: ExecutionPlanMetricsSet::new(), } @@ -295,12 +409,9 @@ impl MaterializedCteBuffer { *self.body.lock() = Some(body); } - fn reset(&self) { - *self.output.lock() = Arc::default(); - } - /// Return a future that resolves once the body has been fully buffered. - /// The body runs at most once, whichever consumer asks first. + /// The body runs at most once for each run, whichever consumer asks + /// first. The run is identified by the [`RunState`] of `context`. fn materialize( self: &Arc, context: Arc, @@ -308,11 +419,15 @@ impl MaterializedCteBuffer { let Some(body) = self.body.lock().clone() else { return internal_err!("MaterializedCte {} has no body", self.name); }; - let once = Arc::clone(&self.output.lock()); + let once = context + .run_state() + .get_or_init::() + .get(self.id)?; let name = self.name.clone(); let scan_partitions = self.scan_partitions.lock().clone(); let metrics = self.metrics.clone(); once.try_once(move || { + let context = internal_context(&context); Ok(buffer_body(name, body, scan_partitions, context, metrics)) }) } @@ -569,23 +684,6 @@ impl ExecutionPlan for MaterializedCteExec { ) } - /// Clears the shared buffer in place and returns `self`. - /// - /// This is an exception to the `reset_state` contract, which expects a - /// new node and leaves the old node unchanged. `RecursiveQueryExec` resets - /// the recursive term before each iteration, and a `MATERIALIZED` CTE in - /// that term must be computed again. A new buffer would also need new - /// scans, and a scan in a scalar subquery is not below this node, so this - /// node cannot rebind it. `ScalarSubqueryExec::reset_state` does the same. - /// - /// Two overlapping runs of one plan share this buffer. Nothing in - /// DataFusion does that today. See - /// . - fn reset_state(self: Arc) -> Result> { - self.buffer.reset(); - Ok(self) - } - fn maintains_input_order(&self) -> Vec { vec![false, true] } @@ -898,12 +996,18 @@ impl ExecutionPlan for MaterializedCteScanExec { self.name ); }; + // The stream keeps the outputs of the run until it has the output, so + // that the body runs even if the caller drops the context. A scan in + // a CTE body keeps them weakly. See `internal_context`. + let outputs = context.run_state().get_or_init::(); + let outputs = outputs.weak_parent.is_none().then_some(outputs); let mut output = buffer.materialize(context)?; let output_partitions = self.cache.partitioning.partition_count(); let baseline = BaselineMetrics::new(&self.metrics, partition); let projection = self.projection.clone(); let stream = futures::stream::once(async move { let output = std::future::poll_fn(|cx| output.get_shared(cx)).await?; + drop(outputs); replay(output, partition, output_partitions) }) .try_flatten() @@ -957,6 +1061,7 @@ mod tests { use super::*; use crate::common::collect; use crate::empty::EmptyExec; + use crate::execution_plan::reset_plan_states; use crate::filter_pushdown::PushedDown; use crate::statistics::StatisticsContext; use crate::test::TestMemoryExec; @@ -965,6 +1070,8 @@ mod tests { use datafusion_common::stats::Precision; use datafusion_execution::runtime_env::RuntimeEnvBuilder; use datafusion_physical_expr::expressions::{col, lit}; + use std::sync::atomic::{AtomicUsize, Ordering}; + use std::time::Duration; #[test] fn scan_reports_body_statistics() -> Result<()> { @@ -1227,8 +1334,8 @@ mod tests { .map(|scan| scan.execute(0, Arc::clone(&context))) .collect::>>()?; drop((once, output, scans, exec, buffer)); - // Once every stream has returned a batch, only the streams hold the - // buffered output. + // Once every stream has returned a batch, only the streams and the + // context hold the buffered output. let mut firsts = vec![]; for stream in &mut streams { firsts.push(stream.next().await.transpose()?.unwrap()); @@ -1247,7 +1354,11 @@ mod tests { .collect(); assert_eq!(values, (0..10_000).collect::>()); } - assert_eq!(context.memory_pool().reserved(), 0); + // The context of the run holds the output until it is dropped. + let pool = Arc::clone(context.memory_pool()); + assert_eq!(pool.reserved(), reserved); + drop(context); + assert_eq!(pool.reserved(), 0); Ok(()) } @@ -1386,4 +1497,319 @@ mod tests { } Ok(()) } + + /// Counts the `execute` calls of `input`. + #[derive(Debug)] + struct CountingExec { + input: Arc, + executions: Arc, + } + + impl DisplayAs for CountingExec { + fn fmt_as(&self, _: DisplayFormatType, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "CountingExec") + } + } + + impl ExecutionPlan for CountingExec { + fn name(&self) -> &'static str { + "CountingExec" + } + + fn properties(&self) -> &Arc { + self.input.properties() + } + + fn children(&self) -> Vec<&Arc> { + vec![&self.input] + } + + fn apply_expressions( + &self, + _f: &mut dyn FnMut(&Arc) -> Result, + ) -> Result { + Ok(TreeNodeRecursion::Continue) + } + + fn with_new_children( + self: Arc, + mut children: Vec>, + ) -> Result> { + Ok(Arc::new(Self { + input: children.swap_remove(0), + executions: Arc::clone(&self.executions), + })) + } + + fn execute( + &self, + partition: usize, + context: Arc, + ) -> Result { + self.executions.fetch_add(1, Ordering::Relaxed); + self.input.execute(partition, context) + } + } + + /// A plan `MaterializedCteExec(body, scan)` whose body has the rows + /// `0..rows` in batches of one row, and the count of body executions. + fn counting_plan(rows: i32) -> Result<(Arc, Arc)> { + let schema = Arc::new(Schema::new(vec![Field::new("a", DataType::Int32, false)])); + let batches = (0..rows) + .map(|i| { + let values = Int32Array::from(vec![i]); + RecordBatch::try_new(Arc::clone(&schema), vec![Arc::new(values)]) + }) + .collect::, _>>()?; + let executions = Arc::new(AtomicUsize::new(0)); + let body = Arc::new(CountingExec { + input: TestMemoryExec::try_new_exec(&[batches], Arc::clone(&schema), None)?, + executions: Arc::clone(&executions), + }); + let buffer = Arc::new(MaterializedCteBuffer::new(0, "c")); + let scan = MaterializedCteScanExec::new(0, "c", schema, 1); + let scan = Arc::new(scan.bind(Arc::clone(&buffer))); + let plan = Arc::new(MaterializedCteExec::new(body, scan, buffer)); + Ok((plan, executions)) + } + + fn values(batches: &[RecordBatch]) -> Vec { + batches + .iter() + .flat_map(|b| { + let array = b.column(0).as_any().downcast_ref::(); + array.unwrap().values().to_vec() + }) + .collect() + } + + /// Two runs of one plan overlap. Each run has its own `TaskContext`, so + /// each run computes the body and holds its own output. + #[tokio::test] + async fn overlapping_runs_do_not_share_the_output() -> Result<()> { + let (plan, executions) = counting_plan(3)?; + let context_1 = Arc::new(TaskContext::default()); + let context_2 = Arc::new(TaskContext::default()); + + let mut run_1 = plan.execute(0, Arc::clone(&context_1))?; + let first = run_1.next().await.transpose()?.unwrap(); + assert_eq!(executions.load(Ordering::Relaxed), 1); + assert!(context_1.memory_pool().reserved() > 0); + assert_eq!(context_2.memory_pool().reserved(), 0); + + // The second run starts and completes while the first run is open. + let run_2 = collect(plan.execute(0, Arc::clone(&context_2))?).await?; + assert_eq!(values(&run_2), vec![0, 1, 2]); + assert_eq!(executions.load(Ordering::Relaxed), 2); + assert!(context_2.memory_pool().reserved() > 0); + + // To drop the second run releases its output only. + drop(context_2); + let mut run_1_batches = vec![first]; + run_1_batches.extend(collect(run_1).await?); + assert_eq!(values(&run_1_batches), vec![0, 1, 2]); + + // One more scan in the first run replays the output of that run. + let again = collect(plan.execute(0, Arc::clone(&context_1))?).await?; + assert_eq!(values(&again), vec![0, 1, 2]); + assert_eq!(executions.load(Ordering::Relaxed), 2); + + // The output lives until the context of the run is dropped. + let pool = Arc::clone(context_1.memory_pool()); + assert!(pool.reserved() > 0); + drop(context_1); + assert_eq!(pool.reserved(), 0); + Ok(()) + } + + /// `reset_state` returns a new plan and does not change the old plan or + /// the output of a run. + #[tokio::test] + async fn reset_state_leaves_the_old_plan_usable() -> Result<()> { + let (plan, executions) = counting_plan(3)?; + let context = Arc::new(TaskContext::default()); + + let mut stream = plan.execute(0, Arc::clone(&context))?; + let first = stream.next().await.transpose()?.unwrap(); + assert_eq!(executions.load(Ordering::Relaxed), 1); + + let reset = reset_plan_states(Arc::clone(&plan))?; + assert!(!Arc::ptr_eq(&plan, &reset)); + + // A scan of the old plan that starts after the reset, in the run + // that is open, replays the output of that run. + let old = collect(plan.execute(0, Arc::clone(&context))?).await?; + assert_eq!(values(&old), vec![0, 1, 2]); + let mut batches = vec![first]; + batches.extend(collect(stream).await?); + assert_eq!(values(&batches), vec![0, 1, 2]); + assert_eq!(executions.load(Ordering::Relaxed), 1); + + // The new plan in the same run also replays that output. + let new = collect(reset.execute(0, Arc::clone(&context))?).await?; + assert_eq!(values(&new), vec![0, 1, 2]); + assert_eq!(executions.load(Ordering::Relaxed), 1); + + // The new plan in a new run computes the body again. + let new = collect(reset.execute(0, Arc::new(TaskContext::default()))?).await?; + assert_eq!(values(&new), vec![0, 1, 2]); + assert_eq!(executions.load(Ordering::Relaxed), 2); + Ok(()) + } + + /// A context from `with_new_materialized_cte_outputs` computes the given + /// CTEs again and keeps the output of the other CTEs. + #[tokio::test] + async fn new_outputs_are_only_for_the_given_ctes() -> Result<()> { + let (plan, executions) = counting_plan(3)?; + let context = Arc::new(TaskContext::default()); + collect(plan.execute(0, Arc::clone(&context))?).await?; + assert_eq!(executions.load(Ordering::Relaxed), 1); + + // The CTE has the id 0, so it keeps its output. + let other = with_new_materialized_cte_outputs(&context, &HashSet::from([1])); + collect(plan.execute(0, Arc::new(other))?).await?; + assert_eq!(executions.load(Ordering::Relaxed), 1); + + let ids = materialized_cte_ids(&plan); + assert_eq!(ids, HashSet::from([0])); + let renewed = Arc::new(with_new_materialized_cte_outputs(&context, &ids)); + collect(plan.execute(0, Arc::clone(&renewed))?).await?; + collect(plan.execute(0, Arc::clone(&renewed))?).await?; + assert_eq!(executions.load(Ordering::Relaxed), 2); + + // A nested context reads the CTEs that it does not renew from the + // enclosing context. + let nested = with_new_materialized_cte_outputs(&renewed, &HashSet::new()); + collect(plan.execute(0, Arc::new(nested))?).await?; + assert_eq!(executions.load(Ordering::Relaxed), 2); + + // The first context still has its output. + collect(plan.execute(0, context)?).await?; + assert_eq!(executions.load(Ordering::Relaxed), 2); + Ok(()) + } + + /// A body whose one partition yields one batch and then waits forever. + /// Its stream keeps its context, and adds one to `dropped` when it is + /// dropped. + #[derive(Debug)] + struct PendingExec { + properties: Arc, + dropped: Arc, + } + + impl DisplayAs for PendingExec { + fn fmt_as(&self, _: DisplayFormatType, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "PendingExec") + } + } + + impl ExecutionPlan for PendingExec { + fn name(&self) -> &'static str { + "PendingExec" + } + + fn properties(&self) -> &Arc { + &self.properties + } + + fn children(&self) -> Vec<&Arc> { + vec![] + } + + fn apply_expressions( + &self, + _f: &mut dyn FnMut(&Arc) -> Result, + ) -> Result { + Ok(TreeNodeRecursion::Continue) + } + + fn with_new_children( + self: Arc, + _children: Vec>, + ) -> Result> { + Ok(self) + } + + fn execute( + &self, + _partition: usize, + context: Arc, + ) -> Result { + struct OnDrop(Arc); + impl Drop for OnDrop { + fn drop(&mut self) { + self.0.fetch_add(1, Ordering::Relaxed); + } + } + let schema = self.schema(); + let batch = RecordBatch::try_new( + Arc::clone(&schema), + vec![Arc::new(Int32Array::from(vec![0]))], + )?; + let guard = (OnDrop(Arc::clone(&self.dropped)), context); + let stream = futures::stream::once(async move { Ok(batch) }).chain( + futures::stream::once(async move { + let _guard = guard; + std::future::pending().await + }), + ); + Ok(Box::pin(RecordBatchStreamAdapter::new(schema, stream))) + } + } + + /// The caller drops its stream and its context while the body is + /// buffered. The body stream keeps its context, but that context does not + /// keep the run, so the run is released and the body is cancelled. + #[tokio::test] + async fn abandoned_run_cancels_the_body() -> Result<()> { + let schema = Arc::new(Schema::new(vec![Field::new("a", DataType::Int32, false)])); + let dropped = Arc::new(AtomicUsize::new(0)); + let body = Arc::new(PendingExec { + properties: Arc::new(PlanProperties::new( + EquivalenceProperties::new(Arc::clone(&schema)), + Partitioning::UnknownPartitioning(1), + EmissionType::Incremental, + Boundedness::Bounded, + )), + dropped: Arc::clone(&dropped), + }); + // The CTE `b` reads the CTE `a`, so the body of `b` holds a scan of `a`. + let a_buffer = Arc::new(MaterializedCteBuffer::new(0, "a")); + let a_scan = MaterializedCteScanExec::new(0, "a", Arc::clone(&schema), 1); + let b_body = Arc::new(a_scan.bind(Arc::clone(&a_buffer))); + let b_buffer = Arc::new(MaterializedCteBuffer::new(1, "b")); + let b_scan = MaterializedCteScanExec::new(1, "b", Arc::clone(&schema), 1); + let b_scan = Arc::new(b_scan.bind(Arc::clone(&b_buffer))); + let b_exec = Arc::new(MaterializedCteExec::new( + b_body, + Arc::clone(&b_scan) as Arc, + b_buffer, + )); + let _a_exec = MaterializedCteExec::new(body, b_exec, a_buffer); + + let context = Arc::new(TaskContext::default()); + let pool = Arc::clone(context.memory_pool()); + let run = + Arc::downgrade(&context.run_state().get_or_init::()); + let mut stream = b_scan.execute(0, Arc::clone(&context))?; + // The stream keeps the run alive without the context. + drop(context); + let polled = tokio::time::timeout(Duration::from_millis(100), stream.next()); + assert!(polled.await.is_err(), "the body never completes"); + assert!(pool.reserved() > 0); + assert!(run.upgrade().is_some()); + drop(stream); + assert!(run.upgrade().is_none(), "the run is kept alive"); + let wait = async { + while dropped.load(Ordering::Relaxed) == 0 || pool.reserved() > 0 { + tokio::task::yield_now().await; + } + }; + tokio::time::timeout(Duration::from_secs(20), wait) + .await + .expect("the body must be cancelled"); + Ok(()) + } } diff --git a/datafusion/physical-plan/src/recursive_query.rs b/datafusion/physical-plan/src/recursive_query.rs index dd1ccbaf82f75..c221ac6bad652 100644 --- a/datafusion/physical-plan/src/recursive_query.rs +++ b/datafusion/physical-plan/src/recursive_query.rs @@ -5,6 +5,7 @@ //! Defines the recursive query plan use std::any::Any; +use std::collections::HashSet; use std::sync::Arc; use std::task::{Context, Poll}; @@ -13,6 +14,7 @@ use crate::aggregates::group_values::{GroupValues, new_group_values}; use crate::aggregates::order::GroupClustering; use crate::common::project_plan_to_schema; use crate::execution_plan::{Boundedness, EmissionType, reset_plan_states}; +use crate::materialized_cte::{materialized_cte_ids, with_new_materialized_cte_outputs}; use crate::metrics::{ BaselineMetrics, ExecutionPlanMetricsSet, MetricsSet, RecordOutput, }; @@ -270,6 +272,9 @@ struct RecursiveQueryStream { work_table: Arc, /// The dynamic part (recursive term) as is (without being executed) recursive_term: Arc, + /// The materialized CTEs that the recursive term declares. They are + /// computed again in each iteration. + materialized_cte_ids: HashSet, /// The static part (static term) as a stream. If the processing of this /// part is completed, then it will be None. static_stream: Option, @@ -305,10 +310,12 @@ impl RecursiveQueryStream { let distinct_deduplicator = is_distinct .then(|| DistinctDeduplicator::new(Arc::clone(&schema), &task_context)) .transpose()?; + let materialized_cte_ids = materialized_cte_ids(&recursive_term); Ok(Self { task_context, work_table, recursive_term, + materialized_cte_ids, static_stream: Some(static_stream), recursive_stream: None, schema, @@ -368,8 +375,17 @@ impl RecursiveQueryStream { let partition = 0; let recursive_plan = reset_plan_states(Arc::clone(&self.recursive_term))?; - self.recursive_stream = - Some(recursive_plan.execute(partition, Arc::clone(&self.task_context))?); + // The plan nodes do not hold the output of a materialized CTE, so + // `reset_plan_states` does not clear it. + let task_context = if self.materialized_cte_ids.is_empty() { + Arc::clone(&self.task_context) + } else { + Arc::new(with_new_materialized_cte_outputs( + &self.task_context, + &self.materialized_cte_ids, + )) + }; + self.recursive_stream = Some(recursive_plan.execute(partition, task_context)?); self.poll_next(cx) } } diff --git a/datafusion/sqllogictest/test_files/cte_materialized.slt b/datafusion/sqllogictest/test_files/cte_materialized.slt index a5d86e9f13241..cb397a093f3e4 100644 --- a/datafusion/sqllogictest/test_files/cte_materialized.slt +++ b/datafusion/sqllogictest/test_files/cte_materialized.slt @@ -1103,6 +1103,42 @@ SELECT n FROM r 3 4 +# A recursive query nested inside the recursive term of another recursive +# query. Each level declares a MATERIALIZED CTE whose body reads the work table +# of its own level. Each CTE must be evaluated again in each iteration of its +# own recursive query, or that level does not terminate. +query II rowsort +WITH RECURSIVE o AS ( + SELECT 1 AS n, 0 AS s + UNION ALL + SELECT mo.n + 1, t.s + FROM (WITH mo AS MATERIALIZED (SELECT n FROM o) SELECT n FROM mo) mo, + (WITH RECURSIVE i AS ( + SELECT 1 AS k + UNION ALL + SELECT k + 1 FROM (WITH mi AS MATERIALIZED (SELECT k FROM i) SELECT k FROM mi) WHERE k < 3) + SELECT sum(k) AS s FROM i) t + WHERE mo.n < 3) +SELECT n, s FROM o +---- +1 0 +2 6 +3 6 + +# UNION (DISTINCT) recursion with a MATERIALIZED CTE in the recursive term. +# The CTE reads the work table, so each iteration sees only the new rows. +# The query stops when an iteration produces no new distinct rows. +query I rowsort +WITH RECURSIVE r AS ( + SELECT 1 AS n + UNION + SELECT n % 3 + 1 FROM (WITH m AS MATERIALIZED (SELECT n FROM r) SELECT n FROM m)) +SELECT n FROM r +---- +1 +2 +3 + # A recursive CTE referenced two times, with a volatile static term. # MATERIALIZED # PostgreSQL: 1. DuckDB: 1.