parquet-cli 0.2.1

A Parquet CLI for AI agents: inspect, measure and convert Parquet files.
Documentation
//! Writing a file again with different settings, and saying what it cost.
//!
//! A compression experiment is one question: *what would this file weigh if
//! it were written this way?* The answer is a number, and the number is what
//! decides things.

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, Plan};

/// One run and what it weighed.
#[derive(Clone, Debug)]
pub struct Run {
    /// What was changed.
    pub label: String,
    /// The settings it ran with.
    pub settings: String,
    /// How many bytes the rewritten file took.
    pub bytes: u64,
}

/// The result of a bench.
#[derive(Clone, Debug)]
pub struct Bench {
    pub file: String,
    /// How many bytes the original file takes.
    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,
        })
    }
}

/// Read the settings a file was written with, as a plan.
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
}

/// Write the file again with these settings, and say how big it is.
///
/// `wanted` is what the caller asked for; the file's own settings are what it
/// starts from.
pub fn bench(path: &Path, wanted: &Plan, sweep: bool, keep: Option<&Path>) -> Result<Bench> {
    let facts = meta::file_facts(path)?;
    let base = baseline(&facts);

    let mut plan = base.clone();
    plan.merge(wanted);

    let mut runs = Vec::new();
    runs.push(Run {
        label: if wanted.entries().next().is_none() {
            "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,
    })
}

/// One variation of the sweep: what it changes, and the options it changes it
/// with.
type Variation = (String, Vec<(String, String)>);

/// The settings a sweep tries: one knob at a time, from the file's own.
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)
}

/// A plan, as a line of text.
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(", ")
    }
}

/// Read a file and write it again with these settings. The original is left
/// alone.
fn rewrite(path: &Path, plan: &Plan, rows: i64, keep: Option<&Path>) -> Result<u64> {
    let columns = plan::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)
}

/// A temporary file to write the rewritten file into.
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"))
}