parquet-cli 0.1.6

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
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
//! End-to-end tests: build a Parquet file, then ask every question of it.

use std::fs::File;
use std::path::{Path, PathBuf};
use std::sync::Arc;

use arrow_array::{ArrayRef, BooleanArray, Float64Array, Int64Array, RecordBatch, StringArray};
use arrow_schema::{DataType, Field, Schema};
use parquet::arrow::arrow_writer::ArrowWriter;
use parquet::basic::Compression;
use parquet::file::properties::WriterProperties;

use parquet::schema::types::ColumnPath;
use parquet_cli::advise;
use parquet_cli::bench;
use parquet_cli::compare;
use parquet_cli::meta;
use parquet_cli::output::Format;
use parquet_cli::plan;
use parquet_cli::rows;

/// Write a small Parquet file: three rows, four columns, one of them null.
fn fixture(directory: &Path) -> PathBuf {
    let schema = Schema::new(vec![
        Field::new("id", DataType::Int64, false),
        Field::new("path", DataType::Utf8, false),
        Field::new("score", DataType::Float64, true),
        Field::new("ok", DataType::Boolean, false),
    ]);

    let ids: ArrayRef = Arc::new(Int64Array::from(vec![1i64, 2, 3]));
    let paths: ArrayRef = Arc::new(StringArray::from(vec!["/a", "/b", "/c"]));
    let scores: ArrayRef = Arc::new(Float64Array::from(vec![Some(1.5), None, Some(3.5)]));
    let flags: ArrayRef = Arc::new(BooleanArray::from(vec![true, false, true]));
    let batch = RecordBatch::try_new(Arc::new(schema.clone()), vec![ids, paths, scores, flags])
        .expect("the batch matches the schema");

    let properties = WriterProperties::builder()
        .set_compression(Compression::ZSTD(
            parquet::basic::ZstdLevel::try_new(1).expect("a level"),
        ))
        .build();

    let path = directory.join("events.parquet");
    let file = File::create(&path).expect("create the fixture");
    let mut writer =
        ArrowWriter::try_new(file, Arc::new(schema), Some(properties)).expect("the writer opens");
    writer.write(&batch).expect("write the batch");
    writer.close().expect("close the file");
    path
}

fn temporary_directory(name: &str) -> PathBuf {
    let path = std::env::temp_dir().join(format!("parquet-cli-{name}"));
    let _ = std::fs::remove_dir_all(&path);
    std::fs::create_dir_all(&path).expect("create the temporary directory");
    path
}

#[test]
fn facts_count_the_rows_and_the_columns() {
    let directory = temporary_directory("facts");
    let path = fixture(&directory);

    let facts = meta::facts(&path).expect("the facts are readable");
    assert_eq!(facts["rows"], 3);
    assert_eq!(facts["row_groups"], 1);
    assert_eq!(facts["columns"], 4);
    assert!(facts["size_bytes"].as_u64().expect("a size") > 0);
    assert_eq!(facts["compressions"][0], "ZSTD");
}

#[test]
fn the_schema_names_every_column() {
    let directory = temporary_directory("schema");
    let path = fixture(&directory);

    let schema = meta::schema(&path).expect("the schema is readable");
    let fields = schema["fields"].as_array().expect("a list of fields");
    assert_eq!(fields.len(), 4);
    assert_eq!(fields[0]["name"], "id");
    assert_eq!(fields[0]["type"], "int64");
    assert_eq!(fields[1]["type"], "utf8");
    assert_eq!(fields[3]["nullable"], false);
}

#[test]
fn the_columns_carry_their_statistics() {
    let directory = temporary_directory("columns");
    let path = fixture(&directory);

    let columns = meta::columns(&path, false).expect("the columns are readable");
    let columns = columns["columns"].as_array().expect("a list of columns");
    assert_eq!(columns.len(), 4);

    let id = &columns[0];
    assert_eq!(id["name"], "id");
    assert_eq!(id["num_values"], 3);
    assert_eq!(id["null_count"], 0);
    assert_eq!(id["min"], 1);
    assert_eq!(id["max"], 3);

    let score = &columns[2];
    assert_eq!(score["null_count"], 1);
}

#[test]
fn scanning_counts_the_distinct_values() {
    let directory = temporary_directory("scan");
    let path = fixture(&directory);

    let columns = meta::columns(&path, true).expect("the columns are readable");
    let columns = columns["columns"].as_array().expect("a list of columns");
    assert_eq!(columns[1]["distinct_count"], 3);
}

#[test]
fn the_head_is_the_first_rows() {
    let directory = temporary_directory("head");
    let path = fixture(&directory);

    let table = rows::head(&path, 2).expect("the rows are readable");
    assert_eq!(table.rows.len(), 2);
    assert_eq!(table.columns, vec!["id", "path", "score", "ok"]);
    assert_eq!(table.rows[0][0], serde_json::json!(1));
    assert_eq!(table.rows[0][1], serde_json::json!("/a"));
    assert_eq!(table.rows[1][2], serde_json::Value::Null);
}

#[test]
fn a_valid_file_passes_every_check() {
    let directory = temporary_directory("validate");
    let path = fixture(&directory);

    let report = parquet_cli::validate::validate(&path).expect("the report is readable");
    assert_eq!(report["ok"], true, "the report: {report}");
    let checks = report["checks"].as_array().expect("a list of checks");
    assert!(checks.len() >= 4);
    assert!(checks.iter().all(|check| check["ok"] == true));
}

#[test]
fn the_command_line_answers_in_json() {
    let directory = temporary_directory("cli");
    let path = fixture(&directory);

    let output = std::process::Command::new(env!("CARGO_BIN_EXE_pqt"))
        .args(["--json", "info"])
        .arg(&path)
        .output()
        .expect("the command runs");
    assert!(output.status.success(), "the command failed");
    let text = String::from_utf8(output.stdout).expect("utf8");
    let parsed: serde_json::Value = serde_json::from_str(&text).expect("valid JSON");
    assert_eq!(parsed["rows"], 3);
}

#[test]
fn the_command_line_prints_a_table() {
    let directory = temporary_directory("cli-table");
    let path = fixture(&directory);

    let output = std::process::Command::new(env!("CARGO_BIN_EXE_pqt"))
        .args(["columns"])
        .arg(&path)
        .output()
        .expect("the command runs");
    assert!(output.status.success(), "the command failed");
    let text = String::from_utf8(output.stdout).expect("utf8");
    assert!(text.contains("id"), "the table names the column: {text}");
    assert!(text.contains("path"), "the table names the column: {text}");
}

#[test]
fn a_file_can_be_converted() {
    let directory = temporary_directory("convert");
    let path = fixture(&directory);
    let out = directory.join("events.csv");

    rows::convert(&path, &out, rows::ConvertFormat::Csv).expect("the conversion works");
    let text = std::fs::read_to_string(&out).expect("the output is readable");
    assert!(text.starts_with("id,path,score,ok"), "the header: {text}");
    assert!(text.contains("1,/a,1.5,true"), "the row: {text}");
}

#[test]
fn the_json_flag_covers_the_row_commands_too() {
    let directory = temporary_directory("json-flag");
    let path = fixture(&directory);

    let output = std::process::Command::new(env!("CARGO_BIN_EXE_pqt"))
        .args(["--json", "head", "-n", "1"])
        .arg(&path)
        .output()
        .expect("the command runs");
    assert!(output.status.success(), "the command failed");
    let text = String::from_utf8(output.stdout).expect("utf8");
    let parsed: serde_json::Value = serde_json::from_str(&text).expect("valid JSON");
    assert_eq!(parsed[0]["id"], 1);
}

#[test]
fn json_lines_keep_the_types() {
    let directory = temporary_directory("jsonl");
    let path = fixture(&directory);

    let table = rows::head(&path, 3).expect("the rows are readable");
    let mut buffer = Vec::new();
    parquet_cli::output::write_table(&mut buffer, &table, Format::Jsonl).expect("the output works");
    let text = String::from_utf8(buffer).expect("utf8");
    let lines: Vec<&str> = text.lines().collect();
    assert_eq!(lines.len(), 3);

    let first: serde_json::Value = serde_json::from_str(lines[0]).expect("valid JSON");
    assert_eq!(first["id"], 1);
    assert_eq!(first["score"], 1.5);
}

/// A file whose columns are there to be complained about.
fn advice_fixture(directory: &Path) -> PathBuf {
    let schema = Schema::new(vec![
        Field::new("id", DataType::Int64, false),
        Field::new("ratio", DataType::Float64, false),
        Field::new("note", DataType::Utf8, true),
        Field::new("kind", DataType::Utf8, false),
    ]);

    let ids: ArrayRef = Arc::new(Int64Array::from(vec![1i64, 2, 3]));
    let ratios: ArrayRef = Arc::new(Float64Array::from(vec![1.0, 2.0, 3.0]));
    let notes: ArrayRef = Arc::new(StringArray::from(vec![None::<&str>, None, None]));
    let kinds: ArrayRef = Arc::new(StringArray::from(vec!["a", "a", "a"]));
    let batch = RecordBatch::try_new(Arc::new(schema.clone()), vec![ids, ratios, notes, kinds])
        .expect("the batch matches the schema");

    let path = directory.join("advice.parquet");
    let file = File::create(&path).expect("create the fixture");
    let mut writer = ArrowWriter::try_new(file, Arc::new(schema), None).expect("the writer opens");
    writer.write(&batch).expect("write the batch");
    writer.close().expect("close the file");
    path
}

#[test]
fn the_advice_finds_the_wide_types() {
    let directory = temporary_directory("advice");
    let path = advice_fixture(&directory);

    let advice = advise::advise(&path, false, None).expect("the advice is readable");
    let rules: Vec<&str> = advice.findings.iter().map(|finding| finding.rule).collect();

    assert!(rules.contains(&"type-too-wide"), "{rules:?}");
    assert!(rules.contains(&"mostly-null"), "{rules:?}");
    assert!(rules.contains(&"constant-column"), "{rules:?}");

    let wide = advice
        .findings
        .iter()
        .find(|finding| finding.rule == "type-too-wide")
        .expect("a type that is too wide");
    assert_eq!(wide.column.as_deref(), Some("id"));
}

#[test]
fn the_advice_says_how_big_each_column_is() {
    let directory = temporary_directory("advice-share");
    let path = advice_fixture(&directory);

    let advice = advise::advise(&path, false, None).expect("the advice is readable");
    assert_eq!(advice.columns.len(), 4);
    let total: f64 = advice.columns.iter().map(|column| column.share).sum();
    assert!(total > 0.0 && total <= 1.0, "the shares add up: {total}");
}

#[test]
fn the_contrast_says_what_the_values_cost() {
    let directory = temporary_directory("advice-contrast");
    let path = advice_fixture(&directory);

    let advice = advise::advise(&path, false, Some(1)).expect("the advice is readable");
    let measured = advice
        .columns
        .iter()
        .find(|column| column.value_bytes.is_some())
        .expect("one column was measured");

    assert!(measured.value_bytes.unwrap_or(0) >= 0);
    assert!(measured.structure_bytes.is_some());
    assert!(advice
        .findings
        .iter()
        .any(|finding| finding.rule == "value-vs-structure"));
}

#[test]
fn the_command_line_prints_the_advice() {
    let directory = temporary_directory("advice-cli");
    let path = advice_fixture(&directory);

    let output = std::process::Command::new(env!("CARGO_BIN_EXE_pqt"))
        .args(["advise"])
        .arg(&path)
        .output()
        .expect("the command runs");
    assert!(output.status.success(), "the command failed");
    let text = String::from_utf8(output.stdout).expect("utf8");
    assert!(
        text.contains("type-too-wide"),
        "the advice is printed: {text}"
    );
}

/// A file with the given columns, so that two of them can disagree.
fn shaped_file(directory: &Path, name: &str, with_score: bool) -> PathBuf {
    let mut fields = vec![
        Field::new("id", DataType::Int64, false),
        Field::new("country", DataType::Utf8, false),
    ];
    if with_score {
        fields.push(Field::new("score", DataType::Float64, false));
    }
    let schema = Schema::new(fields);

    let ids: ArrayRef = Arc::new(Int64Array::from(vec![1i64, 2, 3]));
    let countries: ArrayRef = Arc::new(StringArray::from(vec!["a", "b", "c"]));
    let mut columns = vec![ids, countries];
    if with_score {
        columns.push(Arc::new(Float64Array::from(vec![1.0, 2.0, 3.0])));
    }
    let batch = RecordBatch::try_new(Arc::new(schema.clone()), columns).expect("the batch");

    let path = directory.join(name);
    let file = File::create(&path).expect("create the fixture");
    let mut writer = ArrowWriter::try_new(file, Arc::new(schema), None).expect("the writer opens");
    writer.write(&batch).expect("write the batch");
    writer.close().expect("close the file");
    path
}

#[test]
fn the_comparison_says_where_the_files_disagree() {
    let directory = temporary_directory("compare");
    let first = shaped_file(&directory, "first.parquet", false);
    let second = shaped_file(&directory, "second.parquet", true);

    let comparison = compare::compare(&[first, second]).expect("the comparison is readable");
    assert_eq!(comparison.files.len(), 2);

    // The richer shape is the yardstick, so the thinner file is the one that
    // is missing a column.
    let rules: Vec<&str> = comparison
        .findings
        .iter()
        .map(|finding| finding.rule)
        .collect();
    assert!(rules.contains(&"column-missing"), "{rules:?}");
}

#[test]
fn the_comparison_uses_the_shape_most_files_have() {
    let directory = temporary_directory("compare-majority");
    let first = shaped_file(&directory, "first.parquet", false);
    let second = shaped_file(&directory, "second.parquet", false);
    let odd = shaped_file(&directory, "odd.parquet", true);

    let comparison = compare::compare(&[first, second, odd]).expect("the comparison is readable");
    let rules: Vec<&str> = comparison
        .findings
        .iter()
        .map(|finding| finding.rule)
        .collect();
    assert!(rules.contains(&"column-extra"), "{rules:?}");
    assert!(!rules.contains(&"column-missing"), "{rules:?}");
}

#[test]
fn the_comparison_walks_a_directory() {
    let directory = temporary_directory("compare-dir");
    let nested = directory.join("week=2026-06-01");
    std::fs::create_dir_all(&nested).expect("create the nested directory");
    shaped_file(&nested, "events.parquet", false);
    shaped_file(&directory, "other.parquet", false);

    let comparison = compare::compare(&[directory]).expect("the comparison is readable");
    assert_eq!(comparison.files.len(), 2);
    let labels: Vec<&str> = comparison
        .files
        .iter()
        .map(|file| file.label.as_str())
        .collect();
    assert!(
        labels.contains(&"week=2026-06-01/events.parquet"),
        "{labels:?}"
    );
}

#[test]
fn the_command_line_compares_the_files() {
    let directory = temporary_directory("compare-cli");
    let first = shaped_file(&directory, "first.parquet", false);
    let second = shaped_file(&directory, "second.parquet", true);

    let output = std::process::Command::new(env!("CARGO_BIN_EXE_pqt"))
        .args(["compare"])
        .arg(&first)
        .arg(&second)
        .output()
        .expect("the command runs");
    assert!(output.status.success(), "the command failed");
    let text = String::from_utf8(output.stdout).expect("utf8");
    assert!(
        text.contains("column-missing"),
        "the finding is printed: {text}"
    );
}

#[test]
fn the_lookup_cost_adds_up() {
    let directory = temporary_directory("lookup");
    let path = fixture(&directory);

    let facts = meta::facts(&path).expect("the facts are readable");
    let footer = facts["footer_bytes"].as_i64().expect("a footer size");
    let typical = facts["lookup_reads_typical"]
        .as_i64()
        .expect("a lookup cost");
    let worst = facts["lookup_reads_worst"].as_i64().expect("a lookup cost");

    assert!(footer > 0, "the footer takes {footer} bytes");
    assert!(typical > footer, "a lookup reads more than the footer");
    assert!(
        worst >= typical,
        "the worst lookup is not cheaper than the typical one"
    );
}

#[test]
fn the_row_groups_carry_their_own_statistics() {
    let directory = temporary_directory("groups");
    let path = fixture(&directory);

    let columns = meta::columns(&path, false).expect("the columns are readable");
    let column = &columns["columns"][0];
    let groups = column["row_groups"].as_array().expect("the row groups");
    assert_eq!(groups.len(), 1);
    assert_eq!(groups[0]["rows"], 3);
    assert_eq!(groups[0]["min"], 1);
    assert_eq!(groups[0]["max"], 3);
}

#[test]
fn the_bench_writes_the_file_again_and_says_what_it_cost() {
    let directory = temporary_directory("bench");
    let path = fixture(&directory);
    let mut plan = plan::Plan::new();
    plan.set("compression", "zstd").expect("known");

    let result = bench::bench(&path, &plan, false, None).expect("the bench runs");
    assert_eq!(result.runs.len(), 1);
    assert!(result.runs[0].bytes > 0, "the rewritten file has bytes");

    // The original is left alone.
    let facts = meta::facts(&path).expect("the facts are readable");
    assert_eq!(
        facts["size_bytes"].as_u64().expect("a size"),
        result.original_bytes
    );
}

#[test]
fn the_bench_understands_the_settings() {
    let mut plan = plan::Plan::new();
    for option in ["zstd:19", "row-group:1000", "dictionary:off"] {
        for (name, value) in plan::parse_option(option).expect("the option is readable") {
            plan.set(&name, &value).expect("the option is known");
        }
    }
    assert_eq!(plan.get("row_group_size"), Some("1000"));
    assert_eq!(plan.get("dictionary"), Some("off"));
    assert_eq!(plan.get("compression"), Some("zstd"));
    assert_eq!(plan.get("compression_level"), Some("19"));
}

#[test]
fn the_command_line_benches_the_file() {
    let directory = temporary_directory("bench-cli");
    let path = fixture(&directory);

    let output = std::process::Command::new(env!("CARGO_BIN_EXE_pqt"))
        .args(["bench", "--with", "zstd:19"])
        .arg(&path)
        .output()
        .expect("the command runs");
    assert!(output.status.success(), "the command failed");
    let text = String::from_utf8(output.stdout).expect("utf8");
    assert!(text.contains("rewritten"), "the result is printed: {text}");
}

#[test]
fn the_plan_speaks_duckdb() {
    let mut plan = plan::Plan::new();
    plan.set("compression", "zstd").expect("known");
    plan.set("compression_level", "19").expect("known");
    plan.set("row_group_size", "1000").expect("known");
    plan.set("write_bloom_filter", "on").expect("known");

    assert_eq!(plan.get("compression"), Some("zstd"));
    assert_eq!(plan.get("row_group_size"), Some("1000"));
}

#[test]
fn the_plan_refuses_what_it_does_not_know() {
    let mut plan = plan::Plan::new();
    let error = plan
        .set("compresion", "zstd")
        .expect_err("a typo is an error");
    assert!(error.to_string().contains("unknown option"), "{error}");

    let error = plan.set("field_ids", "{}").expect_err("not yet");
    assert!(error.to_string().contains("not do yet"), "{error}");
}

#[test]
fn the_short_form_works_too() {
    let mut plan = plan::Plan::new();
    for (name, value) in plan::parse_option("zstd:19").expect("readable") {
        plan.set(&name, &value).expect("known");
    }
    assert_eq!(plan.get("compression"), Some("zstd"));
    assert_eq!(plan.get("compression_level"), Some("19"));
}

#[test]
fn the_dictionary_is_left_out_when_the_values_do_not_repeat() {
    // A column whose values are all different does not pay for a dictionary.
    let columns = vec![plan::Column {
        name: "id".to_string(),
        distinct: Some(1000),
        rows: 1000,
    }];
    let mut plan = plan::Plan::new();
    plan.set("dictionary_compression_ratio_threshold", "0.5")
        .expect("known");
    let properties = plan.writer_properties(&columns).expect("the settings");
    let path = ColumnPath::from("id".to_string());
    assert!(!properties.dictionary_enabled(&path));
}

#[test]
fn a_script_can_drive_the_tool() {
    let directory = temporary_directory("script");
    let path = fixture(&directory);
    let script = directory.join("demo.luau");
    std::fs::write(
        &script,
        format!(
            "local facts = pqt.info(\"{}\")\n\
             print(facts.rows)\n\
             local cost = pqt.lookup_cost(\"{}\")\n\
             print(cost.footer_bytes > 0)\n",
            path.display(),
            path.display()
        ),
    )
    .expect("write the script");

    let output = std::process::Command::new(env!("CARGO_BIN_EXE_pqt"))
        .args(["script"])
        .arg(&script)
        .output()
        .expect("the command runs");
    assert!(output.status.success(), "the command failed");
    let text = String::from_utf8(output.stdout).expect("utf8");
    assert!(text.contains('3'), "the script printed the rows: {text}");
    assert!(
        text.contains("true"),
        "the script printed the footer: {text}"
    );
}

#[test]
fn a_script_gets_the_plan_vocabulary() {
    let directory = temporary_directory("script-options");
    let script = directory.join("options.luau");
    std::fs::write(
        &script,
        "local options = pqt.options()\n\
         for _, option in options do\n\
         \tif option.name == \"compression\" then print(option.supported) end\n\
         end\n",
    )
    .expect("write the script");

    let output = std::process::Command::new(env!("CARGO_BIN_EXE_pqt"))
        .args(["script"])
        .arg(&script)
        .output()
        .expect("the command runs");
    assert!(output.status.success(), "the command failed");
    let text = String::from_utf8(output.stdout).expect("utf8");
    assert!(text.contains("true"), "the option is listed: {text}");
}