datafusion_datasource/morsel/mod.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
5//! Structures for Morsel Driven IO.
6//!
7//! NOTE: As of DataFusion 54.0.0, these are experimental APIs that may change
8//! substantially.
9//!
10//! Morsel Driven IO is a technique for parallelizing the reading of large files
11//! by dividing them into smaller "morsels" that are processed independently.
12//!
13//! It is inspired by the paper [Morsel-Driven Parallelism: A NUMA-Aware Query
14//! Evaluation Framework for the Many-Core Age](https://db.in.tum.de/~leis/papers/morsels.pdf).
15
16mod adapters;
17#[cfg(test)]
18pub(crate) mod mocks;
19
20use crate::PartitionedFile;
21pub(crate) use adapters::FileOpenerMorselizer;
22use arrow::array::RecordBatch;
23use datafusion_common::Result;
24use futures::FutureExt;
25use futures::future::BoxFuture;
26use futures::stream::BoxStream;
27use std::fmt::Debug;
28use std::pin::Pin;
29use std::task::{Context, Poll};
30
31/// A Morsel of work ready to resolve to a stream of [`RecordBatch`]es.
32///
33/// This represents a single morsel of work that is ready to be processed. It
34/// has all data necessary (does not need any I/O) and is ready to be turned
35/// into a stream of [`RecordBatch`]es for processing by the execution engine.
36pub trait Morsel: Send + Debug {
37 /// Consume this morsel and produce a stream of [`RecordBatch`]es for processing.
38 ///
39 /// Note: This may do CPU work to decode already-loaded data, but should not
40 /// do any I/O work such as reading from the file.
41 fn into_stream(self: Box<Self>) -> BoxStream<'static, Result<RecordBatch>>;
42}
43
44/// A Morselizer takes a single [`PartitionedFile`] and creates the initial planner
45/// for that file.
46///
47/// This is the entry point for morsel driven I/O.
48pub trait Morselizer: Send + Sync + Debug {
49 /// Return the initial [`MorselPlanner`] for this file.
50 ///
51 /// Morselizing a file may involve CPU work, such as parsing parquet
52 /// metadata and evaluating pruning predicates. It should NOT do any I/O
53 /// work, such as reading from the file. Any needed I/O should be done using
54 /// [`MorselPlan::with_pending_planner`].
55 fn plan_file(&self, file: PartitionedFile) -> Result<Box<dyn MorselPlanner>>;
56}
57
58/// A Morsel Planner is responsible for creating morsels for a given scan.
59///
60/// The [`MorselPlanner`] is the unit of I/O. There is only ever a single I/O
61/// outstanding for a specific planner. DataFusion may run
62/// multiple planners in parallel, which corresponds to multiple parallel
63/// I/O requests.
64///
65/// It is not a Rust `Stream` so that it can explicitly separate CPU bound
66/// work from I/O work.
67///
68/// The design is similar to `ParquetPushDecoder`: when `plan` is called, it
69/// should do CPU work to produce the next morsels or discover the next I/O
70/// phase.
71///
72/// Best practice is to spawn I/O in a Tokio task on a separate runtime to
73/// ensure that CPU work doesn't block or slow down I/O work, but this is not
74/// strictly required by the API.
75pub trait MorselPlanner: Send + Debug {
76 /// Attempt to plan morsels. This may involve CPU work, such as parsing
77 /// parquet metadata and evaluating pruning predicates.
78 ///
79 /// It should NOT do any I/O work, such as reading from the file. If I/O is
80 /// required, the returned [`MorselPlan`] should contain a pending planner
81 /// future that the caller polls to drive the I/O work to completion. Once
82 /// that future resolves, it yields a planner ready for work.
83 ///
84 /// Note this function is **not async** to make it explicitly clear that if
85 /// I/O is required, it should be done in the returned `io_future`.
86 ///
87 /// Returns `None` if the planner has no more work to do.
88 ///
89 /// # Empty Morsel Plans
90 ///
91 /// It may return `None`, which means no batches will be read from the file
92 /// (e.g. due to late-pruning based on statistics).
93 ///
94 /// # Output Ordering
95 ///
96 /// See the comments on [`MorselPlan`] for the logical output order.
97 fn plan(self: Box<Self>) -> Result<Option<MorselPlan>>;
98}
99
100/// Return result of [`MorselPlanner::plan`].
101///
102/// # Logical Ordering
103///
104/// For plans where the output order of rows is maintained, the output order of
105/// a [`MorselPlanner`] is logically defined as follows:
106/// 1. All morsels that are directly produced
107/// 2. Recursively, all morsels produced by the returned `planners`
108#[derive(Default)]
109pub struct MorselPlan {
110 /// Morsels ready for CPU work
111 morsels: Vec<Box<dyn Morsel>>,
112 /// Planners that are ready for CPU work.
113 ready_planners: Vec<Box<dyn MorselPlanner>>,
114 /// A future with planner I/O that resolves to a CPU ready planner.
115 ///
116 /// DataFusion will poll this future occasionally to drive the I/O work to
117 /// completion. Once it resolves, planning continues with the returned
118 /// planner.
119 pending_planner: Option<PendingMorselPlanner>,
120}
121
122impl MorselPlan {
123 /// Create an empty morsel plan.
124 pub fn new() -> Self {
125 Self::default()
126 }
127
128 /// Set the ready morsels.
129 pub fn with_morsels(mut self, morsels: Vec<Box<dyn Morsel>>) -> Self {
130 self.morsels = morsels;
131 self
132 }
133
134 /// Set the ready child planners.
135 pub fn with_planners(mut self, planners: Vec<Box<dyn MorselPlanner>>) -> Self {
136 self.ready_planners = planners;
137 self
138 }
139
140 /// Set the pending planner for an I/O phase.
141 pub fn with_pending_planner<F>(mut self, io_future: F) -> Self
142 where
143 F: Future<Output = Result<Box<dyn MorselPlanner>>> + Send + 'static,
144 {
145 self.pending_planner = Some(PendingMorselPlanner::new(io_future));
146 self
147 }
148
149 /// Set the pending planner for an I/O phase.
150 pub fn set_pending_planner<F>(&mut self, io_future: F)
151 where
152 F: Future<Output = Result<Box<dyn MorselPlanner>>> + Send + 'static,
153 {
154 self.pending_planner = Some(PendingMorselPlanner::new(io_future));
155 }
156
157 /// Take the ready morsels.
158 pub fn take_morsels(&mut self) -> Vec<Box<dyn Morsel>> {
159 std::mem::take(&mut self.morsels)
160 }
161
162 /// Take the ready child planners.
163 pub fn take_ready_planners(&mut self) -> Vec<Box<dyn MorselPlanner>> {
164 std::mem::take(&mut self.ready_planners)
165 }
166
167 /// Take the pending I/O future, if any.
168 pub fn take_pending_planner(&mut self) -> Option<PendingMorselPlanner> {
169 self.pending_planner.take()
170 }
171
172 /// Returns `true` if this plan contains an I/O future.
173 pub fn has_io_future(&self) -> bool {
174 self.pending_planner.is_some()
175 }
176}
177
178/// Wrapper for I/O that must complete before planning can continue.
179pub struct PendingMorselPlanner {
180 future: BoxFuture<'static, Result<Box<dyn MorselPlanner>>>,
181}
182
183impl PendingMorselPlanner {
184 /// Create a new pending planner future.
185 ///
186 /// Example
187 /// ```
188 /// # use datafusion_common::DataFusionError;
189 /// # use datafusion_datasource::morsel::{MorselPlanner, PendingMorselPlanner};
190 /// let work = async move {
191 /// let planner: Box<dyn MorselPlanner> = {
192 /// // Do I/O work here, then return the next planner to run.
193 /// # unimplemented!();
194 /// };
195 /// Ok(planner) as Result<_, DataFusionError>;
196 /// };
197 /// let pending_io = PendingMorselPlanner::new(work);
198 /// ```
199 pub fn new<F>(future: F) -> Self
200 where
201 F: Future<Output = Result<Box<dyn MorselPlanner>>> + Send + 'static,
202 {
203 Self {
204 future: future.boxed(),
205 }
206 }
207
208 /// Consume this wrapper and return the underlying future.
209 pub fn into_future(self) -> BoxFuture<'static, Result<Box<dyn MorselPlanner>>> {
210 self.future
211 }
212}
213
214/// Forwards polling to the underlying future.
215impl Future for PendingMorselPlanner {
216 type Output = Result<Box<dyn MorselPlanner>>;
217 fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
218 // forward request to inner
219 self.future.as_mut().poll(cx)
220 }
221}