datafusion-physical-plan 53.1.0

Physical (ExecutionPlan) implementations for DataFusion query engine
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.

//! [`BufferExec`] decouples production and consumption on messages by buffering the input in the
//! background up to a certain capacity.

use crate::execution_plan::{CardinalityEffect, SchedulingType};
use crate::filter_pushdown::{
    ChildPushdownResult, FilterDescription, FilterPushdownPhase,
    FilterPushdownPropagation,
};
use crate::projection::ProjectionExec;
use crate::stream::RecordBatchStreamAdapter;
use crate::{
    DisplayAs, DisplayFormatType, ExecutionPlan, PlanProperties, SortOrderPushdownResult,
    check_if_same_properties,
};
use arrow::array::RecordBatch;
use datafusion_common::config::ConfigOptions;
use datafusion_common::{Result, Statistics, internal_err, plan_err};
use datafusion_common_runtime::SpawnedTask;
use datafusion_execution::memory_pool::{MemoryConsumer, MemoryReservation};
use datafusion_execution::{SendableRecordBatchStream, TaskContext};
use datafusion_physical_expr_common::metrics::{
    ExecutionPlanMetricsSet, MetricBuilder, MetricsSet,
};
use datafusion_physical_expr_common::physical_expr::PhysicalExpr;
use datafusion_physical_expr_common::sort_expr::PhysicalSortExpr;
use futures::{Stream, StreamExt, TryStreamExt};
use pin_project_lite::pin_project;
use std::any::Any;
use std::fmt;
use std::pin::Pin;
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::task::{Context, Poll};
use tokio::sync::mpsc::UnboundedReceiver;
use tokio::sync::{OwnedSemaphorePermit, Semaphore};

/// WARNING: EXPERIMENTAL
///
/// Decouples production and consumption of record batches with an internal queue per partition,
/// eagerly filling up the capacity of the queues even before any message is requested.
///
/// ```text
///             ┌───────────────────────────┐
///             │        BufferExec         │
///             │                           │
///             │┌────── Partition 0 ──────┐│
///             ││            ┌────┐ ┌────┐││       ┌────┐
/// ──background poll────────▶│    │ │    ├┼┼───────▶    │
///             ││            └────┘ └────┘││       └────┘
///             │└─────────────────────────┘│
///             │┌────── Partition 1 ──────┐│
///             ││     ┌────┐ ┌────┐ ┌────┐││       ┌────┐
/// ──background poll─▶│    │ │    │ │    ├┼┼───────▶    │
///             ││     └────┘ └────┘ └────┘││       └────┘
///             │└─────────────────────────┘│
///             │                           │
///             │           ...             │
///             │                           │
///             │┌────── Partition N ──────┐│
///             ││                   ┌────┐││       ┌────┐
/// ──background poll───────────────▶│    ├┼┼───────▶    │
///             ││                   └────┘││       └────┘
///             │└─────────────────────────┘│
///             └───────────────────────────┘
/// ```
///
/// The capacity is provided in bytes, and for each buffered record batch it will take into account
/// the size reported by [RecordBatch::get_array_memory_size].
///
/// If a single record batch exceeds the maximum capacity set in the `capacity` argument, it's still
/// allowed to pass in order to not deadlock the buffer.
///
/// This is useful for operators that conditionally start polling one of their children only after
/// other child has finished, allowing to perform some early work and accumulating batches in
/// memory so that they can be served immediately when requested.
#[derive(Debug, Clone)]
pub struct BufferExec {
    input: Arc<dyn ExecutionPlan>,
    properties: Arc<PlanProperties>,
    capacity: usize,
    metrics: ExecutionPlanMetricsSet,
}

impl BufferExec {
    /// Builds a new [BufferExec] with the provided capacity in bytes.
    pub fn new(input: Arc<dyn ExecutionPlan>, capacity: usize) -> Self {
        let properties = PlanProperties::clone(input.properties())
            .with_scheduling_type(SchedulingType::Cooperative);

        Self {
            input,
            properties: Arc::new(properties),
            capacity,
            metrics: ExecutionPlanMetricsSet::new(),
        }
    }

    /// Returns the input [ExecutionPlan] of this [BufferExec].
    pub fn input(&self) -> &Arc<dyn ExecutionPlan> {
        &self.input
    }

    /// Returns the per-partition capacity in bytes for this [BufferExec].
    pub fn capacity(&self) -> usize {
        self.capacity
    }

    fn with_new_children_and_same_properties(
        &self,
        mut children: Vec<Arc<dyn ExecutionPlan>>,
    ) -> Self {
        Self {
            input: children.swap_remove(0),
            metrics: ExecutionPlanMetricsSet::new(),
            ..Self::clone(self)
        }
    }
}

impl DisplayAs for BufferExec {
    fn fmt_as(&self, t: DisplayFormatType, f: &mut fmt::Formatter) -> fmt::Result {
        match t {
            DisplayFormatType::Default | DisplayFormatType::Verbose => {
                write!(f, "BufferExec: capacity={}", self.capacity)
            }
            DisplayFormatType::TreeRender => {
                writeln!(f, "target_batch_size={}", self.capacity)
            }
        }
    }
}

impl ExecutionPlan for BufferExec {
    fn name(&self) -> &str {
        "BufferExec"
    }

    fn as_any(&self) -> &dyn Any {
        self
    }

    fn properties(&self) -> &Arc<PlanProperties> {
        &self.properties
    }

    fn maintains_input_order(&self) -> Vec<bool> {
        vec![true]
    }

    fn benefits_from_input_partitioning(&self) -> Vec<bool> {
        vec![false]
    }

    fn children(&self) -> Vec<&Arc<dyn ExecutionPlan>> {
        vec![&self.input]
    }

    fn with_new_children(
        self: Arc<Self>,
        mut children: Vec<Arc<dyn ExecutionPlan>>,
    ) -> Result<Arc<dyn ExecutionPlan>> {
        check_if_same_properties!(self, children);
        if children.len() != 1 {
            return plan_err!("BufferExec can only have one child");
        }
        Ok(Arc::new(Self::new(children.swap_remove(0), self.capacity)))
    }

    fn execute(
        &self,
        partition: usize,
        context: Arc<TaskContext>,
    ) -> Result<SendableRecordBatchStream> {
        let mem_reservation = MemoryConsumer::new(format!("BufferExec[{partition}]"))
            .register(context.memory_pool());
        let in_stream = self.input.execute(partition, context)?;

        // Set up the metrics for the stream.
        let curr_mem_in = Arc::new(AtomicUsize::new(0));
        let curr_mem_out = Arc::clone(&curr_mem_in);
        let mut max_mem_in = 0;
        let max_mem = MetricBuilder::new(&self.metrics).gauge("max_mem_used", partition);

        let curr_queued_in = Arc::new(AtomicUsize::new(0));
        let curr_queued_out = Arc::clone(&curr_queued_in);
        let mut max_queued_in = 0;
        let max_queued = MetricBuilder::new(&self.metrics).gauge("max_queued", partition);

        // Capture metrics when an element is queued on the stream.
        let in_stream = in_stream.inspect_ok(move |v| {
            let size = v.get_array_memory_size();
            let curr_size = curr_mem_in.fetch_add(size, Ordering::Relaxed) + size;
            if curr_size > max_mem_in {
                max_mem_in = curr_size;
                max_mem.set(max_mem_in);
            }

            let curr_queued = curr_queued_in.fetch_add(1, Ordering::Relaxed) + 1;
            if curr_queued > max_queued_in {
                max_queued_in = curr_queued;
                max_queued.set(max_queued_in);
            }
        });
        // Buffer the input.
        let out_stream =
            MemoryBufferedStream::new(in_stream, self.capacity, mem_reservation);
        // Update in the metrics that when an element gets out, some memory gets freed.
        let out_stream = out_stream.inspect_ok(move |v| {
            curr_mem_out.fetch_sub(v.get_array_memory_size(), Ordering::Relaxed);
            curr_queued_out.fetch_sub(1, Ordering::Relaxed);
        });

        Ok(Box::pin(RecordBatchStreamAdapter::new(
            self.schema(),
            out_stream,
        )))
    }

    fn metrics(&self) -> Option<MetricsSet> {
        Some(self.metrics.clone_inner())
    }

    fn partition_statistics(&self, partition: Option<usize>) -> Result<Statistics> {
        self.input.partition_statistics(partition)
    }

    fn supports_limit_pushdown(&self) -> bool {
        self.input.supports_limit_pushdown()
    }

    fn cardinality_effect(&self) -> CardinalityEffect {
        CardinalityEffect::Equal
    }

    fn try_swapping_with_projection(
        &self,
        projection: &ProjectionExec,
    ) -> Result<Option<Arc<dyn ExecutionPlan>>> {
        match self.input.try_swapping_with_projection(projection)? {
            Some(new_input) => Ok(Some(
                Arc::new(self.clone()).with_new_children(vec![new_input])?,
            )),
            None => Ok(None),
        }
    }

    fn gather_filters_for_pushdown(
        &self,
        _phase: FilterPushdownPhase,
        parent_filters: Vec<Arc<dyn PhysicalExpr>>,
        _config: &ConfigOptions,
    ) -> Result<FilterDescription> {
        FilterDescription::from_children(parent_filters, &self.children())
    }

    fn handle_child_pushdown_result(
        &self,
        _phase: FilterPushdownPhase,
        child_pushdown_result: ChildPushdownResult,
        _config: &ConfigOptions,
    ) -> Result<FilterPushdownPropagation<Arc<dyn ExecutionPlan>>> {
        Ok(FilterPushdownPropagation::if_all(child_pushdown_result))
    }

    fn try_pushdown_sort(
        &self,
        order: &[PhysicalSortExpr],
    ) -> Result<SortOrderPushdownResult<Arc<dyn ExecutionPlan>>> {
        // CoalesceBatchesExec is transparent for sort ordering - it preserves order
        // Delegate to the child and wrap with a new CoalesceBatchesExec
        self.input.try_pushdown_sort(order)?.try_map(|new_input| {
            Ok(Arc::new(Self::new(new_input, self.capacity)) as Arc<dyn ExecutionPlan>)
        })
    }
}

/// Represents anything that occupies a capacity in a [MemoryBufferedStream].
pub trait SizedMessage {
    fn size(&self) -> usize;
}

impl SizedMessage for RecordBatch {
    fn size(&self) -> usize {
        self.get_array_memory_size()
    }
}

pin_project! {
/// Decouples production and consumption of messages in a stream with an internal queue, eagerly
/// filling it up to the specified maximum capacity even before any message is requested.
///
/// Allows each message to have a different size, which is taken into account for determining if
/// the queue is full or not.
pub struct MemoryBufferedStream<T: SizedMessage> {
    task: SpawnedTask<()>,
    batch_rx: UnboundedReceiver<Result<(T, OwnedSemaphorePermit)>>,
    memory_reservation: Arc<MemoryReservation>,
}}

impl<T: Send + SizedMessage + 'static> MemoryBufferedStream<T> {
    /// Builds a new [MemoryBufferedStream] with the provided capacity and event handler.
    ///
    /// This immediately spawns a Tokio task that will start consumption of the input stream.
    pub fn new(
        mut input: impl Stream<Item = Result<T>> + Unpin + Send + 'static,
        capacity: usize,
        memory_reservation: MemoryReservation,
    ) -> Self {
        let semaphore = Arc::new(Semaphore::new(capacity));
        let (batch_tx, batch_rx) = tokio::sync::mpsc::unbounded_channel();

        let memory_reservation = Arc::new(memory_reservation);
        let memory_reservation_clone = Arc::clone(&memory_reservation);
        let task = SpawnedTask::spawn(async move {
            loop {
                // Select on both the input stream and the channel being closed.
                // By down this, we abort polling the input as soon as the consumer channel is
                // closed. Otherwise, we would need to wait for a full new message to be available
                // in order to consider aborting the stream
                let item_or_err = tokio::select! {
                    biased;
                    _ = batch_tx.closed() => break,
                    item_or_err = input.next() => {
                        let Some(item_or_err) = item_or_err else {
                            break; // stream finished
                        };
                        item_or_err
                    }
                };

                let item = match item_or_err {
                    Ok(batch) => batch,
                    Err(err) => {
                        let _ = batch_tx.send(Err(err)); // If there's an error it means the channel was closed, which is fine.
                        break;
                    }
                };

                let size = item.size();
                if let Err(err) = memory_reservation.try_grow(size) {
                    let _ = batch_tx.send(Err(err)); // If there's an error it means the channel was closed, which is fine.
                    break;
                }

                // We need to cap the minimum between amount of permits and the actual size of the
                // message. If at any point we try to acquire more permits than the capacity of the
                // semaphore, the stream will deadlock.
                let capped_size = size.min(capacity) as u32;

                let semaphore = Arc::clone(&semaphore);
                let Ok(permit) = semaphore.acquire_many_owned(capped_size).await else {
                    let _ = batch_tx.send(internal_err!("Closed semaphore in MemoryBufferedStream. This is a bug in DataFusion, please report it!"));
                    break;
                };

                if batch_tx.send(Ok((item, permit))).is_err() {
                    break; // stream was closed
                };
            }
        });

        Self {
            task,
            batch_rx,
            memory_reservation: memory_reservation_clone,
        }
    }

    /// Returns the number of queued messages.
    pub fn messages_queued(&self) -> usize {
        self.batch_rx.len()
    }
}

impl<T: SizedMessage> Stream for MemoryBufferedStream<T> {
    type Item = Result<T>;

    fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
        let self_project = self.project();
        match self_project.batch_rx.poll_recv(cx) {
            Poll::Ready(Some(Ok((item, _semaphore_permit)))) => {
                self_project.memory_reservation.shrink(item.size());
                Poll::Ready(Some(Ok(item)))
            }
            Poll::Ready(Some(Err(err))) => Poll::Ready(Some(Err(err))),
            Poll::Ready(None) => Poll::Ready(None),
            Poll::Pending => Poll::Pending,
        }
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        if self.batch_rx.is_closed() {
            let len = self.batch_rx.len();
            (len, Some(len))
        } else {
            (self.batch_rx.len(), None)
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use datafusion_common::{DataFusionError, assert_contains};
    use datafusion_execution::memory_pool::{
        GreedyMemoryPool, MemoryPool, UnboundedMemoryPool,
    };
    use std::error::Error;
    use std::fmt::Debug;
    use std::sync::Arc;
    use std::time::Duration;
    use tokio::time::timeout;

    #[tokio::test]
    async fn buffers_only_some_messages() -> Result<(), Box<dyn Error>> {
        let input = futures::stream::iter([1, 2, 3, 4]).map(Ok);
        let (_, res) = memory_pool_and_reservation();

        let buffered = MemoryBufferedStream::new(input, 4, res);
        wait_for_buffering().await;
        assert_eq!(buffered.messages_queued(), 2);
        Ok(())
    }

    #[tokio::test]
    async fn yields_all_messages() -> Result<(), Box<dyn Error>> {
        let input = futures::stream::iter([1, 2, 3, 4]).map(Ok);
        let (_, res) = memory_pool_and_reservation();

        let mut buffered = MemoryBufferedStream::new(input, 10, res);
        wait_for_buffering().await;
        assert_eq!(buffered.messages_queued(), 4);

        pull_ok_msg(&mut buffered).await?;
        pull_ok_msg(&mut buffered).await?;
        pull_ok_msg(&mut buffered).await?;
        pull_ok_msg(&mut buffered).await?;
        finished(&mut buffered).await?;
        Ok(())
    }

    #[tokio::test]
    async fn yields_first_msg_even_if_big() -> Result<(), Box<dyn Error>> {
        let input = futures::stream::iter([25, 1, 2, 3]).map(Ok);
        let (_, res) = memory_pool_and_reservation();

        let mut buffered = MemoryBufferedStream::new(input, 10, res);
        wait_for_buffering().await;
        assert_eq!(buffered.messages_queued(), 1);
        pull_ok_msg(&mut buffered).await?;
        Ok(())
    }

    #[tokio::test]
    async fn memory_pool_kills_stream() -> Result<(), Box<dyn Error>> {
        let input = futures::stream::iter([1, 2, 3, 4]).map(Ok);
        let (_, res) = bounded_memory_pool_and_reservation(7);

        let mut buffered = MemoryBufferedStream::new(input, 10, res);
        wait_for_buffering().await;

        pull_ok_msg(&mut buffered).await?;
        pull_ok_msg(&mut buffered).await?;
        pull_ok_msg(&mut buffered).await?;
        let msg = pull_err_msg(&mut buffered).await?;

        assert_contains!(msg.to_string(), "Failed to allocate additional 4.0 B");
        Ok(())
    }

    #[tokio::test]
    async fn memory_pool_does_not_kill_stream() -> Result<(), Box<dyn Error>> {
        let input = futures::stream::iter([1, 2, 3, 4]).map(Ok);
        let (_, res) = bounded_memory_pool_and_reservation(7);

        let mut buffered = MemoryBufferedStream::new(input, 3, res);
        wait_for_buffering().await;
        pull_ok_msg(&mut buffered).await?;

        wait_for_buffering().await;
        pull_ok_msg(&mut buffered).await?;

        wait_for_buffering().await;
        pull_ok_msg(&mut buffered).await?;

        wait_for_buffering().await;
        pull_ok_msg(&mut buffered).await?;

        wait_for_buffering().await;
        finished(&mut buffered).await?;
        Ok(())
    }

    #[tokio::test]
    async fn messages_pass_even_if_all_exceed_limit() -> Result<(), Box<dyn Error>> {
        let input = futures::stream::iter([3, 3, 3, 3]).map(Ok);
        let (_, res) = memory_pool_and_reservation();

        let mut buffered = MemoryBufferedStream::new(input, 2, res);
        wait_for_buffering().await;
        assert_eq!(buffered.messages_queued(), 1);
        pull_ok_msg(&mut buffered).await?;

        wait_for_buffering().await;
        assert_eq!(buffered.messages_queued(), 1);
        pull_ok_msg(&mut buffered).await?;

        wait_for_buffering().await;
        assert_eq!(buffered.messages_queued(), 1);
        pull_ok_msg(&mut buffered).await?;

        wait_for_buffering().await;
        assert_eq!(buffered.messages_queued(), 1);
        pull_ok_msg(&mut buffered).await?;

        wait_for_buffering().await;
        finished(&mut buffered).await?;
        Ok(())
    }

    #[tokio::test]
    async fn errors_get_propagated() -> Result<(), Box<dyn Error>> {
        let input = futures::stream::iter([1, 2, 3, 4]).map(|v| {
            if v == 3 {
                return internal_err!("Error on 3");
            }
            Ok(v)
        });
        let (_, res) = memory_pool_and_reservation();

        let mut buffered = MemoryBufferedStream::new(input, 10, res);
        wait_for_buffering().await;

        pull_ok_msg(&mut buffered).await?;
        pull_ok_msg(&mut buffered).await?;
        pull_err_msg(&mut buffered).await?;

        Ok(())
    }

    #[tokio::test]
    async fn memory_gets_released_if_stream_drops() -> Result<(), Box<dyn Error>> {
        let input = futures::stream::iter([1, 2, 3, 4]).map(Ok);
        let (pool, res) = memory_pool_and_reservation();

        let mut buffered = MemoryBufferedStream::new(input, 10, res);
        wait_for_buffering().await;
        assert_eq!(buffered.messages_queued(), 4);
        assert_eq!(pool.reserved(), 10);

        pull_ok_msg(&mut buffered).await?;
        assert_eq!(buffered.messages_queued(), 3);
        assert_eq!(pool.reserved(), 9);

        pull_ok_msg(&mut buffered).await?;
        assert_eq!(buffered.messages_queued(), 2);
        assert_eq!(pool.reserved(), 7);

        drop(buffered);
        assert_eq!(pool.reserved(), 0);
        Ok(())
    }

    fn memory_pool_and_reservation() -> (Arc<dyn MemoryPool>, MemoryReservation) {
        let pool = Arc::new(UnboundedMemoryPool::default()) as _;
        let reservation = MemoryConsumer::new("test").register(&pool);
        (pool, reservation)
    }

    fn bounded_memory_pool_and_reservation(
        size: usize,
    ) -> (Arc<dyn MemoryPool>, MemoryReservation) {
        let pool = Arc::new(GreedyMemoryPool::new(size)) as _;
        let reservation = MemoryConsumer::new("test").register(&pool);
        (pool, reservation)
    }

    async fn wait_for_buffering() {
        // We do not have control over the spawned task, so the best we can do is to yield some
        // cycles to the tokio runtime and let the task make progress on its own.
        tokio::time::sleep(Duration::from_millis(1)).await;
    }

    async fn pull_ok_msg<T: SizedMessage>(
        buffered: &mut MemoryBufferedStream<T>,
    ) -> Result<T, Box<dyn Error>> {
        Ok(timeout(Duration::from_millis(1), buffered.next())
            .await?
            .unwrap_or_else(|| internal_err!("Stream should not have finished"))?)
    }

    async fn pull_err_msg<T: SizedMessage + Debug>(
        buffered: &mut MemoryBufferedStream<T>,
    ) -> Result<DataFusionError, Box<dyn Error>> {
        Ok(timeout(Duration::from_millis(1), buffered.next())
            .await?
            .map(|v| match v {
                Ok(v) => internal_err!(
                    "Stream should not have failed, but succeeded with {v:?}"
                ),
                Err(err) => Ok(err),
            })
            .unwrap_or_else(|| internal_err!("Stream should not have finished"))?)
    }

    async fn finished<T: SizedMessage>(
        buffered: &mut MemoryBufferedStream<T>,
    ) -> Result<(), Box<dyn Error>> {
        match timeout(Duration::from_millis(1), buffered.next())
            .await?
            .is_none()
        {
            true => Ok(()),
            false => internal_err!("Stream should have finished")?,
        }
    }

    impl SizedMessage for usize {
        fn size(&self) -> usize {
            *self
        }
    }
}