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::Result;
11use parquet::arrow::arrow_reader::ParquetRecordBatchReaderBuilder;
12use parquet::arrow::arrow_writer::ArrowWriter;
13use serde_json::{json, Map, Value};
14
15use crate::meta::{self, FileFacts};
16use crate::plan::{self, Plan};
17
18/// One run and what it weighed.
19#[derive(Clone, Debug)]
20pub struct Run {
21    /// What was changed.
22    pub label: String,
23    /// The settings it ran with.
24    pub settings: String,
25    /// How many bytes the rewritten file took.
26    pub bytes: u64,
27}
28
29/// The result of a bench.
30#[derive(Clone, Debug)]
31pub struct Bench {
32    pub file: String,
33    /// How many bytes the original file takes.
34    pub original_bytes: u64,
35    pub runs: Vec<Run>,
36}
37
38impl Bench {
39    pub fn to_json(&self) -> Value {
40        let runs: Vec<Value> = self
41            .runs
42            .iter()
43            .map(|run| {
44                let mut object = Map::new();
45                object.insert("label".into(), Value::String(run.label.clone()));
46                object.insert("settings".into(), Value::String(run.settings.clone()));
47                object.insert("bytes".into(), json!(run.bytes));
48                object.insert(
49                    "difference".into(),
50                    json!(run.bytes as i64 - self.original_bytes as i64),
51                );
52                object.insert(
53                    "ratio".into(),
54                    json!(run.bytes as f64 / self.original_bytes as f64),
55                );
56                Value::Object(object)
57            })
58            .collect();
59        json!({
60            "file": self.file,
61            "original_bytes": self.original_bytes,
62            "runs": runs,
63        })
64    }
65}
66
67/// Read the settings a file was written with, as a plan.
68pub fn baseline(facts: &FileFacts) -> Plan {
69    let mut plan = Plan::new();
70    if let Some(codec) = facts.compressions.first() {
71        let _ = plan.set("compression", codec);
72    }
73    if facts.row_groups > 0 {
74        let rows = (facts.rows / facts.row_groups as i64).max(1);
75        let _ = plan.set("row_group_size", &rows.to_string());
76    }
77    let dictionary = facts
78        .encodings
79        .iter()
80        .any(|encoding| encoding.contains("DICTIONARY"));
81    let _ = plan.set("dictionary", if dictionary { "on" } else { "off" });
82    let _ = plan.set(
83        "parquet_version",
84        if facts.format_version >= 2 {
85            "v2"
86        } else {
87            "v1"
88        },
89    );
90    plan
91}
92
93/// Write the file again with these settings, and say how big it is.
94///
95/// `wanted` is what the caller asked for; the file's own settings are what it
96/// starts from.
97pub fn bench(path: &Path, wanted: &Plan, sweep: bool, keep: Option<&Path>) -> Result<Bench> {
98    let facts = meta::file_facts(path)?;
99    let base = baseline(&facts);
100
101    let mut plan = base.clone();
102    plan.merge(wanted);
103
104    let mut runs = Vec::new();
105    runs.push(Run {
106        label: if wanted.entries().next().is_none() {
107            "the file's own settings".to_string()
108        } else {
109            "the settings you asked for".to_string()
110        },
111        settings: describe(&plan),
112        bytes: rewrite(path, &plan, facts.rows, keep)?,
113    });
114
115    if sweep {
116        for (label, options) in sweep_options()? {
117            let mut plan = base.clone();
118            for (name, value) in options {
119                plan.set(&name, &value)?;
120            }
121            runs.push(Run {
122                label,
123                settings: describe(&plan),
124                bytes: rewrite(path, &plan, facts.rows, None)?,
125            });
126        }
127    }
128
129    Ok(Bench {
130        file: facts.path,
131        original_bytes: facts.size_bytes,
132        runs,
133    })
134}
135
136/// One variation of the sweep: what it changes, and the options it changes it
137/// with.
138type Variation = (String, Vec<(String, String)>);
139
140/// The settings a sweep tries: one knob at a time, from the file's own.
141fn sweep_options() -> Result<Vec<Variation>> {
142    let mut sweep = Vec::new();
143    for rows in ["1000", "10000", "100000", "1000000"] {
144        sweep.push((
145            format!("row_group_size={rows}"),
146            vec![("row_group_size".to_string(), rows.to_string())],
147        ));
148    }
149    for codec in ["snappy", "zstd:1", "zstd:9", "zstd:19", "gzip:6"] {
150        let mut options = Vec::new();
151        for (name, value) in plan::parse_option(codec)? {
152            options.push((name, value));
153        }
154        sweep.push((format!("compression={codec}"), options));
155    }
156    for (label, name, value) in [
157        ("dictionary=off", "dictionary", "off"),
158        (
159            "dictionary_compression_ratio_threshold=0.5",
160            "dictionary_compression_ratio_threshold",
161            "0.5",
162        ),
163        ("write_bloom_filter=on", "write_bloom_filter", "on"),
164        ("write_page_index=off", "write_page_index", "off"),
165        ("parquet_version=v2", "parquet_version", "v2"),
166    ] {
167        sweep.push((
168            label.to_string(),
169            vec![(name.to_string(), value.to_string())],
170        ));
171    }
172    Ok(sweep)
173}
174
175/// A plan, as a line of text.
176fn describe(plan: &Plan) -> String {
177    let parts: Vec<String> = plan
178        .entries()
179        .map(|(name, value)| format!("{name}={value}"))
180        .collect();
181    if parts.is_empty() {
182        "the defaults".to_string()
183    } else {
184        parts.join(", ")
185    }
186}
187
188/// Read a file and write it again with these settings. The original is left
189/// alone.
190fn rewrite(path: &Path, plan: &Plan, rows: i64, keep: Option<&Path>) -> Result<u64> {
191    let columns = plan::columns_of(path, plan, rows)?;
192    let properties = plan.writer_properties(&columns)?;
193
194    let file = File::open(path)?;
195    let builder = ParquetRecordBatchReaderBuilder::try_new(file)?;
196    let schema = builder.schema().clone();
197
198    let target = match keep {
199        Some(path) => path.to_path_buf(),
200        None => temporary_path(path),
201    };
202    let output = File::create(&target)?;
203    let mut writer = ArrowWriter::try_new(output, schema, Some(properties))?;
204    for batch in builder.build()? {
205        writer.write(&batch?)?;
206    }
207    writer.close()?;
208
209    let size = std::fs::metadata(&target)?.len();
210    if keep.is_none() {
211        let _ = std::fs::remove_file(&target);
212    }
213    Ok(size)
214}
215
216/// A temporary file to write the rewritten file into.
217fn temporary_path(path: &Path) -> PathBuf {
218    let stamp = std::time::SystemTime::now()
219        .duration_since(std::time::UNIX_EPOCH)
220        .map(|since| since.as_nanos())
221        .unwrap_or(0);
222    let name = path
223        .file_name()
224        .map(|name| name.to_string_lossy().to_string())
225        .unwrap_or_else(|| "bench".to_string());
226    let directory = path.parent().unwrap_or_else(|| Path::new("."));
227    directory.join(format!(".pqt-bench-{name}-{stamp}.parquet"))
228}