parquet-cli 0.1.2

A Parquet CLI for AI agents: inspect, measure and convert Parquet files.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
//! Looking at a file's data and saying what could be better.
//!
//! Two layers. The cheap one reads only the footer: how big each column is,
//! what type it was written as, how the rows are grouped. The expensive one
//! rewrites a column with a constant in it, so the difference in size says
//! whether the column is expensive because of its values or because of its
//! shape.

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};

/// One thing worth knowing about the file.
#[derive(Clone, Debug)]
pub struct Finding {
    /// The name of the rule.
    pub rule: &'static str,
    /// `warning` or `info`.
    pub severity: &'static str,
    /// The column it is about, when it is about one.
    pub column: Option<String>,
    /// What is worth doing, in one sentence.
    pub message: String,
    /// The numbers behind it.
    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)
    }
}

/// One column, with what the advice needs to know about it.
#[derive(Clone, Debug)]
pub struct ColumnAdvice {
    pub name: String,
    pub data_type: String,
    pub bytes: i64,
    /// The share of the file this column takes.
    pub share: f64,
    /// The distinct values, when the file was read to count them.
    pub distinct: Option<u64>,
    /// The bytes its values take, when the contrast was run.
    pub value_bytes: Option<i64>,
    /// The bytes its shape takes, when the contrast was run.
    pub structure_bytes: Option<i64>,
}

/// Everything the advice is about.
#[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>>(),
        })
    }
}

/// Look at a file and say what could be better.
///
/// With `scan`, the file is read as well, so the advice can use the distinct
/// values. With `contrast`, the largest columns are rewritten with a constant
/// in them, so the advice can say whether a column is expensive because of its
/// values or because of its shape. That costs a rewrite of the file.
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 {
        // The biggest columns first: they are the ones worth the rewrite.
        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,
    })
}

/// The rules that read only the footer.
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);
        }
    }

    // One column taking most of the file.
    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,
                })),
            });
        }
    }

    // Row groups that are too small, and the footer they add up to.
    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
}

/// A type that is wider than the values need.
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
}

/// The precision and scale of a decimal type, when it is one.
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()?))
}

/// A string column whose values repeat but that was written without a
/// dictionary.
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,
        })),
    })
}

/// A column that is mostly empty.
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,
        })),
    })
}

/// A column whose values are all the same.
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,
        })),
    })
}

/// Rewrite one column with a constant in it, and see what the difference is.
///
/// The column is written twice: once as it is, once with every value replaced
/// by the first one. The difference is what the values cost; what is left is
/// what the column's shape costs.
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))
}

/// What the contrast says about one column.
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,
        })),
    }
}

/// Write one column of a file out as its own Parquet file.
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))
        // The same row group size as the file has, so the two sides of the
        // contrast differ only in the values.
        .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,
        );
    }
    // A writer that did not use a dictionary for this column (its values are
    // too varied for one to pay off) is matched by writing without one too.
    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)
}

/// A copy of a column where every value is the first one.
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")
}

/// The compression to write with.
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,
    }
}

/// A temporary file name for the contrast.
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"))
}