Skip to main content

parquet_cli/
advise.rs

1//! Looking at a file's data and saying what could be better.
2//!
3//! Two layers. The cheap one reads only the footer: how big each column is,
4//! what type it was written as, how the rows are grouped. The expensive one
5//! rewrites a column with a constant in it, so the difference in size says
6//! whether the column is expensive because of its values or because of its
7//! shape.
8
9use std::fs::File;
10use std::path::Path;
11use std::sync::Arc;
12
13use anyhow::{Context, Result};
14use arrow_array::types::UInt32Type;
15use arrow_array::{ArrayRef, PrimitiveArray, RecordBatch};
16use arrow_schema::{FieldRef, Schema};
17use parquet::arrow::arrow_reader::ParquetRecordBatchReaderBuilder;
18use parquet::arrow::arrow_writer::ArrowWriter;
19use parquet::basic::{Compression, Encoding};
20use parquet::file::properties::WriterProperties;
21use parquet::schema::types::ColumnPath;
22use serde_json::{json, Map, Value};
23
24use crate::meta::{self, ColumnFacts, FileFacts};
25
26/// One thing worth knowing about the file.
27#[derive(Clone, Debug)]
28pub struct Finding {
29    /// The name of the rule.
30    pub rule: &'static str,
31    /// `warning` or `info`.
32    pub severity: &'static str,
33    /// The column it is about, when it is about one.
34    pub column: Option<String>,
35    /// What is worth doing, in one sentence.
36    pub message: String,
37    /// The numbers behind it.
38    pub numbers: Option<Value>,
39}
40
41impl Finding {
42    pub fn to_json(&self) -> Value {
43        let mut object = Map::new();
44        object.insert("rule".into(), Value::String(self.rule.into()));
45        object.insert("severity".into(), Value::String(self.severity.into()));
46        if let Some(column) = &self.column {
47            object.insert("column".into(), Value::String(column.clone()));
48        }
49        object.insert("message".into(), Value::String(self.message.clone()));
50        if let Some(numbers) = &self.numbers {
51            object.insert("numbers".into(), numbers.clone());
52        }
53        Value::Object(object)
54    }
55}
56
57/// One column, with what the advice needs to know about it.
58#[derive(Clone, Debug)]
59pub struct ColumnAdvice {
60    pub name: String,
61    pub data_type: String,
62    pub bytes: i64,
63    /// The share of the file this column takes.
64    pub share: f64,
65    /// The distinct values, when the file was read to count them.
66    pub distinct: Option<u64>,
67    /// The bytes its values take, when the contrast was run.
68    pub value_bytes: Option<i64>,
69    /// The bytes its shape takes, when the contrast was run.
70    pub structure_bytes: Option<i64>,
71}
72
73/// Everything the advice is about.
74#[derive(Clone, Debug)]
75pub struct Advice {
76    pub file: String,
77    pub size_bytes: u64,
78    pub rows: i64,
79    pub columns: Vec<ColumnAdvice>,
80    pub findings: Vec<Finding>,
81}
82
83impl Advice {
84    pub fn to_json(&self) -> Value {
85        let columns: Vec<Value> = self
86            .columns
87            .iter()
88            .map(|column| {
89                let mut object = Map::new();
90                object.insert("name".into(), Value::String(column.name.clone()));
91                object.insert("type".into(), Value::String(column.data_type.clone()));
92                object.insert("bytes".into(), json!(column.bytes));
93                object.insert("share".into(), json!(column.share));
94                if let Some(distinct) = column.distinct {
95                    object.insert("distinct".into(), json!(distinct));
96                }
97                if let Some(value_bytes) = column.value_bytes {
98                    object.insert("value_bytes".into(), json!(value_bytes));
99                }
100                if let Some(structure_bytes) = column.structure_bytes {
101                    object.insert("structure_bytes".into(), json!(structure_bytes));
102                }
103                Value::Object(object)
104            })
105            .collect();
106        json!({
107            "file": self.file,
108            "size_bytes": self.size_bytes,
109            "rows": self.rows,
110            "columns": columns,
111            "findings": self
112                .findings
113                .iter()
114                .map(|finding| finding.to_json())
115                .collect::<Vec<Value>>(),
116        })
117    }
118}
119
120/// Look at a file and say what could be better.
121///
122/// With `scan`, the file is read as well, so the advice can use the distinct
123/// values. With `contrast`, the largest columns are rewritten with a constant
124/// in them, so the advice can say whether a column is expensive because of its
125/// values or because of its shape. That costs a rewrite of the file.
126pub fn advise(path: &Path, scan: bool, contrast: Option<usize>) -> Result<Advice> {
127    let file = meta::file_facts(path)?;
128    let facts = meta::column_facts(path, scan)?;
129
130    let mut columns: Vec<ColumnAdvice> = facts
131        .iter()
132        .map(|column| ColumnAdvice {
133            name: column.name.clone(),
134            data_type: column.data_type.clone(),
135            bytes: column.compressed_size,
136            share: if file.size_bytes > 0 {
137                column.compressed_size as f64 / file.size_bytes as f64
138            } else {
139                0.0
140            },
141            distinct: column.distinct_count,
142            value_bytes: None,
143            structure_bytes: None,
144        })
145        .collect();
146
147    let mut findings = rules(&file, &facts);
148
149    if let Some(count) = contrast {
150        // The biggest columns first: they are the ones worth the rewrite.
151        let mut order: Vec<usize> = (0..columns.len()).collect();
152        order.sort_by(|left, right| columns[*right].bytes.cmp(&columns[*left].bytes));
153        let rows_per_group = if file.row_group_rows.is_empty() {
154            0
155        } else {
156            file.rows / file.row_groups as i64
157        };
158        for index in order.into_iter().take(count) {
159            let (value_bytes, structure_bytes) =
160                contrast_column(path, index, &facts[index], rows_per_group)?;
161            columns[index].value_bytes = Some(value_bytes);
162            columns[index].structure_bytes = Some(structure_bytes);
163            findings.push(value_versus_structure_finding(
164                &columns[index],
165                value_bytes,
166                structure_bytes,
167            ));
168        }
169    }
170
171    Ok(Advice {
172        file: file.path.clone(),
173        size_bytes: file.size_bytes,
174        rows: file.rows,
175        columns,
176        findings,
177    })
178}
179
180/// The rules that read only the footer.
181fn rules(file: &FileFacts, columns: &[ColumnFacts]) -> Vec<Finding> {
182    let mut findings = Vec::new();
183
184    for column in columns {
185        if let Some(finding) = type_too_wide(column) {
186            findings.push(finding);
187        }
188        if let Some(finding) = no_dictionary(column) {
189            findings.push(finding);
190        }
191        if let Some(finding) = mostly_null(column) {
192            findings.push(finding);
193        }
194        if let Some(finding) = constant_column(column) {
195            findings.push(finding);
196        }
197    }
198
199    // One column taking most of the file.
200    for column in columns {
201        if file.size_bytes == 0 {
202            break;
203        }
204        let share = column.compressed_size as f64 / file.size_bytes as f64;
205        if share > 0.4 {
206            findings.push(Finding {
207                rule: "column-dominates",
208                severity: "warning",
209                column: Some(column.name.clone()),
210                message: format!(
211                    "这一列占了全文件的 {:.1}%({} 字节)",
212                    share * 100.0,
213                    column.compressed_size
214                ),
215                numbers: Some(json!({
216                    "bytes": column.compressed_size,
217                    "share": share,
218                })),
219            });
220        }
221    }
222
223    // Row groups that are too small, and the footer they add up to.
224    if file.row_groups > 1 {
225        let average = file.rows / file.row_groups as i64;
226        if average > 0 && average < 10_000 {
227            findings.push(Finding {
228                rule: "small-row-groups",
229                severity: "warning",
230                column: None,
231                message: format!(
232                    "行组太小(平均 {average} 行,{} 个行组)⇒ 每个行组都要一份页脚记录 ⇒ 合成更大的行组",
233                    file.row_groups
234                ),
235                numbers: Some(json!({
236                    "row_groups": file.row_groups,
237                    "rows_per_group": average,
238                })),
239            });
240        }
241    }
242    if file.size_bytes > 0 {
243        let footer_share = file.footer_bytes as f64 / file.size_bytes as f64;
244        if footer_share > 0.05 {
245            findings.push(Finding {
246                rule: "footer-heavy",
247                severity: "warning",
248                column: None,
249                message: format!(
250                    "页脚占了 {:.1}%({} 字节)⇒ 列多行组多的时候,页脚自己就贵",
251                    footer_share * 100.0,
252                    file.footer_bytes
253                ),
254                numbers: Some(json!({
255                    "footer_bytes": file.footer_bytes,
256                    "footer_share": footer_share,
257                })),
258            });
259        }
260    }
261
262    findings
263}
264
265/// A type that is wider than the values need.
266fn type_too_wide(column: &ColumnFacts) -> Option<Finding> {
267    let (min, max) = (column.min.as_ref()?, column.max.as_ref()?);
268    let data_type = column.data_type.as_str();
269
270    let integral = |value: &Value| -> bool {
271        value
272            .as_f64()
273            .map(|number| number.fract() == 0.0)
274            .unwrap_or(false)
275    };
276
277    if (data_type == "float64" || data_type == "float32") && integral(min) && integral(max) {
278        return Some(Finding {
279            rule: "type-too-wide",
280            severity: "warning",
281            column: Some(column.name.clone()),
282            message: format!("这一列的值都是整数,却存成 {data_type} ⇒ 换成 BIGINT 少一半"),
283            numbers: Some(json!({
284                "type": data_type,
285                "min": min,
286                "max": max,
287            })),
288        });
289    }
290
291    if data_type == "int64" || data_type == "uint64" {
292        let fits = |value: &Value| {
293            value
294                .as_i64()
295                .map(|number| i32::try_from(number).is_ok())
296                .unwrap_or(false)
297        };
298        if fits(min) && fits(max) {
299            return Some(Finding {
300                rule: "type-too-wide",
301                severity: "warning",
302                column: Some(column.name.clone()),
303                message: "值域装得下 int32,却存成 int64 ⇒ 换成 int32 少一半".into(),
304                numbers: Some(json!({
305                    "type": data_type,
306                    "min": min,
307                    "max": max,
308                })),
309            });
310        }
311    }
312
313    if let Some((precision, scale)) = decimal_shape(data_type) {
314        if scale == 0 {
315            return Some(Finding {
316                rule: "type-too-wide",
317                severity: "warning",
318                column: Some(column.name.clone()),
319                message: format!("小数位是 0(decimal128({precision},0))⇒ 换成 BIGINT 少一半"),
320                numbers: Some(json!({
321                    "type": data_type,
322                    "precision": precision,
323                    "scale": scale,
324                })),
325            });
326        }
327        if precision > 18 {
328            return Some(Finding {
329                rule: "type-too-wide",
330                severity: "warning",
331                column: Some(column.name.clone()),
332                message: format!("精度 {precision} > 18 ⇒ 一个值 16 字节;用得着那么多位吗"),
333                numbers: Some(json!({
334                    "type": data_type,
335                    "precision": precision,
336                    "scale": scale,
337                })),
338            });
339        }
340    }
341
342    None
343}
344
345/// The precision and scale of a decimal type, when it is one.
346fn decimal_shape(data_type: &str) -> Option<(u32, u32)> {
347    let rest = data_type
348        .strip_prefix("decimal128(")
349        .or_else(|| data_type.strip_prefix("decimal256("))?;
350    let rest = rest.strip_suffix(')')?;
351    let (precision, scale) = rest.split_once(',')?;
352    Some((precision.parse().ok()?, scale.parse().ok()?))
353}
354
355/// A string column whose values repeat but that was written without a
356/// dictionary.
357fn no_dictionary(column: &ColumnFacts) -> Option<Finding> {
358    let data_type = column.data_type.as_str();
359    if !matches!(data_type, "utf8" | "large_utf8" | "binary" | "large_binary") {
360        return None;
361    }
362    let has_dictionary = column
363        .encodings
364        .iter()
365        .any(|encoding| encoding.contains("DICTIONARY"));
366    if has_dictionary {
367        return None;
368    }
369    let distinct = column.distinct_count?;
370    if distinct == 0 || column.num_values == 0 {
371        return None;
372    }
373    let repeat = column.num_values as f64 / distinct as f64;
374    if repeat < 4.0 {
375        return None;
376    }
377    Some(Finding {
378        rule: "no-dictionary",
379        severity: "warning",
380        column: Some(column.name.clone()),
381        message: format!(
382            "值只有 {distinct} 种(每个值平均重复 {repeat:.1} 次),却写成 PLAIN 没有字典"
383        ),
384        numbers: Some(json!({
385            "distinct": distinct,
386            "values": column.num_values,
387            "encodings": column.encodings,
388        })),
389    })
390}
391
392/// A column that is mostly empty.
393fn mostly_null(column: &ColumnFacts) -> Option<Finding> {
394    if column.num_values == 0 {
395        return None;
396    }
397    let share = column.null_count as f64 / column.num_values as f64;
398    if share < 0.8 {
399        return None;
400    }
401    Some(Finding {
402        rule: "mostly-null",
403        severity: "info",
404        column: Some(column.name.clone()),
405        message: format!("这一列 {:.0}% 是空的", share * 100.0),
406        numbers: Some(json!({
407            "null_count": column.null_count,
408            "values": column.num_values,
409        })),
410    })
411}
412
413/// A column whose values are all the same.
414fn constant_column(column: &ColumnFacts) -> Option<Finding> {
415    let min = column.min.as_ref()?;
416    let max = column.max.as_ref()?;
417    if min != max {
418        return None;
419    }
420    Some(Finding {
421        rule: "constant-column",
422        severity: "info",
423        column: Some(column.name.clone()),
424        message: format!(
425            "这一列的值都一样 ⇒ 它的 {} 字节几乎全是结构(每行组的字典与页头)",
426            column.compressed_size
427        ),
428        numbers: Some(json!({
429            "value": min,
430            "bytes": column.compressed_size,
431        })),
432    })
433}
434
435/// Rewrite one column with a constant in it, and see what the difference is.
436///
437/// The column is written twice: once as it is, once with every value replaced
438/// by the first one. The difference is what the values cost; what is left is
439/// what the column's shape costs.
440fn contrast_column(
441    path: &Path,
442    index: usize,
443    column: &ColumnFacts,
444    rows_per_group: i64,
445) -> Result<(i64, i64)> {
446    let as_is = write_column(path, index, column, false, rows_per_group)?;
447    let constant = write_column(path, index, column, true, rows_per_group)?;
448    Ok((as_is - constant, constant))
449}
450
451/// What the contrast says about one column.
452fn value_versus_structure_finding(
453    column: &ColumnAdvice,
454    value_bytes: i64,
455    structure_bytes: i64,
456) -> Finding {
457    let total = value_bytes + structure_bytes;
458    let share = if total > 0 {
459        value_bytes as f64 / total as f64
460    } else {
461        0.0
462    };
463    Finding {
464        rule: "value-vs-structure",
465        severity: "info",
466        column: Some(column.name.clone()),
467        message: format!(
468            "值占 {value_bytes}({:.0}%),结构占 {structure_bytes} —— 把这一列单独重写一遍量出来的(同样的压缩器与行组大小)",
469            share * 100.0
470        ),
471        numbers: Some(json!({
472            "value_bytes": value_bytes,
473            "structure_bytes": structure_bytes,
474            "total_bytes": total,
475        })),
476    }
477}
478
479/// Write one column of a file out as its own Parquet file.
480fn write_column(
481    path: &Path,
482    index: usize,
483    column: &ColumnFacts,
484    constant: bool,
485    rows_per_group: i64,
486) -> Result<i64> {
487    let file = File::open(path).with_context(|| format!("open {}", path.display()))?;
488    let builder = ParquetRecordBatchReaderBuilder::try_new(file)
489        .with_context(|| format!("read the footer of {}", path.display()))?;
490    let schema = builder.schema().clone();
491    let field: FieldRef = schema.fields()[index].clone();
492
493    let single = Schema::new(vec![field.clone()]);
494    let mut properties_builder = WriterProperties::builder()
495        .set_compression(compression_of(&column.compression))
496        // The same row group size as the file has, so the two sides of the
497        // contrast differ only in the values.
498        .set_max_row_group_row_count(Some(rows_per_group.max(1) as usize));
499    if column
500        .encodings
501        .iter()
502        .any(|encoding| encoding.contains("DELTA"))
503    {
504        properties_builder = properties_builder.set_column_encoding(
505            ColumnPath::from(field.name().clone()),
506            Encoding::DELTA_BINARY_PACKED,
507        );
508    }
509    // A writer that did not use a dictionary for this column (its values are
510    // too varied for one to pay off) is matched by writing without one too.
511    if !column
512        .encodings
513        .iter()
514        .any(|encoding| encoding.contains("DICTIONARY"))
515    {
516        properties_builder = properties_builder.set_dictionary_enabled(false);
517    }
518    let properties = properties_builder.build();
519
520    let target = temporary_path(&column.name.replace(['.', '/'], "_"));
521    let output = File::create(&target).with_context(|| format!("create {}", target.display()))?;
522    let mut writer = ArrowWriter::try_new(output, Arc::new(single.clone()), Some(properties))
523        .context("open the writer")?;
524
525    let reader = builder.build()?;
526    for batch in reader {
527        let batch = batch?;
528        let values = batch.column(index).clone();
529        let values = if constant {
530            constantize(&values)?
531        } else {
532            values
533        };
534        let batch = RecordBatch::try_new(Arc::new(single.clone()), vec![values])
535            .context("build the batch")?;
536        writer.write(&batch)?;
537    }
538    writer.close()?;
539
540    let size = std::fs::metadata(&target)?.len() as i64;
541    let _ = std::fs::remove_file(&target);
542    Ok(size)
543}
544
545/// A copy of a column where every value is the first one.
546fn constantize(values: &ArrayRef) -> Result<ArrayRef> {
547    let indices = PrimitiveArray::<UInt32Type>::from(vec![0u32; values.len()]);
548    arrow_select::take::take(&**values, &indices, None).context("make the constant column")
549}
550
551/// The compression to write with.
552fn compression_of(name: &str) -> Compression {
553    match name {
554        "SNAPPY" => Compression::SNAPPY,
555        "GZIP" => Compression::GZIP(Default::default()),
556        "BROTLI" => Compression::BROTLI(Default::default()),
557        "LZ4_RAW" => Compression::LZ4_RAW,
558        "LZ4" => Compression::LZ4,
559        "ZSTD" => Compression::ZSTD(Default::default()),
560        _ => Compression::UNCOMPRESSED,
561    }
562}
563
564/// A temporary file name for the contrast.
565fn temporary_path(name: &str) -> std::path::PathBuf {
566    let stamp = std::time::SystemTime::now()
567        .duration_since(std::time::UNIX_EPOCH)
568        .map(|since| since.as_nanos())
569        .unwrap_or(0);
570    std::env::temp_dir().join(format!("pqt-contrast-{name}-{stamp}.parquet"))
571}