datafusion-physical-plan 56.0.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
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership
// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements

use arrow::array::{Array, AsArray, BooleanArray, RecordBatch};
use arrow::compute::{BatchCoalescer, filter_record_batch, prep_null_mask_filter};
use arrow::datatypes::{DataType, SchemaRef};
use datafusion_common::{Result, assert_or_internal_err};

/// Concatenate multiple [`RecordBatch`]es and apply a limit
///
/// See [`BatchCoalescer`] for more details on how this works.
#[derive(Debug)]
pub struct LimitedBatchCoalescer {
    /// The arrow structure that builds the output batches
    inner: BatchCoalescer,
    /// Total number of rows returned so far
    total_rows: usize,
    /// Limit: maximum number of rows to fetch, `None` means fetch all rows
    fetch: Option<usize>,
    /// Indicates if the coalescer is finished
    finished: bool,
}

/// Status returned by [`LimitedBatchCoalescer::push_batch`]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PushBatchStatus {
    /// The limit has **not** been reached, and more batches can be pushed
    Continue,
    /// The limit **has** been reached after processing this batch
    /// The caller should call [`LimitedBatchCoalescer::finish`]
    /// to flush any buffered rows and stop pushing more batches.
    LimitReached,
}

impl LimitedBatchCoalescer {
    /// Create a new `BatchCoalescer`
    ///
    /// # Arguments
    /// - `schema` - the schema of the output batches
    /// - `target_batch_size` - the minimum number of rows for each
    ///   output batch (until limit reached)
    /// - `fetch` - the maximum number of rows to fetch, `None` means fetch all rows
    pub fn new(
        schema: SchemaRef,
        target_batch_size: usize,
        fetch: Option<usize>,
    ) -> Self {
        Self {
            inner: BatchCoalescer::new(schema, target_batch_size)
                .with_biggest_coalesce_batch_size(Some(target_batch_size / 2)),
            total_rows: 0,
            fetch,
            finished: false,
        }
    }

    /// Return the schema of the output batches
    pub fn schema(&self) -> SchemaRef {
        self.inner.schema()
    }

    /// Pushes the next [`RecordBatch`] into the coalescer and returns its status.
    ///
    /// # Arguments
    /// * `batch` - The [`RecordBatch`] to append.
    ///
    /// # Returns
    /// * [`PushBatchStatus::Continue`] - More batches can still be pushed.
    /// * [`PushBatchStatus::LimitReached`] - The row limit was reached after processing
    ///   this batch. The caller should call [`Self::finish`] before retrieving the
    ///   remaining buffered batches.
    ///
    /// # Errors
    /// Returns an error if called after [`Self::finish`] or if the internal push
    /// operation fails.
    pub fn push_batch(&mut self, batch: RecordBatch) -> Result<PushBatchStatus> {
        assert_or_internal_err!(
            !self.finished,
            "LimitedBatchCoalescer: cannot push batch after finish"
        );

        // if we are at the limit, return LimitReached
        if let Some(fetch) = self.fetch {
            // limit previously reached
            if self.total_rows >= fetch {
                return Ok(PushBatchStatus::LimitReached);
            }

            // limit now reached
            if self.total_rows + batch.num_rows() >= fetch {
                // Limit is reached
                let remaining_rows = fetch - self.total_rows;
                debug_assert!(remaining_rows > 0);

                let batch_head = batch.slice(0, remaining_rows);
                self.total_rows += batch_head.num_rows();
                self.inner.push_batch(batch_head)?;
                return Ok(PushBatchStatus::LimitReached);
            }
        }

        // Limit not reached, push the entire batch
        self.total_rows += batch.num_rows();
        self.inner.push_batch(batch)?;

        Ok(PushBatchStatus::Continue)
    }

    /// Pushes the next [`RecordBatch`] into the coalescer after applying `filter`,
    /// avoiding a separate materialization pass compared to calling
    /// [`filter_record_batch`] followed by [`Self::push_batch`].
    ///
    /// Batches with `Utf8View` or `BinaryView` columns that reference data
    /// buffers are filtered first and then pushed with [`Self::push_batch`]:
    /// arrow's fused path keeps the whole input data buffers alive for the few
    /// selected strings, while [`Self::push_batch`] copies them into compact
    /// buffers.
    pub fn push_batch_with_filter(
        &mut self,
        batch: RecordBatch,
        filter: &BooleanArray,
    ) -> Result<PushBatchStatus> {
        assert_or_internal_err!(
            !self.finished,
            "LimitedBatchCoalescer: cannot push batch after finish"
        );

        if has_view_data_buffers(&batch) {
            let batch = filter_record_batch(&batch, filter)?;
            return self.push_batch(batch);
        }

        let Some(fetch) = self.fetch else {
            self.inner.push_batch_with_filter(batch, filter)?;
            return Ok(PushBatchStatus::Continue);
        };

        if self.total_rows >= fetch {
            return Ok(PushBatchStatus::LimitReached);
        }

        let selected_count = filter.true_count();
        if self.total_rows + selected_count >= fetch {
            let remaining = fetch - self.total_rows;
            let mask = match filter.null_count() {
                0 => filter.clone(),
                _ => prep_null_mask_filter(filter),
            };
            let end = mask
                .values()
                .set_indices()
                .nth(remaining - 1)
                .map_or(0, |i| i + 1);
            self.total_rows += remaining;
            self.inner
                .push_batch_with_filter(batch.slice(0, end), &mask.slice(0, end))?;
            return Ok(PushBatchStatus::LimitReached);
        }

        self.total_rows += selected_count;
        self.inner.push_batch_with_filter(batch, filter)?;
        Ok(PushBatchStatus::Continue)
    }

    /// Return true if there is no data buffered
    pub fn is_empty(&self) -> bool {
        self.inner.is_empty()
    }

    /// Complete the current buffered batch and finish the coalescer
    ///
    /// Any subsequent calls to `push_batch()` will return an Err
    pub fn finish(&mut self) -> Result<()> {
        self.inner.finish_buffered_batch()?;
        self.finished = true;
        Ok(())
    }

    pub(crate) fn is_finished(&self) -> bool {
        self.finished
    }

    /// Return the next completed batch, if any
    pub fn next_completed_batch(&mut self) -> Option<RecordBatch> {
        self.inner.next_completed_batch()
    }
}

/// Returns true if `batch` has a `Utf8View` or `BinaryView` column whose views
/// reference data buffers (strings longer than 12 bytes).
fn has_view_data_buffers(batch: &RecordBatch) -> bool {
    batch.columns().iter().any(|array| match array.data_type() {
        DataType::Utf8View => !array.as_string_view().data_buffers().is_empty(),
        DataType::BinaryView => !array.as_binary_view().data_buffers().is_empty(),
        _ => false,
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::ops::Range;
    use std::sync::Arc;

    use arrow::array::{StringViewArray, UInt32Array};
    use arrow::compute::concat_batches;
    use arrow::datatypes::{DataType, Field, Schema};

    #[test]
    fn test_coalesce() {
        let batch = uint32_batch(0..8);
        Test::new()
            .with_batches(std::iter::repeat_n(batch, 10))
            // expected output is batches of exactly 21 rows (except for the final batch)
            .with_target_batch_size(21)
            .with_expected_output_sizes(vec![21, 21, 21, 17])
            .run()
    }

    #[test]
    fn test_coalesce_with_fetch_larger_than_input_size() {
        let batch = uint32_batch(0..8);
        Test::new()
            .with_batches(std::iter::repeat_n(batch, 10))
            // input is 10 batches x 8 rows (80 rows) with fetch limit of 100
            // expected to behave the same as `test_concat_batches`
            .with_target_batch_size(21)
            .with_fetch(Some(100))
            .with_expected_output_sizes(vec![21, 21, 21, 17])
            .run();
    }

    #[test]
    fn test_coalesce_with_fetch_less_than_input_size() {
        let batch = uint32_batch(0..8);
        Test::new()
            .with_batches(std::iter::repeat_n(batch, 10))
            // input is 10 batches x 8 rows (80 rows) with fetch limit of 50
            .with_target_batch_size(21)
            .with_fetch(Some(50))
            .with_expected_output_sizes(vec![21, 21, 8])
            .run();
    }

    #[test]
    fn test_coalesce_with_fetch_less_than_target_and_no_remaining_rows() {
        let batch = uint32_batch(0..8);
        Test::new()
            .with_batches(std::iter::repeat_n(batch, 10))
            // input is 10 batches x 8 rows (80 rows) with fetch limit of 48
            .with_target_batch_size(24)
            .with_fetch(Some(48))
            .with_expected_output_sizes(vec![24, 24])
            .run();
    }

    #[test]
    fn test_coalesce_with_fetch_less_target_batch_size() {
        let batch = uint32_batch(0..8);
        Test::new()
            .with_batches(std::iter::repeat_n(batch, 10))
            // input is 10 batches x 8 rows (80 rows) with fetch limit of 10
            .with_target_batch_size(21)
            .with_fetch(Some(10))
            .with_expected_output_sizes(vec![10])
            .run();
    }

    #[test]
    fn test_coalesce_single_large_batch_over_fetch() {
        let large_batch = uint32_batch(0..100);
        Test::new()
            .with_batch(large_batch)
            .with_target_batch_size(20)
            .with_fetch(Some(7))
            .with_expected_output_sizes(vec![7])
            .run()
    }

    #[test]
    fn test_push_batch_with_filter_nulls_and_fetch() {
        let batch = uint32_batch(0..8);
        let mut coalescer = LimitedBatchCoalescer::new(batch.schema(), 100, Some(3));
        let filter = BooleanArray::from(vec![
            None,
            Some(true),
            None,
            Some(false),
            Some(true),
            Some(true),
            None,
            Some(true),
        ]);

        assert_eq!(
            coalescer.push_batch_with_filter(batch, &filter).unwrap(),
            PushBatchStatus::LimitReached,
        );
        coalescer.finish().unwrap();
        assert_next_batch_values(&mut coalescer, vec![1, 4, 5]);
    }

    #[test]
    fn test_push_batch_with_filter_fetch_boundaries() {
        let batch1 = uint32_batch(0..4);
        let batch2 = uint32_batch(4..8);
        let mut coalescer = LimitedBatchCoalescer::new(batch1.schema(), 100, Some(3));

        assert_eq!(
            coalescer
                .push_batch_with_filter(
                    batch1,
                    &BooleanArray::from(vec![true, false, true, false]),
                )
                .unwrap(),
            PushBatchStatus::Continue,
        );
        assert_eq!(
            coalescer
                .push_batch_with_filter(
                    batch2,
                    &BooleanArray::from(vec![true, true, true, true]),
                )
                .unwrap(),
            PushBatchStatus::LimitReached,
        );
        coalescer.finish().unwrap();
        assert_next_batch_values(&mut coalescer, vec![0, 2, 4]);

        let batch = uint32_batch(0..4);
        let mut coalescer = LimitedBatchCoalescer::new(batch.schema(), 100, Some(2));
        assert_eq!(
            coalescer
                .push_batch_with_filter(
                    batch,
                    &BooleanArray::from(vec![true, false, true, false]),
                )
                .unwrap(),
            PushBatchStatus::LimitReached,
        );
        assert_eq!(
            coalescer
                .push_batch_with_filter(
                    uint32_batch(4..8),
                    &BooleanArray::from(vec![true, true, true, true]),
                )
                .unwrap(),
            PushBatchStatus::LimitReached,
        );
        coalescer.finish().unwrap();
        assert_next_batch_values(&mut coalescer, vec![0, 2]);

        let batch = uint32_batch(0..4);
        let mut coalescer = LimitedBatchCoalescer::new(batch.schema(), 100, Some(0));
        assert_eq!(
            coalescer
                .push_batch_with_filter(
                    batch,
                    &BooleanArray::from(vec![true, true, true, true]),
                )
                .unwrap(),
            PushBatchStatus::LimitReached,
        );
        coalescer.finish().unwrap();
        assert!(coalescer.next_completed_batch().is_none());
    }

    /// A selective filter over long strings must not keep the whole input
    /// data buffer alive for the few selected rows.
    #[test]
    fn test_push_batch_with_filter_compacts_string_views() {
        let strings =
            (0..1600).map(|i| format!("a string longer than twelve bytes {i:05}"));
        let array = StringViewArray::from_iter_values(strings);
        let input_bytes: usize = array.data_buffers().iter().map(|b| b.capacity()).sum();
        let schema = Arc::new(Schema::new(vec![Field::new(
            "s",
            DataType::Utf8View,
            false,
        )]));
        let batch =
            RecordBatch::try_new(Arc::clone(&schema), vec![Arc::new(array)]).unwrap();
        // Select every 100th row: 16 of 1600 rows
        let filter = BooleanArray::from_iter((0..1600).map(|i| Some(i % 100 == 0)));

        let mut coalescer = LimitedBatchCoalescer::new(schema, 100, None);
        coalescer.push_batch_with_filter(batch, &filter).unwrap();
        coalescer.finish().unwrap();
        let output = coalescer.next_completed_batch().unwrap();

        let output = output.column(0).as_string_view();
        assert_eq!(output.len(), 16);
        assert_eq!(output.value(1), "a string longer than twelve bytes 00100");
        let output_bytes: usize =
            output.data_buffers().iter().map(|b| b.capacity()).sum();
        assert!(
            output_bytes * 4 < input_bytes,
            "output keeps {output_bytes} of {input_bytes} input string bytes"
        );
    }

    /// Test for [`LimitedBatchCoalescer`]
    ///
    /// Pushes the input batches to the coalescer and verifies that the resulting
    /// batches have the expected number of rows and contents.
    #[derive(Debug, Clone, Default)]
    struct Test {
        /// Batches to feed to the coalescer. Tests must have at least one
        /// schema
        input_batches: Vec<RecordBatch>,
        /// Expected output sizes of the resulting batches
        expected_output_sizes: Vec<usize>,
        /// target batch size
        target_batch_size: usize,
        /// Fetch (limit)
        fetch: Option<usize>,
    }

    impl Test {
        fn new() -> Self {
            Self::default()
        }

        /// Set the target batch size
        fn with_target_batch_size(mut self, target_batch_size: usize) -> Self {
            self.target_batch_size = target_batch_size;
            self
        }

        /// Set the fetch (limit)
        fn with_fetch(mut self, fetch: Option<usize>) -> Self {
            self.fetch = fetch;
            self
        }

        /// Extend the input batches with `batch`
        fn with_batch(mut self, batch: RecordBatch) -> Self {
            self.input_batches.push(batch);
            self
        }

        /// Extends the input batches with `batches`
        fn with_batches(
            mut self,
            batches: impl IntoIterator<Item = RecordBatch>,
        ) -> Self {
            self.input_batches.extend(batches);
            self
        }

        /// Extends `sizes` to expected output sizes
        fn with_expected_output_sizes(
            mut self,
            sizes: impl IntoIterator<Item = usize>,
        ) -> Self {
            self.expected_output_sizes.extend(sizes);
            self
        }

        /// Runs the test -- see documentation on [`Test`] for details
        fn run(self) {
            let Self {
                input_batches,
                target_batch_size,
                fetch,
                expected_output_sizes,
            } = self;

            let schema = input_batches[0].schema();

            // create a single large input batch for output comparison
            let single_input_batch = concat_batches(&schema, &input_batches).unwrap();

            let mut coalescer =
                LimitedBatchCoalescer::new(Arc::clone(&schema), target_batch_size, fetch);

            let mut output_batches = vec![];
            for batch in input_batches {
                match coalescer.push_batch(batch).unwrap() {
                    PushBatchStatus::Continue => {
                        // continue pushing batches
                    }
                    PushBatchStatus::LimitReached => {
                        break;
                    }
                }
            }
            coalescer.finish().unwrap();
            while let Some(batch) = coalescer.next_completed_batch() {
                output_batches.push(batch);
            }

            let actual_output_sizes: Vec<usize> =
                output_batches.iter().map(|b| b.num_rows()).collect();
            assert_eq!(
                expected_output_sizes, actual_output_sizes,
                "Unexpected number of rows in output batches\n\
                Expected\n{expected_output_sizes:#?}\nActual:{actual_output_sizes:#?}"
            );

            // make sure we got the expected number of output batches and content
            let mut starting_idx = 0;
            assert_eq!(expected_output_sizes.len(), output_batches.len());
            for (i, (expected_size, batch)) in
                expected_output_sizes.iter().zip(output_batches).enumerate()
            {
                assert_eq!(
                    *expected_size,
                    batch.num_rows(),
                    "Unexpected number of rows in Batch {i}"
                );

                // compare the contents of the batch (using `==` compares the
                // underlying memory layout too)
                let expected_batch =
                    single_input_batch.slice(starting_idx, *expected_size);
                let batch_strings = batch_to_pretty_strings(&batch);
                let expected_batch_strings = batch_to_pretty_strings(&expected_batch);
                let batch_strings = batch_strings.lines().collect::<Vec<_>>();
                let expected_batch_strings =
                    expected_batch_strings.lines().collect::<Vec<_>>();
                assert_eq!(
                    expected_batch_strings, batch_strings,
                    "Unexpected content in Batch {i}:\
                    \n\nExpected:\n{expected_batch_strings:#?}\n\nActual:\n{batch_strings:#?}"
                );
                starting_idx += *expected_size;
            }
        }
    }

    /// Return a batch of  UInt32 with the specified range
    fn uint32_batch(range: Range<u32>) -> RecordBatch {
        let schema =
            Arc::new(Schema::new(vec![Field::new("c0", DataType::UInt32, false)]));

        RecordBatch::try_new(
            Arc::clone(&schema),
            vec![Arc::new(UInt32Array::from_iter_values(range))],
        )
        .unwrap()
    }

    fn assert_next_batch_values(
        coalescer: &mut LimitedBatchCoalescer,
        expected: Vec<u32>,
    ) {
        let output = coalescer.next_completed_batch().unwrap();
        let expected = UInt32Array::from(expected);
        assert_eq!(output.column(0).as_ref(), &expected as &dyn Array);
    }

    fn batch_to_pretty_strings(batch: &RecordBatch) -> String {
        arrow::util::pretty::pretty_format_batches(std::slice::from_ref(batch))
            .unwrap()
            .to_string()
    }
}