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/// A column whose row groups all cover the same ground.
181///
182/// When the rows are in order, each row group's min and max say something and
183/// a reader can skip the groups it does not need. When they are not, every
184/// group covers the whole range and nothing can be skipped.
185fn not_sorted(column: &ColumnFacts) -> Option<Finding> {
186    let groups = &column.row_groups;
187    if groups.len() < 3 {
188        return None;
189    }
190    let mut overlapping = 0;
191    for pair in groups.windows(2) {
192        let (Some(first_min), Some(first_max), Some(second_min), Some(second_max)) =
193            (&pair[0].min, &pair[0].max, &pair[1].min, &pair[1].max)
194        else {
195            continue;
196        };
197        if overlaps(first_min, first_max, second_min, second_max) {
198            overlapping += 1;
199        }
200    }
201    let count = groups.len();
202    if overlapping * 2 <= count {
203        return None;
204    }
205    Some(Finding {
206        rule: "not-sorted",
207        severity: "warning",
208        column: Some(column.name.clone()),
209        message: format!(
210            "这一列的行组区间互相重叠({overlapping}/{count})⇒ 带谓词的查找读不了几个行组;按它排序再写,剪枝才用得上"
211        ),
212        numbers: Some(json!({
213            "overlapping_groups": overlapping,
214            "groups": count,
215        })),
216    })
217}
218
219/// Whether two ranges share any ground.
220fn overlaps(first_min: &Value, first_max: &Value, second_min: &Value, second_max: &Value) -> bool {
221    // Each range has to be in order, and the two must share ground.
222    let (Some(first_ordered), Some(second_ordered)) = (
223        compare(first_min, first_max).map(|order| order.is_le()),
224        compare(second_min, second_max).map(|order| order.is_le()),
225    ) else {
226        return false;
227    };
228    if !first_ordered || !second_ordered {
229        return false;
230    }
231    let first_before_second = compare(first_min, second_max)
232        .map(|order| order.is_le())
233        .unwrap_or(false);
234    let second_before_first = compare(second_min, first_max)
235        .map(|order| order.is_le())
236        .unwrap_or(false);
237    first_before_second && second_before_first
238}
239
240/// Compare two values, when they can be compared.
241fn compare(left: &Value, right: &Value) -> Option<std::cmp::Ordering> {
242    match (left, right) {
243        (Value::Number(left), Value::Number(right)) => left
244            .as_f64()
245            .zip(right.as_f64())
246            .and_then(|(left, right)| left.partial_cmp(&right)),
247        (Value::String(left), Value::String(right)) => Some(left.cmp(right)),
248        _ => None,
249    }
250}
251
252/// The rules that read only the footer.
253fn rules(file: &FileFacts, columns: &[ColumnFacts]) -> Vec<Finding> {
254    let mut findings = Vec::new();
255
256    for column in columns {
257        if let Some(finding) = type_too_wide(column) {
258            findings.push(finding);
259        }
260        if let Some(finding) = no_dictionary(column) {
261            findings.push(finding);
262        }
263        if let Some(finding) = mostly_null(column) {
264            findings.push(finding);
265        }
266        if let Some(finding) = constant_column(column) {
267            findings.push(finding);
268        }
269        if let Some(finding) = not_sorted(column) {
270            findings.push(finding);
271        }
272    }
273
274    // One column taking most of the file.
275    for column in columns {
276        if file.size_bytes == 0 {
277            break;
278        }
279        let share = column.compressed_size as f64 / file.size_bytes as f64;
280        if share > 0.4 {
281            findings.push(Finding {
282                rule: "column-dominates",
283                severity: "warning",
284                column: Some(column.name.clone()),
285                message: format!(
286                    "这一列占了全文件的 {:.1}%({} 字节)",
287                    share * 100.0,
288                    column.compressed_size
289                ),
290                numbers: Some(json!({
291                    "bytes": column.compressed_size,
292                    "share": share,
293                })),
294            });
295        }
296    }
297
298    // Row groups that are too small, and the footer they add up to.
299    if file.row_groups > 1 {
300        let average = file.rows / file.row_groups as i64;
301        if average > 0 && average < 10_000 {
302            findings.push(Finding {
303                rule: "small-row-groups",
304                severity: "warning",
305                column: None,
306                message: format!(
307                    "行组太小(平均 {average} 行,{} 个行组)⇒ 每个行组都要一份页脚记录 ⇒ 合成更大的行组",
308                    file.row_groups
309                ),
310                numbers: Some(json!({
311                    "row_groups": file.row_groups,
312                    "rows_per_group": average,
313                })),
314            });
315        }
316    }
317    if file.size_bytes > 0 {
318        let footer_share = file.footer_bytes as f64 / file.size_bytes as f64;
319        if footer_share > 0.05 {
320            findings.push(Finding {
321                rule: "footer-heavy",
322                severity: "warning",
323                column: None,
324                message: format!(
325                    "页脚占了 {:.1}%({} 字节)⇒ 列多行组多的时候,页脚自己就贵",
326                    footer_share * 100.0,
327                    file.footer_bytes
328                ),
329                numbers: Some(json!({
330                    "footer_bytes": file.footer_bytes,
331                    "footer_share": footer_share,
332                })),
333            });
334        }
335    }
336
337    findings
338}
339
340/// A type that is wider than the values need.
341fn type_too_wide(column: &ColumnFacts) -> Option<Finding> {
342    let (min, max) = (column.min.as_ref()?, column.max.as_ref()?);
343    let data_type = column.data_type.as_str();
344
345    let integral = |value: &Value| -> bool {
346        value
347            .as_f64()
348            .map(|number| number.fract() == 0.0)
349            .unwrap_or(false)
350    };
351
352    if (data_type == "float64" || data_type == "float32") && integral(min) && integral(max) {
353        return Some(Finding {
354            rule: "type-too-wide",
355            severity: "warning",
356            column: Some(column.name.clone()),
357            message: format!("这一列的值都是整数,却存成 {data_type} ⇒ 换成 BIGINT 少一半"),
358            numbers: Some(json!({
359                "type": data_type,
360                "min": min,
361                "max": max,
362            })),
363        });
364    }
365
366    if data_type == "int64" || data_type == "uint64" {
367        let fits = |value: &Value| {
368            value
369                .as_i64()
370                .map(|number| i32::try_from(number).is_ok())
371                .unwrap_or(false)
372        };
373        if fits(min) && fits(max) {
374            return Some(Finding {
375                rule: "type-too-wide",
376                severity: "warning",
377                column: Some(column.name.clone()),
378                message: "值域装得下 int32,却存成 int64 ⇒ 换成 int32 少一半".into(),
379                numbers: Some(json!({
380                    "type": data_type,
381                    "min": min,
382                    "max": max,
383                })),
384            });
385        }
386    }
387
388    if let Some((precision, scale)) = decimal_shape(data_type) {
389        if scale == 0 {
390            return Some(Finding {
391                rule: "type-too-wide",
392                severity: "warning",
393                column: Some(column.name.clone()),
394                message: format!("小数位是 0(decimal128({precision},0))⇒ 换成 BIGINT 少一半"),
395                numbers: Some(json!({
396                    "type": data_type,
397                    "precision": precision,
398                    "scale": scale,
399                })),
400            });
401        }
402        if precision > 18 {
403            return Some(Finding {
404                rule: "type-too-wide",
405                severity: "warning",
406                column: Some(column.name.clone()),
407                message: format!("精度 {precision} > 18 ⇒ 一个值 16 字节;用得着那么多位吗"),
408                numbers: Some(json!({
409                    "type": data_type,
410                    "precision": precision,
411                    "scale": scale,
412                })),
413            });
414        }
415    }
416
417    None
418}
419
420/// The precision and scale of a decimal type, when it is one.
421fn decimal_shape(data_type: &str) -> Option<(u32, u32)> {
422    let rest = data_type
423        .strip_prefix("decimal128(")
424        .or_else(|| data_type.strip_prefix("decimal256("))?;
425    let rest = rest.strip_suffix(')')?;
426    let (precision, scale) = rest.split_once(',')?;
427    Some((precision.parse().ok()?, scale.parse().ok()?))
428}
429
430/// A string column whose values repeat but that was written without a
431/// dictionary.
432fn no_dictionary(column: &ColumnFacts) -> Option<Finding> {
433    let data_type = column.data_type.as_str();
434    if !matches!(data_type, "utf8" | "large_utf8" | "binary" | "large_binary") {
435        return None;
436    }
437    let has_dictionary = column
438        .encodings
439        .iter()
440        .any(|encoding| encoding.contains("DICTIONARY"));
441    if has_dictionary {
442        return None;
443    }
444    let distinct = column.distinct_count?;
445    if distinct == 0 || column.num_values == 0 {
446        return None;
447    }
448    let repeat = column.num_values as f64 / distinct as f64;
449    if repeat < 4.0 {
450        return None;
451    }
452    Some(Finding {
453        rule: "no-dictionary",
454        severity: "warning",
455        column: Some(column.name.clone()),
456        message: format!(
457            "值只有 {distinct} 种(每个值平均重复 {repeat:.1} 次),却写成 PLAIN 没有字典"
458        ),
459        numbers: Some(json!({
460            "distinct": distinct,
461            "values": column.num_values,
462            "encodings": column.encodings,
463        })),
464    })
465}
466
467/// A column that is mostly empty.
468fn mostly_null(column: &ColumnFacts) -> Option<Finding> {
469    if column.num_values == 0 {
470        return None;
471    }
472    let share = column.null_count as f64 / column.num_values as f64;
473    if share < 0.8 {
474        return None;
475    }
476    Some(Finding {
477        rule: "mostly-null",
478        severity: "info",
479        column: Some(column.name.clone()),
480        message: format!("这一列 {:.0}% 是空的", share * 100.0),
481        numbers: Some(json!({
482            "null_count": column.null_count,
483            "values": column.num_values,
484        })),
485    })
486}
487
488/// A column whose values are all the same.
489fn constant_column(column: &ColumnFacts) -> Option<Finding> {
490    let min = column.min.as_ref()?;
491    let max = column.max.as_ref()?;
492    if min != max {
493        return None;
494    }
495    Some(Finding {
496        rule: "constant-column",
497        severity: "info",
498        column: Some(column.name.clone()),
499        message: format!(
500            "这一列的值都一样 ⇒ 它的 {} 字节几乎全是结构(每行组的字典与页头)",
501            column.compressed_size
502        ),
503        numbers: Some(json!({
504            "value": min,
505            "bytes": column.compressed_size,
506        })),
507    })
508}
509
510/// Rewrite one column with a constant in it, and see what the difference is.
511///
512/// The column is written twice: once as it is, once with every value replaced
513/// by the first one. The difference is what the values cost; what is left is
514/// what the column's shape costs.
515fn contrast_column(
516    path: &Path,
517    index: usize,
518    column: &ColumnFacts,
519    rows_per_group: i64,
520) -> Result<(i64, i64)> {
521    let as_is = write_column(path, index, column, false, rows_per_group)?;
522    let constant = write_column(path, index, column, true, rows_per_group)?;
523    Ok((as_is - constant, constant))
524}
525
526/// What the contrast says about one column.
527fn value_versus_structure_finding(
528    column: &ColumnAdvice,
529    value_bytes: i64,
530    structure_bytes: i64,
531) -> Finding {
532    let total = value_bytes + structure_bytes;
533    let share = if total > 0 {
534        value_bytes as f64 / total as f64
535    } else {
536        0.0
537    };
538    Finding {
539        rule: "value-vs-structure",
540        severity: "info",
541        column: Some(column.name.clone()),
542        message: format!(
543            "值占 {value_bytes}({:.0}%),结构占 {structure_bytes} —— 把这一列单独重写一遍量出来的(同样的压缩器与行组大小)",
544            share * 100.0
545        ),
546        numbers: Some(json!({
547            "value_bytes": value_bytes,
548            "structure_bytes": structure_bytes,
549            "total_bytes": total,
550        })),
551    }
552}
553
554/// Write one column of a file out as its own Parquet file.
555fn write_column(
556    path: &Path,
557    index: usize,
558    column: &ColumnFacts,
559    constant: bool,
560    rows_per_group: i64,
561) -> Result<i64> {
562    let file = File::open(path).with_context(|| format!("open {}", path.display()))?;
563    let builder = ParquetRecordBatchReaderBuilder::try_new(file)
564        .with_context(|| format!("read the footer of {}", path.display()))?;
565    let schema = builder.schema().clone();
566    let field: FieldRef = schema.fields()[index].clone();
567
568    let single = Schema::new(vec![field.clone()]);
569    let mut properties_builder = WriterProperties::builder()
570        .set_compression(compression_of(&column.compression))
571        // The same row group size as the file has, so the two sides of the
572        // contrast differ only in the values.
573        .set_max_row_group_row_count(Some(rows_per_group.max(1) as usize));
574    if column
575        .encodings
576        .iter()
577        .any(|encoding| encoding.contains("DELTA"))
578    {
579        properties_builder = properties_builder.set_column_encoding(
580            ColumnPath::from(field.name().clone()),
581            Encoding::DELTA_BINARY_PACKED,
582        );
583    }
584    // A writer that did not use a dictionary for this column (its values are
585    // too varied for one to pay off) is matched by writing without one too.
586    if !column
587        .encodings
588        .iter()
589        .any(|encoding| encoding.contains("DICTIONARY"))
590    {
591        properties_builder = properties_builder.set_dictionary_enabled(false);
592    }
593    let properties = properties_builder.build();
594
595    let target = temporary_path(&column.name.replace(['.', '/'], "_"));
596    let output = File::create(&target).with_context(|| format!("create {}", target.display()))?;
597    let mut writer = ArrowWriter::try_new(output, Arc::new(single.clone()), Some(properties))
598        .context("open the writer")?;
599
600    let reader = builder.build()?;
601    for batch in reader {
602        let batch = batch?;
603        let values = batch.column(index).clone();
604        let values = if constant {
605            constantize(&values)?
606        } else {
607            values
608        };
609        let batch = RecordBatch::try_new(Arc::new(single.clone()), vec![values])
610            .context("build the batch")?;
611        writer.write(&batch)?;
612    }
613    writer.close()?;
614
615    let size = std::fs::metadata(&target)?.len() as i64;
616    let _ = std::fs::remove_file(&target);
617    Ok(size)
618}
619
620/// A copy of a column where every value is the first one.
621fn constantize(values: &ArrayRef) -> Result<ArrayRef> {
622    let indices = PrimitiveArray::<UInt32Type>::from(vec![0u32; values.len()]);
623    arrow_select::take::take(&**values, &indices, None).context("make the constant column")
624}
625
626/// The compression to write with.
627fn compression_of(name: &str) -> Compression {
628    match name {
629        "SNAPPY" => Compression::SNAPPY,
630        "GZIP" => Compression::GZIP(Default::default()),
631        "BROTLI" => Compression::BROTLI(Default::default()),
632        "LZ4_RAW" => Compression::LZ4_RAW,
633        "LZ4" => Compression::LZ4,
634        "ZSTD" => Compression::ZSTD(Default::default()),
635        _ => Compression::UNCOMPRESSED,
636    }
637}
638
639/// A temporary file name for the contrast.
640fn temporary_path(name: &str) -> std::path::PathBuf {
641    let stamp = std::time::SystemTime::now()
642        .duration_since(std::time::UNIX_EPOCH)
643        .map(|since| since.as_nanos())
644        .unwrap_or(0);
645    std::env::temp_dir().join(format!("pqt-contrast-{name}-{stamp}.parquet"))
646}