parquet-cli 0.1.9

A Parquet CLI for AI agents: inspect, measure and convert Parquet files.
Documentation
//! Comparing several Parquet files with each other.
//!
//! A directory of shards is a thing that drifts: one day a column is added,
//! another day a column grows. Comparing the files says where they disagree,
//! before a query silently drops a column.

use std::path::PathBuf;

use anyhow::{Context, Result};
use serde_json::{json, Map, Value};

use crate::meta::{self, ColumnFacts};

/// One file, with what the comparison needs to know about it.
#[derive(Clone, Debug)]
pub struct FileEntry {
    /// The path, as it was given.
    pub path: String,
    /// The name to show it by (the file's name).
    pub label: String,
    pub rows: i64,
    pub size_bytes: u64,
    pub row_groups: usize,
    pub columns: Vec<ColumnFacts>,
}

/// One thing worth knowing about the set of files.
#[derive(Clone, Debug)]
pub struct Finding {
    pub rule: &'static str,
    pub severity: &'static str,
    /// The file it is about, when it is about one.
    pub file: Option<String>,
    pub message: String,
}

impl Finding {
    pub fn to_json(&self) -> Value {
        let mut object = Map::new();
        object.insert("rule".into(), Value::String(self.rule.into()));
        object.insert("severity".into(), Value::String(self.severity.into()));
        if let Some(file) = &self.file {
            object.insert("file".into(), Value::String(file.clone()));
        }
        object.insert("message".into(), Value::String(self.message.clone()));
        Value::Object(object)
    }
}

/// Everything the comparison is about.
#[derive(Clone, Debug)]
pub struct Comparison {
    pub files: Vec<FileEntry>,
    pub findings: Vec<Finding>,
}

impl Comparison {
    pub fn to_json(&self) -> Value {
        let files: Vec<Value> = self
            .files
            .iter()
            .map(|file| {
                json!({
                    "file": file.path,
                    "label": file.label,
                    "rows": file.rows,
                    "size_bytes": file.size_bytes,
                    "row_groups": file.row_groups,
                    "columns": file.columns.len(),
                })
            })
            .collect();
        json!({
            "files": files,
            "findings": self
                .findings
                .iter()
                .map(|finding| finding.to_json())
                .collect::<Vec<Value>>(),
        })
    }
}

/// A file to compare, with the name to show it by.
pub struct Found {
    pub path: PathBuf,
    /// The path relative to the directory it was found in, so that the files
    /// of a directory of shards can be told apart.
    pub label: String,
}

/// The files to compare: the ones given, plus the Parquet files under the
/// directories given.
///
/// The directories are walked, because a directory of shards has the shape of
/// the cold layer: `site/week=…/table.parquet`.
pub fn collect(paths: &[PathBuf]) -> Result<Vec<Found>> {
    let mut files = Vec::new();
    for path in paths {
        if path.is_dir() {
            let mut inside = Vec::new();
            walk(path, 0, &mut inside)?;
            inside.sort();
            for found in inside {
                let label = found
                    .strip_prefix(path)
                    .unwrap_or(&found)
                    .to_string_lossy()
                    .to_string();
                files.push(Found { path: found, label });
            }
        } else {
            let label = path
                .file_name()
                .map(|name| name.to_string_lossy().to_string())
                .unwrap_or_else(|| path.display().to_string());
            files.push(Found {
                path: path.clone(),
                label,
            });
        }
    }
    Ok(files)
}

/// The Parquet files under a directory, up to a few levels down.
fn walk(directory: &std::path::Path, depth: usize, files: &mut Vec<PathBuf>) -> Result<()> {
    if depth > 4 {
        return Ok(());
    }
    for entry in
        std::fs::read_dir(directory).with_context(|| format!("read {}", directory.display()))?
    {
        let path = entry?.path();
        if path.is_dir() {
            walk(&path, depth + 1, files)?;
        } else if path
            .extension()
            .and_then(|extension| extension.to_str())
            .map(|extension| extension.eq_ignore_ascii_case("parquet"))
            .unwrap_or(false)
        {
            files.push(path);
        }
    }
    Ok(())
}

/// Compare a set of files.
pub fn compare(paths: &[PathBuf]) -> Result<Comparison> {
    let files = collect(paths)?;
    if files.is_empty() {
        anyhow::bail!("there is nothing to compare");
    }

    let mut entries = Vec::new();
    for found in &files {
        let facts = meta::file_facts(&found.path)?;
        let columns = meta::column_facts(&found.path, false)?;
        entries.push(FileEntry {
            label: found.label.clone(),
            path: facts.path,
            rows: facts.rows,
            size_bytes: facts.size_bytes,
            row_groups: facts.row_groups,
            columns,
        });
    }

    let findings = differences(&entries);
    Ok(Comparison {
        files: entries,
        findings,
    })
}

/// Where the files disagree with each other.
fn differences(files: &[FileEntry]) -> Vec<Finding> {
    let mut findings = Vec::new();
    if files.len() < 2 {
        return findings;
    }

    // The shape most of the files have is the yardstick: one shard that
    // drifted should not define what the others look like.
    let mut shapes: Vec<(Vec<(String, String)>, usize)> = Vec::new();
    for file in files {
        let shape: Vec<(String, String)> = file
            .columns
            .iter()
            .map(|column| (column.name.clone(), column.data_type.clone()))
            .collect();
        match shapes.iter_mut().find(|(other, _)| *other == shape) {
            Some((_, count)) => *count += 1,
            None => shapes.push((shape, 1)),
        }
    }
    // Most files first; when they are all different, the richest shape is the
    // yardstick (a column that was added later shows up as missing in the
    // older files).
    shapes.sort_by(|left, right| {
        right
            .1
            .cmp(&left.1)
            .then_with(|| right.0.len().cmp(&left.0.len()))
    });
    let reference_types = shapes[0].0.clone();

    for file in files {
        let types: Vec<(String, String)> = file
            .columns
            .iter()
            .map(|column| (column.name.clone(), column.data_type.clone()))
            .collect();

        if types == reference_types {
            continue;
        }
        for (name, data_type) in &types {
            match reference_types.iter().find(|(other, _)| other == name) {
                None => findings.push(Finding {
                    rule: "column-extra",
                    severity: "error",
                    file: Some(file.label.clone()),
                    message: format!("多了一个列「{name}」,别的文件没有"),
                }),
                Some((_, other_type)) if other_type != data_type => findings.push(Finding {
                    rule: "column-type-changed",
                    severity: "error",
                    file: Some(file.label.clone()),
                    message: format!("列「{name}」在这里是 {data_type},别的文件是 {other_type}"),
                }),
                Some(_) => {}
            }
        }
        for (name, _) in &reference_types {
            if !types.iter().any(|(other, _)| other == name) {
                findings.push(Finding {
                    rule: "column-missing",
                    severity: "error",
                    file: Some(file.label.clone()),
                    message: format!("少了列「{name}」,别的文件有"),
                });
            }
        }
    }

    // A column whose size changed a lot between the files.
    let mut names: Vec<String> = Vec::new();
    for file in files {
        for column in &file.columns {
            if !names.contains(&column.name) {
                names.push(column.name.clone());
            }
        }
    }
    for name in names {
        let sizes: Vec<i64> = files
            .iter()
            .map(|file| {
                file.columns
                    .iter()
                    .find(|column| column.name == name)
                    .map(|column| column.compressed_size)
                    .unwrap_or(0)
            })
            .collect();
        let largest = sizes.iter().copied().max().unwrap_or(0);
        let smallest = sizes.iter().copied().min().unwrap_or(0);
        if smallest > 0 && largest > smallest * 2 {
            let file = files
                .iter()
                .zip(sizes.iter())
                .max_by_key(|(_, size)| **size)
                .map(|(file, _)| file.label.clone());
            findings.push(Finding {
                rule: "size-jump",
                severity: "warning",
                file,
                message: format!(
                    "列「{name}」的字节从 {smallest} 涨到 {largest}({:.1} 倍)",
                    largest as f64 / smallest as f64
                ),
            });
        }
    }

    // The files themselves growing a lot.
    let sizes: Vec<u64> = files.iter().map(|file| file.size_bytes).collect();
    let largest = sizes.iter().copied().max().unwrap_or(0);
    let smallest = sizes.iter().copied().min().unwrap_or(0);
    if smallest > 0 && largest > smallest * 2 {
        findings.push(Finding {
            rule: "file-size-jump",
            severity: "warning",
            file: None,
            message: format!(
                "文件的大小从 {smallest} 涨到 {largest}({:.1} 倍)",
                largest as f64 / smallest as f64
            ),
        });
    }

    findings
}

/// The bytes each column takes in each file.
pub fn column_bytes(files: &[FileEntry]) -> Vec<(String, Vec<i64>)> {
    let mut names: Vec<String> = Vec::new();
    for file in files {
        for column in &file.columns {
            if !names.contains(&column.name) {
                names.push(column.name.clone());
            }
        }
    }
    names
        .into_iter()
        .map(|name| {
            let sizes = files
                .iter()
                .map(|file| {
                    file.columns
                        .iter()
                        .find(|column| column.name == name)
                        .map(|column| column.compressed_size)
                        .unwrap_or(0)
                })
                .collect();
            (name, sizes)
        })
        .collect()
}