parquet-cli 0.1.9

A Parquet CLI for AI agents: inspect, measure and convert Parquet files.
Documentation
//! What a reader could skip, according to the file's own statistics.
//!
//! This is the Parquet-primitive counterpart of a query with a filter: the
//! file says, for every row group, the smallest and the largest value of every
//! column. A reader that trusts those numbers can skip the row groups that
//! cannot match.
//!
//! It is deliberately *not* a query engine: it answers "what does the file say
//! a reader could skip", which is a different number from what any particular
//! engine actually read. The gap between the two is where the problems are.

use std::path::Path;

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

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

/// A condition on the values of a file.
#[derive(Clone, Debug)]
pub enum Condition {
    /// `column <op> value`
    Compare {
        column: String,
        op: String,
        value: Value,
    },
    /// `column IN (values)`
    In { column: String, values: Vec<Value> },
    /// `column BETWEEN low AND high`
    Between {
        column: String,
        low: Value,
        high: Value,
    },
    /// Every one of them has to hold.
    And(Vec<Condition>),
    /// At least one of them has to hold.
    Or(Vec<Condition>),
    /// The opposite of it.
    Not(Box<Condition>),
}

impl Condition {
    /// The columns this condition looks at.
    pub fn columns(&self) -> Vec<String> {
        match self {
            Condition::Compare { column, .. }
            | Condition::In { column, .. }
            | Condition::Between { column, .. } => vec![column.clone()],
            Condition::And(conditions) | Condition::Or(conditions) => conditions
                .iter()
                .flat_map(|condition| condition.columns())
                .collect(),
            Condition::Not(condition) => condition.columns(),
        }
    }

    /// Whether a row group with these bounds could hold a matching row.
    ///
    /// `None` means "we cannot tell" — the group has to be read.
    fn may_match(&self, column: &ColumnFacts) -> bool {
        match self {
            Condition::Compare { op, value, .. } => {
                let (Some(min), Some(max)) = (&column.min, &column.max) else {
                    return true;
                };
                match op.as_str() {
                    "==" => in_range(value, min, max),
                    "!=" => true, // a different value may still be there
                    // The group may hold a match when its range reaches the
                    // value: `id < 90000` needs the group's smallest value.
                    "<" => less_than(min, value),
                    "<=" => less_or_equal(min, value),
                    ">" => greater_than(max, value),
                    ">=" => greater_or_equal(max, value),
                    _ => true,
                }
            }
            Condition::In { values, .. } => {
                let (Some(min), Some(max)) = (&column.min, &column.max) else {
                    return true;
                };
                values.iter().any(|value| in_range(value, min, max))
            }
            Condition::Between { low, high, .. } => {
                let (Some(min), Some(max)) = (&column.min, &column.max) else {
                    return true;
                };
                // The group could hold a value between low and high.
                less_or_equal(low, max) && greater_or_equal(high, min)
            }
            Condition::And(conditions) => conditions
                .iter()
                .all(|condition| condition.may_match(column)),
            Condition::Or(conditions) => conditions
                .iter()
                .any(|condition| condition.may_match(column)),
            Condition::Not(condition) => condition.may_match(column),
        }
    }
}

/// Read a condition the way a script writes it.
pub fn parse(value: &Value) -> Result<Condition> {
    let object = value
        .as_object()
        .ok_or_else(|| anyhow!("a condition is a table"))?;

    if let Some(conditions) = object.get("and") {
        return Ok(Condition::And(parse_all(conditions)?));
    }
    if let Some(conditions) = object.get("or") {
        return Ok(Condition::Or(parse_all(conditions)?));
    }
    if let Some(inner) = object.get("not") {
        return Ok(Condition::Not(Box::new(parse(inner)?)));
    }

    let column = object
        .get("column")
        .and_then(Value::as_str)
        .ok_or_else(|| anyhow!("a condition needs a column"))?
        .to_string();

    if let Some(values) = object.get("in") {
        let values = values
            .as_array()
            .ok_or_else(|| anyhow!("in takes a list"))?
            .clone();
        return Ok(Condition::In { column, values });
    }
    if let Some(bounds) = object.get("between") {
        let bounds = bounds
            .as_array()
            .ok_or_else(|| anyhow!("between takes a list of two"))?;
        if bounds.len() != 2 {
            return Err(anyhow!("between takes a list of two"));
        }
        return Ok(Condition::Between {
            column,
            low: bounds[0].clone(),
            high: bounds[1].clone(),
        });
    }

    let op = object
        .get("op")
        .and_then(Value::as_str)
        .ok_or_else(|| anyhow!("a condition needs an op"))?
        .to_string();
    let value = object
        .get("value")
        .cloned()
        .ok_or_else(|| anyhow!("a condition needs a value"))?;
    Ok(Condition::Compare { column, op, value })
}

/// A list of conditions.
fn parse_all(value: &Value) -> Result<Vec<Condition>> {
    let list = value
        .as_array()
        .ok_or_else(|| anyhow!("and/or take a list of conditions"))?;
    list.iter().map(parse).collect()
}

/// What a reader could skip, according to the file.
#[derive(Clone, Debug)]
pub struct Prune {
    /// How many row groups the file has.
    pub groups_total: usize,
    /// How many of them cannot hold a matching row.
    pub groups_skipped: usize,
    /// How many of them have to be read.
    pub groups_read: usize,
    /// How many rows the file has.
    pub rows_total: i64,
    /// How many rows are in the groups that have to be read.
    pub rows_read: i64,
    /// How many bytes the whole file takes.
    pub bytes_total: i64,
    /// How many bytes the groups that have to be read take.
    pub bytes_read: i64,
    /// For every row group: whether it can be skipped, and why.
    pub groups: Vec<GroupPrune>,
}

/// One row group, and what the statistics say about it.
#[derive(Clone, Debug)]
pub struct GroupPrune {
    pub index: usize,
    pub rows: i64,
    pub bytes: i64,
    /// Whether this group cannot hold a matching row.
    pub skipped: bool,
    /// Which column ruled it out.
    pub ruled_out_by: Option<String>,
}

impl Prune {
    pub fn to_json(&self) -> Value {
        json!({
            "groups_total": self.groups_total,
            "groups_skipped": self.groups_skipped,
            "groups_read": self.groups_read,
            "rows_total": self.rows_total,
            "rows_read": self.rows_read,
            "bytes_total": self.bytes_total,
            "bytes_read": self.bytes_read,
            "skip_ratio": if self.groups_total > 0 {
                self.groups_skipped as f64 / self.groups_total as f64
            } else {
                0.0
            },
            "groups": self.groups.iter().map(|group| json!({
                "index": group.index,
                "rows": group.rows,
                "bytes": group.bytes,
                "skipped": group.skipped,
                "ruled_out_by": group.ruled_out_by,
            })).collect::<Vec<Value>>(),
        })
    }
}

/// Work out what a reader could skip.
pub fn prune(path: &Path, condition: &Condition) -> Result<Prune> {
    let facts = meta::file_facts(path)?;
    let columns = meta::column_facts(path, false)?;

    let wanted: Vec<String> = condition.columns();
    let mut per_column: Vec<(&String, &ColumnFacts)> = Vec::new();
    for name in &wanted {
        match columns.iter().find(|column| &column.name == name) {
            Some(column) => per_column.push((name, column)),
            None => return Err(anyhow!("the file has no column named {name}")),
        }
    }

    let group_count = facts.row_group_rows.len();
    let mut groups = Vec::new();
    let mut groups_skipped = 0;
    let mut rows_read = 0;
    let mut bytes_read = 0;

    for (index, group) in facts.row_group_rows.iter().enumerate() {
        let bytes = facts
            .row_group_bytes
            .get(index)
            .copied()
            .unwrap_or_default();
        let mut skipped = false;
        let mut ruled_out_by = None;
        for (name, column) in &per_column {
            let group_min = column
                .row_groups
                .get(index)
                .and_then(|group| group.min.as_ref());
            let group_max = column
                .row_groups
                .get(index)
                .and_then(|group| group.max.as_ref());
            let scoped = ColumnFacts {
                min: group_min.cloned(),
                max: group_max.cloned(),
                ..(*column).clone()
            };
            if !condition.may_match(&scoped) {
                skipped = true;
                ruled_out_by = Some((*name).clone());
                break;
            }
        }
        if skipped {
            groups_skipped += 1;
        } else {
            rows_read += group;
            bytes_read += bytes;
        }
        groups.push(GroupPrune {
            index,
            rows: *group,
            bytes,
            skipped,
            ruled_out_by,
        });
    }

    Ok(Prune {
        groups_total: group_count,
        groups_skipped,
        groups_read: group_count - groups_skipped,
        rows_total: facts.rows,
        rows_read,
        bytes_total: facts.size_bytes as i64,
        bytes_read,
        groups,
    })
}

/// Is a value inside a range?
fn in_range(value: &Value, min: &Value, max: &Value) -> bool {
    less_or_equal(min, value) && less_or_equal(value, max)
}

/// Is the value smaller than the bound?
fn less_than(value: &Value, bound: &Value) -> bool {
    compare(value, bound)
        .map(|order| order.is_lt())
        .unwrap_or(true)
}

/// Is the value smaller than or equal to the bound?
fn less_or_equal(value: &Value, bound: &Value) -> bool {
    compare(value, bound)
        .map(|order| order.is_le())
        .unwrap_or(true)
}

/// Is the value bigger than the bound?
fn greater_than(value: &Value, bound: &Value) -> bool {
    compare(value, bound)
        .map(|order| order.is_gt())
        .unwrap_or(true)
}

/// Is the value bigger than or equal to the bound?
fn greater_or_equal(value: &Value, bound: &Value) -> bool {
    compare(value, bound)
        .map(|order| order.is_ge())
        .unwrap_or(true)
}

/// Compare two values, when they can be compared.
fn compare(left: &Value, right: &Value) -> Option<std::cmp::Ordering> {
    match (left, right) {
        (Value::Number(left), Value::Number(right)) => left
            .as_f64()
            .zip(right.as_f64())
            .and_then(|(left, right)| left.partial_cmp(&right)),
        (Value::String(left), Value::String(right)) => Some(left.cmp(right)),
        (Value::Bool(left), Value::Bool(right)) => Some(left.cmp(right)),
        _ => None,
    }
}

/// The condition as JSON, for printing.
pub fn describe(condition: &Condition) -> Value {
    match condition {
        Condition::Compare { column, op, value } => {
            let mut object = Map::new();
            object.insert("column".into(), Value::String(column.clone()));
            object.insert("op".into(), Value::String(op.clone()));
            object.insert("value".into(), value.clone());
            Value::Object(object)
        }
        Condition::In { column, values } => {
            let mut object = Map::new();
            object.insert("column".into(), Value::String(column.clone()));
            object.insert("in".into(), Value::Array(values.clone()));
            Value::Object(object)
        }
        Condition::Between { column, low, high } => {
            let mut object = Map::new();
            object.insert("column".into(), Value::String(column.clone()));
            object.insert(
                "between".into(),
                Value::Array(vec![low.clone(), high.clone()]),
            );
            Value::Object(object)
        }
        Condition::And(conditions) => {
            let mut object = Map::new();
            object.insert(
                "and".into(),
                Value::Array(conditions.iter().map(describe).collect()),
            );
            Value::Object(object)
        }
        Condition::Or(conditions) => {
            let mut object = Map::new();
            object.insert(
                "or".into(),
                Value::Array(conditions.iter().map(describe).collect()),
            );
            Value::Object(object)
        }
        Condition::Not(inner) => {
            let mut object = Map::new();
            object.insert("not".into(), describe(inner));
            Value::Object(object)
        }
    }
}