use std::sync::Arc;
use datafusion::arrow::record_batch::RecordBatch;
use datafusion::error::Result;
use datafusion::execution::TaskContext;
use datafusion::physical_plan::{
ExecutionPlan, ExecutionPlanProperties, SendableRecordBatchStream,
};
use futures::StreamExt;
pub(crate) const READ_AHEAD_BYTES: usize = 1 << 30;
#[cfg(not(target_arch = "wasm32"))]
const HEAD_DEPTH: usize = 2;
pub(crate) struct InOrder {
inner: Inner,
}
enum Inner {
Serial(Serial),
#[cfg(not(target_arch = "wasm32"))]
Parallel(parallel::Parallel),
}
impl InOrder {
pub(crate) fn new(plan: &Arc<dyn ExecutionPlan>, context: &Arc<TaskContext>) -> Self {
Self::with_budget(plan, context, Some(READ_AHEAD_BYTES))
}
#[cfg(test)]
pub(crate) fn serial(plan: &Arc<dyn ExecutionPlan>, context: &Arc<TaskContext>) -> Self {
Self::with_budget(plan, context, None)
}
pub(crate) fn with_budget(
plan: &Arc<dyn ExecutionPlan>,
context: &Arc<TaskContext>,
budget: Option<usize>,
) -> Self {
let partitions = plan.output_partitioning().partition_count();
#[cfg(not(target_arch = "wasm32"))]
if let (Some(budget), true) = (budget, partitions > 1) {
return Self {
inner: Inner::Parallel(parallel::Parallel::start(plan, context, budget)),
};
}
let _ = budget;
Self {
inner: Inner::Serial(Serial {
plan: Arc::clone(plan),
context: Arc::clone(context),
partitions,
next: 0,
stream: None,
}),
}
}
pub(crate) async fn next(&mut self) -> Option<Result<RecordBatch>> {
match &mut self.inner {
Inner::Serial(serial) => serial.next().await,
#[cfg(not(target_arch = "wasm32"))]
Inner::Parallel(parallel) => parallel.next().await,
}
}
}
struct Serial {
plan: Arc<dyn ExecutionPlan>,
context: Arc<TaskContext>,
partitions: usize,
next: usize,
stream: Option<SendableRecordBatchStream>,
}
impl Serial {
async fn next(&mut self) -> Option<Result<RecordBatch>> {
loop {
if let Some(stream) = &mut self.stream {
match stream.next().await {
Some(batch) => return Some(batch),
None => self.stream = None,
}
}
if self.next >= self.partitions {
return None;
}
match self.plan.execute(self.next, Arc::clone(&self.context)) {
Ok(stream) => self.stream = Some(stream),
Err(e) => {
self.next = self.partitions;
return Some(Err(e));
}
}
self.next += 1;
}
}
}
#[cfg(not(target_arch = "wasm32"))]
mod parallel {
use std::sync::{Arc, Mutex};
use datafusion::arrow::record_batch::RecordBatch;
use datafusion::common::runtime::SpawnedTask;
use datafusion::error::{DataFusionError, Result};
use datafusion::execution::TaskContext;
use datafusion::physical_plan::{ExecutionPlan, ExecutionPlanProperties};
use futures::StreamExt;
use tokio::sync::mpsc::{unbounded_channel, UnboundedReceiver, UnboundedSender};
use tokio::sync::Notify;
use super::HEAD_DEPTH;
enum Item {
Batch(RecordBatch, usize),
Error(DataFusionError),
End,
}
struct Budget {
limit: usize,
state: Mutex<State>,
changed: Notify,
}
struct State {
head: usize,
held: usize,
pending: Vec<usize>,
}
impl Budget {
fn state(&self) -> std::sync::MutexGuard<'_, State> {
self.state.lock().unwrap_or_else(|e| e.into_inner())
}
async fn admit(&self, partition: usize, bytes: usize) {
loop {
let changed = self.changed.notified();
{
let mut state = self.state();
let fits = state.held + bytes <= self.limit;
let head = state.head == partition && state.pending[partition] < HEAD_DEPTH;
if fits || head {
state.held += bytes;
state.pending[partition] += 1;
return;
}
}
changed.await;
}
}
fn release(&self, partition: usize, bytes: usize) {
{
let mut state = self.state();
state.held -= bytes;
state.pending[partition] -= 1;
}
self.changed.notify_waiters();
}
fn advance(&self, head: usize) {
self.state().head = head;
self.changed.notify_waiters();
}
}
pub(super) struct Parallel {
budget: Arc<Budget>,
receivers: Vec<UnboundedReceiver<Item>>,
head: usize,
_tasks: Vec<SpawnedTask<()>>,
}
impl Parallel {
pub(super) fn start(
plan: &Arc<dyn ExecutionPlan>,
context: &Arc<TaskContext>,
limit: usize,
) -> Self {
let partitions = plan.output_partitioning().partition_count();
let budget = Arc::new(Budget {
limit,
state: Mutex::new(State {
head: 0,
held: 0,
pending: vec![0; partitions],
}),
changed: Notify::new(),
});
let mut receivers = Vec::with_capacity(partitions);
let mut tasks = Vec::with_capacity(partitions);
for partition in 0..partitions {
let (tx, rx) = unbounded_channel();
receivers.push(rx);
let (plan, context) = (Arc::clone(plan), Arc::clone(context));
let budget = Arc::clone(&budget);
tasks.push(SpawnedTask::spawn(read_partition(
plan, partition, context, budget, tx,
)));
}
Self {
budget,
receivers,
head: 0,
_tasks: tasks,
}
}
pub(super) async fn next(&mut self) -> Option<Result<RecordBatch>> {
while self.head < self.receivers.len() {
match self.receivers[self.head].recv().await {
Some(Item::Batch(batch, bytes)) => {
self.budget.release(self.head, bytes);
return Some(Ok(batch));
}
Some(Item::Error(e)) => {
self.head = self.receivers.len();
return Some(Err(e));
}
Some(Item::End) => {
self.head += 1;
self.budget.advance(self.head);
}
None => {
let partition = self.head;
self.head = self.receivers.len();
return Some(Err(DataFusionError::Execution(format!(
"reading partition {partition} of a graph's edges stopped early"
))));
}
}
}
None
}
}
async fn read_partition(
plan: Arc<dyn ExecutionPlan>,
partition: usize,
context: Arc<TaskContext>,
budget: Arc<Budget>,
tx: UnboundedSender<Item>,
) {
let mut stream = match plan.execute(partition, context) {
Ok(stream) => stream,
Err(e) => {
let _ = tx.send(Item::Error(e));
return;
}
};
while let Some(batch) = stream.next().await {
let batch = match batch {
Ok(batch) => batch,
Err(e) => {
let _ = tx.send(Item::Error(e));
return;
}
};
let bytes = batch.get_array_memory_size();
budget.admit(partition, bytes).await;
if tx.send(Item::Batch(batch, bytes)).is_err() {
return;
}
}
let _ = tx.send(Item::End);
}
}
#[cfg(test)]
mod tests {
use super::*;
use datafusion::arrow::array::{Array, Int64Array};
use datafusion::prelude::{SessionConfig, SessionContext};
async fn values(mut reader: InOrder) -> Vec<i64> {
let mut out = Vec::new();
while let Some(batch) = reader.next().await {
let batch = batch.unwrap();
let column = batch.column(0);
let column = column.as_any().downcast_ref::<Int64Array>().unwrap();
out.extend(column.values().iter().copied());
}
out
}
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn partitions_read_in_parallel_come_in_partition_order() {
let ctx = SessionContext::new_with_config(SessionConfig::new().with_target_partitions(8));
let sql = (0..8)
.map(|i| {
format!(
"SELECT value AS v FROM generate_series({}, {})",
i * 100_000,
i * 100_000 + 99_999
)
})
.collect::<Vec<_>>()
.join(" UNION ALL ");
let plan = ctx
.sql(&sql)
.await
.unwrap()
.create_physical_plan()
.await
.unwrap();
assert!(plan.output_partitioning().partition_count() > 1);
let context = ctx.task_ctx();
let serial = values(InOrder::serial(&plan, &context)).await;
assert_eq!(serial, (0..800_000).collect::<Vec<i64>>());
assert_eq!(values(InOrder::new(&plan, &context)).await, serial);
assert_eq!(
values(InOrder::with_budget(&plan, &context, Some(1))).await,
serial
);
}
}