use std::fs::File;
use std::path::{Path, PathBuf};
use anyhow::Result;
use parquet::arrow::arrow_reader::ParquetRecordBatchReaderBuilder;
use parquet::arrow::arrow_writer::ArrowWriter;
use serde_json::{json, Map, Value};
use crate::meta::{self, FileFacts};
use crate::plan::{self, Column, Plan};
#[derive(Clone, Debug)]
pub struct Run {
pub label: String,
pub settings: String,
pub bytes: u64,
}
#[derive(Clone, Debug)]
pub struct Bench {
pub file: String,
pub original_bytes: u64,
pub runs: Vec<Run>,
}
impl Bench {
pub fn to_json(&self) -> Value {
let runs: Vec<Value> = self
.runs
.iter()
.map(|run| {
let mut object = Map::new();
object.insert("label".into(), Value::String(run.label.clone()));
object.insert("settings".into(), Value::String(run.settings.clone()));
object.insert("bytes".into(), json!(run.bytes));
object.insert(
"difference".into(),
json!(run.bytes as i64 - self.original_bytes as i64),
);
object.insert(
"ratio".into(),
json!(run.bytes as f64 / self.original_bytes as f64),
);
Value::Object(object)
})
.collect();
json!({
"file": self.file,
"original_bytes": self.original_bytes,
"runs": runs,
})
}
}
pub fn baseline(facts: &FileFacts) -> Plan {
let mut plan = Plan::new();
if let Some(codec) = facts.compressions.first() {
let _ = plan.set("compression", codec);
}
if facts.row_groups > 0 {
let rows = (facts.rows / facts.row_groups as i64).max(1);
let _ = plan.set("row_group_size", &rows.to_string());
}
let dictionary = facts
.encodings
.iter()
.any(|encoding| encoding.contains("DICTIONARY"));
let _ = plan.set("dictionary", if dictionary { "on" } else { "off" });
let _ = plan.set(
"parquet_version",
if facts.format_version >= 2 {
"v2"
} else {
"v1"
},
);
plan
}
pub fn bench(path: &Path, overrides: &[String], sweep: bool, keep: Option<&Path>) -> Result<Bench> {
let facts = meta::file_facts(path)?;
let base = baseline(&facts);
let mut plan = base.clone();
for option in overrides {
for (name, value) in plan::parse_option(option)? {
plan.set(&name, &value)?;
}
}
let mut runs = Vec::new();
runs.push(Run {
label: if overrides.is_empty() {
"the file's own settings".to_string()
} else {
"the settings you asked for".to_string()
},
settings: describe(&plan),
bytes: rewrite(path, &plan, facts.rows, keep)?,
});
if sweep {
for (label, options) in sweep_options()? {
let mut plan = base.clone();
for (name, value) in options {
plan.set(&name, &value)?;
}
runs.push(Run {
label,
settings: describe(&plan),
bytes: rewrite(path, &plan, facts.rows, None)?,
});
}
}
Ok(Bench {
file: facts.path,
original_bytes: facts.size_bytes,
runs,
})
}
type Variation = (String, Vec<(String, String)>);
fn sweep_options() -> Result<Vec<Variation>> {
let mut sweep = Vec::new();
for rows in ["1000", "10000", "100000", "1000000"] {
sweep.push((
format!("row_group_size={rows}"),
vec![("row_group_size".to_string(), rows.to_string())],
));
}
for codec in ["snappy", "zstd:1", "zstd:9", "zstd:19", "gzip:6"] {
let mut options = Vec::new();
for (name, value) in plan::parse_option(codec)? {
options.push((name, value));
}
sweep.push((format!("compression={codec}"), options));
}
for (label, name, value) in [
("dictionary=off", "dictionary", "off"),
(
"dictionary_compression_ratio_threshold=0.5",
"dictionary_compression_ratio_threshold",
"0.5",
),
("write_bloom_filter=on", "write_bloom_filter", "on"),
("write_page_index=off", "write_page_index", "off"),
("parquet_version=v2", "parquet_version", "v2"),
] {
sweep.push((
label.to_string(),
vec![(name.to_string(), value.to_string())],
));
}
Ok(sweep)
}
fn describe(plan: &Plan) -> String {
let parts: Vec<String> = plan
.entries()
.map(|(name, value)| format!("{name}={value}"))
.collect();
if parts.is_empty() {
"the defaults".to_string()
} else {
parts.join(", ")
}
}
fn rewrite(path: &Path, plan: &Plan, rows: i64, keep: Option<&Path>) -> Result<u64> {
let columns = columns_of(path, plan, rows)?;
let properties = plan.writer_properties(&columns)?;
let file = File::open(path)?;
let builder = ParquetRecordBatchReaderBuilder::try_new(file)?;
let schema = builder.schema().clone();
let target = match keep {
Some(path) => path.to_path_buf(),
None => temporary_path(path),
};
let output = File::create(&target)?;
let mut writer = ArrowWriter::try_new(output, schema, Some(properties))?;
for batch in builder.build()? {
writer.write(&batch?)?;
}
writer.close()?;
let size = std::fs::metadata(&target)?.len();
if keep.is_none() {
let _ = std::fs::remove_file(&target);
}
Ok(size)
}
fn columns_of(path: &Path, plan: &Plan, rows: i64) -> Result<Vec<Column>> {
let facts = meta::column_facts(path, false)?;
let mut columns: Vec<Column> = facts
.iter()
.map(|column| Column {
name: column.name.clone(),
distinct: None,
rows,
})
.collect();
if plan.needs_distinct() {
let distinct = meta::scan_distinct(path)?;
for (index, column) in columns.iter_mut().enumerate() {
column.distinct = distinct.get(index).map(|values| values.len() as u64);
}
}
Ok(columns)
}
fn temporary_path(path: &Path) -> PathBuf {
let stamp = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|since| since.as_nanos())
.unwrap_or(0);
let name = path
.file_name()
.map(|name| name.to_string_lossy().to_string())
.unwrap_or_else(|| "bench".to_string());
let directory = path.parent().unwrap_or_else(|| Path::new("."));
directory.join(format!(".pqt-bench-{name}-{stamp}.parquet"))
}