1use parquet::file::metadata::ParquetMetaData;
18
19use crate::sst::parquet::{DEFAULT_READ_BATCH_SIZE, max_row_value_width};
20
21pub(crate) const TARGET_BATCH_BYTES: usize = 64 * 1024 * 1024;
23
24pub(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
43pub(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
49pub 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
67fn 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}