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
// 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

//! Per-row sizes of a batch once it is written to a spill file.

use arrow::array::{
    AnyDictionaryArray, Array, ArrayRef, AsArray, RecordBatch, downcast_integer_array,
    make_array,
};
use arrow::buffer::{OffsetBuffer, ScalarBuffer};
use arrow::datatypes::{ArrowNativeType, DataType};
use arrow_data::MAX_INLINE_VIEW_LEN;

use super::VIEW_SIZE_BYTES;

/// Estimates how many bytes each row of a batch takes once written to a spill
/// file, where view arrays are compacted (see [`super::gc_view_arrays`]), and
/// so are the dictionaries of [`Self::compacted_columns`].
///
/// A row counts its fixed-width values, the offsets and bytes of its
/// variable-width values, the elements of its nested values, and the values
/// that the keys of compacted dictionaries reference. Buffers that every row
/// shares, such as validity bitmaps and the values of other dictionaries, are
/// not counted. Each view counts the bytes of its value, and each key the
/// value it references, so rows that share bytes are counted as if compaction
/// copied them, although it can write shared bytes only once.
pub(crate) struct SpilledRowSizes {
    /// Bytes that every row takes in the fixed-width columns
    fixed: usize,
    /// The other columns
    variable: Vec<ColumnSize>,
    /// See [`Self::max_row`]
    max_row: usize,
    /// See [`Self::compacted_columns`]
    compacted_columns: Vec<usize>,
}

impl SpilledRowSizes {
    pub(crate) fn new(batch: &RecordBatch) -> Self {
        let mut fixed = 0;
        let mut variable = vec![];
        let mut compacted_columns = vec![];
        for (index, column) in batch.columns().iter().enumerate() {
            let column = ColumnSize::new(column.as_ref());
            if column.compacted() {
                compacted_columns.push(index);
            }
            match column.fixed() {
                Some(width) => fixed += width,
                None => variable.push(column),
            }
        }
        let max_row = variable.iter().fold(fixed, |bytes, column| {
            bytes.saturating_add(column.max_row())
        });
        Self {
            fixed,
            variable,
            max_row,
            compacted_columns,
        }
    }

    /// Returns the size in bytes of row `row`.
    pub(crate) fn row(&self, row: usize) -> usize {
        self.variable.iter().fold(self.fixed, |bytes, column| {
            bytes + column.rows(row, row + 1)
        })
    }

    /// Returns the size in bytes of every row, if they all have the same size.
    pub(crate) fn fixed(&self) -> Option<usize> {
        self.variable.is_empty().then_some(self.fixed)
    }

    /// Returns an upper bound on the size in bytes of any row.
    pub(crate) fn max_row(&self) -> usize {
        self.max_row
    }

    /// Returns the columns with dictionaries whose values are mostly unique.
    /// Their rows count the values their keys reference, so batches taken
    /// from them must be compacted to hold only those values (see
    /// [`super::gc_columns`]).
    ///
    /// `take` keeps every value of a dictionary, so a batch of a few rows
    /// would otherwise hold the values of all rows, such as the `array_agg`
    /// states of every group. Compacting writes a value once per batch that
    /// references it, while a dictionary that consecutive batches share is
    /// written only once, so values that many keys reference stay shared.
    pub(crate) fn compacted_columns(&self) -> &[usize] {
        &self.compacted_columns
    }
}

/// Size model of one column, see [`SpilledRowSizes`].
enum ColumnSize {
    /// Every row takes the same number of bytes.
    Fixed(usize),
    /// An offset per row, plus the bytes between consecutive offsets.
    Bytes(Offsets),
    /// A view per row, plus the bytes of values too long to be inlined.
    Views(ScalarBuffer<u128>),
    /// An offset per row, plus the elements between consecutive offsets.
    List(Offsets, Box<ColumnSize>),
    /// A fixed number of elements per row.
    FixedSizeList(usize, Box<ColumnSize>),
    /// A row of each field.
    Struct(Vec<ColumnSize>),
    /// A key of the given width per row, plus the value it references unless
    /// the key is null. Only dictionaries that are compacted are sized this
    /// way, the others take the bytes of their keys only.
    Dictionary(usize, ArrayRef, Box<ColumnSize>),
}

impl ColumnSize {
    fn new(array: &dyn Array) -> Self {
        match array.data_type() {
            DataType::Utf8 => Self::Bytes(array.as_string::<i32>().offsets().into()),
            DataType::LargeUtf8 => Self::Bytes(array.as_string::<i64>().offsets().into()),
            DataType::Binary => Self::Bytes(array.as_binary::<i32>().offsets().into()),
            DataType::LargeBinary => {
                Self::Bytes(array.as_binary::<i64>().offsets().into())
            }
            DataType::Utf8View => Self::Views(array.as_string_view().views().clone()),
            DataType::BinaryView => Self::Views(array.as_binary_view().views().clone()),
            DataType::List(_) => {
                let list = array.as_list::<i32>();
                Self::List(list.offsets().into(), Box::new(Self::new(list.values())))
            }
            DataType::LargeList(_) => {
                let list = array.as_list::<i64>();
                Self::List(list.offsets().into(), Box::new(Self::new(list.values())))
            }
            DataType::Map(_, _) => {
                let map = array.as_map();
                Self::List(map.offsets().into(), Box::new(Self::new(map.entries())))
            }
            DataType::FixedSizeList(_, size) => Self::FixedSizeList(
                *size as usize,
                Box::new(Self::new(array.as_fixed_size_list().values())),
            ),
            DataType::Struct(_) => Self::Struct(
                array
                    .as_struct()
                    .columns()
                    .iter()
                    .map(|field| Self::new(field.as_ref()))
                    .collect(),
            ),
            DataType::Dictionary(key, _) => {
                let width = key.primitive_width().unwrap_or_default();
                let dictionary = array.as_any_dictionary();
                if should_compact(dictionary) {
                    Self::Dictionary(
                        width,
                        make_array(dictionary.keys().to_data()),
                        Box::new(Self::new(dictionary.values().as_ref())),
                    )
                } else {
                    Self::Fixed(width)
                }
            }
            DataType::FixedSizeBinary(size) => Self::Fixed(*size as usize),
            DataType::Null | DataType::Boolean => Self::Fixed(0),
            data_type => Self::Fixed(data_type.primitive_width().unwrap_or_else(|| {
                // Other layouts are spread evenly over their rows
                let bytes = array.to_data().get_slice_memory_size().unwrap_or_default();
                bytes / array.len().max(1)
            })),
        }
    }

    /// Returns whether this column has a dictionary that is compacted.
    fn compacted(&self) -> bool {
        match self {
            Self::Dictionary(_, _, _) => true,
            Self::List(_, values) | Self::FixedSizeList(_, values) => values.compacted(),
            Self::Struct(fields) => fields.iter().any(Self::compacted),
            Self::Fixed(_) | Self::Bytes(_) | Self::Views(_) => false,
        }
    }

    /// Returns the size in bytes of every row, if they all have the same size.
    fn fixed(&self) -> Option<usize> {
        match self {
            Self::Fixed(width) => Some(*width),
            Self::FixedSizeList(size, values) => values.fixed().map(|width| size * width),
            Self::Struct(fields) => fields.iter().map(Self::fixed).sum(),
            Self::Bytes(_)
            | Self::Views(_)
            | Self::List(_, _)
            | Self::Dictionary(_, _, _) => None,
        }
    }

    /// Returns an upper bound on the size in bytes of a row.
    fn max_row(&self) -> usize {
        match self {
            Self::Fixed(width) => *width,
            Self::Bytes(offsets) => offsets.width() + offsets.max_len(),
            Self::Views(views) => views
                .iter()
                .copied()
                .map(view_bytes)
                .max()
                .unwrap_or_default(),
            Self::List(offsets, values) => offsets
                .width()
                .saturating_add(offsets.max_len().saturating_mul(values.max_row())),
            Self::FixedSizeList(size, values) => size.saturating_mul(values.max_row()),
            Self::Struct(fields) => fields
                .iter()
                .fold(0, |bytes, field| bytes.saturating_add(field.max_row())),
            Self::Dictionary(width, _, values) => width.saturating_add(values.max_row()),
        }
    }

    /// Returns the size in bytes of rows `start..end`.
    fn rows(&self, start: usize, end: usize) -> usize {
        let num_rows = end - start;
        match self {
            Self::Fixed(width) => num_rows * width,
            Self::Bytes(offsets) => {
                num_rows * offsets.width() + offsets.get(end) - offsets.get(start)
            }
            Self::Views(views) => views[start..end].iter().copied().map(view_bytes).sum(),
            Self::List(offsets, values) => {
                num_rows * offsets.width()
                    + values.rows(offsets.get(start), offsets.get(end))
            }
            Self::FixedSizeList(size, values) => values.rows(start * size, end * size),
            Self::Struct(fields) => {
                fields.iter().map(|field| field.rows(start, end)).sum()
            }
            Self::Dictionary(width, keys, values) => {
                let value_bytes = downcast_integer_array!(
                    keys => (start..end)
                        .filter(|&row| keys.is_valid(row))
                        .map(|row| {
                            let key = keys.value(row).as_usize();
                            values.rows(key, key + 1)
                        })
                        .sum::<usize>(),
                    data_type => unreachable!("dictionary keys of type {data_type}")
                );
                num_rows * width + value_bytes
            }
        }
    }
}

/// Returns whether to compact the batches of `dictionary`, which is when fewer
/// than two keys reference each of its values on average (see
/// [`SpilledRowSizes::compacted_columns`]).
fn should_compact(dictionary: &dyn AnyDictionaryArray) -> bool {
    let keys = dictionary.keys();
    keys.len() - keys.null_count() < 2 * dictionary.values().len()
}

/// Returns the size in bytes of a view, plus its value unless it is inlined.
fn view_bytes(view: u128) -> usize {
    let len = view as u32;
    if len > MAX_INLINE_VIEW_LEN {
        VIEW_SIZE_BYTES + len as usize
    } else {
        VIEW_SIZE_BYTES
    }
}

/// The offsets of a variable-width or list column.
enum Offsets {
    Small(ScalarBuffer<i32>),
    Large(ScalarBuffer<i64>),
}

impl Offsets {
    /// Returns the size in bytes of one offset.
    fn width(&self) -> usize {
        match self {
            Self::Small(_) => size_of::<i32>(),
            Self::Large(_) => size_of::<i64>(),
        }
    }

    fn get(&self, index: usize) -> usize {
        match self {
            Self::Small(offsets) => offsets[index] as usize,
            Self::Large(offsets) => offsets[index] as usize,
        }
    }

    /// Returns the largest distance between consecutive offsets.
    fn max_len(&self) -> usize {
        match self {
            Self::Small(offsets) => offsets
                .windows(2)
                .map(|pair| (pair[1] - pair[0]) as usize)
                .max(),
            Self::Large(offsets) => offsets
                .windows(2)
                .map(|pair| (pair[1] - pair[0]) as usize)
                .max(),
        }
        .unwrap_or_default()
    }
}

impl From<&OffsetBuffer<i32>> for Offsets {
    fn from(offsets: &OffsetBuffer<i32>) -> Self {
        Self::Small(offsets.inner().clone())
    }
}

impl From<&OffsetBuffer<i64>> for Offsets {
    fn from(offsets: &OffsetBuffer<i64>) -> Self {
        Self::Large(offsets.inner().clone())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use arrow::array::{
        ArrayRef, BooleanArray, DictionaryArray, FixedSizeBinaryArray, Int32Array,
        Int64Array, ListArray, StringArray, StringViewArray, StructArray,
    };
    use arrow::buffer::Buffer;
    use arrow::datatypes::{Field, Int32Type, Int64Type};
    use std::sync::Arc;

    fn batch(columns: Vec<ArrayRef>) -> RecordBatch {
        RecordBatch::try_from_iter(
            columns
                .into_iter()
                .enumerate()
                .map(|(i, column)| (format!("c{i}"), column)),
        )
        .unwrap()
    }

    /// Returns the size of each row of a batch of `columns`, and the upper
    /// bound on the size of any row.
    fn row_sizes(columns: Vec<ArrayRef>) -> (Vec<usize>, usize) {
        let batch = batch(columns);
        let sizes = SpilledRowSizes::new(&batch);
        let rows = (0..batch.num_rows()).map(|row| sizes.row(row)).collect();
        (rows, sizes.max_row())
    }

    #[test]
    fn fixed_width_and_offsets() {
        let ints: ArrayRef = Arc::new(Int64Array::from(vec![1, 2]));
        let strings: ArrayRef = Arc::new(StringArray::from(vec!["a", "bbbb"]));
        // 8 bytes of Int64, plus a 4 byte offset and the string bytes
        assert_eq!(row_sizes(vec![ints, strings]), (vec![13, 16], 16));
    }

    #[test]
    fn rows_of_fixed_width_columns_have_one_size() {
        let ints: ArrayRef = Arc::new(Int64Array::from(vec![1, 2]));
        let fixed: ArrayRef = Arc::new(FixedSizeBinaryArray::new(
            3,
            Buffer::from(vec![0u8; 6]),
            None,
        ));
        let booleans: ArrayRef = Arc::new(BooleanArray::from(vec![true, false]));
        let strings: ArrayRef = Arc::new(StringArray::from(vec!["a", "bbbb"]));
        // 8 bytes of Int64 and 3 of FixedSizeBinary(3). The bits of booleans
        // are not counted.
        let columns = vec![Arc::clone(&ints), fixed, booleans];
        assert_eq!(row_sizes(columns.clone()), (vec![11, 11], 11));
        assert_eq!(SpilledRowSizes::new(&batch(columns)).fixed(), Some(11));
        assert_eq!(
            SpilledRowSizes::new(&batch(vec![ints, strings])).fixed(),
            None
        );
    }

    #[test]
    fn views_count_their_bytes_unless_inlined() {
        let long = "a string longer than twelve";
        let views: ArrayRef = Arc::new(StringViewArray::from(vec!["short", long]));
        let long_row = 16 + long.len();
        assert_eq!(row_sizes(vec![views]), (vec![16, long_row], long_row));
    }

    #[test]
    fn views_sharing_bytes_count_them_for_every_row() {
        // Three views of the same 100 bytes, stored once
        let value = "x".repeat(100);
        let one = StringViewArray::from(vec![value.as_str()]);
        let view = one.views()[0];
        let shared = StringViewArray::new(
            ScalarBuffer::from(vec![view; 3]),
            one.data_buffers().to_vec(),
            None,
        );
        // Compacting before spilling copies the bytes for each view
        assert_eq!(row_sizes(vec![Arc::new(shared)]), (vec![116; 3], 116));
    }

    #[test]
    fn lists_count_their_elements() {
        let list: ArrayRef =
            Arc::new(ListArray::from_iter_primitive::<Int64Type, _, _>(vec![
                Some(vec![Some(1), Some(2), Some(3)]),
                Some(vec![]),
                Some(vec![Some(4)]),
            ]));
        // An offset plus the elements of the row. The bound is an offset plus
        // the most elements in a row, each of the largest size.
        assert_eq!(row_sizes(vec![Arc::clone(&list)]), (vec![28, 4, 12], 28));
        // A slice keeps the sizes of its own rows
        assert_eq!(row_sizes(vec![list.slice(1, 2)]), (vec![4, 12], 12));
    }

    #[test]
    fn nested_views_count_their_bytes() {
        let values =
            StringViewArray::from(vec!["x".repeat(20), "y".repeat(5), "z".repeat(30)]);
        let list: ArrayRef = Arc::new(ListArray::new(
            Arc::new(Field::new_list_field(DataType::Utf8View, true)),
            OffsetBuffer::new(vec![0, 2, 3].into()),
            Arc::new(values),
            None,
        ));
        // The bound takes two elements, the most in a row, of the largest size
        assert_eq!(
            row_sizes(vec![list]),
            (vec![4 + 36 + 16, 4 + 46], 4 + 2 * 46)
        );
    }

    #[test]
    fn struct_fields_add_up() {
        let fields: ArrayRef = Arc::new(StructArray::from(vec![
            (
                Arc::new(Field::new("a", DataType::Int32, false)),
                Arc::new(Int32Array::from(vec![1, 2])) as ArrayRef,
            ),
            (
                Arc::new(Field::new("b", DataType::Utf8, false)),
                Arc::new(StringArray::from(vec!["", "abc"])) as ArrayRef,
            ),
        ]));
        assert_eq!(row_sizes(vec![fields]), (vec![8, 11], 11));
    }

    #[test]
    fn dictionaries_of_unique_values_count_them() {
        let values = StringArray::from(vec!["a long dictionary value", "b", "cc"]);
        let dictionary: ArrayRef = Arc::new(DictionaryArray::new(
            Int32Array::from(vec![Some(2), None, Some(0)]),
            Arc::new(values),
        ));
        // A 4 byte key, plus the 4 byte offset and the bytes of the value it
        // references. A null key references none.
        let long_row = 4 + 4 + 23;
        assert_eq!(
            row_sizes(vec![Arc::clone(&dictionary)]),
            (vec![4 + 4 + 2, 4, long_row], long_row)
        );
        let sizes = SpilledRowSizes::new(&batch(vec![dictionary]));
        assert_eq!(sizes.compacted_columns(), [0]);
    }

    #[test]
    fn dictionaries_of_shared_values_count_their_keys() {
        // Two keys reference each value, which every batch keeps
        let dictionary: ArrayRef = Arc::new(
            vec![
                "a long dictionary value",
                "b",
                "a long dictionary value",
                "b",
            ]
            .into_iter()
            .collect::<DictionaryArray<Int32Type>>(),
        );
        assert_eq!(row_sizes(vec![Arc::clone(&dictionary)]), (vec![4; 4], 4));
        let sizes = SpilledRowSizes::new(&batch(vec![dictionary]));
        assert!(sizes.compacted_columns().is_empty());
    }

    #[test]
    fn nested_dictionaries_count_their_values() {
        let values = DictionaryArray::new(
            Int32Array::from(vec![0, 1, 2]),
            Arc::new(StringArray::from(vec![
                "x".repeat(20),
                "y".repeat(5),
                "z".repeat(30),
            ])),
        );
        let list: ArrayRef = Arc::new(ListArray::new(
            Arc::new(Field::new_list_field(values.data_type().clone(), true)),
            OffsetBuffer::new(vec![0, 2, 3, 3].into()),
            Arc::new(values),
            None,
        ));
        // An offset, plus a key, an offset and the bytes of the value of each
        // element. The bound takes two elements of the largest size.
        assert_eq!(
            row_sizes(vec![Arc::clone(&list)]),
            (vec![4 + 28 + 13, 4 + 38, 4], 4 + 2 * 38)
        );
        let sizes = SpilledRowSizes::new(&batch(vec![list]));
        assert_eq!(sizes.compacted_columns(), [0]);
    }

    #[test]
    fn empty_nested_dictionaries_count_nothing() {
        // The values of null lists are an empty dictionary, without values
        let dictionary =
            DataType::Dictionary(Box::new(DataType::Int32), Box::new(DataType::Utf8));
        let list: ArrayRef = Arc::new(ListArray::new_null(
            Arc::new(Field::new_list_field(dictionary, true)),
            2,
        ));
        assert_eq!(row_sizes(vec![list]), (vec![4, 4], 4));
    }
}