Skip to main content

mito2/
batch_size.rs

1// Copyright 2023 Greptime Team
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! Utilities for choosing an execution batch size from source statistics.
16
17use parquet::file::metadata::ParquetMetaData;
18
19use crate::sst::parquet::{DEFAULT_READ_BATCH_SIZE, max_row_value_width};
20
21/// Approximate decoded bytes to produce in one batch.
22pub(crate) const TARGET_BATCH_BYTES: usize = 64 * 1024 * 1024;
23
24/// Returns `(num_rows, bytes)` estimates of the row groups in a Parquet file: the uncompressed
25/// size of each row group, and one row of the largest decoded string and binary value bytes per
26/// row of the file (see [max_row_value_width]). Dictionary encoding can make the uncompressed size
27/// far smaller than the decoded values.
28pub(crate) fn row_group_statistics(
29    metadata: &ParquetMetaData,
30) -> impl Iterator<Item = (u64, u64)> + '_ {
31    let encoded = metadata.row_groups().iter().map(|row_group| {
32        let uncompressed_bytes = row_group
33            .columns()
34            .iter()
35            .map(|column| column.uncompressed_size() as u64)
36            .sum();
37        (row_group.num_rows() as u64, uncompressed_bytes)
38    });
39    let width = max_row_value_width(metadata);
40    encoded.chain((width > 0).then_some((1, width)))
41}
42
43/// Returns the statistic of [row_group_statistics] with the widest rows, which bounds the decoded
44/// size of a batch read from the file.
45pub(crate) fn widest_row_group_statistic(metadata: &ParquetMetaData) -> Option<(u64, u64)> {
46    row_group_statistics(metadata).max_by_key(|(rows, bytes)| estimate_row_width(*rows, *bytes))
47}
48
49/// Estimates a batch size from `(num_rows, estimated_bytes)` pairs.
50///
51/// Uses the widest source with valid statistics and targets approximately 64 MiB of decoded data.
52/// The result is clamped to `1..=DEFAULT_READ_BATCH_SIZE`. Returns the default read batch size if
53/// no source contains usable statistics.
54pub fn estimate_batch_size(sources: impl IntoIterator<Item = (u64, u64)>) -> usize {
55    let max_row_width = sources
56        .into_iter()
57        .filter_map(|(rows, bytes)| estimate_row_width(rows, bytes))
58        .max();
59
60    let Some(row_width) = max_row_width else {
61        return DEFAULT_READ_BATCH_SIZE;
62    };
63
64    (TARGET_BATCH_BYTES as u64 / row_width).clamp(1, DEFAULT_READ_BATCH_SIZE as u64) as usize
65}
66
67/// Returns the ceiling of the estimated bytes per row.
68fn estimate_row_width(rows: u64, bytes: u64) -> Option<u64> {
69    if rows == 0 || bytes == 0 {
70        return None;
71    }
72
73    Some(bytes / rows + u64::from(!bytes.is_multiple_of(rows)))
74}
75
76#[cfg(test)]
77mod tests {
78    use super::*;
79
80    #[test]
81    fn test_estimate_batch_size_without_stats() {
82        assert_eq!(DEFAULT_READ_BATCH_SIZE, estimate_batch_size([]));
83        assert_eq!(
84            DEFAULT_READ_BATCH_SIZE,
85            estimate_batch_size([(0, 100), (100, 0)])
86        );
87    }
88
89    #[test]
90    fn test_estimate_batch_size_for_narrow_and_wide_rows() {
91        assert_eq!(DEFAULT_READ_BATCH_SIZE, estimate_batch_size([(100, 100)]));
92        assert_eq!(256, estimate_batch_size([(1, 256 * 1024)]));
93        assert_eq!(1, estimate_batch_size([(1, TARGET_BATCH_BYTES as u64 + 1)]));
94    }
95
96    #[test]
97    fn test_estimate_batch_size_uses_widest_known_source() {
98        assert_eq!(
99            256,
100            estimate_batch_size([(100, 0), (100, 100), (4, 1024 * 1024)])
101        );
102    }
103
104    #[test]
105    fn test_estimate_batch_size_saturates() {
106        assert_eq!(
107            DEFAULT_READ_BATCH_SIZE,
108            estimate_batch_size([(u64::MAX, u64::MAX)])
109        );
110        assert_eq!(1, estimate_batch_size([(1, u64::MAX)]));
111        assert_eq!(1, estimate_batch_size([(2, u64::MAX)]));
112    }
113}