Skip to main content

parquet_cli/
bench.rs

1//! Writing a file again with different settings, and saying what it cost.
2//!
3//! A compression experiment is one question: *what would this file weigh if
4//! it were written this way?* The answer is a number, and the number is what
5//! decides things.
6
7use std::fs::File;
8use std::path::{Path, PathBuf};
9
10use anyhow::{anyhow, Context, Result};
11use parquet::arrow::arrow_reader::ParquetRecordBatchReaderBuilder;
12use parquet::arrow::arrow_writer::ArrowWriter;
13use parquet::basic::{BrotliLevel, Compression, Encoding, GzipLevel, ZstdLevel};
14use parquet::file::properties::{WriterProperties, WriterVersion};
15use serde_json::{json, Map, Value};
16
17use crate::meta::{self, FileFacts};
18
19/// The settings one run uses.
20#[derive(Clone, Debug, Default)]
21pub struct Settings {
22    /// How the columns are compressed.
23    pub compression: Option<Compression>,
24    /// How many rows go into a row group.
25    pub row_group: Option<usize>,
26    /// Whether the columns get a dictionary.
27    pub dictionary: Option<bool>,
28    /// How big a data page may get.
29    pub page_size: Option<usize>,
30    /// Whether the data pages are written as version 2.
31    pub data_page_v2: Option<bool>,
32    /// How the values are encoded.
33    pub encoding: Option<Encoding>,
34}
35
36impl Settings {
37    /// The settings as they read on a line.
38    pub fn describe(&self) -> String {
39        let mut parts = Vec::new();
40        if let Some(compression) = &self.compression {
41            parts.push(compression.to_string());
42        }
43        if let Some(row_group) = self.row_group {
44            parts.push(format!("row-group:{row_group}"));
45        }
46        if let Some(dictionary) = self.dictionary {
47            parts.push(format!(
48                "dictionary:{}",
49                if dictionary { "on" } else { "off" }
50            ));
51        }
52        if let Some(page_size) = self.page_size {
53            parts.push(format!("page-size:{page_size}"));
54        }
55        if let Some(data_page_v2) = self.data_page_v2 {
56            parts.push(format!(
57                "data-page:{}",
58                if data_page_v2 { "v2" } else { "v1" }
59            ));
60        }
61        if let Some(encoding) = &self.encoding {
62            parts.push(format!("encoding:{}", encoding_name(encoding)));
63        }
64        if parts.is_empty() {
65            "the defaults".to_string()
66        } else {
67            parts.join(", ")
68        }
69    }
70}
71
72/// One run and what it weighed.
73#[derive(Clone, Debug)]
74pub struct Run {
75    /// What was changed.
76    pub label: String,
77    /// The settings it ran with.
78    pub settings: String,
79    /// How many bytes the rewritten file took.
80    pub bytes: u64,
81}
82
83/// The result of a bench.
84#[derive(Clone, Debug)]
85pub struct Bench {
86    pub file: String,
87    /// How many bytes the original file takes.
88    pub original_bytes: u64,
89    pub runs: Vec<Run>,
90}
91
92impl Bench {
93    pub fn to_json(&self) -> Value {
94        let runs: Vec<Value> = self
95            .runs
96            .iter()
97            .map(|run| {
98                let mut object = Map::new();
99                object.insert("label".into(), Value::String(run.label.clone()));
100                object.insert("settings".into(), Value::String(run.settings.clone()));
101                object.insert("bytes".into(), json!(run.bytes));
102                object.insert(
103                    "difference".into(),
104                    json!(run.bytes as i64 - self.original_bytes as i64),
105                );
106                object.insert(
107                    "ratio".into(),
108                    json!(run.bytes as f64 / self.original_bytes as f64),
109                );
110                Value::Object(object)
111            })
112            .collect();
113        json!({
114            "file": self.file,
115            "original_bytes": self.original_bytes,
116            "runs": runs,
117        })
118    }
119}
120
121/// Read the settings a file was written with.
122pub fn baseline(facts: &FileFacts) -> Settings {
123    let mut dictionary = false;
124    let mut encoding = None;
125    for group in facts.encodings.iter() {
126        if group.contains("DICTIONARY") {
127            dictionary = true;
128        }
129        if group.contains("DELTA_BINARY_PACKED") {
130            encoding = Some(Encoding::DELTA_BINARY_PACKED);
131        } else if group.contains("DELTA_LENGTH_BYTE_ARRAY") {
132            encoding = Some(Encoding::DELTA_LENGTH_BYTE_ARRAY);
133        }
134    }
135    let compression = facts
136        .compressions
137        .first()
138        .map(|codec| compression_of(codec));
139    Settings {
140        compression,
141        row_group: if facts.row_groups > 0 {
142            Some((facts.rows / facts.row_groups as i64).max(1) as usize)
143        } else {
144            None
145        },
146        dictionary: Some(dictionary),
147        page_size: None,
148        data_page_v2: Some(facts.format_version >= 2),
149        encoding,
150    }
151}
152
153/// Read the settings out of the strings the user gave.
154///
155/// A string is either a setting (`row-group:1000`, `dictionary:off`,
156/// `page-size:65536`, `data-page:v2`, `encoding:delta`) or a compression
157/// (`zstd:19`, `snappy`, `gzip:6`).
158pub fn parse(settings: &[String]) -> Result<Settings> {
159    let mut parsed = Settings::default();
160    for setting in settings {
161        let whole = setting.to_lowercase();
162        let (key, value) = match setting.split_once(':') {
163            Some((key, value)) => (key.to_lowercase(), value.to_lowercase()),
164            None => (String::new(), whole.clone()),
165        };
166        match key.as_str() {
167            "row-group" | "row_group" | "rowgroup" => {
168                parsed.row_group = Some(value.parse().context("the row group size")?);
169            }
170            "dictionary" => {
171                parsed.dictionary = Some(match value.as_str() {
172                    "on" | "true" | "yes" => true,
173                    "off" | "false" | "no" => false,
174                    other => return Err(anyhow!("dictionary takes on or off, not {other}")),
175                });
176            }
177            "page-size" | "page_size" => {
178                parsed.page_size = Some(value.parse().context("the page size")?);
179            }
180            "data-page" | "data_page" => {
181                parsed.data_page_v2 = Some(match value.as_str() {
182                    "v1" | "1" => false,
183                    "v2" | "2" => true,
184                    other => return Err(anyhow!("data-page takes v1 or v2, not {other}")),
185                });
186            }
187            "encoding" => {
188                parsed.encoding = Some(match value.as_str() {
189                    "plain" => Encoding::PLAIN,
190                    "delta" => Encoding::DELTA_BINARY_PACKED,
191                    "delta-length-bytes" => Encoding::DELTA_LENGTH_BYTE_ARRAY,
192                    other => return Err(anyhow!("unknown encoding: {other}")),
193                });
194            }
195            _ => {
196                // Not a setting name: it must be a compression, like `zstd:19`.
197                parsed.compression = Some(compression_of_spec(&whole)?);
198            }
199        }
200    }
201    Ok(parsed)
202}
203
204/// Write the file again with these settings, and say how big it is.
205pub fn bench(path: &Path, overrides: &[String], sweep: bool) -> Result<Bench> {
206    let facts = meta::file_facts(path)?;
207    let base = baseline(&facts);
208
209    let mut runs = Vec::new();
210    let mut settings = base.clone();
211    for override_setting in overrides {
212        let one = parse(std::slice::from_ref(override_setting))?;
213        settings = merge(&settings, &one);
214    }
215    runs.push(Run {
216        label: if overrides.is_empty() {
217            "the file's own settings".to_string()
218        } else {
219            "the settings you asked for".to_string()
220        },
221        settings: settings.describe(),
222        bytes: rewrite(path, &settings)?,
223    });
224
225    if sweep {
226        for (label, change) in sweep_settings() {
227            let mut settings = base.clone();
228            settings = merge(&settings, &change);
229            runs.push(Run {
230                label,
231                settings: settings.describe(),
232                bytes: rewrite(path, &settings)?,
233            });
234        }
235    }
236
237    Ok(Bench {
238        file: facts.path,
239        original_bytes: facts.size_bytes,
240        runs,
241    })
242}
243
244/// The settings the sweep tries: one knob at a time, from the file's own.
245fn sweep_settings() -> Vec<(String, Settings)> {
246    let mut sweep = Vec::new();
247    for rows in [1_000usize, 10_000, 100_000, 1_000_000] {
248        sweep.push((
249            format!("row-group:{rows}"),
250            Settings {
251                row_group: Some(rows),
252                ..Settings::default()
253            },
254        ));
255    }
256    for codec in ["snappy", "zstd:1", "zstd:9", "zstd:19", "gzip:6"] {
257        let compression = compression_of_spec(codec).ok();
258        sweep.push((
259            format!("codec:{codec}"),
260            Settings {
261                compression,
262                ..Settings::default()
263            },
264        ));
265    }
266    sweep.push((
267        "dictionary:off".to_string(),
268        Settings {
269            dictionary: Some(false),
270            ..Settings::default()
271        },
272    ));
273    sweep.push((
274        "data-page:v2".to_string(),
275        Settings {
276            data_page_v2: Some(true),
277            ..Settings::default()
278        },
279    ));
280    sweep.push((
281        "page-size:65536".to_string(),
282        Settings {
283            page_size: Some(65_536),
284            ..Settings::default()
285        },
286    ));
287    sweep
288}
289
290/// One set of settings on top of another.
291fn merge(base: &Settings, other: &Settings) -> Settings {
292    Settings {
293        compression: other.compression.or(base.compression),
294        row_group: other.row_group.or(base.row_group),
295        dictionary: other.dictionary.or(base.dictionary),
296        page_size: other.page_size.or(base.page_size),
297        data_page_v2: other.data_page_v2.or(base.data_page_v2),
298        encoding: other.encoding.or(base.encoding),
299    }
300}
301
302/// Read a file and write it again with these settings. The original is left
303/// alone.
304fn rewrite(path: &Path, settings: &Settings) -> Result<u64> {
305    let file = File::open(path).with_context(|| format!("open {}", path.display()))?;
306    let builder = ParquetRecordBatchReaderBuilder::try_new(file)
307        .with_context(|| format!("read the footer of {}", path.display()))?;
308    let schema = builder.schema().clone();
309
310    let mut properties = WriterProperties::builder();
311    if let Some(compression) = &settings.compression {
312        properties = properties.set_compression(*compression);
313    }
314    if let Some(row_group) = settings.row_group {
315        properties = properties.set_max_row_group_row_count(Some(row_group));
316    }
317    if let Some(dictionary) = settings.dictionary {
318        properties = properties.set_dictionary_enabled(dictionary);
319    }
320    if let Some(page_size) = settings.page_size {
321        properties = properties.set_data_page_size_limit(page_size);
322    }
323    if let Some(data_page_v2) = settings.data_page_v2 {
324        properties = properties.set_writer_version(if data_page_v2 {
325            WriterVersion::PARQUET_2_0
326        } else {
327            WriterVersion::PARQUET_1_0
328        });
329    }
330    if let Some(encoding) = settings.encoding {
331        properties = properties.set_encoding(encoding);
332    }
333
334    let target = temporary_path(path);
335    let output = File::create(&target).with_context(|| format!("create {}", target.display()))?;
336    let mut writer = ArrowWriter::try_new(output, schema.clone(), Some(properties.build()))
337        .context("open the writer")?;
338    for batch in builder.build()? {
339        writer.write(&batch?)?;
340    }
341    writer.close()?;
342
343    let size = std::fs::metadata(&target)?.len();
344    let _ = std::fs::remove_file(&target);
345    Ok(size)
346}
347
348/// The compression a name stands for.
349fn compression_of(name: &str) -> Compression {
350    match name.to_uppercase().as_str() {
351        "SNAPPY" => Compression::SNAPPY,
352        "GZIP" => Compression::GZIP(GzipLevel::default()),
353        "BROTLI" => Compression::BROTLI(BrotliLevel::default()),
354        "ZSTD" => Compression::ZSTD(ZstdLevel::default()),
355        "LZ4" => Compression::LZ4,
356        "LZ4_RAW" => Compression::LZ4_RAW,
357        _ => Compression::UNCOMPRESSED,
358    }
359}
360
361/// Read a compression like `zstd:19`.
362fn compression_of_spec(spec: &str) -> Result<Compression> {
363    let (codec, level) = match spec.split_once(':') {
364        Some((codec, level)) => (codec, Some(level)),
365        None => (spec, None),
366    };
367    let level = level.map(|level| {
368        level
369            .parse::<i32>()
370            .map_err(|_| anyhow!("the compression level: {level}"))
371    });
372    let level = match level {
373        Some(level) => Some(level?),
374        None => None,
375    };
376    match codec.to_lowercase().as_str() {
377        "snappy" => Ok(Compression::SNAPPY),
378        "none" | "uncompressed" => Ok(Compression::UNCOMPRESSED),
379        "lz4" | "lz4_raw" => Ok(Compression::LZ4_RAW),
380        "zstd" => Ok(Compression::ZSTD(ZstdLevel::try_new(level.unwrap_or(1))?)),
381        "gzip" => Ok(Compression::GZIP(GzipLevel::try_new(
382            level.unwrap_or(6) as u32
383        )?)),
384        "brotli" => Ok(Compression::BROTLI(BrotliLevel::try_new(
385            level.unwrap_or(6) as u32,
386        )?)),
387        other => Err(anyhow!("unknown compression: {other}")),
388    }
389}
390
391/// The name of an encoding, as the user writes it.
392fn encoding_name(encoding: &Encoding) -> &'static str {
393    match encoding {
394        Encoding::PLAIN => "plain",
395        Encoding::DELTA_BINARY_PACKED => "delta",
396        Encoding::DELTA_LENGTH_BYTE_ARRAY => "delta-length-bytes",
397        _ => "other",
398    }
399}
400
401/// A temporary file to write the rewritten file into.
402fn temporary_path(path: &Path) -> PathBuf {
403    let stamp = std::time::SystemTime::now()
404        .duration_since(std::time::UNIX_EPOCH)
405        .map(|since| since.as_nanos())
406        .unwrap_or(0);
407    let name = path
408        .file_name()
409        .map(|name| name.to_string_lossy().to_string())
410        .unwrap_or_else(|| "bench".to_string());
411    let directory = path.parent().unwrap_or_else(|| Path::new("."));
412    directory.join(format!(".pqt-bench-{name}-{stamp}.parquet"))
413}