Skip to main content

parquet_cli/
prune.rs

1//! What a reader could skip, according to the file's own statistics.
2//!
3//! This is the Parquet-primitive counterpart of a query with a filter: the
4//! file says, for every row group, the smallest and the largest value of every
5//! column. A reader that trusts those numbers can skip the row groups that
6//! cannot match.
7//!
8//! It is deliberately *not* a query engine: it answers "what does the file say
9//! a reader could skip", which is a different number from what any particular
10//! engine actually read. The gap between the two is where the problems are.
11
12use std::path::Path;
13
14use anyhow::{anyhow, Result};
15use serde_json::{json, Map, Value};
16
17use crate::meta::{self, ColumnFacts};
18
19/// A condition on the values of a file.
20#[derive(Clone, Debug)]
21pub enum Condition {
22    /// `column <op> value`
23    Compare {
24        column: String,
25        op: String,
26        value: Value,
27    },
28    /// `column IN (values)`
29    In { column: String, values: Vec<Value> },
30    /// `column BETWEEN low AND high`
31    Between {
32        column: String,
33        low: Value,
34        high: Value,
35    },
36    /// Every one of them has to hold.
37    And(Vec<Condition>),
38    /// At least one of them has to hold.
39    Or(Vec<Condition>),
40    /// The opposite of it.
41    Not(Box<Condition>),
42}
43
44impl Condition {
45    /// The columns this condition looks at.
46    pub fn columns(&self) -> Vec<String> {
47        match self {
48            Condition::Compare { column, .. }
49            | Condition::In { column, .. }
50            | Condition::Between { column, .. } => vec![column.clone()],
51            Condition::And(conditions) | Condition::Or(conditions) => conditions
52                .iter()
53                .flat_map(|condition| condition.columns())
54                .collect(),
55            Condition::Not(condition) => condition.columns(),
56        }
57    }
58
59    /// Whether a row group with these bounds could hold a matching row.
60    ///
61    /// `None` means "we cannot tell" — the group has to be read.
62    fn may_match(&self, column: &ColumnFacts) -> bool {
63        match self {
64            Condition::Compare { op, value, .. } => {
65                let (Some(min), Some(max)) = (&column.min, &column.max) else {
66                    return true;
67                };
68                match op.as_str() {
69                    "==" => in_range(value, min, max),
70                    "!=" => true, // a different value may still be there
71                    // The group may hold a match when its range reaches the
72                    // value: `id < 90000` needs the group's smallest value.
73                    "<" => less_than(min, value),
74                    "<=" => less_or_equal(min, value),
75                    ">" => greater_than(max, value),
76                    ">=" => greater_or_equal(max, value),
77                    _ => true,
78                }
79            }
80            Condition::In { values, .. } => {
81                let (Some(min), Some(max)) = (&column.min, &column.max) else {
82                    return true;
83                };
84                values.iter().any(|value| in_range(value, min, max))
85            }
86            Condition::Between { low, high, .. } => {
87                let (Some(min), Some(max)) = (&column.min, &column.max) else {
88                    return true;
89                };
90                // The group could hold a value between low and high.
91                less_or_equal(low, max) && greater_or_equal(high, min)
92            }
93            Condition::And(conditions) => conditions
94                .iter()
95                .all(|condition| condition.may_match(column)),
96            Condition::Or(conditions) => conditions
97                .iter()
98                .any(|condition| condition.may_match(column)),
99            Condition::Not(condition) => condition.may_match(column),
100        }
101    }
102}
103
104/// Read a condition the way a script writes it.
105pub fn parse(value: &Value) -> Result<Condition> {
106    let object = value
107        .as_object()
108        .ok_or_else(|| anyhow!("a condition is a table"))?;
109
110    // Luau has no `and` as a table key (it is a keyword), so the scripts
111    // write `["and"]`; `all` and `any` are there for the ones that prefer them.
112    if let Some(conditions) = object.get("and").or_else(|| object.get("all")) {
113        return Ok(Condition::And(parse_all(conditions)?));
114    }
115    if let Some(conditions) = object.get("or").or_else(|| object.get("any")) {
116        return Ok(Condition::Or(parse_all(conditions)?));
117    }
118    if let Some(inner) = object.get("not") {
119        return Ok(Condition::Not(Box::new(parse(inner)?)));
120    }
121
122    let column = object
123        .get("column")
124        .and_then(Value::as_str)
125        .ok_or_else(|| anyhow!("a condition needs a column"))?
126        .to_string();
127
128    if let Some(values) = object.get("in") {
129        let values = values
130            .as_array()
131            .ok_or_else(|| anyhow!("in takes a list"))?
132            .clone();
133        return Ok(Condition::In { column, values });
134    }
135    if let Some(bounds) = object.get("between") {
136        let bounds = bounds
137            .as_array()
138            .ok_or_else(|| anyhow!("between takes a list of two"))?;
139        if bounds.len() != 2 {
140            return Err(anyhow!("between takes a list of two"));
141        }
142        return Ok(Condition::Between {
143            column,
144            low: bounds[0].clone(),
145            high: bounds[1].clone(),
146        });
147    }
148
149    let op = object
150        .get("op")
151        .and_then(Value::as_str)
152        .ok_or_else(|| anyhow!("a condition needs an op"))?
153        .to_string();
154    let value = object
155        .get("value")
156        .cloned()
157        .ok_or_else(|| anyhow!("a condition needs a value"))?;
158    Ok(Condition::Compare { column, op, value })
159}
160
161/// A list of conditions.
162fn parse_all(value: &Value) -> Result<Vec<Condition>> {
163    let list = value
164        .as_array()
165        .ok_or_else(|| anyhow!("and/or take a list of conditions"))?;
166    list.iter().map(parse).collect()
167}
168
169/// What a reader could skip, according to the file.
170#[derive(Clone, Debug)]
171pub struct Prune {
172    /// How many row groups the file has.
173    pub groups_total: usize,
174    /// How many of them cannot hold a matching row.
175    pub groups_skipped: usize,
176    /// How many of them have to be read.
177    pub groups_read: usize,
178    /// How many rows the file has.
179    pub rows_total: i64,
180    /// How many rows are in the groups that have to be read.
181    pub rows_read: i64,
182    /// How many bytes the whole file takes.
183    pub bytes_total: i64,
184    /// How many bytes the groups that have to be read take.
185    pub bytes_read: i64,
186    /// For every row group: whether it can be skipped, and why.
187    pub groups: Vec<GroupPrune>,
188}
189
190/// One row group, and what the statistics say about it.
191#[derive(Clone, Debug)]
192pub struct GroupPrune {
193    pub index: usize,
194    pub rows: i64,
195    pub bytes: i64,
196    /// Whether this group cannot hold a matching row.
197    pub skipped: bool,
198    /// Which column ruled it out.
199    pub ruled_out_by: Option<String>,
200}
201
202impl Prune {
203    pub fn to_json(&self) -> Value {
204        json!({
205            "groups_total": self.groups_total,
206            "groups_skipped": self.groups_skipped,
207            "groups_read": self.groups_read,
208            "rows_total": self.rows_total,
209            "rows_read": self.rows_read,
210            "bytes_total": self.bytes_total,
211            "bytes_read": self.bytes_read,
212            "skip_ratio": if self.groups_total > 0 {
213                self.groups_skipped as f64 / self.groups_total as f64
214            } else {
215                0.0
216            },
217            "groups": self.groups.iter().map(|group| json!({
218                "index": group.index,
219                "rows": group.rows,
220                "bytes": group.bytes,
221                "skipped": group.skipped,
222                "ruled_out_by": group.ruled_out_by,
223            })).collect::<Vec<Value>>(),
224        })
225    }
226}
227
228/// Work out what a reader could skip.
229pub fn prune(path: &Path, condition: &Condition) -> Result<Prune> {
230    let facts = meta::file_facts(path)?;
231    let columns = meta::column_facts(path, false)?;
232
233    let wanted: Vec<String> = condition.columns();
234    let mut per_column: Vec<(&String, &ColumnFacts)> = Vec::new();
235    for name in &wanted {
236        match columns.iter().find(|column| &column.name == name) {
237            Some(column) => per_column.push((name, column)),
238            None => return Err(anyhow!("the file has no column named {name}")),
239        }
240    }
241
242    let group_count = facts.row_group_rows.len();
243    let mut groups = Vec::new();
244    let mut groups_skipped = 0;
245    let mut rows_read = 0;
246    let mut bytes_read = 0;
247
248    for (index, group) in facts.row_group_rows.iter().enumerate() {
249        let bytes = facts
250            .row_group_bytes
251            .get(index)
252            .copied()
253            .unwrap_or_default();
254        let mut skipped = false;
255        let mut ruled_out_by = None;
256        for (name, column) in &per_column {
257            let group_min = column
258                .row_groups
259                .get(index)
260                .and_then(|group| group.min.as_ref());
261            let group_max = column
262                .row_groups
263                .get(index)
264                .and_then(|group| group.max.as_ref());
265            let scoped = ColumnFacts {
266                min: group_min.cloned(),
267                max: group_max.cloned(),
268                ..(*column).clone()
269            };
270            if !condition.may_match(&scoped) {
271                skipped = true;
272                ruled_out_by = Some((*name).clone());
273                break;
274            }
275        }
276        if skipped {
277            groups_skipped += 1;
278        } else {
279            rows_read += group;
280            bytes_read += bytes;
281        }
282        groups.push(GroupPrune {
283            index,
284            rows: *group,
285            bytes,
286            skipped,
287            ruled_out_by,
288        });
289    }
290
291    Ok(Prune {
292        groups_total: group_count,
293        groups_skipped,
294        groups_read: group_count - groups_skipped,
295        rows_total: facts.rows,
296        rows_read,
297        bytes_total: facts.size_bytes as i64,
298        bytes_read,
299        groups,
300    })
301}
302
303/// Is a value inside a range?
304fn in_range(value: &Value, min: &Value, max: &Value) -> bool {
305    less_or_equal(min, value) && less_or_equal(value, max)
306}
307
308/// Is the value smaller than the bound?
309fn less_than(value: &Value, bound: &Value) -> bool {
310    compare(value, bound)
311        .map(|order| order.is_lt())
312        .unwrap_or(true)
313}
314
315/// Is the value smaller than or equal to the bound?
316fn less_or_equal(value: &Value, bound: &Value) -> bool {
317    compare(value, bound)
318        .map(|order| order.is_le())
319        .unwrap_or(true)
320}
321
322/// Is the value bigger than the bound?
323fn greater_than(value: &Value, bound: &Value) -> bool {
324    compare(value, bound)
325        .map(|order| order.is_gt())
326        .unwrap_or(true)
327}
328
329/// Is the value bigger than or equal to the bound?
330fn greater_or_equal(value: &Value, bound: &Value) -> bool {
331    compare(value, bound)
332        .map(|order| order.is_ge())
333        .unwrap_or(true)
334}
335
336/// Compare two values, when they can be compared.
337fn compare(left: &Value, right: &Value) -> Option<std::cmp::Ordering> {
338    match (left, right) {
339        (Value::Number(left), Value::Number(right)) => left
340            .as_f64()
341            .zip(right.as_f64())
342            .and_then(|(left, right)| left.partial_cmp(&right)),
343        (Value::String(left), Value::String(right)) => Some(left.cmp(right)),
344        (Value::Bool(left), Value::Bool(right)) => Some(left.cmp(right)),
345        _ => None,
346    }
347}
348
349/// The condition as JSON, for printing.
350pub fn describe(condition: &Condition) -> Value {
351    match condition {
352        Condition::Compare { column, op, value } => {
353            let mut object = Map::new();
354            object.insert("column".into(), Value::String(column.clone()));
355            object.insert("op".into(), Value::String(op.clone()));
356            object.insert("value".into(), value.clone());
357            Value::Object(object)
358        }
359        Condition::In { column, values } => {
360            let mut object = Map::new();
361            object.insert("column".into(), Value::String(column.clone()));
362            object.insert("in".into(), Value::Array(values.clone()));
363            Value::Object(object)
364        }
365        Condition::Between { column, low, high } => {
366            let mut object = Map::new();
367            object.insert("column".into(), Value::String(column.clone()));
368            object.insert(
369                "between".into(),
370                Value::Array(vec![low.clone(), high.clone()]),
371            );
372            Value::Object(object)
373        }
374        Condition::And(conditions) => {
375            let mut object = Map::new();
376            object.insert(
377                "and".into(),
378                Value::Array(conditions.iter().map(describe).collect()),
379            );
380            Value::Object(object)
381        }
382        Condition::Or(conditions) => {
383            let mut object = Map::new();
384            object.insert(
385                "or".into(),
386                Value::Array(conditions.iter().map(describe).collect()),
387            );
388            Value::Object(object)
389        }
390        Condition::Not(inner) => {
391            let mut object = Map::new();
392            object.insert("not".into(), describe(inner));
393            Value::Object(object)
394        }
395    }
396}