use std::fs::File;
use std::path::Path;
use std::sync::Arc;
use anyhow::{Context, Result};
use arrow_array::types::UInt32Type;
use arrow_array::{ArrayRef, PrimitiveArray, RecordBatch};
use arrow_schema::{FieldRef, Schema};
use parquet::arrow::arrow_reader::ParquetRecordBatchReaderBuilder;
use parquet::arrow::arrow_writer::ArrowWriter;
use parquet::basic::{Compression, Encoding};
use parquet::file::properties::WriterProperties;
use parquet::schema::types::ColumnPath;
use serde_json::{json, Map, Value};
use crate::meta::{self, ColumnFacts, FileFacts};
#[derive(Clone, Debug)]
pub struct Finding {
pub rule: &'static str,
pub severity: &'static str,
pub column: Option<String>,
pub message: String,
pub numbers: Option<Value>,
}
impl Finding {
pub fn to_json(&self) -> Value {
let mut object = Map::new();
object.insert("rule".into(), Value::String(self.rule.into()));
object.insert("severity".into(), Value::String(self.severity.into()));
if let Some(column) = &self.column {
object.insert("column".into(), Value::String(column.clone()));
}
object.insert("message".into(), Value::String(self.message.clone()));
if let Some(numbers) = &self.numbers {
object.insert("numbers".into(), numbers.clone());
}
Value::Object(object)
}
}
#[derive(Clone, Debug)]
pub struct ColumnAdvice {
pub name: String,
pub data_type: String,
pub bytes: i64,
pub share: f64,
pub distinct: Option<u64>,
pub value_bytes: Option<i64>,
pub structure_bytes: Option<i64>,
}
#[derive(Clone, Debug)]
pub struct Advice {
pub file: String,
pub size_bytes: u64,
pub rows: i64,
pub columns: Vec<ColumnAdvice>,
pub findings: Vec<Finding>,
}
impl Advice {
pub fn to_json(&self) -> Value {
let columns: Vec<Value> = self
.columns
.iter()
.map(|column| {
let mut object = Map::new();
object.insert("name".into(), Value::String(column.name.clone()));
object.insert("type".into(), Value::String(column.data_type.clone()));
object.insert("bytes".into(), json!(column.bytes));
object.insert("share".into(), json!(column.share));
if let Some(distinct) = column.distinct {
object.insert("distinct".into(), json!(distinct));
}
if let Some(value_bytes) = column.value_bytes {
object.insert("value_bytes".into(), json!(value_bytes));
}
if let Some(structure_bytes) = column.structure_bytes {
object.insert("structure_bytes".into(), json!(structure_bytes));
}
Value::Object(object)
})
.collect();
json!({
"file": self.file,
"size_bytes": self.size_bytes,
"rows": self.rows,
"columns": columns,
"findings": self
.findings
.iter()
.map(|finding| finding.to_json())
.collect::<Vec<Value>>(),
})
}
}
pub fn advise(path: &Path, scan: bool, contrast: Option<usize>) -> Result<Advice> {
let file = meta::file_facts(path)?;
let facts = meta::column_facts(path, scan)?;
let mut columns: Vec<ColumnAdvice> = facts
.iter()
.map(|column| ColumnAdvice {
name: column.name.clone(),
data_type: column.data_type.clone(),
bytes: column.compressed_size,
share: if file.size_bytes > 0 {
column.compressed_size as f64 / file.size_bytes as f64
} else {
0.0
},
distinct: column.distinct_count,
value_bytes: None,
structure_bytes: None,
})
.collect();
let mut findings = rules(&file, &facts);
if let Some(count) = contrast {
let mut order: Vec<usize> = (0..columns.len()).collect();
order.sort_by(|left, right| columns[*right].bytes.cmp(&columns[*left].bytes));
let rows_per_group = if file.row_group_rows.is_empty() {
0
} else {
file.rows / file.row_groups as i64
};
for index in order.into_iter().take(count) {
let (value_bytes, structure_bytes) =
contrast_column(path, index, &facts[index], rows_per_group)?;
columns[index].value_bytes = Some(value_bytes);
columns[index].structure_bytes = Some(structure_bytes);
findings.push(value_versus_structure_finding(
&columns[index],
value_bytes,
structure_bytes,
));
}
}
Ok(Advice {
file: file.path.clone(),
size_bytes: file.size_bytes,
rows: file.rows,
columns,
findings,
})
}
fn rules(file: &FileFacts, columns: &[ColumnFacts]) -> Vec<Finding> {
let mut findings = Vec::new();
for column in columns {
if let Some(finding) = type_too_wide(column) {
findings.push(finding);
}
if let Some(finding) = no_dictionary(column) {
findings.push(finding);
}
if let Some(finding) = mostly_null(column) {
findings.push(finding);
}
if let Some(finding) = constant_column(column) {
findings.push(finding);
}
}
for column in columns {
if file.size_bytes == 0 {
break;
}
let share = column.compressed_size as f64 / file.size_bytes as f64;
if share > 0.4 {
findings.push(Finding {
rule: "column-dominates",
severity: "warning",
column: Some(column.name.clone()),
message: format!(
"这一列占了全文件的 {:.1}%({} 字节)",
share * 100.0,
column.compressed_size
),
numbers: Some(json!({
"bytes": column.compressed_size,
"share": share,
})),
});
}
}
if file.row_groups > 1 {
let average = file.rows / file.row_groups as i64;
if average > 0 && average < 10_000 {
findings.push(Finding {
rule: "small-row-groups",
severity: "warning",
column: None,
message: format!(
"行组太小(平均 {average} 行,{} 个行组)⇒ 每个行组都要一份页脚记录 ⇒ 合成更大的行组",
file.row_groups
),
numbers: Some(json!({
"row_groups": file.row_groups,
"rows_per_group": average,
})),
});
}
}
if file.size_bytes > 0 {
let footer_share = file.footer_bytes as f64 / file.size_bytes as f64;
if footer_share > 0.05 {
findings.push(Finding {
rule: "footer-heavy",
severity: "warning",
column: None,
message: format!(
"页脚占了 {:.1}%({} 字节)⇒ 列多行组多的时候,页脚自己就贵",
footer_share * 100.0,
file.footer_bytes
),
numbers: Some(json!({
"footer_bytes": file.footer_bytes,
"footer_share": footer_share,
})),
});
}
}
findings
}
fn type_too_wide(column: &ColumnFacts) -> Option<Finding> {
let (min, max) = (column.min.as_ref()?, column.max.as_ref()?);
let data_type = column.data_type.as_str();
let integral = |value: &Value| -> bool {
value
.as_f64()
.map(|number| number.fract() == 0.0)
.unwrap_or(false)
};
if (data_type == "float64" || data_type == "float32") && integral(min) && integral(max) {
return Some(Finding {
rule: "type-too-wide",
severity: "warning",
column: Some(column.name.clone()),
message: format!("这一列的值都是整数,却存成 {data_type} ⇒ 换成 BIGINT 少一半"),
numbers: Some(json!({
"type": data_type,
"min": min,
"max": max,
})),
});
}
if data_type == "int64" || data_type == "uint64" {
let fits = |value: &Value| {
value
.as_i64()
.map(|number| i32::try_from(number).is_ok())
.unwrap_or(false)
};
if fits(min) && fits(max) {
return Some(Finding {
rule: "type-too-wide",
severity: "warning",
column: Some(column.name.clone()),
message: "值域装得下 int32,却存成 int64 ⇒ 换成 int32 少一半".into(),
numbers: Some(json!({
"type": data_type,
"min": min,
"max": max,
})),
});
}
}
if let Some((precision, scale)) = decimal_shape(data_type) {
if scale == 0 {
return Some(Finding {
rule: "type-too-wide",
severity: "warning",
column: Some(column.name.clone()),
message: format!("小数位是 0(decimal128({precision},0))⇒ 换成 BIGINT 少一半"),
numbers: Some(json!({
"type": data_type,
"precision": precision,
"scale": scale,
})),
});
}
if precision > 18 {
return Some(Finding {
rule: "type-too-wide",
severity: "warning",
column: Some(column.name.clone()),
message: format!("精度 {precision} > 18 ⇒ 一个值 16 字节;用得着那么多位吗"),
numbers: Some(json!({
"type": data_type,
"precision": precision,
"scale": scale,
})),
});
}
}
None
}
fn decimal_shape(data_type: &str) -> Option<(u32, u32)> {
let rest = data_type
.strip_prefix("decimal128(")
.or_else(|| data_type.strip_prefix("decimal256("))?;
let rest = rest.strip_suffix(')')?;
let (precision, scale) = rest.split_once(',')?;
Some((precision.parse().ok()?, scale.parse().ok()?))
}
fn no_dictionary(column: &ColumnFacts) -> Option<Finding> {
let data_type = column.data_type.as_str();
if !matches!(data_type, "utf8" | "large_utf8" | "binary" | "large_binary") {
return None;
}
let has_dictionary = column
.encodings
.iter()
.any(|encoding| encoding.contains("DICTIONARY"));
if has_dictionary {
return None;
}
let distinct = column.distinct_count?;
if distinct == 0 || column.num_values == 0 {
return None;
}
let repeat = column.num_values as f64 / distinct as f64;
if repeat < 4.0 {
return None;
}
Some(Finding {
rule: "no-dictionary",
severity: "warning",
column: Some(column.name.clone()),
message: format!(
"值只有 {distinct} 种(每个值平均重复 {repeat:.1} 次),却写成 PLAIN 没有字典"
),
numbers: Some(json!({
"distinct": distinct,
"values": column.num_values,
"encodings": column.encodings,
})),
})
}
fn mostly_null(column: &ColumnFacts) -> Option<Finding> {
if column.num_values == 0 {
return None;
}
let share = column.null_count as f64 / column.num_values as f64;
if share < 0.8 {
return None;
}
Some(Finding {
rule: "mostly-null",
severity: "info",
column: Some(column.name.clone()),
message: format!("这一列 {:.0}% 是空的", share * 100.0),
numbers: Some(json!({
"null_count": column.null_count,
"values": column.num_values,
})),
})
}
fn constant_column(column: &ColumnFacts) -> Option<Finding> {
let min = column.min.as_ref()?;
let max = column.max.as_ref()?;
if min != max {
return None;
}
Some(Finding {
rule: "constant-column",
severity: "info",
column: Some(column.name.clone()),
message: format!(
"这一列的值都一样 ⇒ 它的 {} 字节几乎全是结构(每行组的字典与页头)",
column.compressed_size
),
numbers: Some(json!({
"value": min,
"bytes": column.compressed_size,
})),
})
}
fn contrast_column(
path: &Path,
index: usize,
column: &ColumnFacts,
rows_per_group: i64,
) -> Result<(i64, i64)> {
let as_is = write_column(path, index, column, false, rows_per_group)?;
let constant = write_column(path, index, column, true, rows_per_group)?;
Ok((as_is - constant, constant))
}
fn value_versus_structure_finding(
column: &ColumnAdvice,
value_bytes: i64,
structure_bytes: i64,
) -> Finding {
let total = value_bytes + structure_bytes;
let share = if total > 0 {
value_bytes as f64 / total as f64
} else {
0.0
};
Finding {
rule: "value-vs-structure",
severity: "info",
column: Some(column.name.clone()),
message: format!(
"值占 {value_bytes}({:.0}%),结构占 {structure_bytes} —— 把这一列单独重写一遍量出来的(同样的压缩器与行组大小)",
share * 100.0
),
numbers: Some(json!({
"value_bytes": value_bytes,
"structure_bytes": structure_bytes,
"total_bytes": total,
})),
}
}
fn write_column(
path: &Path,
index: usize,
column: &ColumnFacts,
constant: bool,
rows_per_group: i64,
) -> Result<i64> {
let file = File::open(path).with_context(|| format!("open {}", path.display()))?;
let builder = ParquetRecordBatchReaderBuilder::try_new(file)
.with_context(|| format!("read the footer of {}", path.display()))?;
let schema = builder.schema().clone();
let field: FieldRef = schema.fields()[index].clone();
let single = Schema::new(vec![field.clone()]);
let mut properties_builder = WriterProperties::builder()
.set_compression(compression_of(&column.compression))
.set_max_row_group_row_count(Some(rows_per_group.max(1) as usize));
if column
.encodings
.iter()
.any(|encoding| encoding.contains("DELTA"))
{
properties_builder = properties_builder.set_column_encoding(
ColumnPath::from(field.name().clone()),
Encoding::DELTA_BINARY_PACKED,
);
}
if !column
.encodings
.iter()
.any(|encoding| encoding.contains("DICTIONARY"))
{
properties_builder = properties_builder.set_dictionary_enabled(false);
}
let properties = properties_builder.build();
let target = temporary_path(&column.name.replace(['.', '/'], "_"));
let output = File::create(&target).with_context(|| format!("create {}", target.display()))?;
let mut writer = ArrowWriter::try_new(output, Arc::new(single.clone()), Some(properties))
.context("open the writer")?;
let reader = builder.build()?;
for batch in reader {
let batch = batch?;
let values = batch.column(index).clone();
let values = if constant {
constantize(&values)?
} else {
values
};
let batch = RecordBatch::try_new(Arc::new(single.clone()), vec![values])
.context("build the batch")?;
writer.write(&batch)?;
}
writer.close()?;
let size = std::fs::metadata(&target)?.len() as i64;
let _ = std::fs::remove_file(&target);
Ok(size)
}
fn constantize(values: &ArrayRef) -> Result<ArrayRef> {
let indices = PrimitiveArray::<UInt32Type>::from(vec![0u32; values.len()]);
arrow_select::take::take(&**values, &indices, None).context("make the constant column")
}
fn compression_of(name: &str) -> Compression {
match name {
"SNAPPY" => Compression::SNAPPY,
"GZIP" => Compression::GZIP(Default::default()),
"BROTLI" => Compression::BROTLI(Default::default()),
"LZ4_RAW" => Compression::LZ4_RAW,
"LZ4" => Compression::LZ4,
"ZSTD" => Compression::ZSTD(Default::default()),
_ => Compression::UNCOMPRESSED,
}
}
fn temporary_path(name: &str) -> std::path::PathBuf {
let stamp = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|since| since.as_nanos())
.unwrap_or(0);
std::env::temp_dir().join(format!("pqt-contrast-{name}-{stamp}.parquet"))
}