parquet-cli 0.1.4

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
//! Writing a file again with different settings, and saying what it cost.
//!
//! A compression experiment is one question: *what would this file weigh if
//! it were written this way?* The answer is a number, and the number is what
//! decides things.

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

use anyhow::{anyhow, Context, Result};
use parquet::arrow::arrow_reader::ParquetRecordBatchReaderBuilder;
use parquet::arrow::arrow_writer::ArrowWriter;
use parquet::basic::{BrotliLevel, Compression, Encoding, GzipLevel, ZstdLevel};
use parquet::file::properties::{WriterProperties, WriterVersion};
use serde_json::{json, Map, Value};

use crate::meta::{self, FileFacts};

/// The settings one run uses.
#[derive(Clone, Debug, Default)]
pub struct Settings {
    /// How the columns are compressed.
    pub compression: Option<Compression>,
    /// How many rows go into a row group.
    pub row_group: Option<usize>,
    /// Whether the columns get a dictionary.
    pub dictionary: Option<bool>,
    /// How big a data page may get.
    pub page_size: Option<usize>,
    /// Whether the data pages are written as version 2.
    pub data_page_v2: Option<bool>,
    /// How the values are encoded.
    pub encoding: Option<Encoding>,
}

impl Settings {
    /// The settings as they read on a line.
    pub fn describe(&self) -> String {
        let mut parts = Vec::new();
        if let Some(compression) = &self.compression {
            parts.push(compression.to_string());
        }
        if let Some(row_group) = self.row_group {
            parts.push(format!("row-group:{row_group}"));
        }
        if let Some(dictionary) = self.dictionary {
            parts.push(format!(
                "dictionary:{}",
                if dictionary { "on" } else { "off" }
            ));
        }
        if let Some(page_size) = self.page_size {
            parts.push(format!("page-size:{page_size}"));
        }
        if let Some(data_page_v2) = self.data_page_v2 {
            parts.push(format!(
                "data-page:{}",
                if data_page_v2 { "v2" } else { "v1" }
            ));
        }
        if let Some(encoding) = &self.encoding {
            parts.push(format!("encoding:{}", encoding_name(encoding)));
        }
        if parts.is_empty() {
            "the defaults".to_string()
        } else {
            parts.join(", ")
        }
    }
}

/// One run and what it weighed.
#[derive(Clone, Debug)]
pub struct Run {
    /// What was changed.
    pub label: String,
    /// The settings it ran with.
    pub settings: String,
    /// How many bytes the rewritten file took.
    pub bytes: u64,
}

/// The result of a bench.
#[derive(Clone, Debug)]
pub struct Bench {
    pub file: String,
    /// How many bytes the original file takes.
    pub original_bytes: u64,
    pub runs: Vec<Run>,
}

impl Bench {
    pub fn to_json(&self) -> Value {
        let runs: Vec<Value> = self
            .runs
            .iter()
            .map(|run| {
                let mut object = Map::new();
                object.insert("label".into(), Value::String(run.label.clone()));
                object.insert("settings".into(), Value::String(run.settings.clone()));
                object.insert("bytes".into(), json!(run.bytes));
                object.insert(
                    "difference".into(),
                    json!(run.bytes as i64 - self.original_bytes as i64),
                );
                object.insert(
                    "ratio".into(),
                    json!(run.bytes as f64 / self.original_bytes as f64),
                );
                Value::Object(object)
            })
            .collect();
        json!({
            "file": self.file,
            "original_bytes": self.original_bytes,
            "runs": runs,
        })
    }
}

/// Read the settings a file was written with.
pub fn baseline(facts: &FileFacts) -> Settings {
    let mut dictionary = false;
    let mut encoding = None;
    for group in facts.encodings.iter() {
        if group.contains("DICTIONARY") {
            dictionary = true;
        }
        if group.contains("DELTA_BINARY_PACKED") {
            encoding = Some(Encoding::DELTA_BINARY_PACKED);
        } else if group.contains("DELTA_LENGTH_BYTE_ARRAY") {
            encoding = Some(Encoding::DELTA_LENGTH_BYTE_ARRAY);
        }
    }
    let compression = facts
        .compressions
        .first()
        .map(|codec| compression_of(codec));
    Settings {
        compression,
        row_group: if facts.row_groups > 0 {
            Some((facts.rows / facts.row_groups as i64).max(1) as usize)
        } else {
            None
        },
        dictionary: Some(dictionary),
        page_size: None,
        data_page_v2: Some(facts.format_version >= 2),
        encoding,
    }
}

/// Read the settings out of the strings the user gave.
///
/// A string is either a setting (`row-group:1000`, `dictionary:off`,
/// `page-size:65536`, `data-page:v2`, `encoding:delta`) or a compression
/// (`zstd:19`, `snappy`, `gzip:6`).
pub fn parse(settings: &[String]) -> Result<Settings> {
    let mut parsed = Settings::default();
    for setting in settings {
        let whole = setting.to_lowercase();
        let (key, value) = match setting.split_once(':') {
            Some((key, value)) => (key.to_lowercase(), value.to_lowercase()),
            None => (String::new(), whole.clone()),
        };
        match key.as_str() {
            "row-group" | "row_group" | "rowgroup" => {
                parsed.row_group = Some(value.parse().context("the row group size")?);
            }
            "dictionary" => {
                parsed.dictionary = Some(match value.as_str() {
                    "on" | "true" | "yes" => true,
                    "off" | "false" | "no" => false,
                    other => return Err(anyhow!("dictionary takes on or off, not {other}")),
                });
            }
            "page-size" | "page_size" => {
                parsed.page_size = Some(value.parse().context("the page size")?);
            }
            "data-page" | "data_page" => {
                parsed.data_page_v2 = Some(match value.as_str() {
                    "v1" | "1" => false,
                    "v2" | "2" => true,
                    other => return Err(anyhow!("data-page takes v1 or v2, not {other}")),
                });
            }
            "encoding" => {
                parsed.encoding = Some(match value.as_str() {
                    "plain" => Encoding::PLAIN,
                    "delta" => Encoding::DELTA_BINARY_PACKED,
                    "delta-length-bytes" => Encoding::DELTA_LENGTH_BYTE_ARRAY,
                    other => return Err(anyhow!("unknown encoding: {other}")),
                });
            }
            _ => {
                // Not a setting name: it must be a compression, like `zstd:19`.
                parsed.compression = Some(compression_of_spec(&whole)?);
            }
        }
    }
    Ok(parsed)
}

/// Write the file again with these settings, and say how big it is.
pub fn bench(path: &Path, overrides: &[String], sweep: bool) -> Result<Bench> {
    let facts = meta::file_facts(path)?;
    let base = baseline(&facts);

    let mut runs = Vec::new();
    let mut settings = base.clone();
    for override_setting in overrides {
        let one = parse(std::slice::from_ref(override_setting))?;
        settings = merge(&settings, &one);
    }
    runs.push(Run {
        label: if overrides.is_empty() {
            "the file's own settings".to_string()
        } else {
            "the settings you asked for".to_string()
        },
        settings: settings.describe(),
        bytes: rewrite(path, &settings)?,
    });

    if sweep {
        for (label, change) in sweep_settings() {
            let mut settings = base.clone();
            settings = merge(&settings, &change);
            runs.push(Run {
                label,
                settings: settings.describe(),
                bytes: rewrite(path, &settings)?,
            });
        }
    }

    Ok(Bench {
        file: facts.path,
        original_bytes: facts.size_bytes,
        runs,
    })
}

/// The settings the sweep tries: one knob at a time, from the file's own.
fn sweep_settings() -> Vec<(String, Settings)> {
    let mut sweep = Vec::new();
    for rows in [1_000usize, 10_000, 100_000, 1_000_000] {
        sweep.push((
            format!("row-group:{rows}"),
            Settings {
                row_group: Some(rows),
                ..Settings::default()
            },
        ));
    }
    for codec in ["snappy", "zstd:1", "zstd:9", "zstd:19", "gzip:6"] {
        let compression = compression_of_spec(codec).ok();
        sweep.push((
            format!("codec:{codec}"),
            Settings {
                compression,
                ..Settings::default()
            },
        ));
    }
    sweep.push((
        "dictionary:off".to_string(),
        Settings {
            dictionary: Some(false),
            ..Settings::default()
        },
    ));
    sweep.push((
        "data-page:v2".to_string(),
        Settings {
            data_page_v2: Some(true),
            ..Settings::default()
        },
    ));
    sweep.push((
        "page-size:65536".to_string(),
        Settings {
            page_size: Some(65_536),
            ..Settings::default()
        },
    ));
    sweep
}

/// One set of settings on top of another.
fn merge(base: &Settings, other: &Settings) -> Settings {
    Settings {
        compression: other.compression.or(base.compression),
        row_group: other.row_group.or(base.row_group),
        dictionary: other.dictionary.or(base.dictionary),
        page_size: other.page_size.or(base.page_size),
        data_page_v2: other.data_page_v2.or(base.data_page_v2),
        encoding: other.encoding.or(base.encoding),
    }
}

/// Read a file and write it again with these settings. The original is left
/// alone.
fn rewrite(path: &Path, settings: &Settings) -> Result<u64> {
    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 mut properties = WriterProperties::builder();
    if let Some(compression) = &settings.compression {
        properties = properties.set_compression(*compression);
    }
    if let Some(row_group) = settings.row_group {
        properties = properties.set_max_row_group_row_count(Some(row_group));
    }
    if let Some(dictionary) = settings.dictionary {
        properties = properties.set_dictionary_enabled(dictionary);
    }
    if let Some(page_size) = settings.page_size {
        properties = properties.set_data_page_size_limit(page_size);
    }
    if let Some(data_page_v2) = settings.data_page_v2 {
        properties = properties.set_writer_version(if data_page_v2 {
            WriterVersion::PARQUET_2_0
        } else {
            WriterVersion::PARQUET_1_0
        });
    }
    if let Some(encoding) = settings.encoding {
        properties = properties.set_encoding(encoding);
    }

    let target = temporary_path(path);
    let output = File::create(&target).with_context(|| format!("create {}", target.display()))?;
    let mut writer = ArrowWriter::try_new(output, schema.clone(), Some(properties.build()))
        .context("open the writer")?;
    for batch in builder.build()? {
        writer.write(&batch?)?;
    }
    writer.close()?;

    let size = std::fs::metadata(&target)?.len();
    let _ = std::fs::remove_file(&target);
    Ok(size)
}

/// The compression a name stands for.
fn compression_of(name: &str) -> Compression {
    match name.to_uppercase().as_str() {
        "SNAPPY" => Compression::SNAPPY,
        "GZIP" => Compression::GZIP(GzipLevel::default()),
        "BROTLI" => Compression::BROTLI(BrotliLevel::default()),
        "ZSTD" => Compression::ZSTD(ZstdLevel::default()),
        "LZ4" => Compression::LZ4,
        "LZ4_RAW" => Compression::LZ4_RAW,
        _ => Compression::UNCOMPRESSED,
    }
}

/// Read a compression like `zstd:19`.
fn compression_of_spec(spec: &str) -> Result<Compression> {
    let (codec, level) = match spec.split_once(':') {
        Some((codec, level)) => (codec, Some(level)),
        None => (spec, None),
    };
    let level = level.map(|level| {
        level
            .parse::<i32>()
            .map_err(|_| anyhow!("the compression level: {level}"))
    });
    let level = match level {
        Some(level) => Some(level?),
        None => None,
    };
    match codec.to_lowercase().as_str() {
        "snappy" => Ok(Compression::SNAPPY),
        "none" | "uncompressed" => Ok(Compression::UNCOMPRESSED),
        "lz4" | "lz4_raw" => Ok(Compression::LZ4_RAW),
        "zstd" => Ok(Compression::ZSTD(ZstdLevel::try_new(level.unwrap_or(1))?)),
        "gzip" => Ok(Compression::GZIP(GzipLevel::try_new(
            level.unwrap_or(6) as u32
        )?)),
        "brotli" => Ok(Compression::BROTLI(BrotliLevel::try_new(
            level.unwrap_or(6) as u32,
        )?)),
        other => Err(anyhow!("unknown compression: {other}")),
    }
}

/// The name of an encoding, as the user writes it.
fn encoding_name(encoding: &Encoding) -> &'static str {
    match encoding {
        Encoding::PLAIN => "plain",
        Encoding::DELTA_BINARY_PACKED => "delta",
        Encoding::DELTA_LENGTH_BYTE_ARRAY => "delta-length-bytes",
        _ => "other",
    }
}

/// A temporary file to write the rewritten file into.
fn temporary_path(path: &Path) -> PathBuf {
    let stamp = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|since| since.as_nanos())
        .unwrap_or(0);
    let name = path
        .file_name()
        .map(|name| name.to_string_lossy().to_string())
        .unwrap_or_else(|| "bench".to_string());
    let directory = path.parent().unwrap_or_else(|| Path::new("."));
    directory.join(format!(".pqt-bench-{name}-{stamp}.parquet"))
}