1use 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, Column, Plan};
17
18#[derive(Clone, Debug)]
20pub struct Run {
21 pub label: String,
23 pub settings: String,
25 pub bytes: u64,
27}
28
29#[derive(Clone, Debug)]
31pub struct Bench {
32 pub file: String,
33 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
67pub 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
93pub 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
136type Variation = (String, Vec<(String, String)>);
139
140fn 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
175fn 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
188fn rewrite(path: &Path, plan: &Plan, rows: i64, keep: Option<&Path>) -> Result<u64> {
191 let columns = 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
216fn columns_of(path: &Path, plan: &Plan, rows: i64) -> Result<Vec<Column>> {
219 let facts = meta::column_facts(path, false)?;
220 let mut columns: Vec<Column> = facts
221 .iter()
222 .map(|column| Column {
223 name: column.name.clone(),
224 distinct: None,
225 rows,
226 })
227 .collect();
228
229 if plan.needs_distinct() {
230 let distinct = meta::scan_distinct(path)?;
231 for (index, column) in columns.iter_mut().enumerate() {
232 column.distinct = distinct.get(index).map(|values| values.len() as u64);
233 }
234 }
235 Ok(columns)
236}
237
238fn temporary_path(path: &Path) -> PathBuf {
240 let stamp = std::time::SystemTime::now()
241 .duration_since(std::time::UNIX_EPOCH)
242 .map(|since| since.as_nanos())
243 .unwrap_or(0);
244 let name = path
245 .file_name()
246 .map(|name| name.to_string_lossy().to_string())
247 .unwrap_or_else(|| "bench".to_string());
248 let directory = path.parent().unwrap_or_else(|| Path::new("."));
249 directory.join(format!(".pqt-bench-{name}-{stamp}.parquet"))
250}