Skip to main content

parquet_cli/
validate.rs

1//! Checking that a Parquet file is sound.
2//!
3//! The checks read the footer and compare it with the file's own bytes: the
4//! row counts have to add up, the column chunks have to fit inside the file,
5//! and they must not overlap.
6
7use std::path::Path;
8
9use anyhow::Result;
10use serde_json::{json, Value};
11
12use crate::meta::open;
13
14/// One check and what it found.
15struct Check {
16    name: &'static str,
17    ok: bool,
18    detail: String,
19}
20
21/// Run every check against a file.
22pub fn validate(path: &Path) -> Result<Value> {
23    let metadata = open(path)?;
24    let file_size = std::fs::metadata(path)?.len();
25    let file = metadata.file_metadata();
26    let mut checks = Vec::new();
27
28    let rows_in_groups: i64 = metadata.row_groups().iter().map(|g| g.num_rows()).sum();
29    checks.push(Check {
30        name: "row-count",
31        ok: rows_in_groups == file.num_rows(),
32        detail: format!(
33            "the footer says {} rows, the row groups hold {rows_in_groups}",
34            file.num_rows()
35        ),
36    });
37
38    let mut values_in_groups: i64 = 0;
39    let mut group_rows_mismatch = Vec::new();
40    for (index, group) in metadata.row_groups().iter().enumerate() {
41        let first = group.columns().first().map(|c| c.num_values()).unwrap_or(0);
42        if group.columns().iter().any(|c| c.num_values() != first) {
43            group_rows_mismatch.push(index);
44        }
45        values_in_groups += first;
46    }
47    checks.push(Check {
48        name: "column-counts",
49        ok: group_rows_mismatch.is_empty(),
50        detail: if group_rows_mismatch.is_empty() {
51            format!(
52                "every column of a row group holds the same number of values ({values_in_groups})"
53            )
54        } else {
55            format!(
56                "these row groups have columns with different value counts: {group_rows_mismatch:?}"
57            )
58        },
59    });
60
61    let mut chunks: Vec<(u64, u64)> = Vec::new();
62    let mut out_of_bounds = Vec::new();
63    for group in metadata.row_groups() {
64        for chunk in group.columns() {
65            let (start, length) = chunk.byte_range();
66            let end = start.saturating_add(length);
67            if end > file_size {
68                out_of_bounds.push(chunk.column_path().string());
69            }
70            chunks.push((start, end));
71        }
72    }
73    checks.push(Check {
74        name: "within-file",
75        ok: out_of_bounds.is_empty(),
76        detail: if out_of_bounds.is_empty() {
77            format!("every column chunk fits inside the file ({file_size} bytes)")
78        } else {
79            format!("these column chunks point past the end of the file: {out_of_bounds:?}")
80        },
81    });
82
83    chunks.sort_unstable();
84    let mut overlapping = Vec::new();
85    for pair in chunks.windows(2) {
86        if pair[0].1 > pair[1].0 {
87            overlapping.push(format!("{} and {}", pair[0].1, pair[1].0));
88        }
89    }
90    checks.push(Check {
91        name: "no-overlap",
92        ok: overlapping.is_empty(),
93        detail: if overlapping.is_empty() {
94            "no two column chunks share bytes".to_string()
95        } else {
96            format!("{} overlapping byte ranges", overlapping.len())
97        },
98    });
99
100    let compressed: i64 = metadata
101        .row_groups()
102        .iter()
103        .flat_map(|group| group.columns().iter())
104        .map(|chunk| chunk.compressed_size())
105        .sum();
106    let footer_share = if file_size > 0 {
107        compressed as f64 / file_size as f64
108    } else {
109        0.0
110    };
111    checks.push(Check {
112        name: "sizes",
113        ok: compressed as u64 <= file_size,
114        detail: format!(
115            "the column chunks hold {compressed} bytes of the {file_size} byte file ({:.1}% of it, the rest is the footer)",
116            footer_share * 100.0
117        ),
118    });
119
120    let ok = checks.iter().all(|check| check.ok);
121    Ok(json!({
122        "file": path.display().to_string(),
123        "ok": ok,
124        "checks": checks
125            .iter()
126            .map(|check| json!({
127                "name": check.name,
128                "ok": check.ok,
129                "detail": check.detail,
130            }))
131            .collect::<Vec<Value>>(),
132    }))
133}