From cf6e5b098de9432055f9a24aa2c4bd9e874a6469 Mon Sep 17 00:00:00 2001 From: Will Manning Date: Fri, 20 Nov 2026 16:26:48 -0500 Subject: [PATCH 01/44] Record each benchmark Parquet file's codec in its file size capture-file-sizes.py reads each Parquet file's footer and names its format by codec: zstd stays `parquet`, the codec the benchmarks write, and other codecs record as `parquet-`, as `vortex` and `vortex-compact` name Vortex's. ClickBench and FineWeb measure downloaded files, and the statpopgen and vortex suites write without zstd, so their sizes were recorded as zstd Parquet. Signed-off-by: Will Manning --- scripts/capture-file-sizes.py | 140 +++++++++++++++++++++- scripts/tests/test_benchmark_reporting.py | 72 +++++++++++ 2 files changed, 211 insertions(+), 1 deletion(-) diff --git a/scripts/capture-file-sizes.py b/scripts/capture-file-sizes.py index f987cbc28f9..a6179a12c48 100644 --- a/scripts/capture-file-sizes.py +++ b/scripts/capture-file-sizes.py @@ -11,11 +11,144 @@ import argparse import json +import struct import sys from pathlib import Path DUCKDB_CATALOG_FILES = {"duckdb.db", "duckdb.db.wal"} +# Parquet's `CompressionCodec` enum, from `parquet.thrift`. +PARQUET_CODECS = { + 0: "uncompressed", + 1: "snappy", + 2: "gzip", + 3: "lzo", + 4: "brotli", + 5: "lz4", + 6: "zstd", + 7: "lz4-raw", +} + +# Thrift compact protocol type ids. +_T_STOP, _T_TRUE, _T_FALSE, _T_BYTE, _T_I16, _T_I32, _T_I64, _T_DOUBLE = range(8) +_T_BINARY, _T_LIST, _T_SET, _T_MAP, _T_STRUCT = range(8, 13) + + +class _CompactReader: + """Read Thrift compact protocol values. Structs read as dicts keyed by field id.""" + + def __init__(self, data: bytes) -> None: + self.data = data + self.pos = 0 + + def byte(self) -> int: + value = self.data[self.pos] + self.pos += 1 + return value + + def varint(self) -> int: + shift = result = 0 + while True: + b = self.byte() + result |= (b & 0x7F) << shift + if not b & 0x80: + return result + shift += 7 + + def zigzag(self) -> int: + n = self.varint() + return (n >> 1) ^ -(n & 1) + + def value(self, kind: int) -> object: + if kind in (_T_TRUE, _T_FALSE): + # A bool list element is a whole byte; a bool field carries its value in its type. + return self.byte() == _T_TRUE + if kind == _T_BYTE: + return self.byte() + if kind in (_T_I16, _T_I32, _T_I64): + return self.zigzag() + if kind == _T_DOUBLE: + self.pos += 8 + return None + if kind == _T_BINARY: + length = self.varint() + self.pos += length + return None + if kind in (_T_LIST, _T_SET): + header = self.byte() + size = header >> 4 + if size == 15: + size = self.varint() + return [self.value(header & 0x0F) for _ in range(size)] + if kind == _T_MAP: + size = self.varint() + if size == 0: + return {} + types = self.byte() + for _ in range(size): + self.value(types >> 4) + self.value(types & 0x0F) + return None + if kind == _T_STRUCT: + return self.struct() + raise ValueError(f"unknown thrift compact type {kind}") + + def struct(self) -> dict[int, object]: + fields: dict[int, object] = {} + field_id = 0 + while True: + header = self.byte() + kind = header & 0x0F + if kind == _T_STOP: + return fields + delta = header >> 4 + field_id = field_id + delta if delta else self.zigzag() + if kind in (_T_TRUE, _T_FALSE): + fields[field_id] = kind == _T_TRUE + else: + fields[field_id] = self.value(kind) + + +def parquet_codecs(path: Path) -> set[str]: + """The codecs of every column chunk in a Parquet file, read from its footer.""" + with open(path, "rb") as f: + f.seek(-8, 2) + length_bytes, magic = struct.unpack(" RowGroup.columns (1) -> ColumnChunk.meta_data (3) + # -> ColumnMetaData.codec (4). + for row_group in metadata.get(4) or []: + for column in row_group.get(1) or []: + meta = column.get(3) + if isinstance(meta, dict) and isinstance(meta.get(4), int): + codecs.add(PARQUET_CODECS.get(meta[4], f"codec-{meta[4]}")) + return codecs + + +def parquet_format_name(path: Path) -> str: + """Name a Parquet file's format by its codec, as `vortex` and `vortex-compact` name Vortex's. + + `parquet` is zstd, the codec every Parquet file the benchmarks write themselves uses (zstd + level 3). A file written with another codec, such as Snappy in a downloaded dataset, is + `parquet-`. A file whose footer cannot be read, or that mixes codecs, keeps `parquet` + with a warning, as before codecs were recorded. + """ + try: + codecs = parquet_codecs(path) + except (OSError, ValueError, IndexError, struct.error) as error: + print(f"Could not read the Parquet footer of {path}: {error}", file=sys.stderr) + return "parquet" + if len(codecs) != 1: + if codecs: + print(f"{path} mixes Parquet codecs {sorted(codecs)}; recording it as parquet", file=sys.stderr) + return "parquet" + codec = next(iter(codecs)) + return "parquet" if codec == "zstd" else f"parquet-{codec}" + def main() -> None: parser = argparse.ArgumentParser(description="Capture file sizes from benchmark data directories") @@ -86,6 +219,11 @@ def main() -> None: continue size_bytes = file_path.stat().st_size + recorded_format = ( + parquet_format_name(file_path) + if format_name == "parquet" and file_path.suffix == ".parquet" + else format_name + ) records.append( { @@ -96,7 +234,7 @@ def main() -> None: "file_size": { "benchmark": args.benchmark, "scale_factor": scale_factor, - "format": format_name, + "format": recorded_format, "file": str(relative_path), }, } diff --git a/scripts/tests/test_benchmark_reporting.py b/scripts/tests/test_benchmark_reporting.py index 1b55c84191a..c1ccbbfb9c3 100644 --- a/scripts/tests/test_benchmark_reporting.py +++ b/scripts/tests/test_benchmark_reporting.py @@ -936,6 +936,78 @@ def test_summary_reports_hot_alone_when_no_row_recorded_its_runs(tmp_path: Path) assert "cold" not in summary +def parquet_with_codecs(codecs: list[int], body: bytes = b"data") -> bytes: + """A Parquet file with one row group whose column chunks use `codecs`, footer only. + + The footer is the Thrift compact encoding of `FileMetaData{4: [RowGroup{1: [ColumnChunk{3: + ColumnMetaData{4: codec}}]}]}`, plus an unread field before each so the reader must skip it. + """ + + def i32_field(delta: int, value: int) -> bytes: + return bytes([(delta << 4) | 5, (value << 1) ^ (value >> 31)]) + + def list_field(delta: int, items: list[bytes]) -> bytes: + return bytes([(delta << 4) | 9, (len(items) << 4) | 12]) + b"".join(items) + + columns = [ + # ColumnChunk: file_offset (2, i64) skipped, then meta_data (3). + bytes([0x26, 0x00, 0x1C]) + bytes([0x15, 0x02]) + i32_field(3, codec) + b"\x00\x00" + for codec in codecs + ] + row_group = list_field(1, columns) + b"\x00" + metadata = bytes([0x15, 0x04]) + list_field(3, [row_group]) + b"\x00" + return b"PAR1" + body + metadata + len(metadata).to_bytes(4, "little") + b"PAR1" + + +def test_capture_file_sizes_names_parquet_by_codec(tmp_path: Path) -> None: + data_dir = tmp_path / "data" + parquet_dir = data_dir / "clickbench_partitioned" / "parquet" + parquet_dir.mkdir(parents=True) + zstd, snappy, uncompressed = 6, 1, 0 + files = { + "hits_0.parquet": parquet_with_codecs([zstd, zstd]), + "hits_1.parquet": parquet_with_codecs([snappy, snappy]), + "hits_2.parquet": parquet_with_codecs([uncompressed]), + "hits_3.parquet": parquet_with_codecs([zstd, snappy]), + "hits_4.parquet": b"not parquet", + } + for name, data in files.items(): + (parquet_dir / name).write_bytes(data) + output_path = tmp_path / "sizes.jsonl" + + result = subprocess.run( + [ + sys.executable, + str(CAPTURE_SCRIPT), + str(data_dir), + "--benchmark", + "clickbench", + "--dataset-dir", + "clickbench_partitioned", + "--commit", + "deadbeef", + "-o", + str(output_path), + ], + check=False, + capture_output=True, + text=True, + ) + + assert result.returncode == 0, result.stderr + records = [json.loads(line) for line in output_path.read_text(encoding="utf-8").splitlines()] + assert sorted((r["file_size"]["file"], r["file_size"]["format"], r["value"]) for r in records) == [ + ("hits_0.parquet", "parquet", len(files["hits_0.parquet"])), + ("hits_1.parquet", "parquet-snappy", len(files["hits_1.parquet"])), + ("hits_2.parquet", "parquet-uncompressed", len(files["hits_2.parquet"])), + # Mixed codecs and unreadable footers keep the plain name, with a warning. + ("hits_3.parquet", "parquet", len(files["hits_3.parquet"])), + ("hits_4.parquet", "parquet", len(files["hits_4.parquet"])), + ] + assert "mixes Parquet codecs" in result.stderr + assert "Could not read the Parquet footer" in result.stderr + + def test_capture_file_sizes_reads_only_the_named_directory(tmp_path: Path) -> None: data_dir = tmp_path / "data" for name, size in (("clickbench_partitioned", 42), ("clickbench_partitioned_10", 7)): From 07651098418492e003459b0cee16661f80c3fc8f Mon Sep 17 00:00:00 2001 From: Will Manning Date: Fri, 20 Nov 2026 16:31:51 -0500 Subject: [PATCH 02/44] Record Snappy Parquet sizes in compress-bench compress-bench writes each dataset once more as Snappy Parquet, untimed, and records its size as `parquet-snappy` beside `parquet` (zstd level 3). Only sizes: Snappy adds no compression or decompression timings. Signed-off-by: Will Manning --- benchmarks/compress-bench/src/main.rs | 21 ++++++++++++++++++ vortex-bench/src/v3.rs | 31 ++++++++++++++++++++++++++- 2 files changed, 51 insertions(+), 1 deletion(-) diff --git a/benchmarks/compress-bench/src/main.rs b/benchmarks/compress-bench/src/main.rs index 9e6e9aeafa9..9cdacdabf16 100644 --- a/benchmarks/compress-bench/src/main.rs +++ b/benchmarks/compress-bench/src/main.rs @@ -21,6 +21,7 @@ use futures::FutureExt; use indicatif::ProgressBar; use itertools::Itertools; use mimalloc::MiMalloc; +use parquet::basic::Compression; use regex::Regex; use vortex::utils::aliases::hash_map::HashMap; use vortex_bench::Engine; @@ -58,6 +59,9 @@ use vortex_bench::setup_logging_and_tracing_with_format; use vortex_bench::statpopgen::StatPopGenBenchmark; use vortex_bench::v3; +/// The size record name of Parquet written with Snappy, beside `parquet`, which is zstd level 3. +const PARQUET_SNAPPY_FORMAT: &str = "parquet-snappy"; + #[derive(Parser, Debug)] #[command(version, about, long_about = None)] struct Args { @@ -527,6 +531,23 @@ async fn run_benchmark_for_dataset( result.compressed_size, uncompressed_size.context("compression size requires Arrow memory size")?, )); + if *format == Format::Parquet && !mode.is_gpu() { + // Snappy Parquet is measured for size only: one untimed write. + let snappy = ParquetCompressor::with_compression(Compression::SNAPPY) + .compress(&input) + .await + .with_context(|| { + format!("compressing {bench_name} as Snappy Parquet") + })?; + v3_records.push(v3::named_compression_size_record( + v3_dataset, + v3_variant, + PARQUET_SNAPPY_FORMAT, + snappy.size, + uncompressed_size + .context("compression size requires Arrow memory size")?, + )); + } ratios.extend(result.ratios); timings.push(result.timing); compressed = Some(result.compressed); diff --git a/vortex-bench/src/v3.rs b/vortex-bench/src/v3.rs index e79cf8ad75d..bc7e5a25a7b 100644 --- a/vortex-bench/src/v3.rs +++ b/vortex-bench/src/v3.rs @@ -417,12 +417,30 @@ pub fn compression_size_record( format: Format, value_bytes: u64, uncompressed_bytes: u64, +) -> V3Record { + named_compression_size_record( + dataset, + dataset_variant, + format.name(), + value_bytes, + uncompressed_bytes, + ) +} + +/// Build a `compression_size` record for a format that has no [`Format`] of its own, such as +/// `parquet-snappy`, which `compress-bench` measures for size only. +pub fn named_compression_size_record( + dataset: &str, + dataset_variant: Option<&str>, + format: &str, + value_bytes: u64, + uncompressed_bytes: u64, ) -> V3Record { V3Record::CompressionSize(CompressionSizeRecord { commit_sha: GIT_COMMIT_ID.clone(), dataset: dataset.to_lowercase(), dataset_variant: dataset_variant.map(str::to_string), - format: format.name().to_string(), + format: format.to_string(), value_bytes, uncompressed_bytes, }) @@ -832,6 +850,17 @@ mod tests { assert_eq!(size.dataset, "cmsprovider"); } + #[test] + fn named_compression_size_record_keeps_the_format_name() { + let record = named_compression_size_record("Taxi", None, "parquet-snappy", 42, 420); + let V3Record::CompressionSize(size) = &record else { + panic!("expected CompressionSize variant, got {record:?}"); + }; + assert_eq!(size.dataset, "taxi"); + assert_eq!(size.format, "parquet-snappy"); + assert_eq!((size.value_bytes, size.uncompressed_bytes), (42, 420)); + } + #[test] fn nested_tpch_dims_carry_shape_and_scale_factor() { let (ds, variant, sf) = benchmark_dataset_dims(&BenchmarkDataset::TpcHNested { From f81ace6ca70a7de36ac6b69aad830e9e0dd52471 Mon Sep 17 00:00:00 2001 From: Will Manning Date: Fri, 20 Nov 2026 16:56:27 -0500 Subject: [PATCH 03/44] Record compact Vortex sizes in compress-bench compress-bench now writes each dataset once more with the compact Vortex strategy and records its size as vortex-compact, as the SQL benchmarks name it. The write is not timed and does not run in GPU mode. bench can then compare Vortex and compact Vortex on the compression datasets, as it does on the SQL benchmarks' files. Signed-off-by: Will Manning --- benchmarks/compress-bench/README.md | 5 +++++ benchmarks/compress-bench/src/main.rs | 16 ++++++++++++++++ benchmarks/compress-bench/src/vortex.rs | 18 ++++++++++++++++++ 3 files changed, 39 insertions(+) diff --git a/benchmarks/compress-bench/README.md b/benchmarks/compress-bench/README.md index 8f3764823d3..c9e3009349c 100644 --- a/benchmarks/compress-bench/README.md +++ b/benchmarks/compress-bench/README.md @@ -9,6 +9,11 @@ optional buffer compression. Its timings therefore isolate serialization and des without codec cost. Its file size provides the approximately 1x baseline for compression ratios. Parquet provides the established reference for a compressed columnar representation. +The suite also records the file size of two formats that it does not time: Parquet with Snappy +(`parquet-snappy`), beside the timed Parquet with zstd level 3, and Vortex with the compact +strategy (`vortex-compact`), as the SQL benchmarks write it. Each is one write per dataset, and +neither runs in GPU mode. bench shows these sizes in its `File Sizes` group. + The suite covers NYC taxi data and several [Public BI](https://github.com/cwida/public_bi_benchmark) tables (Arade, Bimbo, CMSprovider, Euro2016, Food, HashTags), TPC-H `l_comment` variants, the TPC-H `lineitem`, diff --git a/benchmarks/compress-bench/src/main.rs b/benchmarks/compress-bench/src/main.rs index 9cdacdabf16..f8d07d4208c 100644 --- a/benchmarks/compress-bench/src/main.rs +++ b/benchmarks/compress-bench/src/main.rs @@ -17,6 +17,7 @@ use compress_bench::gpu::compressor as gpu_compressor; use compress_bench::parquet::ParquetCompressor; use compress_bench::parquet::arrow_uncompressed_size; use compress_bench::vortex::VortexCompressor; +use compress_bench::vortex::vortex_compact_size; use futures::FutureExt; use indicatif::ProgressBar; use itertools::Itertools; @@ -548,6 +549,21 @@ async fn run_benchmark_for_dataset( .context("compression size requires Arrow memory size")?, )); } + if *format == Format::OnDiskVortex && !mode.is_gpu() { + // Compact Vortex is measured for size only: one untimed write. + let compact_size = + vortex_compact_size(&input).await.with_context(|| { + format!("compressing {bench_name} as compact Vortex") + })?; + v3_records.push(v3::compression_size_record( + v3_dataset, + v3_variant, + Format::VortexCompact, + compact_size, + uncompressed_size + .context("compression size requires Arrow memory size")?, + )); + } ratios.extend(result.ratios); timings.push(result.timing); compressed = Some(result.compressed); diff --git a/benchmarks/compress-bench/src/vortex.rs b/benchmarks/compress-bench/src/vortex.rs index 885fe0eb179..8bcdfec6149 100644 --- a/benchmarks/compress-bench/src/vortex.rs +++ b/benchmarks/compress-bench/src/vortex.rs @@ -22,6 +22,7 @@ use vortex::file::WriteOptionsSessionExt; use vortex::io::session::RuntimeSessionExt; use vortex::layout::scan::v2::ScanBuilder; use vortex::scan::execution::driver::ScanDriver; +use vortex_bench::CompactionStrategy; use vortex_bench::Format; use vortex_bench::SESSION; use vortex_bench::compress::Compressed; @@ -81,6 +82,23 @@ impl Compressor for VortexCompressor { } } +/// The size in bytes of `input` written as a Vortex file with the compact strategy, the one the +/// SQL benchmarks write as `vortex-compact`. The write is not timed: compress-bench records only +/// the size of compact files. +pub async fn vortex_compact_size(input: &Uncompressed) -> Result { + let array = input.vortex()?.clone(); + let buf = tokio::spawn(async move { + let mut buf = Vec::new(); + CompactionStrategy::Compact + .apply_options(SESSION.write_options()) + .write(&mut Cursor::new(&mut buf), array.to_array_stream()) + .await?; + anyhow::Ok(buf) + }) + .await??; + Ok(buf.len() as u64) +} + /// Scan every record batch out of an in-memory Vortex file. async fn vortex_decompress_read(data: Bytes) -> Result<()> { let file = SESSION.open_options().open_buffer(data)?; From 2b22043e78233d257df46f4aa648e9dd133e0f75 Mon Sep 17 00:00:00 2001 From: Will Manning Date: Fri, 20 Nov 2026 17:25:29 -0500 Subject: [PATCH 04/44] Record Arrow IPC, Lance, and Snappy Parquet sizes for TPC-DS SF1 Develop's TPC-DS SF1 run now writes three formats that no query reads, after its queries, so their file sizes are recorded with the others: - `data-gen --size-formats arrow-ipc,parquet-snappy` writes uncompressed Arrow IPC and Snappy Parquet from the base Parquet files. The Snappy files keep the base files' other writer settings and row groups. - `lance-bench --data-only` writes the Lance data and exits. - `vx-bench write-size-formats` runs both, from a new `size_formats` list on a matrix coverage. CI runs it before "Capture file sizes". `capture-file-sizes.py` records the `parquet-snappy` directory, and labels its files by codec like the `parquet` directory's. At SF1 the writes take about 8 seconds and 3.8 GB of disk. Signed-off-by: Will Manning --- .github/workflows/sql-bench-matrix.yml | 10 + .../bench_orchestrator/ci_matrix/catalog.py | 10 +- .../bench_orchestrator/ci_matrix/model.py | 4 +- .../bench_orchestrator/ci_matrix/render.py | 13 +- .../bench_orchestrator/ci_matrix/validate.py | 12 + bench-orchestrator/bench_orchestrator/cli.py | 53 +++++ .../bench_orchestrator/config.py | 26 +++ bench-orchestrator/tests/test_cli.py | 42 ++++ bench-orchestrator/tests/test_matrix.py | 37 +++- benchmarks/lance-bench/src/main.rs | 9 + scripts/capture-file-sizes.py | 21 +- scripts/tests/test_benchmark_reporting.py | 46 ++++ vortex-bench/src/bin/data-gen.rs | 12 + vortex-bench/src/lib.rs | 1 + vortex-bench/src/size_formats.rs | 209 ++++++++++++++++++ 15 files changed, 490 insertions(+), 15 deletions(-) create mode 100644 vortex-bench/src/size_formats.rs diff --git a/.github/workflows/sql-bench-matrix.yml b/.github/workflows/sql-bench-matrix.yml index eda55e47275..9bad1becaeb 100644 --- a/.github/workflows/sql-bench-matrix.yml +++ b/.github/workflows/sql-bench-matrix.yml @@ -294,6 +294,16 @@ jobs: --opt remote-data-dir="$REMOTE_STORAGE" \ ${{ matrix.scale_factor && format('--opt scale-factor={0}', matrix.scale_factor) || '' }} + # Formats that no query reads, written after the queries so they cannot affect them, only + # for the file sizes that "Capture file sizes" records. + - name: Write size-only formats + if: matrix.remote_key == null && matrix.records_data && join(matrix.size_formats, ',') != '' + shell: bash + run: | + uv run --project bench-orchestrator vx-bench write-size-formats "${{ matrix.subcommand }}" \ + --formats-json '${{ toJSON(matrix.size_formats) }}' \ + ${{ matrix.scale_factor && format('--opt scale-factor={0}', matrix.scale_factor) || '' }} + # The `file_size` records join the run's ingest records: develop runs store them in the # benchmarks database (the `file_sizes` table), and PR runs fetch them back as the baseline. - parallel: diff --git a/bench-orchestrator/bench_orchestrator/ci_matrix/catalog.py b/bench-orchestrator/bench_orchestrator/ci_matrix/catalog.py index e905cd85c91..9fbeb146d6c 100644 --- a/bench-orchestrator/bench_orchestrator/ci_matrix/catalog.py +++ b/bench-orchestrator/bench_orchestrator/ci_matrix/catalog.py @@ -9,7 +9,7 @@ from dataclasses import replace -from ..config import Benchmark, BenchmarkTarget, Engine, Format, Integration, ScanEngine +from ..config import Benchmark, BenchmarkTarget, Engine, Format, Integration, ScanEngine, SizeFormat from .model import BenchmarkCase, Catalog, Coverage, ScanCoverage, Storage from .render import merge_coverage from .targets import TargetSet, df, duck @@ -91,6 +91,12 @@ def with_all_scans(coverage: Coverage) -> Coverage: data_formats=(Format.PARQUET, Format.VORTEX, Format.VORTEX_COMPACT, Format.DUCKDB), ) STANDARD_WITH_DUCKDB = Coverage(STANDARD_WITH_DUCKDB_TARGETS) +# TPC-DS SF1 is the SQL data that bench.vortex.dev's File Sizes summary ranks, so develop also +# writes the formats `compress-bench` measures that its queries do not read. They are small at SF1. +STANDARD_WITH_DUCKDB_AND_SIZE_FORMATS = Coverage( + STANDARD_WITH_DUCKDB_TARGETS, + size_formats=(SizeFormat.ARROW_IPC, SizeFormat.LANCE, SizeFormat.PARQUET_SNAPPY), +) DATAFUSION_VORTEX = Coverage(DATAFUSION_VORTEX_TARGETS) COMPACT = Coverage(COMPACT_TARGETS) JOB_DUCKDB = Coverage(duck(Format.PARQUET, Format.VORTEX, Format.DUCKDB)) @@ -252,7 +258,7 @@ def _tpcds_sf100_job(target: BenchmarkTarget) -> str: "pr": DEFAULT, "pr-compact": COMPACT, "pr-full": STANDARD_WITH_DUCKDB, - "develop": STANDARD_WITH_DUCKDB, + "develop": STANDARD_WITH_DUCKDB_AND_SIZE_FORMATS, }, ), BenchmarkCase( diff --git a/bench-orchestrator/bench_orchestrator/ci_matrix/model.py b/bench-orchestrator/bench_orchestrator/ci_matrix/model.py index b30537ae500..15bc670b7d6 100644 --- a/bench-orchestrator/bench_orchestrator/ci_matrix/model.py +++ b/bench-orchestrator/bench_orchestrator/ci_matrix/model.py @@ -7,7 +7,7 @@ from dataclasses import dataclass, replace from enum import Enum -from ..config import SCAN_COMBINATIONS, Benchmark, BenchmarkTarget, Format +from ..config import SCAN_COMBINATIONS, Benchmark, BenchmarkTarget, Format, SizeFormat from .targets import TargetSet @@ -36,6 +36,8 @@ class Coverage: targets: TargetSet data_formats: tuple[Format, ...] | None = None scans: ScanCoverage = ScanCoverage.DEFAULT + # Formats written after the queries only to record their file sizes. No query reads them. + size_formats: tuple[SizeFormat, ...] = () def resolved_targets(self, benchmark: Benchmark) -> TargetSet: """Return the targets this coverage runs in `benchmark`, with every scan engine named. diff --git a/bench-orchestrator/bench_orchestrator/ci_matrix/render.py b/bench-orchestrator/bench_orchestrator/ci_matrix/render.py index d74b9ee90a7..2de2c0310a5 100644 --- a/bench-orchestrator/bench_orchestrator/ci_matrix/render.py +++ b/bench-orchestrator/bench_orchestrator/ci_matrix/render.py @@ -3,7 +3,7 @@ """Render declarative benchmark coverage as GitHub Actions matrices.""" -from ..config import Benchmark, BenchmarkTarget, Engine, Format, Integration, ScanEngine +from ..config import Benchmark, BenchmarkTarget, Engine, Format, Integration, ScanEngine, SizeFormat from .model import BenchmarkCase, Catalog, Coverage, ScanCoverage from .targets import TargetSet from .validate import validate_catalog @@ -31,12 +31,19 @@ def merge_coverage(benchmark: Benchmark, coverages: list[Coverage]) -> Coverage: """Union several coverages of `benchmark`: every resolved target and every generated format.""" targets = TargetSet() formats: set[Format] = set() + size_formats: set[SizeFormat] = set() for coverage in coverages: resolved = coverage.resolved_targets(benchmark) targets = targets | resolved formats.update(_data_formats(coverage, resolved)) + size_formats.update(coverage.size_formats) scans = ScanCoverage.ALL if any(c.scans is ScanCoverage.ALL for c in coverages) else ScanCoverage.DEFAULT - return Coverage(targets, data_formats=tuple(fmt for fmt in _FORMAT_ORDER if fmt in formats), scans=scans) + return Coverage( + targets, + data_formats=tuple(fmt for fmt in _FORMAT_ORDER if fmt in formats), + scans=scans, + size_formats=tuple(fmt for fmt in SizeFormat if fmt in size_formats), + ) ScanGroup = tuple[Engine, Integration, ScanEngine] @@ -95,6 +102,8 @@ def _matrix_entry( # File sizes and trees describe the data, which every entry of a case generates alike, so # only the default entry records them. "records_data": group is None, + # Formats the default entry writes after its queries, only for their file sizes. + "size_formats": [fmt.value for fmt in coverage.size_formats] if group is None else [], } if benchmark.scale_factor is not None: entry["scale_factor"] = str(benchmark.scale_factor) diff --git a/bench-orchestrator/bench_orchestrator/ci_matrix/validate.py b/bench-orchestrator/bench_orchestrator/ci_matrix/validate.py index b07c82038ee..3e5dd87192c 100644 --- a/bench-orchestrator/bench_orchestrator/ci_matrix/validate.py +++ b/bench-orchestrator/bench_orchestrator/ci_matrix/validate.py @@ -31,6 +31,18 @@ def _validate_coverage(benchmark: BenchmarkCase, preset: str, coverage: Coverage if Format.LANCE in coverage.data_formats: raise ValueError(f"Benchmark {benchmark.id!r} cannot generate Lance data in preset {preset!r}") + if len(coverage.size_formats) != len(set(coverage.size_formats)): + raise ValueError(f"Benchmark {benchmark.id!r} repeats a size-only format in preset {preset!r}") + if coverage.size_formats and benchmark.storage is not Storage.NVME: + raise ValueError(f"Benchmark {benchmark.id!r} records no file sizes, so it cannot write size-only formats") + read_formats = {target.format.value for target in coverage.targets} + for size_format in coverage.size_formats: + if size_format.value in read_formats: + raise ValueError( + f"Benchmark {benchmark.id!r} reads {size_format.value!r} in preset {preset!r}, " + "so it needs no size-only write" + ) + def validate_catalog(catalog: Catalog) -> None: """Validate catalog references and per-preset benchmark invariants.""" diff --git a/bench-orchestrator/bench_orchestrator/cli.py b/bench-orchestrator/bench_orchestrator/cli.py index 3ebe58bbfeb..7e0680757da 100644 --- a/bench-orchestrator/bench_orchestrator/cli.py +++ b/bench-orchestrator/bench_orchestrator/cli.py @@ -29,8 +29,10 @@ Engine, Format, RunConfig, + SizeFormat, group_targets_by_backend, parse_formats_json, + parse_size_formats_json, parse_targets_json, resolve_axis_targets, ) @@ -280,6 +282,57 @@ def prepare_data( raise typer.Exit(1) from exc +@app.command("write-size-formats") +def write_size_formats( + benchmark: Annotated[Benchmark, typer.Argument(help="Benchmark suite whose data to write")], + formats_json: Annotated[ + str, + typer.Option("--formats-json", help="Size-only formats to write, as a JSON array"), + ], + verbose: Annotated[bool, typer.Option("--verbose", "-v", help="Log underlying commands")] = False, + options: Annotated[list[str] | None, typer.Option("--opt", help="Benchmark-specific options")] = None, +) -> None: + """Write formats that no query reads, only to record their file sizes. + + Run it after `prepare-data`: each format is written from the benchmark's base Parquet files. + """ + try: + formats = parse_size_formats_json(formats_json) + bench_opts = parse_options(options) + except ValueError as exc: + console.print(f"[red]{exc}[/red]") + raise typer.Exit(1) from exc + + opt_args = [arg for key, value in bench_opts.items() for arg in ("--opt", f"{key}={value}")] + builder = BenchmarkBuilder(verbose=verbose) + commands = [] + data_gen_formats = [fmt.value for fmt in formats if fmt is not SizeFormat.LANCE] + if data_gen_formats: + commands.append( + [ + str(builder.get_data_generator_path()), + benchmark.value, + "--size-formats", + ",".join(data_gen_formats), + *opt_args, + ] + ) + if SizeFormat.LANCE in formats: + commands.append([str(builder.get_binary_path(Engine.LANCE)), benchmark.value, "--data-only", *opt_args]) + + for cmd in commands: + if not Path(cmd[0]).exists(): + console.print(f"[red]Binary not found: {cmd[0]}[/red]") + raise typer.Exit(1) + if verbose: + console.print(f"[dim]$ {' '.join(cmd)}[/dim]") + try: + subprocess.run(cmd, check=True) + except subprocess.CalledProcessError as exc: + console.print(f"[red]Writing size-only formats failed: {exc}[/red]") + raise typer.Exit(1) from exc + + @app.command("matrix") def matrix( preset: Annotated[ diff --git a/bench-orchestrator/bench_orchestrator/config.py b/bench-orchestrator/bench_orchestrator/config.py index 7be6cff9e29..2471cea5804 100644 --- a/bench-orchestrator/bench_orchestrator/config.py +++ b/bench-orchestrator/bench_orchestrator/config.py @@ -68,6 +68,18 @@ class ScanEngine(Enum): V2 = "v2" +class SizeFormat(Enum): + """A format a benchmark writes only to record its file sizes. No query reads it. + + `vx-bench write-size-formats` writes Arrow IPC and Snappy Parquet with `data-gen + --size-formats`, and Lance with `lance-bench --data-only`. + """ + + ARROW_IPC = "arrow-ipc" + LANCE = "lance" + PARQUET_SNAPPY = "parquet-snappy" + + class Benchmark(Enum): """Available benchmark suites.""" @@ -334,6 +346,20 @@ def parse_targets_json(value: str) -> list[BenchmarkTarget]: return _unique_preserve_order(BenchmarkTarget.from_dict(item) for item in raw_targets) +def parse_size_formats_json(value: str) -> list[SizeFormat]: + """Parse a JSON array of size-only format names.""" + try: + raw_formats = json.loads(value) + except json.JSONDecodeError as exc: + raise ValueError("Size formats JSON must be a valid JSON array") from exc + if not isinstance(raw_formats, list) or not all(isinstance(item, str) for item in raw_formats): + raise ValueError("Size formats JSON must be an array of strings") + try: + return _unique_preserve_order(SizeFormat(item) for item in raw_formats) + except ValueError as exc: + raise ValueError(f"Invalid size format in {raw_formats}") from exc + + def parse_formats_json(value: str) -> list[Format]: """Parse a JSON array of format names.""" try: diff --git a/bench-orchestrator/tests/test_cli.py b/bench-orchestrator/tests/test_cli.py index f7f6a0512b4..861c8b08fb6 100644 --- a/bench-orchestrator/tests/test_cli.py +++ b/bench-orchestrator/tests/test_cli.py @@ -47,6 +47,48 @@ def fake_run(cmd: list[str], check: bool) -> None: ] +def test_write_size_formats_runs_data_gen_and_lance_bench(tmp_path, monkeypatch) -> None: + data_gen = tmp_path / "data-gen" + lance_bench = tmp_path / "lance-bench" + for binary in (data_gen, lance_bench): + binary.write_text("", encoding="utf-8") + + commands: list[list[str]] = [] + + def fake_run(cmd: list[str], check: bool) -> None: + assert check is True + commands.append(cmd) + + monkeypatch.setattr(cli_module.BenchmarkBuilder, "get_data_generator_path", lambda self: data_gen) + monkeypatch.setattr(cli_module.BenchmarkBuilder, "get_binary_path", lambda self, engine: lance_bench) + monkeypatch.setattr(cli_module.subprocess, "run", fake_run) + + result = runner.invoke( + cli_module.app, + [ + "write-size-formats", + "tpcds", + "--formats-json", + '["arrow-ipc","lance","parquet-snappy"]', + "--opt", + "scale-factor=1.0", + ], + ) + + assert result.exit_code == 0, result.stdout + assert commands == [ + [str(data_gen), "tpcds", "--size-formats", "arrow-ipc,parquet-snappy", "--opt", "scale-factor=1.0"], + [str(lance_bench), "tpcds", "--data-only", "--opt", "scale-factor=1.0"], + ] + + +def test_write_size_formats_rejects_an_unknown_format() -> None: + result = runner.invoke(cli_module.app, ["write-size-formats", "tpcds", "--formats-json", '["orc"]']) + + assert result.exit_code == 1 + assert "Invalid size format" in result.stdout + + def test_run_writes_compatibility_results_output(tmp_path, monkeypatch) -> None: run_store = ResultStore(base_dir=tmp_path / "runs") output_path = tmp_path / "artifacts" / "results.json" diff --git a/bench-orchestrator/tests/test_matrix.py b/bench-orchestrator/tests/test_matrix.py index 67abe1b8812..780aad801f5 100644 --- a/bench-orchestrator/tests/test_matrix.py +++ b/bench-orchestrator/tests/test_matrix.py @@ -14,7 +14,15 @@ from bench_orchestrator.ci_matrix.model import Catalog, Coverage from bench_orchestrator.ci_matrix.render import render_matrix from bench_orchestrator.ci_matrix.targets import TargetSet -from bench_orchestrator.config import BenchmarkTarget, Engine, Format, Integration, ScanEngine, parse_targets_json +from bench_orchestrator.config import ( + BenchmarkTarget, + Engine, + Format, + Integration, + ScanEngine, + SizeFormat, + parse_targets_json, +) from typer.testing import CliRunner runner = CliRunner() @@ -317,6 +325,33 @@ def test_matrix_entries_name_their_data_directory() -> None: assert entries["tpch-nvme"]["dataset_dir"] == "tpch" +@pytest.mark.parametrize("preset", tuple(MATRIX_PRESETS)) +def test_only_develop_tpcds_sf1_writes_size_only_formats(preset: str) -> None: + writers = {entry["id"]: entry["size_formats"] for entry in _entries(preset) if entry["size_formats"]} + + if preset == "develop": + assert writers == {"tpcds-nvme": ["arrow-ipc", "lance", "parquet-snappy"]} + else: + assert writers == {} + + +def test_resolver_rejects_a_size_only_format_that_a_target_reads() -> None: + benchmark = replace( + CATALOG.benchmarks[0], + id="reads-lance", + runs={ + "develop": Coverage( + TargetSet((BenchmarkTarget(Engine.DATAFUSION, Format.LANCE),)), + size_formats=(SizeFormat.LANCE,), + ) + }, + ) + catalog = Catalog(presets=CATALOG.presets, benchmarks=(benchmark,)) + + with pytest.raises(ValueError, match="reads 'lance'.*needs no size-only write"): + _ = render_matrix("develop", catalog) + + def test_matrix_command() -> None: result = runner.invoke(cli_module.app, ["matrix", "develop"]) assert result.exit_code == 0 diff --git a/benchmarks/lance-bench/src/main.rs b/benchmarks/lance-bench/src/main.rs index ec5209f0b11..2a01b557d87 100644 --- a/benchmarks/lance-bench/src/main.rs +++ b/benchmarks/lance-bench/src/main.rs @@ -65,6 +65,11 @@ struct Args { #[arg(long, default_value_t = false)] print_queries: bool, + /// Write the benchmark's Lance data and exit without running queries. CI uses it to record + /// Lance file sizes for a benchmark whose queries it does not run on Lance. + #[arg(long, default_value_t = false)] + data_only: bool, + #[arg(short)] output_path: Option, @@ -117,6 +122,10 @@ async fn main() -> anyhow::Result<()> { // Convert Parquet to Lance format generate_lance_data(&*benchmark).await?; + if args.data_only { + return Ok(()); + } + let mut runner = SqlBenchmarkRunner::new( &*benchmark, Engine::DataFusion, diff --git a/scripts/capture-file-sizes.py b/scripts/capture-file-sizes.py index a6179a12c48..d421a222701 100644 --- a/scripts/capture-file-sizes.py +++ b/scripts/capture-file-sizes.py @@ -129,23 +129,24 @@ def parquet_codecs(path: Path) -> set[str]: return codecs -def parquet_format_name(path: Path) -> str: +def parquet_format_name(path: Path, directory: str = "parquet") -> str: """Name a Parquet file's format by its codec, as `vortex` and `vortex-compact` name Vortex's. `parquet` is zstd, the codec every Parquet file the benchmarks write themselves uses (zstd level 3). A file written with another codec, such as Snappy in a downloaded dataset, is - `parquet-`. A file whose footer cannot be read, or that mixes codecs, keeps `parquet` - with a warning, as before codecs were recorded. + `parquet-`. A file whose footer cannot be read, or that mixes codecs, keeps the name of + its `directory` with a warning: `parquet`, as before codecs were recorded, or + `parquet-snappy`, which `data-gen --size-formats` writes. """ try: codecs = parquet_codecs(path) except (OSError, ValueError, IndexError, struct.error) as error: print(f"Could not read the Parquet footer of {path}: {error}", file=sys.stderr) - return "parquet" + return directory if len(codecs) != 1: if codecs: - print(f"{path} mixes Parquet codecs {sorted(codecs)}; recording it as parquet", file=sys.stderr) - return "parquet" + print(f"{path} mixes Parquet codecs {sorted(codecs)}; recording it as {directory}", file=sys.stderr) + return directory codec = next(iter(codecs)) return "parquet" if codec == "zstd" else f"parquet-{codec}" @@ -176,7 +177,8 @@ def main() -> None: sys.exit(1) # Every on-disk format, named as `Format::name()` in `vortex-bench/src/lib.rs` names its - # directory. The "vortex" CLI argument maps to the "vortex-file-compressed" directory. + # directory, and `parquet-snappy`, a `SizeFormat` in `vortex-bench/src/size_formats.rs`. The + # "vortex" CLI argument maps to the "vortex-file-compressed" directory. formats_to_capture = { "arrow-ipc", "csv", @@ -184,6 +186,7 @@ def main() -> None: "lance", "litdata", "parquet", + "parquet-snappy", "vortex-compact", "vortex-file-compressed", "vortex-spatial-native", @@ -220,8 +223,8 @@ def main() -> None: size_bytes = file_path.stat().st_size recorded_format = ( - parquet_format_name(file_path) - if format_name == "parquet" and file_path.suffix == ".parquet" + parquet_format_name(file_path, format_name) + if format_name in ("parquet", "parquet-snappy") and file_path.suffix == ".parquet" else format_name ) diff --git a/scripts/tests/test_benchmark_reporting.py b/scripts/tests/test_benchmark_reporting.py index c1ccbbfb9c3..19c3ce68850 100644 --- a/scripts/tests/test_benchmark_reporting.py +++ b/scripts/tests/test_benchmark_reporting.py @@ -1008,6 +1008,52 @@ def test_capture_file_sizes_names_parquet_by_codec(tmp_path: Path) -> None: assert "Could not read the Parquet footer" in result.stderr +def test_capture_file_sizes_records_the_size_only_snappy_directory(tmp_path: Path) -> None: + data_dir = tmp_path / "data" + scale_dir = data_dir / "tpcds" / "1.0" + zstd, snappy = 6, 1 + files = { + ("parquet", "item.parquet"): parquet_with_codecs([zstd]), + ("parquet-snappy", "item.parquet"): parquet_with_codecs([snappy]), + ("parquet-snappy", "store.parquet"): b"not parquet", + ("arrow-ipc", "item.arrow"): b"x" * 80, + } + for (format_name, name), data in files.items(): + path = scale_dir / format_name / name + path.parent.mkdir(parents=True, exist_ok=True) + path.write_bytes(data) + output_path = tmp_path / "sizes.jsonl" + + result = subprocess.run( + [ + sys.executable, + str(CAPTURE_SCRIPT), + str(data_dir), + "--benchmark", + "tpcds", + "--dataset-dir", + "tpcds", + "--commit", + "deadbeef", + "-o", + str(output_path), + ], + check=False, + capture_output=True, + text=True, + ) + + assert result.returncode == 0, result.stderr + records = [json.loads(line) for line in output_path.read_text(encoding="utf-8").splitlines()] + assert [(r["file_size"]["format"], r["file_size"]["file"]) for r in records] == [ + ("arrow-ipc", "item.arrow"), + ("parquet", "item.parquet"), + ("parquet-snappy", "item.parquet"), + # An unreadable footer in the Snappy directory keeps that directory's name. + ("parquet-snappy", "store.parquet"), + ] + + def test_capture_file_sizes_reads_only_the_named_directory(tmp_path: Path) -> None: data_dir = tmp_path / "data" for name, size in (("clickbench_partitioned", 42), ("clickbench_partitioned_10", 7)): diff --git a/vortex-bench/src/bin/data-gen.rs b/vortex-bench/src/bin/data-gen.rs index 61233d1e6fe..8f03ce32801 100644 --- a/vortex-bench/src/bin/data-gen.rs +++ b/vortex-bench/src/bin/data-gen.rs @@ -25,6 +25,8 @@ use vortex_bench::conversions::convert_parquet_directory_to_vortex; use vortex_bench::create_benchmark; use vortex_bench::generate_duckdb_registration_sql; use vortex_bench::setup_logging_and_tracing_with_format; +use vortex_bench::size_formats::SizeFormat; +use vortex_bench::size_formats::write_size_format; #[derive(Parser)] #[command(name = "bench-data-gen")] @@ -47,6 +49,11 @@ struct Args { #[arg(long, value_delimiter = ',', value_parser = value_parser!(Format))] formats: Vec, + /// Formats to write only for their file sizes, from the base Parquet files. No benchmark + /// query reads them. + #[arg(long, value_delimiter = ',', value_enum)] + size_formats: Vec, + #[arg(long = "opt", value_delimiter = ',', value_parser = value_parser!(Opt))] options: Vec, } @@ -101,6 +108,11 @@ async fn main() -> anyhow::Result<()> { for format in args.formats.iter().copied() { benchmark.prepare_format(format, &base_path).await?; } + + for format in args.size_formats.iter().copied() { + let base_path = base_path.clone(); + tokio::task::spawn_blocking(move || write_size_format(&base_path, format)).await??; + } } Ok(()) diff --git a/vortex-bench/src/lib.rs b/vortex-bench/src/lib.rs index 46c6d8b0250..b3744858dda 100644 --- a/vortex-bench/src/lib.rs +++ b/vortex-bench/src/lib.rs @@ -60,6 +60,7 @@ pub mod public_bi; pub mod random_access; pub mod realnest; pub mod runner; +pub mod size_formats; pub mod spatialbench; pub mod statpopgen; pub mod tpcds; diff --git a/vortex-bench/src/size_formats.rs b/vortex-bench/src/size_formats.rs new file mode 100644 index 00000000000..e86055eece1 --- /dev/null +++ b/vortex-bench/src/size_formats.rs @@ -0,0 +1,209 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +//! Formats that a SQL benchmark writes only to record their file sizes. No query reads them. +//! +//! `data-gen --size-formats` writes them from the benchmark's base Parquet files, one output file +//! for each input file, in a directory of the format's name beside the base `parquet` directory. +//! `scripts/capture-file-sizes.py` then records their sizes with the other formats. Lance is also +//! written for size only, but `lance-bench --data-only` writes it, because only that binary +//! depends on Lance. + +use std::fs; +use std::fs::File; +use std::io::BufWriter; +use std::path::Path; +use std::sync::Arc; + +use anyhow::Context; +use anyhow::Result; +use arrow_ipc::writer::FileWriter; +use clap::ValueEnum; +use parquet::arrow::ArrowWriter; +use parquet::arrow::arrow_reader::ParquetRecordBatchReaderBuilder; +use parquet::basic::Compression; +use tracing::info; + +use crate::Format; +use crate::idempotent; +use crate::utils::parquet::parquet_writer_properties; + +/// A format that is written only to record its file size. +#[derive(Clone, Copy, Debug, PartialEq, Eq, ValueEnum)] +pub enum SizeFormat { + /// Uncompressed Arrow IPC, as `compress-bench` writes it. + #[clap(name = "arrow-ipc")] + ArrowIpc, + /// Parquet with Snappy compression and the base files' other writer settings. + #[clap(name = "parquet-snappy")] + ParquetSnappy, +} + +impl SizeFormat { + /// The format's directory name, which is also its name in the file size records. + pub fn name(self) -> &'static str { + match self { + SizeFormat::ArrowIpc => Format::ArrowIpc.name(), + SizeFormat::ParquetSnappy => "parquet-snappy", + } + } + + fn ext(self) -> &'static str { + match self { + SizeFormat::ArrowIpc => Format::ArrowIpc.ext(), + SizeFormat::ParquetSnappy => Format::Parquet.ext(), + } + } +} + +/// Write `format` from every Parquet file in `{base_path}/parquet/` to `{base_path}/{format}/`. +/// +/// The write is idempotent: an output file that exists is not written again. +pub fn write_size_format(base_path: &Path, format: SizeFormat) -> Result<()> { + let parquet_dir = base_path.join(Format::Parquet.name()); + let output_dir = base_path.join(format.name()); + let mut inputs = fs::read_dir(&parquet_dir) + .with_context(|| format!("reading {}", parquet_dir.display()))? + .map(|entry| entry.map(|entry| entry.path())) + .collect::>>()?; + inputs.retain(|path| path.extension().is_some_and(|ext| ext == "parquet")); + inputs.sort(); + + info!( + "Writing {} files as {} in {}", + inputs.len(), + format.name(), + output_dir.display() + ); + for input in inputs { + let stem = input + .file_stem() + .context("a Parquet file has no name")? + .to_os_string(); + let mut output = output_dir.join(stem); + output.set_extension(format.ext()); + idempotent(output.as_path(), |temp| match format { + SizeFormat::ArrowIpc => write_arrow_ipc(&input, temp), + SizeFormat::ParquetSnappy => write_snappy_parquet(&input, temp), + }) + .with_context(|| format!("writing {} as {}", input.display(), format.name()))?; + } + Ok(()) +} + +/// Write the Parquet file `input` as an uncompressed Arrow IPC file. +fn write_arrow_ipc(input: &Path, output: &Path) -> Result<()> { + let reader = ParquetRecordBatchReaderBuilder::try_new(File::open(input)?)?; + let schema = Arc::clone(reader.schema()); + let mut writer = FileWriter::try_new(BufWriter::new(File::create(output)?), &schema)?; + for batch in reader.build()? { + writer.write(&batch?)?; + } + writer.finish()?; + Ok(()) +} + +/// Write the Parquet file `input` again with Snappy. Every other setting is the base files': +/// [`parquet_writer_properties`], and the row group size of `input`'s first row group. +fn write_snappy_parquet(input: &Path, output: &Path) -> Result<()> { + let reader = ParquetRecordBatchReaderBuilder::try_new(File::open(input)?)?; + let schema = Arc::clone(reader.schema()); + let row_group_rows = reader + .metadata() + .row_groups() + .first() + .map(|row_group| usize::try_from(row_group.num_rows())) + .transpose()?; + let props = parquet_writer_properties() + .set_compression(Compression::SNAPPY) + .set_max_row_group_row_count(row_group_rows) + .build(); + let mut writer = ArrowWriter::try_new(File::create(output)?, schema, Some(props))?; + for batch in reader.build()? { + writer.write(&batch?)?; + } + writer.close()?; + Ok(()) +} + +#[cfg(test)] +mod tests { + use arrow_array::Int64Array; + use arrow_array::RecordBatch; + use arrow_array::StringArray; + use arrow_ipc::reader::FileReader; + use arrow_schema::DataType; + use arrow_schema::Field; + use arrow_schema::Schema; + use parquet::file::reader::FileReader as _; + use parquet::file::reader::SerializedFileReader; + + use super::*; + + /// Write `rows` rows to `{base}/parquet/t.parquet`, in row groups of `row_group_rows`. + fn write_base(base: &Path, rows: i64, row_group_rows: usize) -> Result { + let schema = Arc::new(Schema::new(vec![ + Field::new("id", DataType::Int64, false), + Field::new("name", DataType::Utf8, false), + ])); + let batch = RecordBatch::try_new( + Arc::clone(&schema), + vec![ + Arc::new(Int64Array::from_iter_values(0..rows)), + Arc::new(StringArray::from_iter_values( + (0..rows).map(|i| format!("name-{}", i % 7)), + )), + ], + )?; + let dir = base.join(Format::Parquet.name()); + fs::create_dir_all(&dir)?; + let props = parquet_writer_properties() + .set_max_row_group_row_count(Some(row_group_rows)) + .build(); + let mut writer = + ArrowWriter::try_new(File::create(dir.join("t.parquet"))?, schema, Some(props))?; + writer.write(&batch)?; + writer.close()?; + Ok(batch) + } + + #[test] + fn snappy_parquet_keeps_the_row_groups_and_changes_only_the_codec() -> Result<()> { + let base = tempfile::tempdir()?; + write_base(base.path(), 1000, 300)?; + + write_size_format(base.path(), SizeFormat::ParquetSnappy)?; + + let output = base.path().join("parquet-snappy").join("t.parquet"); + let metadata = SerializedFileReader::new(File::open(output)?)? + .metadata() + .clone(); + let row_groups: Vec = metadata + .row_groups() + .iter() + .map(|rg| rg.num_rows()) + .collect(); + assert_eq!(row_groups, [300, 300, 300, 100]); + for row_group in metadata.row_groups() { + for column in row_group.columns() { + assert_eq!(column.compression(), Compression::SNAPPY); + } + } + Ok(()) + } + + #[test] + fn arrow_ipc_holds_the_same_rows() -> Result<()> { + let base = tempfile::tempdir()?; + let expected = write_base(base.path(), 100, 64)?; + + write_size_format(base.path(), SizeFormat::ArrowIpc)?; + + let output = base.path().join("arrow-ipc").join("t.arrow"); + let batches = + FileReader::try_new(File::open(output)?, None)?.collect::, _>>()?; + let actual = arrow_select::concat::concat_batches(&expected.schema(), &batches)?; + assert_eq!(actual, expected); + Ok(()) + } +} From f6b1de048e9e9fd1c2e062b0a30ee253b865fecd Mon Sep 17 00:00:00 2001 From: Will Manning Date: Fri, 20 Nov 2026 17:48:21 -0500 Subject: [PATCH 05/44] Query Snappy Parquet and Lance on TPC-DS SF1 Develop's TPC-DS SF1 run now queries Snappy Parquet on DataFusion and DuckDB, and Lance on DataFusion. data-gen writes Snappy Parquet as the parquet-snappy format, from the base Parquet files with the same row groups. Arrow IPC stays a size-only format. Lance skips TPC-DS q72, which overflows its Utf8 offsets. bench ranks a series that misses a query below every series that ran them all. Signed-off-by: Will Manning --- .../bench_orchestrator/ci_matrix/catalog.py | 9 +-- .../bench_orchestrator/ci_matrix/render.py | 1 + .../bench_orchestrator/config.py | 9 ++- bench-orchestrator/tests/test_cli.py | 4 +- bench-orchestrator/tests/test_matrix.py | 15 ++++- benchmarks/datafusion-bench/src/lib.rs | 2 +- benchmarks/duckdb-bench/src/lib.rs | 1 + benchmarks/lance-bench/src/main.rs | 23 ++++++- scripts/capture-file-sizes.py | 5 +- scripts/compare-benchmark-jsons.py | 9 +-- vortex-bench/src/bin/data-gen.rs | 15 +++-- vortex-bench/src/lib.rs | 9 ++- .../{size_formats.rs => parquet_copies.rs} | 61 +++++++++---------- 13 files changed, 106 insertions(+), 57 deletions(-) rename vortex-bench/src/{size_formats.rs => parquet_copies.rs} (77%) diff --git a/bench-orchestrator/bench_orchestrator/ci_matrix/catalog.py b/bench-orchestrator/bench_orchestrator/ci_matrix/catalog.py index 9fbeb146d6c..aaf2fd58c10 100644 --- a/bench-orchestrator/bench_orchestrator/ci_matrix/catalog.py +++ b/bench-orchestrator/bench_orchestrator/ci_matrix/catalog.py @@ -91,11 +91,12 @@ def with_all_scans(coverage: Coverage) -> Coverage: data_formats=(Format.PARQUET, Format.VORTEX, Format.VORTEX_COMPACT, Format.DUCKDB), ) STANDARD_WITH_DUCKDB = Coverage(STANDARD_WITH_DUCKDB_TARGETS) -# TPC-DS SF1 is the SQL data that bench.vortex.dev's File Sizes summary ranks, so develop also -# writes the formats `compress-bench` measures that its queries do not read. They are small at SF1. +# TPC-DS SF1 is the SQL data that bench.vortex.dev's File Sizes summary ranks, so develop has every +# format `compress-bench` measures. It queries Snappy Parquet on both engines and Lance on +# DataFusion, and writes Arrow IPC only for its size. They are small and fast at SF1. STANDARD_WITH_DUCKDB_AND_SIZE_FORMATS = Coverage( - STANDARD_WITH_DUCKDB_TARGETS, - size_formats=(SizeFormat.ARROW_IPC, SizeFormat.LANCE, SizeFormat.PARQUET_SNAPPY), + STANDARD_WITH_DUCKDB_TARGETS | df(Format.PARQUET_SNAPPY, Format.LANCE) | duck(Format.PARQUET_SNAPPY), + size_formats=(SizeFormat.ARROW_IPC,), ) DATAFUSION_VORTEX = Coverage(DATAFUSION_VORTEX_TARGETS) COMPACT = Coverage(COMPACT_TARGETS) diff --git a/bench-orchestrator/bench_orchestrator/ci_matrix/render.py b/bench-orchestrator/bench_orchestrator/ci_matrix/render.py index 2de2c0310a5..a4d3c18759b 100644 --- a/bench-orchestrator/bench_orchestrator/ci_matrix/render.py +++ b/bench-orchestrator/bench_orchestrator/ci_matrix/render.py @@ -11,6 +11,7 @@ _NOT_GENERATED = frozenset({Format.LANCE}) _FORMAT_ORDER = ( Format.PARQUET, + Format.PARQUET_SNAPPY, Format.VORTEX, Format.VORTEX_COMPACT, Format.VORTEX_SPATIAL_NATIVE, diff --git a/bench-orchestrator/bench_orchestrator/config.py b/bench-orchestrator/bench_orchestrator/config.py index 2471cea5804..2710785d17b 100644 --- a/bench-orchestrator/bench_orchestrator/config.py +++ b/bench-orchestrator/bench_orchestrator/config.py @@ -41,6 +41,8 @@ class Format(Enum): """Data formats for benchmarks.""" PARQUET = "parquet" + # The base Parquet files rewritten with Snappy, which `data-gen` writes beside them. + PARQUET_SNAPPY = "parquet-snappy" VORTEX = "vortex" VORTEX_COMPACT = "vortex-compact" VORTEX_SPATIAL_NATIVE = "vortex-spatial-native" @@ -71,13 +73,12 @@ class ScanEngine(Enum): class SizeFormat(Enum): """A format a benchmark writes only to record its file sizes. No query reads it. - `vx-bench write-size-formats` writes Arrow IPC and Snappy Parquet with `data-gen - --size-formats`, and Lance with `lance-bench --data-only`. + `vx-bench write-size-formats` writes Arrow IPC with `data-gen --size-formats`, and Lance with + `lance-bench --data-only`. """ ARROW_IPC = "arrow-ipc" LANCE = "lance" - PARQUET_SNAPPY = "parquet-snappy" class Benchmark(Enum): @@ -103,12 +104,14 @@ class Benchmark(Enum): ENGINE_FORMATS: dict[Engine, list[Format]] = { Engine.DATAFUSION: [ Format.PARQUET, + Format.PARQUET_SNAPPY, Format.VORTEX, Format.VORTEX_COMPACT, Format.LANCE, ], Engine.DUCKDB: [ Format.PARQUET, + Format.PARQUET_SNAPPY, Format.VORTEX, Format.VORTEX_COMPACT, Format.VORTEX_SPATIAL_NATIVE, diff --git a/bench-orchestrator/tests/test_cli.py b/bench-orchestrator/tests/test_cli.py index 861c8b08fb6..b550ebe45fd 100644 --- a/bench-orchestrator/tests/test_cli.py +++ b/bench-orchestrator/tests/test_cli.py @@ -69,7 +69,7 @@ def fake_run(cmd: list[str], check: bool) -> None: "write-size-formats", "tpcds", "--formats-json", - '["arrow-ipc","lance","parquet-snappy"]', + '["arrow-ipc","lance"]', "--opt", "scale-factor=1.0", ], @@ -77,7 +77,7 @@ def fake_run(cmd: list[str], check: bool) -> None: assert result.exit_code == 0, result.stdout assert commands == [ - [str(data_gen), "tpcds", "--size-formats", "arrow-ipc,parquet-snappy", "--opt", "scale-factor=1.0"], + [str(data_gen), "tpcds", "--size-formats", "arrow-ipc", "--opt", "scale-factor=1.0"], [str(lance_bench), "tpcds", "--data-only", "--opt", "scale-factor=1.0"], ] diff --git a/bench-orchestrator/tests/test_matrix.py b/bench-orchestrator/tests/test_matrix.py index 780aad801f5..24994322bed 100644 --- a/bench-orchestrator/tests/test_matrix.py +++ b/bench-orchestrator/tests/test_matrix.py @@ -330,11 +330,24 @@ def test_only_develop_tpcds_sf1_writes_size_only_formats(preset: str) -> None: writers = {entry["id"]: entry["size_formats"] for entry in _entries(preset) if entry["size_formats"]} if preset == "develop": - assert writers == {"tpcds-nvme": ["arrow-ipc", "lance", "parquet-snappy"]} + assert writers == {"tpcds-nvme": ["arrow-ipc"]} else: assert writers == {} +def test_develop_tpcds_sf1_queries_snappy_parquet_and_lance() -> None: + entry = {entry["id"]: entry for entry in _entries("develop")}["tpcds-nvme"] + targets = {(target["engine"], target["format"]) for target in entry["targets"]} + + assert { + ("datafusion", "parquet-snappy"), + ("duckdb", "parquet-snappy"), + ("datafusion", "lance"), + } <= targets + assert entry["data_formats"][:2] == ["parquet", "parquet-snappy"] + assert "lance" not in entry["data_formats"] + + def test_resolver_rejects_a_size_only_format_that_a_target_reads() -> None: benchmark = replace( CATALOG.benchmarks[0], diff --git a/benchmarks/datafusion-bench/src/lib.rs b/benchmarks/datafusion-bench/src/lib.rs index 5f0b1a6800e..8ebee6129f7 100644 --- a/benchmarks/datafusion-bench/src/lib.rs +++ b/benchmarks/datafusion-bench/src/lib.rs @@ -103,7 +103,7 @@ pub fn format_to_df_format(format: Format, scan_v2: bool) -> anyhow::Result Arc::new(CsvFormat::default()) as _, - Format::Parquet => Arc::new(ParquetFormat::new()), + Format::Parquet | Format::ParquetSnappy => Arc::new(ParquetFormat::new()), Format::OnDiskVortex | Format::VortexCompact | Format::VortexSpatialNative => { Arc::new(VortexFormat::new_with_options(SESSION.clone(), options)) } diff --git a/benchmarks/duckdb-bench/src/lib.rs b/benchmarks/duckdb-bench/src/lib.rs index a5c90ce3c23..324a7646fe4 100644 --- a/benchmarks/duckdb-bench/src/lib.rs +++ b/benchmarks/duckdb-bench/src/lib.rs @@ -206,6 +206,7 @@ impl DuckClient { let object_type = match file_format { Format::Parquet + | Format::ParquetSnappy | Format::OnDiskVortex | Format::VortexCompact | Format::VortexSpatialNative => "VIEW", diff --git a/benchmarks/lance-bench/src/main.rs b/benchmarks/lance-bench/src/main.rs index 2a01b557d87..3dd893f0e01 100644 --- a/benchmarks/lance-bench/src/main.rs +++ b/benchmarks/lance-bench/src/main.rs @@ -93,6 +93,17 @@ struct Args { #[global_allocator] static GLOBAL: MiMalloc = MiMalloc; +/// Queries that Lance cannot run, as `(dataset name, query index)`. They are left out of the +/// query list, so `--print-queries` does not name them either. +/// +/// - TPC-DS q72 fails with an Arrow offset overflow on Lance's data. Lance stores strings as +/// `Utf8`, whose 32-bit offsets overflow when the query collects more than 2 GiB of strings in +/// one array. Parquet reads as `Utf8View`, which does not overflow. +/// +/// A skipped query is not a free win: bench.vortex.dev ranks a series that has no time for a +/// query below every series that ran them all. +const UNSUPPORTED_QUERIES: &[(&str, usize)] = &[("tpcds", 72)]; + #[tokio::main] async fn main() -> anyhow::Result<()> { vortex_bench::configure_allocator(); @@ -103,11 +114,21 @@ async fn main() -> anyhow::Result<()> { let benchmark = create_benchmark(args.benchmark, &opts)?; - let filtered_queries = filter_queries( + let mut filtered_queries = filter_queries( benchmark.queries()?, args.queries.as_ref(), args.exclude_queries.as_ref(), ); + filtered_queries.retain(|(query_idx, _)| { + let unsupported = UNSUPPORTED_QUERIES.contains(&(benchmark.dataset_name(), *query_idx)); + if unsupported { + info!( + "Skipping {} q{query_idx}, which Lance cannot run", + benchmark.dataset_name() + ); + } + !unsupported + }); if args.print_queries { for (query_idx, _) in &filtered_queries { diff --git a/scripts/capture-file-sizes.py b/scripts/capture-file-sizes.py index d421a222701..6c628e9ee76 100644 --- a/scripts/capture-file-sizes.py +++ b/scripts/capture-file-sizes.py @@ -136,7 +136,7 @@ def parquet_format_name(path: Path, directory: str = "parquet") -> str: level 3). A file written with another codec, such as Snappy in a downloaded dataset, is `parquet-`. A file whose footer cannot be read, or that mixes codecs, keeps the name of its `directory` with a warning: `parquet`, as before codecs were recorded, or - `parquet-snappy`, which `data-gen --size-formats` writes. + `parquet-snappy`, which `data-gen --formats parquet-snappy` writes. """ try: codecs = parquet_codecs(path) @@ -177,8 +177,7 @@ def main() -> None: sys.exit(1) # Every on-disk format, named as `Format::name()` in `vortex-bench/src/lib.rs` names its - # directory, and `parquet-snappy`, a `SizeFormat` in `vortex-bench/src/size_formats.rs`. The - # "vortex" CLI argument maps to the "vortex-file-compressed" directory. + # directory. The "vortex" CLI argument maps to the "vortex-file-compressed" directory. formats_to_capture = { "arrow-ipc", "csv", diff --git a/scripts/compare-benchmark-jsons.py b/scripts/compare-benchmark-jsons.py index d8adca90adf..bde7c9d8b14 100644 --- a/scripts/compare-benchmark-jsons.py +++ b/scripts/compare-benchmark-jsons.py @@ -1282,10 +1282,11 @@ def format_report_help() -> str: "vortex-file-compressed": 0, "vortex-compact": 1, "parquet": 2, - "lance": 3, - "duckdb": 4, - "arrow": 5, - "litdata": 6, + "parquet-snappy": 3, + "lance": 4, + "duckdb": 5, + "arrow": 6, + "litdata": 7, } UNIT_ORDER = { diff --git a/vortex-bench/src/bin/data-gen.rs b/vortex-bench/src/bin/data-gen.rs index 8f03ce32801..faa66608b5d 100644 --- a/vortex-bench/src/bin/data-gen.rs +++ b/vortex-bench/src/bin/data-gen.rs @@ -24,9 +24,10 @@ use vortex_bench::Opts; use vortex_bench::conversions::convert_parquet_directory_to_vortex; use vortex_bench::create_benchmark; use vortex_bench::generate_duckdb_registration_sql; +use vortex_bench::parquet_copies::SizeFormat; +use vortex_bench::parquet_copies::write_size_format; +use vortex_bench::parquet_copies::write_snappy_parquet_directory; use vortex_bench::setup_logging_and_tracing_with_format; -use vortex_bench::size_formats::SizeFormat; -use vortex_bench::size_formats::write_size_format; #[derive(Parser)] #[command(name = "bench-data-gen")] @@ -49,8 +50,8 @@ struct Args { #[arg(long, value_delimiter = ',', value_parser = value_parser!(Format))] formats: Vec, - /// Formats to write only for their file sizes, from the base Parquet files. No benchmark - /// query reads them. + /// Formats to write only for their file sizes, from the base Parquet files. No query reads + /// them. #[arg(long, value_delimiter = ',', value_enum)] size_formats: Vec, @@ -97,6 +98,12 @@ async fn main() -> anyhow::Result<()> { convert_parquet_directory_to_vortex(&base_path, CompactionStrategy::Compact).await?; } + if args.formats.contains(&Format::ParquetSnappy) { + let base_path = base_path.clone(); + tokio::task::spawn_blocking(move || write_snappy_parquet_directory(&base_path)) + .await??; + } + if args .formats .iter() diff --git a/vortex-bench/src/lib.rs b/vortex-bench/src/lib.rs index b3744858dda..56e569cece9 100644 --- a/vortex-bench/src/lib.rs +++ b/vortex-bench/src/lib.rs @@ -55,12 +55,12 @@ pub mod job; pub mod measurements; pub mod memory; pub mod output; +pub mod parquet_copies; pub mod polarsignals; pub mod public_bi; pub mod random_access; pub mod realnest; pub mod runner; -pub mod size_formats; pub mod spatialbench; pub mod statpopgen; pub mod tpcds; @@ -218,6 +218,11 @@ pub enum Format { Csv, #[clap(name = "parquet")] Parquet, + /// Parquet with Snappy compression, the base Parquet files written again with Snappy in + /// place of zstd. Only suites that list it generate it. + #[clap(name = "parquet-snappy")] + #[serde(rename = "parquet-snappy")] + ParquetSnappy, #[clap(name = "vortex")] #[serde(rename = "vortex")] OnDiskVortex, @@ -273,6 +278,7 @@ impl Format { Format::ArrowIpc => "arrow-ipc", Format::Csv => "csv", Format::Parquet => "parquet", + Format::ParquetSnappy => "parquet-snappy", Format::OnDiskVortex => "vortex-file-compressed", Format::VortexCompact => "vortex-compact", Format::VortexSpatialNative => "vortex-spatial-native", @@ -287,6 +293,7 @@ impl Format { Format::ArrowIpc => "arrow", Format::Csv => "csv", Format::Parquet => "parquet", + Format::ParquetSnappy => "parquet", Format::OnDiskVortex => "vortex", Format::VortexCompact => "vortex", Format::VortexSpatialNative => "vortex", diff --git a/vortex-bench/src/size_formats.rs b/vortex-bench/src/parquet_copies.rs similarity index 77% rename from vortex-bench/src/size_formats.rs rename to vortex-bench/src/parquet_copies.rs index e86055eece1..1b6ac9e8822 100644 --- a/vortex-bench/src/size_formats.rs +++ b/vortex-bench/src/parquet_copies.rs @@ -1,13 +1,12 @@ -// SPDX-License-Identifier: Apache-2.0 -// SPDX-FileCopyrightText: Copyright the Vortex contributors - -//! Formats that a SQL benchmark writes only to record their file sizes. No query reads them. +//! Copies of a benchmark's base Parquet files in other formats, one output file for each input +//! file, in a directory of the format's name beside the base `parquet` directory. //! -//! `data-gen --size-formats` writes them from the benchmark's base Parquet files, one output file -//! for each input file, in a directory of the format's name beside the base `parquet` directory. -//! `scripts/capture-file-sizes.py` then records their sizes with the other formats. Lance is also -//! written for size only, but `lance-bench --data-only` writes it, because only that binary -//! depends on Lance. +//! - [`Format::ParquetSnappy`]: the same files written with Snappy in place of zstd. The query +//! engines read it like Parquet. `data-gen --formats parquet-snappy` writes it. +//! - [`SizeFormat::ArrowIpc`]: uncompressed Arrow IPC, which no query reads. `data-gen +//! --size-formats arrow-ipc` writes it only so that `scripts/capture-file-sizes.py` records its +//! size. Lance is also written for size only, by `lance-bench --data-only`, because only that +//! binary depends on Lance. use std::fs; use std::fs::File; @@ -28,38 +27,37 @@ use crate::Format; use crate::idempotent; use crate::utils::parquet::parquet_writer_properties; -/// A format that is written only to record its file size. +/// A format that is written only to record its file size. No query reads it. #[derive(Clone, Copy, Debug, PartialEq, Eq, ValueEnum)] pub enum SizeFormat { /// Uncompressed Arrow IPC, as `compress-bench` writes it. #[clap(name = "arrow-ipc")] ArrowIpc, - /// Parquet with Snappy compression and the base files' other writer settings. - #[clap(name = "parquet-snappy")] - ParquetSnappy, } -impl SizeFormat { - /// The format's directory name, which is also its name in the file size records. - pub fn name(self) -> &'static str { - match self { - SizeFormat::ArrowIpc => Format::ArrowIpc.name(), - SizeFormat::ParquetSnappy => "parquet-snappy", +/// Write `format` from the base Parquet files in `base_path`. +pub fn write_size_format(base_path: &Path, format: SizeFormat) -> Result<()> { + match format { + SizeFormat::ArrowIpc => { + copy_parquet_directory(base_path, Format::ArrowIpc, write_arrow_ipc) } } +} - fn ext(self) -> &'static str { - match self { - SizeFormat::ArrowIpc => Format::ArrowIpc.ext(), - SizeFormat::ParquetSnappy => Format::Parquet.ext(), - } - } +/// Write every Parquet file in `{base_path}/parquet/` again with Snappy, to +/// `{base_path}/parquet-snappy/`. +pub fn write_snappy_parquet_directory(base_path: &Path) -> Result<()> { + copy_parquet_directory(base_path, Format::ParquetSnappy, write_snappy_parquet) } -/// Write `format` from every Parquet file in `{base_path}/parquet/` to `{base_path}/{format}/`. +/// Write each Parquet file in `{base_path}/parquet/` with `write`, to `{base_path}/{format}/`. /// /// The write is idempotent: an output file that exists is not written again. -pub fn write_size_format(base_path: &Path, format: SizeFormat) -> Result<()> { +fn copy_parquet_directory( + base_path: &Path, + format: Format, + write: fn(&Path, &Path) -> Result<()>, +) -> Result<()> { let parquet_dir = base_path.join(Format::Parquet.name()); let output_dir = base_path.join(format.name()); let mut inputs = fs::read_dir(&parquet_dir) @@ -82,11 +80,8 @@ pub fn write_size_format(base_path: &Path, format: SizeFormat) -> Result<()> { .to_os_string(); let mut output = output_dir.join(stem); output.set_extension(format.ext()); - idempotent(output.as_path(), |temp| match format { - SizeFormat::ArrowIpc => write_arrow_ipc(&input, temp), - SizeFormat::ParquetSnappy => write_snappy_parquet(&input, temp), - }) - .with_context(|| format!("writing {} as {}", input.display(), format.name()))?; + idempotent(output.as_path(), |temp| write(&input, temp)) + .with_context(|| format!("writing {} as {}", input.display(), format.name()))?; } Ok(()) } @@ -172,7 +167,7 @@ mod tests { let base = tempfile::tempdir()?; write_base(base.path(), 1000, 300)?; - write_size_format(base.path(), SizeFormat::ParquetSnappy)?; + write_snappy_parquet_directory(base.path())?; let output = base.path().join("parquet-snappy").join("t.parquet"); let metadata = SerializedFileReader::new(File::open(output)?)? From 8e897c6397b12a8eb87cab546b4a874a1f412214 Mon Sep 17 00:00:00 2001 From: Will Manning Date: Fri, 20 Nov 2026 20:59:42 -0500 Subject: [PATCH 06/44] Add the license header to parquet_copies.rs Signed-off-by: Will Manning --- vortex-bench/src/parquet_copies.rs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/vortex-bench/src/parquet_copies.rs b/vortex-bench/src/parquet_copies.rs index 1b6ac9e8822..2baa44961a1 100644 --- a/vortex-bench/src/parquet_copies.rs +++ b/vortex-bench/src/parquet_copies.rs @@ -1,3 +1,6 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + //! Copies of a benchmark's base Parquet files in other formats, one output file for each input //! file, in a directory of the format's name beside the base `parquet` directory. //! From e09b40016b41ef5f3e7ca71852e6bc8c5d78e5ea Mon Sep 17 00:00:00 2001 From: Will Manning Date: Fri, 20 Nov 2026 21:08:48 -0500 Subject: [PATCH 07/44] Write zstd Parquet for statpopgen, SpatialBench's zone table, and the vortex suite Every benchmark writes zstd level 3 Parquet, but three writers did not: statpopgen and the SpatialBench zone rewrite passed no writer settings, so parquet-rs wrote them uncompressed, and the vortex suite's DuckDB COPY named no codec, so DuckDB wrote Snappy. Their Parquet sizes and times measured a different codec from every other suite. All three now write zstd level 3. statpopgen's CI data cache also keys on the shared writer settings, so a change to them regenerates the cached files. Signed-off-by: Will Manning --- .../bench_orchestrator/data_cache.py | 2 +- vortex-bench/sql/vortex/init.sql | 2 +- vortex-bench/src/conversions.rs | 45 ++++++++++++++++++- vortex-bench/src/statpopgen/download_vcf.rs | 4 +- 4 files changed, 49 insertions(+), 4 deletions(-) diff --git a/bench-orchestrator/bench_orchestrator/data_cache.py b/bench-orchestrator/bench_orchestrator/data_cache.py index 85387e76456..9c7f4d42367 100644 --- a/bench-orchestrator/bench_orchestrator/data_cache.py +++ b/bench-orchestrator/bench_orchestrator/data_cache.py @@ -74,7 +74,7 @@ def cached_dataset(benchmark: Benchmark, options: dict[str, str], workspace_root f"statpopgen-{n_rows}", data_dir / "statpopgen" / str(n_rows) / "parquet", workspace_root, - ["vortex-bench/src/statpopgen"], + ["vortex-bench/src/statpopgen", "vortex-bench/src/utils/parquet.rs"], ) if benchmark is Benchmark.CLICKBENCH_SORTED: return _dataset( diff --git a/vortex-bench/sql/vortex/init.sql b/vortex-bench/sql/vortex/init.sql index aee587a2d2a..b6ae1cb3a4f 100644 --- a/vortex-bench/sql/vortex/init.sql +++ b/vortex-bench/sql/vortex/init.sql @@ -6,4 +6,4 @@ COPY ( (i % 1000)::INTEGER AS col, ((i * 2654435761) % 100000)::INTEGER AS col2 FROM range(2500000000) t(i) -) TO 'test.parquet' (FORMAT parquet); +) TO 'test.parquet' (FORMAT parquet, COMPRESSION zstd, COMPRESSION_LEVEL 3); diff --git a/vortex-bench/src/conversions.rs b/vortex-bench/src/conversions.rs index eb585a14516..ea91835570b 100644 --- a/vortex-bench/src/conversions.rs +++ b/vortex-bench/src/conversions.rs @@ -72,6 +72,7 @@ use crate::CompactionStrategy; use crate::Format; use crate::SESSION; use crate::utils::file::idempotent_async; +use crate::utils::parquet::parquet_writer_properties; /// Memory budget per concurrent conversion stream in GB. This is somewhat arbitary. const MEMORY_PER_STREAM_GB: u64 = 4; @@ -445,7 +446,10 @@ pub async fn add_geoparquet_metadata( let mut reader = builder.build()?; let tmp_path = parquet_path.with_extension("parquet.tmp"); - let mut writer = AsyncArrowWriter::try_new(File::create(&tmp_path).await?, schema, None)?; + // Rewrite with the zstd settings every benchmark writes, not parquet-rs's default (none). + let props = parquet_writer_properties().build(); + let mut writer = + AsyncArrowWriter::try_new(File::create(&tmp_path).await?, schema, Some(props))?; while let Some(batch) = reader.try_next().await? { writer.write(&batch).await?; } @@ -567,3 +571,42 @@ fn wkb_field_to_little_endian(field: &ArrayRef, ctx: &mut ExecutionCtx) -> Vorte .collect::>()?; Ok(VarBinViewArray::from_iter_nullable_bin(little_endian).into_array()) } + +#[cfg(test)] +mod tests { + use arrow_array::Int64Array; + use arrow_schema::DataType; + use arrow_schema::Field; + use arrow_schema::Schema; + use parquet::arrow::ArrowWriter; + use parquet::basic::Compression; + use parquet::file::reader::FileReader as _; + use parquet::file::reader::SerializedFileReader; + + use super::*; + + #[tokio::test] + async fn geoparquet_tagging_rewrites_an_uncompressed_file_with_zstd() -> anyhow::Result<()> { + let dir = tempfile::tempdir()?; + let path = dir.path().join("zone.parquet"); + let schema = Arc::new(Schema::new(vec![Field::new("id", DataType::Int64, false)])); + let batch = RecordBatch::try_new( + Arc::clone(&schema), + vec![Arc::new(Int64Array::from_iter_values(0..1000))], + )?; + let mut writer = ArrowWriter::try_new(fs::File::create(&path)?, schema, None)?; + writer.write(&batch)?; + writer.close()?; + + add_geoparquet_metadata(&path, "{}").await?; + + let reader = SerializedFileReader::new(fs::File::open(&path)?)?; + let metadata = reader.metadata(); + assert!(matches!( + metadata.row_group(0).column(0).compression(), + Compression::ZSTD(_) + )); + assert_eq!(metadata.file_metadata().num_rows(), 1000); + Ok(()) + } +} diff --git a/vortex-bench/src/statpopgen/download_vcf.rs b/vortex-bench/src/statpopgen/download_vcf.rs index fb7d99e98ee..b04dfcde5d8 100644 --- a/vortex-bench/src/statpopgen/download_vcf.rs +++ b/vortex-bench/src/statpopgen/download_vcf.rs @@ -38,6 +38,7 @@ use super::StatPopGenBenchmark; use crate::idempotent_async; use crate::statpopgen::builder::GnomADBuilder; use crate::statpopgen::schema::schema_from_vcf_header; +use crate::utils::parquet::parquet_writer_properties; // DuckDB parallelizes parquet at row-group granularity. Each of our rows are quite big (~4000 // genotypes each with tens of bytes of data). @@ -82,7 +83,8 @@ impl StatPopGenBenchmark { ); let schema = schema_from_vcf_header(&header); let file = File::create(parquet_output_path).await?; - let mut writer = AsyncArrowWriter::try_new(file, Arc::clone(&schema), None) + let props = parquet_writer_properties().build(); + let mut writer = AsyncArrowWriter::try_new(file, Arc::clone(&schema), Some(props)) .context("Failed to create parquet writer")?; // Splitting lines is cheap and stays serial; parsing each row group's lines into From 43d89ce2b682aa146404c07f2cf15c28fe99b022 Mon Sep 17 00:00:00 2001 From: Will Manning Date: Fri, 20 Nov 2026 21:32:30 -0500 Subject: [PATCH 08/44] Write parquet-snappy with DuckDB and name Parquet sizes by directory `parquet-snappy` is now Parquet as DuckDB writes it: `COPY ... (FORMAT parquet, COMPRESSION snappy)` in the `duckdb` CLI, with DuckDB's row groups, dictionaries, statistics, and Bloom filters. data-gen writes the query files this way, and compress-bench records its Snappy size from the same writer. Every benchmark runner already installs the CLI. File sizes are named by directory again, not by codec. `parquet` is the suite's base Parquet: zstd level 3 where the benchmarks write it, and the dataset's own files where the suite prescribes them, as ClickBench's Snappy files are. This keeps ClickBench's `parquet` series continuous and keeps `parquet-snappy` for DuckDB's files. Signed-off-by: Will Manning --- .../bench_orchestrator/config.py | 2 +- benchmarks/compress-bench/Cargo.toml | 4 +- benchmarks/compress-bench/src/main.rs | 14 +- benchmarks/compress-bench/src/parquet.rs | 18 ++- scripts/capture-file-sizes.py | 145 +----------------- scripts/tests/test_benchmark_reporting.py | 109 ++----------- vortex-bench/src/lib.rs | 4 +- vortex-bench/src/parquet_copies.rs | 113 +++++++++----- 8 files changed, 119 insertions(+), 290 deletions(-) diff --git a/bench-orchestrator/bench_orchestrator/config.py b/bench-orchestrator/bench_orchestrator/config.py index 2710785d17b..ae695b2b44f 100644 --- a/bench-orchestrator/bench_orchestrator/config.py +++ b/bench-orchestrator/bench_orchestrator/config.py @@ -41,7 +41,7 @@ class Format(Enum): """Data formats for benchmarks.""" PARQUET = "parquet" - # The base Parquet files rewritten with Snappy, which `data-gen` writes beside them. + # The base Parquet files as DuckDB writes them, with Snappy, which `data-gen` writes beside them. PARQUET_SNAPPY = "parquet-snappy" VORTEX = "vortex" VORTEX_COMPACT = "vortex-compact" diff --git a/benchmarks/compress-bench/Cargo.toml b/benchmarks/compress-bench/Cargo.toml index 8a57d8fd0dd..bb36994c7a5 100644 --- a/benchmarks/compress-bench/Cargo.toml +++ b/benchmarks/compress-bench/Cargo.toml @@ -31,7 +31,7 @@ parquet = { workspace = true } regex = { workspace = true } serde = { workspace = true, features = ["derive"] } serde_json = { workspace = true } -tempfile = { workspace = true, optional = true } +tempfile = { workspace = true } tokio = { workspace = true, features = ["full"] } tracing = { workspace = true } vortex = { workspace = true } @@ -44,7 +44,7 @@ arrow-select = { workspace = true } rstest = { workspace = true } [features] -cuda = ["dep:tempfile", "dep:vortex-cuda"] +cuda = ["dep:vortex-cuda"] lance = ["dep:lance-bench"] [[bin]] diff --git a/benchmarks/compress-bench/src/main.rs b/benchmarks/compress-bench/src/main.rs index f8d07d4208c..e7702e7e2a0 100644 --- a/benchmarks/compress-bench/src/main.rs +++ b/benchmarks/compress-bench/src/main.rs @@ -16,13 +16,13 @@ use compress_bench::gpu::GpuOptions; use compress_bench::gpu::compressor as gpu_compressor; use compress_bench::parquet::ParquetCompressor; use compress_bench::parquet::arrow_uncompressed_size; +use compress_bench::parquet::duckdb_snappy_parquet_size; use compress_bench::vortex::VortexCompressor; use compress_bench::vortex::vortex_compact_size; use futures::FutureExt; use indicatif::ProgressBar; use itertools::Itertools; use mimalloc::MiMalloc; -use parquet::basic::Compression; use regex::Regex; use vortex::utils::aliases::hash_map::HashMap; use vortex_bench::Engine; @@ -60,7 +60,8 @@ use vortex_bench::setup_logging_and_tracing_with_format; use vortex_bench::statpopgen::StatPopGenBenchmark; use vortex_bench::v3; -/// The size record name of Parquet written with Snappy, beside `parquet`, which is zstd level 3. +/// The size record name of Parquet as DuckDB writes it, with Snappy, beside `parquet`, which is +/// zstd level 3. It is the same writer that `data-gen --formats parquet-snappy` uses. const PARQUET_SNAPPY_FORMAT: &str = "parquet-snappy"; #[derive(Parser, Debug)] @@ -533,18 +534,17 @@ async fn run_benchmark_for_dataset( uncompressed_size.context("compression size requires Arrow memory size")?, )); if *format == Format::Parquet && !mode.is_gpu() { - // Snappy Parquet is measured for size only: one untimed write. - let snappy = ParquetCompressor::with_compression(Compression::SNAPPY) - .compress(&input) + // Snappy Parquet is measured for size only: one untimed write by DuckDB. + let snappy_size = duckdb_snappy_parquet_size(&parquet_path) .await .with_context(|| { - format!("compressing {bench_name} as Snappy Parquet") + format!("writing {bench_name} as Snappy Parquet with DuckDB") })?; v3_records.push(v3::named_compression_size_record( v3_dataset, v3_variant, PARQUET_SNAPPY_FORMAT, - snappy.size, + snappy_size, uncompressed_size .context("compression size requires Arrow memory size")?, )); diff --git a/benchmarks/compress-bench/src/parquet.rs b/benchmarks/compress-bench/src/parquet.rs index 37f8b36a599..438900d67c4 100644 --- a/benchmarks/compress-bench/src/parquet.rs +++ b/benchmarks/compress-bench/src/parquet.rs @@ -38,6 +38,7 @@ use vortex_bench::compress::CompressedData; use vortex_bench::compress::Compressor; use vortex_bench::compress::Uncompressed; use vortex_bench::compress::read_projection; +use vortex_bench::parquet_copies::write_duckdb_snappy_parquet; /// Compressor implementation for Parquet format with ZSTD level 3 compression. pub struct ParquetCompressor { @@ -52,10 +53,6 @@ impl ParquetCompressor { ), } } - - pub fn with_compression(compression: Compression) -> Self { - Self { compression } - } } impl Default for ParquetCompressor { @@ -64,6 +61,19 @@ impl Default for ParquetCompressor { } } +/// Return the size of the Parquet file `parquet_path` written again by DuckDB, with Snappy. See +/// [`write_duckdb_snappy_parquet`]. +pub async fn duckdb_snappy_parquet_size(parquet_path: &Path) -> anyhow::Result { + let parquet_path = parquet_path.to_path_buf(); + tokio::task::spawn_blocking(move || { + let dir = tempfile::tempdir()?; + let output = dir.path().join("snappy.parquet"); + write_duckdb_snappy_parquet(&parquet_path, &output)?; + Ok(std::fs::metadata(&output)?.len()) + }) + .await? +} + /// Return the Arrow memory size after decoding the input Parquet file. pub fn arrow_uncompressed_size(parquet_path: &Path) -> anyhow::Result { let file = File::open(parquet_path)?; diff --git a/scripts/capture-file-sizes.py b/scripts/capture-file-sizes.py index 6c628e9ee76..88b1ea508ae 100644 --- a/scripts/capture-file-sizes.py +++ b/scripts/capture-file-sizes.py @@ -11,145 +11,11 @@ import argparse import json -import struct import sys from pathlib import Path DUCKDB_CATALOG_FILES = {"duckdb.db", "duckdb.db.wal"} -# Parquet's `CompressionCodec` enum, from `parquet.thrift`. -PARQUET_CODECS = { - 0: "uncompressed", - 1: "snappy", - 2: "gzip", - 3: "lzo", - 4: "brotli", - 5: "lz4", - 6: "zstd", - 7: "lz4-raw", -} - -# Thrift compact protocol type ids. -_T_STOP, _T_TRUE, _T_FALSE, _T_BYTE, _T_I16, _T_I32, _T_I64, _T_DOUBLE = range(8) -_T_BINARY, _T_LIST, _T_SET, _T_MAP, _T_STRUCT = range(8, 13) - - -class _CompactReader: - """Read Thrift compact protocol values. Structs read as dicts keyed by field id.""" - - def __init__(self, data: bytes) -> None: - self.data = data - self.pos = 0 - - def byte(self) -> int: - value = self.data[self.pos] - self.pos += 1 - return value - - def varint(self) -> int: - shift = result = 0 - while True: - b = self.byte() - result |= (b & 0x7F) << shift - if not b & 0x80: - return result - shift += 7 - - def zigzag(self) -> int: - n = self.varint() - return (n >> 1) ^ -(n & 1) - - def value(self, kind: int) -> object: - if kind in (_T_TRUE, _T_FALSE): - # A bool list element is a whole byte; a bool field carries its value in its type. - return self.byte() == _T_TRUE - if kind == _T_BYTE: - return self.byte() - if kind in (_T_I16, _T_I32, _T_I64): - return self.zigzag() - if kind == _T_DOUBLE: - self.pos += 8 - return None - if kind == _T_BINARY: - length = self.varint() - self.pos += length - return None - if kind in (_T_LIST, _T_SET): - header = self.byte() - size = header >> 4 - if size == 15: - size = self.varint() - return [self.value(header & 0x0F) for _ in range(size)] - if kind == _T_MAP: - size = self.varint() - if size == 0: - return {} - types = self.byte() - for _ in range(size): - self.value(types >> 4) - self.value(types & 0x0F) - return None - if kind == _T_STRUCT: - return self.struct() - raise ValueError(f"unknown thrift compact type {kind}") - - def struct(self) -> dict[int, object]: - fields: dict[int, object] = {} - field_id = 0 - while True: - header = self.byte() - kind = header & 0x0F - if kind == _T_STOP: - return fields - delta = header >> 4 - field_id = field_id + delta if delta else self.zigzag() - if kind in (_T_TRUE, _T_FALSE): - fields[field_id] = kind == _T_TRUE - else: - fields[field_id] = self.value(kind) - - -def parquet_codecs(path: Path) -> set[str]: - """The codecs of every column chunk in a Parquet file, read from its footer.""" - with open(path, "rb") as f: - f.seek(-8, 2) - length_bytes, magic = struct.unpack(" RowGroup.columns (1) -> ColumnChunk.meta_data (3) - # -> ColumnMetaData.codec (4). - for row_group in metadata.get(4) or []: - for column in row_group.get(1) or []: - meta = column.get(3) - if isinstance(meta, dict) and isinstance(meta.get(4), int): - codecs.add(PARQUET_CODECS.get(meta[4], f"codec-{meta[4]}")) - return codecs - - -def parquet_format_name(path: Path, directory: str = "parquet") -> str: - """Name a Parquet file's format by its codec, as `vortex` and `vortex-compact` name Vortex's. - - `parquet` is zstd, the codec every Parquet file the benchmarks write themselves uses (zstd - level 3). A file written with another codec, such as Snappy in a downloaded dataset, is - `parquet-`. A file whose footer cannot be read, or that mixes codecs, keeps the name of - its `directory` with a warning: `parquet`, as before codecs were recorded, or - `parquet-snappy`, which `data-gen --formats parquet-snappy` writes. - """ - try: - codecs = parquet_codecs(path) - except (OSError, ValueError, IndexError, struct.error) as error: - print(f"Could not read the Parquet footer of {path}: {error}", file=sys.stderr) - return directory - if len(codecs) != 1: - if codecs: - print(f"{path} mixes Parquet codecs {sorted(codecs)}; recording it as {directory}", file=sys.stderr) - return directory - codec = next(iter(codecs)) - return "parquet" if codec == "zstd" else f"parquet-{codec}" - def main() -> None: parser = argparse.ArgumentParser(description="Capture file sizes from benchmark data directories") @@ -185,6 +51,10 @@ def main() -> None: "lance", "litdata", "parquet", + # Parquet as DuckDB writes it, with Snappy. A format is named by its directory, not by + # its codec: `parquet` is the suite's base Parquet, which is zstd level 3 where the + # benchmarks write it, and the dataset's own files where the suite prescribes them, as + # ClickBench's are Snappy. "parquet-snappy", "vortex-compact", "vortex-file-compressed", @@ -221,11 +91,6 @@ def main() -> None: continue size_bytes = file_path.stat().st_size - recorded_format = ( - parquet_format_name(file_path, format_name) - if format_name in ("parquet", "parquet-snappy") and file_path.suffix == ".parquet" - else format_name - ) records.append( { @@ -236,7 +101,7 @@ def main() -> None: "file_size": { "benchmark": args.benchmark, "scale_factor": scale_factor, - "format": recorded_format, + "format": format_name, "file": str(relative_path), }, } diff --git a/scripts/tests/test_benchmark_reporting.py b/scripts/tests/test_benchmark_reporting.py index 19c3ce68850..803fc5f3206 100644 --- a/scripts/tests/test_benchmark_reporting.py +++ b/scripts/tests/test_benchmark_reporting.py @@ -936,46 +936,21 @@ def test_summary_reports_hot_alone_when_no_row_recorded_its_runs(tmp_path: Path) assert "cold" not in summary -def parquet_with_codecs(codecs: list[int], body: bytes = b"data") -> bytes: - """A Parquet file with one row group whose column chunks use `codecs`, footer only. - - The footer is the Thrift compact encoding of `FileMetaData{4: [RowGroup{1: [ColumnChunk{3: - ColumnMetaData{4: codec}}]}]}`, plus an unread field before each so the reader must skip it. - """ - - def i32_field(delta: int, value: int) -> bytes: - return bytes([(delta << 4) | 5, (value << 1) ^ (value >> 31)]) - - def list_field(delta: int, items: list[bytes]) -> bytes: - return bytes([(delta << 4) | 9, (len(items) << 4) | 12]) + b"".join(items) - - columns = [ - # ColumnChunk: file_offset (2, i64) skipped, then meta_data (3). - bytes([0x26, 0x00, 0x1C]) + bytes([0x15, 0x02]) + i32_field(3, codec) + b"\x00\x00" - for codec in codecs - ] - row_group = list_field(1, columns) + b"\x00" - metadata = bytes([0x15, 0x04]) + list_field(3, [row_group]) + b"\x00" - return b"PAR1" + body + metadata + len(metadata).to_bytes(4, "little") + b"PAR1" - - -def test_capture_file_sizes_names_parquet_by_codec(tmp_path: Path) -> None: +def test_capture_file_sizes_names_parquet_by_its_directory(tmp_path: Path) -> None: data_dir = tmp_path / "data" - parquet_dir = data_dir / "clickbench_partitioned" / "parquet" - parquet_dir.mkdir(parents=True) - zstd, snappy, uncompressed = 6, 1, 0 files = { - "hits_0.parquet": parquet_with_codecs([zstd, zstd]), - "hits_1.parquet": parquet_with_codecs([snappy, snappy]), - "hits_2.parquet": parquet_with_codecs([uncompressed]), - "hits_3.parquet": parquet_with_codecs([zstd, snappy]), - "hits_4.parquet": b"not parquet", + # ClickBench's own files are Snappy, and they are its `parquet`. + ("clickbench_partitioned", "parquet", "hits_0.parquet"): 40, + ("clickbench_partitioned", "parquet-snappy", "hits_0.parquet"): 50, + ("clickbench_partitioned", "arrow-ipc", "hits_0.arrow"): 80, } - for name, data in files.items(): - (parquet_dir / name).write_bytes(data) + for parts, size in files.items(): + path = data_dir.joinpath(*parts) + path.parent.mkdir(parents=True, exist_ok=True) + path.write_bytes(b"x" * size) output_path = tmp_path / "sizes.jsonl" - result = subprocess.run( + subprocess.run( [ sys.executable, str(CAPTURE_SCRIPT), @@ -989,68 +964,14 @@ def test_capture_file_sizes_names_parquet_by_codec(tmp_path: Path) -> None: "-o", str(output_path), ], - check=False, - capture_output=True, - text=True, - ) - - assert result.returncode == 0, result.stderr - records = [json.loads(line) for line in output_path.read_text(encoding="utf-8").splitlines()] - assert sorted((r["file_size"]["file"], r["file_size"]["format"], r["value"]) for r in records) == [ - ("hits_0.parquet", "parquet", len(files["hits_0.parquet"])), - ("hits_1.parquet", "parquet-snappy", len(files["hits_1.parquet"])), - ("hits_2.parquet", "parquet-uncompressed", len(files["hits_2.parquet"])), - # Mixed codecs and unreadable footers keep the plain name, with a warning. - ("hits_3.parquet", "parquet", len(files["hits_3.parquet"])), - ("hits_4.parquet", "parquet", len(files["hits_4.parquet"])), - ] - assert "mixes Parquet codecs" in result.stderr - assert "Could not read the Parquet footer" in result.stderr - - -def test_capture_file_sizes_records_the_size_only_snappy_directory(tmp_path: Path) -> None: - data_dir = tmp_path / "data" - scale_dir = data_dir / "tpcds" / "1.0" - zstd, snappy = 6, 1 - files = { - ("parquet", "item.parquet"): parquet_with_codecs([zstd]), - ("parquet-snappy", "item.parquet"): parquet_with_codecs([snappy]), - ("parquet-snappy", "store.parquet"): b"not parquet", - ("arrow-ipc", "item.arrow"): b"x" * 80, - } - for (format_name, name), data in files.items(): - path = scale_dir / format_name / name - path.parent.mkdir(parents=True, exist_ok=True) - path.write_bytes(data) - output_path = tmp_path / "sizes.jsonl" - - result = subprocess.run( - [ - sys.executable, - str(CAPTURE_SCRIPT), - str(data_dir), - "--benchmark", - "tpcds", - "--dataset-dir", - "tpcds", - "--commit", - "deadbeef", - "-o", - str(output_path), - ], - check=False, - capture_output=True, - text=True, + check=True, ) - assert result.returncode == 0, result.stderr records = [json.loads(line) for line in output_path.read_text(encoding="utf-8").splitlines()] - assert [(r["file_size"]["format"], r["file_size"]["file"]) for r in records] == [ - ("arrow-ipc", "item.arrow"), - ("parquet", "item.parquet"), - ("parquet-snappy", "item.parquet"), - # An unreadable footer in the Snappy directory keeps that directory's name. - ("parquet-snappy", "store.parquet"), + assert sorted((r["file_size"]["format"], r["value"]) for r in records) == [ + ("arrow-ipc", 80), + ("parquet", 40), + ("parquet-snappy", 50), ] diff --git a/vortex-bench/src/lib.rs b/vortex-bench/src/lib.rs index 56e569cece9..ff085fe907f 100644 --- a/vortex-bench/src/lib.rs +++ b/vortex-bench/src/lib.rs @@ -218,8 +218,8 @@ pub enum Format { Csv, #[clap(name = "parquet")] Parquet, - /// Parquet with Snappy compression, the base Parquet files written again with Snappy in - /// place of zstd. Only suites that list it generate it. + /// Parquet as DuckDB writes it, with Snappy: the base Parquet files written again by the + /// `duckdb` CLI. Only suites that list it generate it. #[clap(name = "parquet-snappy")] #[serde(rename = "parquet-snappy")] ParquetSnappy, diff --git a/vortex-bench/src/parquet_copies.rs b/vortex-bench/src/parquet_copies.rs index 2baa44961a1..75760827c16 100644 --- a/vortex-bench/src/parquet_copies.rs +++ b/vortex-bench/src/parquet_copies.rs @@ -4,8 +4,11 @@ //! Copies of a benchmark's base Parquet files in other formats, one output file for each input //! file, in a directory of the format's name beside the base `parquet` directory. //! -//! - [`Format::ParquetSnappy`]: the same files written with Snappy in place of zstd. The query -//! engines read it like Parquet. `data-gen --formats parquet-snappy` writes it. +//! - [`Format::ParquetSnappy`]: the same rows as DuckDB writes them by default, with Snappy, +//! DuckDB's row groups, and its dictionaries, statistics, and Bloom filters. This is Parquet as +//! an analytics engine writes it for speed, where the base files are zstd level 3 for size. The +//! query engines read it like Parquet. `data-gen --formats parquet-snappy` writes it with the +//! `duckdb` CLI. //! - [`SizeFormat::ArrowIpc`]: uncompressed Arrow IPC, which no query reads. `data-gen //! --size-formats arrow-ipc` writes it only so that `scripts/capture-file-sizes.py` records its //! size. Lance is also written for size only, by `lance-bench --data-only`, because only that @@ -15,20 +18,19 @@ use std::fs; use std::fs::File; use std::io::BufWriter; use std::path::Path; +use std::process::Command; use std::sync::Arc; use anyhow::Context; use anyhow::Result; +use anyhow::bail; use arrow_ipc::writer::FileWriter; use clap::ValueEnum; -use parquet::arrow::ArrowWriter; use parquet::arrow::arrow_reader::ParquetRecordBatchReaderBuilder; -use parquet::basic::Compression; use tracing::info; use crate::Format; use crate::idempotent; -use crate::utils::parquet::parquet_writer_properties; /// A format that is written only to record its file size. No query reads it. #[derive(Clone, Copy, Debug, PartialEq, Eq, ValueEnum)] @@ -47,10 +49,14 @@ pub fn write_size_format(base_path: &Path, format: SizeFormat) -> Result<()> { } } -/// Write every Parquet file in `{base_path}/parquet/` again with Snappy, to -/// `{base_path}/parquet-snappy/`. +/// Write every Parquet file in `{base_path}/parquet/` again with DuckDB, to +/// `{base_path}/parquet-snappy/`. See [`write_duckdb_snappy_parquet`]. pub fn write_snappy_parquet_directory(base_path: &Path) -> Result<()> { - copy_parquet_directory(base_path, Format::ParquetSnappy, write_snappy_parquet) + copy_parquet_directory( + base_path, + Format::ParquetSnappy, + write_duckdb_snappy_parquet, + ) } /// Write each Parquet file in `{base_path}/parquet/` with `write`, to `{base_path}/{format}/`. @@ -101,29 +107,38 @@ fn write_arrow_ipc(input: &Path, output: &Path) -> Result<()> { Ok(()) } -/// Write the Parquet file `input` again with Snappy. Every other setting is the base files': -/// [`parquet_writer_properties`], and the row group size of `input`'s first row group. -fn write_snappy_parquet(input: &Path, output: &Path) -> Result<()> { - let reader = ParquetRecordBatchReaderBuilder::try_new(File::open(input)?)?; - let schema = Arc::clone(reader.schema()); - let row_group_rows = reader - .metadata() - .row_groups() - .first() - .map(|row_group| usize::try_from(row_group.num_rows())) - .transpose()?; - let props = parquet_writer_properties() - .set_compression(Compression::SNAPPY) - .set_max_row_group_row_count(row_group_rows) - .build(); - let mut writer = ArrowWriter::try_new(File::create(output)?, schema, Some(props))?; - for batch in reader.build()? { - writer.write(&batch?)?; +/// Write the Parquet file `input` again as DuckDB writes Parquet: `COPY ... (FORMAT parquet, +/// COMPRESSION snappy)` in the `duckdb` CLI, which must be on `PATH`. Every setting other than the +/// codec is DuckDB's default, so the file is what a DuckDB user gets. The codec is named because +/// it is the one the `parquet-snappy` name promises, and DuckDB's default could change. +pub fn write_duckdb_snappy_parquet(input: &Path, output: &Path) -> Result<()> { + let sql = format!( + "COPY (FROM read_parquet({})) TO {} (FORMAT parquet, COMPRESSION snappy)", + sql_string(input)?, + sql_string(output)?, + ); + let result = Command::new("duckdb") + .arg("-c") + .arg(&sql) + .output() + .context("running the duckdb CLI, which writes parquet-snappy")?; + if !result.status.success() { + bail!( + "the duckdb CLI failed: {}", + String::from_utf8_lossy(&result.stderr) + ); } - writer.close()?; Ok(()) } +/// `path` as a SQL string literal. +fn sql_string(path: &Path) -> Result { + let path = path + .to_str() + .with_context(|| format!("{} is not UTF-8", path.display()))?; + Ok(format!("'{}'", path.replace('\'', "''"))) +} + #[cfg(test)] mod tests { use arrow_array::Int64Array; @@ -133,10 +148,13 @@ mod tests { use arrow_schema::DataType; use arrow_schema::Field; use arrow_schema::Schema; + use parquet::arrow::ArrowWriter; + use parquet::basic::Compression; use parquet::file::reader::FileReader as _; use parquet::file::reader::SerializedFileReader; use super::*; + use crate::utils::parquet::parquet_writer_properties; /// Write `rows` rows to `{base}/parquet/t.parquet`, in row groups of `row_group_rows`. fn write_base(base: &Path, rows: i64, row_group_rows: usize) -> Result { @@ -166,27 +184,42 @@ mod tests { } #[test] - fn snappy_parquet_keeps_the_row_groups_and_changes_only_the_codec() -> Result<()> { + #[ignore = "needs the duckdb CLI on PATH, which the benchmark runners install"] + fn snappy_parquet_is_duckdbs_parquet_with_the_same_rows() -> Result<()> { let base = tempfile::tempdir()?; - write_base(base.path(), 1000, 300)?; + let expected = write_base(base.path(), 1000, 300)?; write_snappy_parquet_directory(base.path())?; let output = base.path().join("parquet-snappy").join("t.parquet"); - let metadata = SerializedFileReader::new(File::open(output)?)? + let metadata = SerializedFileReader::new(File::open(&output)?)? .metadata() .clone(); - let row_groups: Vec = metadata - .row_groups() - .iter() - .map(|rg| rg.num_rows()) - .collect(); - assert_eq!(row_groups, [300, 300, 300, 100]); - for row_group in metadata.row_groups() { - for column in row_group.columns() { - assert_eq!(column.compression(), Compression::SNAPPY); - } + assert!( + metadata + .file_metadata() + .created_by() + .is_some_and(|created_by| created_by.starts_with("DuckDB")) + ); + // DuckDB's own row groups, not the base file's 300 rows. + assert_eq!(metadata.num_row_groups(), 1); + for column in metadata.row_groups().iter().flat_map(|rg| rg.columns()) { + assert_eq!(column.compression(), Compression::SNAPPY); } + let reader = ParquetRecordBatchReaderBuilder::try_new(File::open(&output)?)?.build()?; + let batches = reader.collect::, _>>()?; + let actual = arrow_select::concat::concat_batches(&batches[0].schema(), &batches)?; + assert_eq!(actual.num_rows(), expected.num_rows()); + assert_eq!(actual.columns(), expected.columns()); + Ok(()) + } + + #[test] + fn sql_strings_escape_quotes() -> Result<()> { + assert_eq!( + sql_string(Path::new("/data/o'brien.parquet"))?, + "'/data/o''brien.parquet'" + ); Ok(()) } From a84b9988d14f4016e2eed12dc7a592295aaee2b1 Mon Sep 17 00:00:00 2001 From: Will Manning Date: Fri, 20 Nov 2026 21:42:39 -0500 Subject: [PATCH 09/44] Match the cast's new overflow message in a CUDA FFI test #11676 changed the integer cast's overflow error from "value exceeds target range" to "values exceed target range". The device batch test looked for the old wording, so CUDA tests fail on develop's code. Match the words both share. Signed-off-by: Will Manning --- vortex-cuda/ffi/src/device_batches/tests.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/vortex-cuda/ffi/src/device_batches/tests.rs b/vortex-cuda/ffi/src/device_batches/tests.rs index 1f4922f1a63..26d14886e81 100644 --- a/vortex-cuda/ffi/src/device_batches/tests.rs +++ b/vortex-cuda/ffi/src/device_batches/tests.rs @@ -539,7 +539,8 @@ fn test_scan_dtype_export_errors_and_panics_are_terminal() -> VortexResult<()> { let message = match failure { "scan" => "injected scan failure", "dtype" => "logical dtype changed", - "export" => "exceeds target range", + // "value exceeds" or "values exceed", as the cast's wording has been. + "export" => "target range", "panic" => "injected polling panic", _ => unreachable!(), }; From 8e0cb973eb791c79b7b77b524e9f2c466e7311de Mon Sep 17 00:00:00 2001 From: Will Manning Date: Sat, 21 Nov 2026 08:11:20 -0500 Subject: [PATCH 10/44] Install the DuckDB 2.0.0 CLI on benchmark runners The queries run on DuckDB 2.0.0, which vortex-duckdb links, but the runners installed the 1.5.5 CLI, which writes parquet-snappy and the native duckdb database. Install the same version. DuckDB 2.0 ships the CLI as a tarball, so the action extracts it with tar. Signed-off-by: Will Manning --- .github/actions/setup-duckdb/action.yml | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/.github/actions/setup-duckdb/action.yml b/.github/actions/setup-duckdb/action.yml index 51d920304e9..8380c248452 100644 --- a/.github/actions/setup-duckdb/action.yml +++ b/.github/actions/setup-duckdb/action.yml @@ -2,8 +2,10 @@ name: "Setup DuckDB" description: "Download the DuckDB CLI and put it on PATH" inputs: duckdb_version: + # Keep this the version that `vortex-duckdb/build.rs` links, so the CLI that writes + # `parquet-snappy` and the `duckdb` database is the DuckDB the queries run on. description: "Version of the DuckDB CLI" - default: "1.5.5" + default: "2.0.0" runs: using: "composite" steps: @@ -19,8 +21,10 @@ runs: ;; esac + # Since 2.0, the release ships the CLI as a tarball that holds the `duckdb` binary. wget -qO- \ - "https://github.com/duckdb/duckdb/releases/download/v${{ inputs.duckdb_version }}/duckdb_cli-linux-${duckdb_arch}.zip" \ - | funzip > duckdb + "https://github.com/duckdb/duckdb/releases/download/v${{ inputs.duckdb_version }}/duckdb-cli-linux-${duckdb_arch}.tar.gz" \ + | tar -xz duckdb chmod +x duckdb + ./duckdb --version echo "$PWD" >> "$GITHUB_PATH" From 147ab29be9c3e98a071a27762d0d4aa4b58ef59c Mon Sep 17 00:00:00 2001 From: Will Manning Date: Sat, 21 Nov 2026 08:14:28 -0500 Subject: [PATCH 11/44] Install the DuckDB 2.0.1 CLI on benchmark runners 2.0.1 is DuckDB 2.0's bugfix release. vortex-duckdb still links 2.0.0, so the CLI stays on the minor version the queries run on. Signed-off-by: Will Manning --- .github/actions/setup-duckdb/action.yml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/actions/setup-duckdb/action.yml b/.github/actions/setup-duckdb/action.yml index 8380c248452..6d39d077b16 100644 --- a/.github/actions/setup-duckdb/action.yml +++ b/.github/actions/setup-duckdb/action.yml @@ -2,10 +2,10 @@ name: "Setup DuckDB" description: "Download the DuckDB CLI and put it on PATH" inputs: duckdb_version: - # Keep this the version that `vortex-duckdb/build.rs` links, so the CLI that writes - # `parquet-snappy` and the `duckdb` database is the DuckDB the queries run on. + # Keep this on the DuckDB minor version that `vortex-duckdb/build.rs` links (2.0), so the CLI + # that writes `parquet-snappy` and the `duckdb` database matches the DuckDB the queries run on. description: "Version of the DuckDB CLI" - default: "2.0.0" + default: "2.0.1" runs: using: "composite" steps: From 756a4d2f44527373667f1c7a524c35a6490d6150 Mon Sep 17 00:00:00 2001 From: Will Manning Date: Sat, 21 Nov 2026 08:33:00 -0500 Subject: [PATCH 12/44] Keep untimed work out of timed benchmark runs, and recompress tagged zone files compress-bench wrote its size-only formats, DuckDB's Snappy Parquet and compact Vortex, between a format's timed compression and its timed decompression. Write them after every timed run of the dataset. vx-bench run dropped the OS caches before each query, but lance-bench wrote its Lance files on its first query, so that query read them from the page cache. The run now writes Lance's data before the first cache drop. SpatialBench's zone file was left as it was when it already had GeoParquet metadata, so a file tagged before the benchmarks wrote zstd stayed uncompressed. It is now rewritten unless it is also zstd. Signed-off-by: Will Manning --- bench-orchestrator/bench_orchestrator/cli.py | 2 + .../bench_orchestrator/runner/executor.py | 22 +++++++ bench-orchestrator/tests/test_cli.py | 27 ++++++++ bench-orchestrator/tests/test_executor.py | 16 +++++ benchmarks/compress-bench/src/main.rs | 66 ++++++++++--------- vortex-bench/src/conversions.rs | 53 +++++++++++++-- 6 files changed, 151 insertions(+), 35 deletions(-) diff --git a/bench-orchestrator/bench_orchestrator/cli.py b/bench-orchestrator/bench_orchestrator/cli.py index 7e0680757da..ea1b1986f44 100644 --- a/bench-orchestrator/bench_orchestrator/cli.py +++ b/bench-orchestrator/bench_orchestrator/cli.py @@ -482,6 +482,8 @@ def stream(line: str, target: BenchmarkTarget = target) -> None: write_result_line(line, ctx.write_raw_json, compatibility_file) try: + # Before the first cache drop, so the first query reads cold files. + executor.write_data(benchmark, bench_opts) query_ids = executor.list_queries(benchmark, query_list, exclude_list) for i, query_id in enumerate(query_ids, start=1): query_results.clear() diff --git a/bench-orchestrator/bench_orchestrator/runner/executor.py b/bench-orchestrator/bench_orchestrator/runner/executor.py index 6a09e872926..00a3e0011cf 100644 --- a/bench-orchestrator/bench_orchestrator/runner/executor.py +++ b/bench-orchestrator/bench_orchestrator/runner/executor.py @@ -107,6 +107,28 @@ def _check_integration(self, integration: Integration) -> None: if self.backend is not Engine.LANCE and (self.backend, integration) not in INTEGRATION_ARGS: raise ValueError(f"{self.backend.value} cannot run the {integration.value} integration") + def write_data(self, benchmark: Benchmark, options: dict[str, str] | None = None) -> None: + """Write the data this backend's queries read, without running a query. + + Only `lance-bench` writes its own data: it converts the base Parquet files to Lance on its + first run. The run loop drops the OS caches before each query, so without this step the + first Lance query would read files that the conversion just left in the page cache. + """ + if self.backend is not Engine.LANCE: + return + cmd = [str(self.binary_path), benchmark.value, "--data-only"] + for key, value in (options or {}).items(): + cmd.extend(["--opt", f"{key}={value}"]) + + if self.verbose: + console.print(f"[dim]$ {' '.join(cmd)}[/dim]") + + result = subprocess.run(cmd, capture_output=True, text=True) + if result.returncode != 0: + raise RuntimeError( + f"Failed to write {self.backend.value} data for {benchmark.value}: {result.stderr.strip()}" + ) + def list_queries( self, benchmark: Benchmark, diff --git a/bench-orchestrator/tests/test_cli.py b/bench-orchestrator/tests/test_cli.py index b550ebe45fd..c99221658b5 100644 --- a/bench-orchestrator/tests/test_cli.py +++ b/bench-orchestrator/tests/test_cli.py @@ -197,6 +197,33 @@ def fake_run(self, **kwargs: object) -> list[str]: assert seen_backend_paths[0] != seen_backend_paths[1] +def test_run_writes_lance_data_before_the_first_cache_drop(tmp_path, monkeypatch) -> None: + run_store = ResultStore(base_dir=tmp_path / "runs") + binary_path = tmp_path / "lance-bench" + binary_path.write_text("", encoding="utf-8") + events = [] + + monkeypatch.setattr(cli_module, "ResultStore", lambda: run_store) + monkeypatch.setattr(cli_module.BenchmarkBuilder, "get_binary_path", lambda self, backend: binary_path) + monkeypatch.setattr(cli_module, "drop_os_caches", lambda: events.append("drop caches")) + monkeypatch.setattr(BenchmarkExecutor, "list_queries", lambda self, *args, **kwargs: [1, 2]) + monkeypatch.setattr(BenchmarkExecutor, "write_data", lambda self, *args, **kwargs: events.append("write data")) + + def fake_run(self, **kwargs: object) -> list[str]: + events.append(f"query {kwargs['query']}") + return [] + + monkeypatch.setattr(BenchmarkExecutor, "run", fake_run) + + result = runner.invoke( + cli_module.app, + ["run", "tpcds", "--targets-json", '[{"engine":"datafusion","format":"lance"}]', "--no-build"], + ) + + assert result.exit_code == 0, result.output + assert events == ["write data", "drop caches", "query 1", "drop caches", "query 2"] + + def test_format_query_reading_summarizes_runtimes() -> None: line = json.dumps( { diff --git a/bench-orchestrator/tests/test_executor.py b/bench-orchestrator/tests/test_executor.py index 709a56b1824..4a08542bdb8 100644 --- a/bench-orchestrator/tests/test_executor.py +++ b/bench-orchestrator/tests/test_executor.py @@ -1,6 +1,7 @@ # SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright the Vortex contributors +import subprocess import sys import textwrap from pathlib import Path @@ -87,6 +88,21 @@ def test_build_command_omits_formats_for_lance_backend() -> None: assert cmd[cmd.index("--queries") + 1] == "3" +def test_write_data_writes_lance_without_running_a_query(monkeypatch) -> None: + calls = [] + + def fake_run(cmd: list[str], **kwargs: object) -> subprocess.CompletedProcess[str]: + calls.append(cmd) + return subprocess.CompletedProcess(cmd, 0, "", "") + + monkeypatch.setattr(subprocess, "run", fake_run) + + BenchmarkExecutor(Path("/tmp/lance-bench"), Engine.LANCE).write_data(Benchmark.TPCDS, {"scale-factor": "1.0"}) + BenchmarkExecutor(Path("/tmp/datafusion-bench"), Engine.DATAFUSION).write_data(Benchmark.TPCDS) + + assert calls == [["/tmp/lance-bench", "tpcds", "--data-only", "--opt", "scale-factor=1.0"]] + + def test_build_command_includes_ingest_output_when_set() -> None: executor = BenchmarkExecutor(Path("/tmp/duckdb-bench"), Engine.DUCKDB) diff --git a/benchmarks/compress-bench/src/main.rs b/benchmarks/compress-bench/src/main.rs index e7702e7e2a0..dc222c0c04a 100644 --- a/benchmarks/compress-bench/src/main.rs +++ b/benchmarks/compress-bench/src/main.rs @@ -533,37 +533,6 @@ async fn run_benchmark_for_dataset( result.compressed_size, uncompressed_size.context("compression size requires Arrow memory size")?, )); - if *format == Format::Parquet && !mode.is_gpu() { - // Snappy Parquet is measured for size only: one untimed write by DuckDB. - let snappy_size = duckdb_snappy_parquet_size(&parquet_path) - .await - .with_context(|| { - format!("writing {bench_name} as Snappy Parquet with DuckDB") - })?; - v3_records.push(v3::named_compression_size_record( - v3_dataset, - v3_variant, - PARQUET_SNAPPY_FORMAT, - snappy_size, - uncompressed_size - .context("compression size requires Arrow memory size")?, - )); - } - if *format == Format::OnDiskVortex && !mode.is_gpu() { - // Compact Vortex is measured for size only: one untimed write. - let compact_size = - vortex_compact_size(&input).await.with_context(|| { - format!("compressing {bench_name} as compact Vortex") - })?; - v3_records.push(v3::compression_size_record( - v3_dataset, - v3_variant, - Format::VortexCompact, - compact_size, - uncompressed_size - .context("compression size requires Arrow memory size")?, - )); - } ratios.extend(result.ratios); timings.push(result.timing); compressed = Some(result.compressed); @@ -613,6 +582,41 @@ async fn run_benchmark_for_dataset( } } + // Size-only formats: one untimed write each. They run after every timed run of the dataset, + // so their reads and writes cannot warm caches for a timed measurement. + if ops.contains(&CompressOp::Compress) && !mode.is_gpu() { + let uncompressed_size = + uncompressed_size.context("compression size requires Arrow memory size")?; + if formats.contains(&Format::Parquet) { + let snappy_size = duckdb_snappy_parquet_size(&parquet_path) + .await + .with_context(|| format!("writing {bench_name} as Snappy Parquet with DuckDB"))?; + v3_records.push(v3::named_compression_size_record( + v3_dataset, + v3_variant, + PARQUET_SNAPPY_FORMAT, + snappy_size, + uncompressed_size, + )); + } + if formats.contains(&Format::OnDiskVortex) { + let input = get_compressor(Format::OnDiskVortex, mode)? + .load(&parquet_path) + .await + .with_context(|| format!("loading {bench_name} for compact Vortex"))?; + let compact_size = vortex_compact_size(&input) + .await + .with_context(|| format!("compressing {bench_name} as compact Vortex"))?; + v3_records.push(v3::compression_size_record( + v3_dataset, + v3_variant, + Format::VortexCompact, + compact_size, + uncompressed_size, + )); + } + } + // Calculate cross-format ratios after all measurements. match mode { // The shared ratio labels name the CPU suite's codec, which the GPU run does not diff --git a/vortex-bench/src/conversions.rs b/vortex-bench/src/conversions.rs index ea91835570b..2760345379c 100644 --- a/vortex-bench/src/conversions.rs +++ b/vortex-bench/src/conversions.rs @@ -16,6 +16,7 @@ use parquet::arrow::ParquetRecordBatchStreamBuilder; use parquet::arrow::arrow_reader::ArrowReaderMetadata; use parquet::arrow::arrow_reader::ArrowReaderOptions; use parquet::arrow::async_reader::ParquetRecordBatchStream; +use parquet::basic::Compression; use parquet::file::metadata::KeyValue; use parquet::file::metadata::ParquetMetaData; use sysinfo::System; @@ -428,17 +429,25 @@ pub async fn write_parquet_as_vortex( } /// Add GeoParquet `geo` file metadata to externally-sourced parquet we don't generate (e.g. SpatialBench `zone`). +/// +/// The file is rewritten with zstd unless it already has both the metadata and zstd, so a file +/// tagged before the benchmarks wrote zstd is compressed too. pub async fn add_geoparquet_metadata( parquet_path: &Path, geoparquet_json: &str, ) -> anyhow::Result<()> { let builder = ParquetRecordBatchStreamBuilder::new(File::open(parquet_path).await?).await?; - let already_tagged = builder - .metadata() + let metadata = builder.metadata(); + let already_tagged = metadata .file_metadata() .key_value_metadata() .is_some_and(|kvs| kvs.iter().any(|kv| kv.key == "geo")); - if already_tagged { + let zstd = metadata + .row_groups() + .iter() + .flat_map(|row_group| row_group.columns()) + .all(|column| matches!(column.compression(), Compression::ZSTD(_))); + if already_tagged && zstd { return Ok(()); } @@ -579,7 +588,7 @@ mod tests { use arrow_schema::Field; use arrow_schema::Schema; use parquet::arrow::ArrowWriter; - use parquet::basic::Compression; + use parquet::file::properties::WriterProperties; use parquet::file::reader::FileReader as _; use parquet::file::reader::SerializedFileReader; @@ -609,4 +618,40 @@ mod tests { assert_eq!(metadata.file_metadata().num_rows(), 1000); Ok(()) } + + #[tokio::test] + async fn geoparquet_tagging_recompresses_a_tagged_uncompressed_file() -> anyhow::Result<()> { + let dir = tempfile::tempdir()?; + let path = dir.path().join("zone.parquet"); + let schema = Arc::new(Schema::new(vec![Field::new("id", DataType::Int64, false)])); + let batch = RecordBatch::try_new( + Arc::clone(&schema), + vec![Arc::new(Int64Array::from_iter_values(0..1000))], + )?; + // A file the previous implementation left: tagged, but uncompressed. + let props = WriterProperties::builder() + .set_key_value_metadata(Some(vec![KeyValue::new( + "geo".to_string(), + Some("{}".to_string()), + )])) + .build(); + let mut writer = ArrowWriter::try_new(fs::File::create(&path)?, schema, Some(props))?; + writer.write(&batch)?; + writer.close()?; + + add_geoparquet_metadata(&path, "{}").await?; + + let reader = SerializedFileReader::new(fs::File::open(&path)?)?; + let metadata = reader.metadata(); + assert!(matches!( + metadata.row_group(0).column(0).compression(), + Compression::ZSTD(_) + )); + let geo_keys = metadata + .file_metadata() + .key_value_metadata() + .map_or(0, |kvs| kvs.iter().filter(|kv| kv.key == "geo").count()); + assert_eq!(geo_keys, 1); + Ok(()) + } } From 6433890712f84e6d08a6850596aa24a2a9dd02ca Mon Sep 17 00:00:00 2001 From: Will Manning Date: Sat, 21 Nov 2026 08:49:00 -0500 Subject: [PATCH 13/44] Move compress-bench's size-only records into their own function Writing them after the timed runs raised run_benchmark_for_dataset's cognitive complexity to 27, over clippy's limit of 25. Signed-off-by: Will Manning --- benchmarks/compress-bench/src/main.rs | 82 +++++++++++++++++---------- 1 file changed, 53 insertions(+), 29 deletions(-) diff --git a/benchmarks/compress-bench/src/main.rs b/benchmarks/compress-bench/src/main.rs index dc222c0c04a..5c1342b99d6 100644 --- a/benchmarks/compress-bench/src/main.rs +++ b/benchmarks/compress-bench/src/main.rs @@ -3,6 +3,7 @@ use std::any::Any; use std::panic::AssertUnwindSafe; +use std::path::Path; use std::path::PathBuf; use std::time::Duration; @@ -460,6 +461,47 @@ async fn run_compress( Ok(()) } +/// Size records of the size-only formats, one untimed write each: DuckDB's Snappy Parquet beside +/// `parquet`, and compact Vortex beside `vortex`. +async fn size_only_records( + parquet_path: &Path, + formats: &[Format], + mode: BenchMode, + bench_name: &str, + (v3_dataset, v3_variant): (&str, Option<&str>), + uncompressed_size: u64, +) -> anyhow::Result> { + let mut records = Vec::new(); + if formats.contains(&Format::Parquet) { + let snappy_size = duckdb_snappy_parquet_size(parquet_path) + .await + .with_context(|| format!("writing {bench_name} as Snappy Parquet with DuckDB"))?; + records.push(v3::named_compression_size_record( + v3_dataset, + v3_variant, + PARQUET_SNAPPY_FORMAT, + snappy_size, + uncompressed_size, + )); + } + if formats.contains(&Format::OnDiskVortex) { + let input = get_compressor(Format::OnDiskVortex, mode)? + .load(parquet_path) + .await + .with_context(|| format!("loading {bench_name} for compact Vortex"))?; + let compact_size = vortex_compact_size(&input) + .await + .with_context(|| format!("compressing {bench_name} as compact Vortex"))?; + records.push(v3::compression_size_record( + v3_dataset, + v3_variant, + Format::VortexCompact, + compact_size, + uncompressed_size, + )); + } + Ok(records) +} async fn run_benchmark_for_dataset( progress: &ProgressBar, @@ -582,39 +624,21 @@ async fn run_benchmark_for_dataset( } } - // Size-only formats: one untimed write each. They run after every timed run of the dataset, - // so their reads and writes cannot warm caches for a timed measurement. + // After every timed run of the dataset, so these writes cannot warm caches for a timed one. if ops.contains(&CompressOp::Compress) && !mode.is_gpu() { let uncompressed_size = uncompressed_size.context("compression size requires Arrow memory size")?; - if formats.contains(&Format::Parquet) { - let snappy_size = duckdb_snappy_parquet_size(&parquet_path) - .await - .with_context(|| format!("writing {bench_name} as Snappy Parquet with DuckDB"))?; - v3_records.push(v3::named_compression_size_record( - v3_dataset, - v3_variant, - PARQUET_SNAPPY_FORMAT, - snappy_size, - uncompressed_size, - )); - } - if formats.contains(&Format::OnDiskVortex) { - let input = get_compressor(Format::OnDiskVortex, mode)? - .load(&parquet_path) - .await - .with_context(|| format!("loading {bench_name} for compact Vortex"))?; - let compact_size = vortex_compact_size(&input) - .await - .with_context(|| format!("compressing {bench_name} as compact Vortex"))?; - v3_records.push(v3::compression_size_record( - v3_dataset, - v3_variant, - Format::VortexCompact, - compact_size, + v3_records.extend( + size_only_records( + &parquet_path, + formats, + mode, + bench_name, + (v3_dataset, v3_variant), uncompressed_size, - )); - } + ) + .await?, + ); } // Calculate cross-format ratios after all measurements. From 48bcff483fd7044e78526ef995f08910046d8349 Mon Sep 17 00:00:00 2001 From: Will Manning Date: Sat, 21 Nov 2026 09:07:56 -0500 Subject: [PATCH 14/44] Query Snappy Parquet in TPC-H SF10 on NVMe and S3 on develop Develop runs DataFusion and DuckDB on parquet-snappy beside zstd Parquet, so bench can compare the two Parquet variants on local disk and on S3. Signed-off-by: Will Manning --- .../bench_orchestrator/ci_matrix/catalog.py | 10 ++++++++-- bench-orchestrator/tests/test_matrix.py | 14 ++++++++++++++ 2 files changed, 22 insertions(+), 2 deletions(-) diff --git a/bench-orchestrator/bench_orchestrator/ci_matrix/catalog.py b/bench-orchestrator/bench_orchestrator/ci_matrix/catalog.py index aaf2fd58c10..6ea58400558 100644 --- a/bench-orchestrator/bench_orchestrator/ci_matrix/catalog.py +++ b/bench-orchestrator/bench_orchestrator/ci_matrix/catalog.py @@ -66,6 +66,8 @@ Format.PARQUET, Format.VORTEX_COMPACT, ) +# Parquet as DuckDB writes it by default, queried beside zstd Parquet where bench compares the two. +SNAPPY_TARGETS = df(Format.PARQUET_SNAPPY) | duck(Format.PARQUET_SNAPPY) # Vortex targets name an integration (`file`, `datasource`) and a scan engine (`v1`, `v2`); see # `BenchmarkTarget`. Declared targets run the file integration on the suite's default engine. @@ -98,6 +100,10 @@ def with_all_scans(coverage: Coverage) -> Coverage: STANDARD_WITH_DUCKDB_TARGETS | df(Format.PARQUET_SNAPPY, Format.LANCE) | duck(Format.PARQUET_SNAPPY), size_formats=(SizeFormat.ARROW_IPC,), ) +# TPC-H SF=10 queries Snappy Parquet on NVMe and S3, so bench can compare the two Parquet variants +# where file size matters most for speed: S3 reads every byte over the network. +FULL_LOCAL_WITH_SNAPPY = Coverage(FULL_LOCAL_TARGETS | SNAPPY_TARGETS) +STANDARD_WITH_SNAPPY = Coverage(STANDARD_TARGETS | SNAPPY_TARGETS) DATAFUSION_VORTEX = Coverage(DATAFUSION_VORTEX_TARGETS) COMPACT = Coverage(COMPACT_TARGETS) JOB_DUCKDB = Coverage(duck(Format.PARQUET, Format.VORTEX, Format.DUCKDB)) @@ -215,7 +221,7 @@ def _tpcds_sf100_job(target: BenchmarkTarget) -> str: "pr": DEFAULT, "pr-compact": COMPACT, "pr-full": FULL_PR, - "develop": FULL_LOCAL, + "develop": FULL_LOCAL_WITH_SNAPPY, }, ), BenchmarkCase( @@ -230,7 +236,7 @@ def _tpcds_sf100_job(target: BenchmarkTarget) -> str: runs={ "pr-compact": COMPACT, "pr-full": STANDARD, - "develop": STANDARD, + "develop": STANDARD_WITH_SNAPPY, }, ), BenchmarkCase( diff --git a/bench-orchestrator/tests/test_matrix.py b/bench-orchestrator/tests/test_matrix.py index 24994322bed..caa30bf522a 100644 --- a/bench-orchestrator/tests/test_matrix.py +++ b/bench-orchestrator/tests/test_matrix.py @@ -348,6 +348,20 @@ def test_develop_tpcds_sf1_queries_snappy_parquet_and_lance() -> None: assert "lance" not in entry["data_formats"] +@pytest.mark.parametrize("case_id", ("tpch-nvme-10", "tpch-s3-10")) +def test_develop_tpch_sf10_queries_both_parquet_variants(case_id: str) -> None: + entry = {entry["id"]: entry for entry in _entries("develop")}[case_id] + targets = {(target["engine"], target["format"]) for target in entry["targets"]} + + assert { + ("datafusion", "parquet"), + ("duckdb", "parquet"), + ("datafusion", "parquet-snappy"), + ("duckdb", "parquet-snappy"), + } <= targets + assert entry["data_formats"][:2] == ["parquet", "parquet-snappy"] + + def test_resolver_rejects_a_size_only_format_that_a_target_reads() -> None: benchmark = replace( CATALOG.benchmarks[0], From e0e95b1de142f20c374ec600e48dced804d7d39f Mon Sep 17 00:00:00 2001 From: Will Manning Date: Sat, 21 Nov 2026 09:08:53 -0500 Subject: [PATCH 15/44] TEMPORARY: run TPC-H SF10 Snappy targets in the pr preset Lets this pull request's action/bench-sql run compare zstd and Snappy Parquet on NVMe and S3. Revert before merge. Signed-off-by: Will Manning --- .../bench_orchestrator/ci_matrix/catalog.py | 3 ++- bench-orchestrator/tests/test_matrix.py | 10 +++++++--- 2 files changed, 9 insertions(+), 4 deletions(-) diff --git a/bench-orchestrator/bench_orchestrator/ci_matrix/catalog.py b/bench-orchestrator/bench_orchestrator/ci_matrix/catalog.py index 6ea58400558..30a5ca735b8 100644 --- a/bench-orchestrator/bench_orchestrator/ci_matrix/catalog.py +++ b/bench-orchestrator/bench_orchestrator/ci_matrix/catalog.py @@ -218,7 +218,7 @@ def _tpcds_sf100_job(target: BenchmarkTarget) -> str: scale_factor=10.0, iterations=10, runs={ - "pr": DEFAULT, + "pr": Coverage(DEFAULT_TARGETS | SNAPPY_TARGETS), # TEMPORARY: compare the Parquet variants on this PR "pr-compact": COMPACT, "pr-full": FULL_PR, "develop": FULL_LOCAL_WITH_SNAPPY, @@ -234,6 +234,7 @@ def _tpcds_sf100_job(target: BenchmarkTarget) -> str: local_dir="vortex-bench/data/tpch/10.0", remote_key="tpch/10.0", runs={ + "pr": Coverage(DEFAULT_TARGETS | SNAPPY_TARGETS), # TEMPORARY: compare the Parquet variants on this PR "pr-compact": COMPACT, "pr-full": STANDARD, "develop": STANDARD_WITH_SNAPPY, diff --git a/bench-orchestrator/tests/test_matrix.py b/bench-orchestrator/tests/test_matrix.py index caa30bf522a..f2373856404 100644 --- a/bench-orchestrator/tests/test_matrix.py +++ b/bench-orchestrator/tests/test_matrix.py @@ -58,7 +58,6 @@ if benchmark_id not in { "clickbench-sorted-nvme", - "tpch-s3-10", "statpopgen", "fineweb-s3", "appian-nvme", @@ -289,10 +288,15 @@ def test_pr_full_covers_pr() -> None: pr = _groups("pr") pr_full = _groups("pr-full") + # TEMPORARY: this PR runs TPC-H SF=10 Snappy targets in `pr` only, to compare the Parquet variants. + def no_snappy(values: set) -> set: + return {v for v in values if "parquet-snappy" not in v} + for benchmark_id, group in pr.items(): full_group = pr_full[benchmark_id] - assert cast("set[object]", group["targets"]) <= cast("set[object]", full_group["targets"]) - assert cast("set[str]", group["data_formats"]) <= cast("set[str]", full_group["data_formats"]) + targets = no_snappy(cast("set[object]", group["targets"])) + assert targets <= cast("set[object]", full_group["targets"]) + assert no_snappy(cast("set[str]", group["data_formats"])) <= cast("set[str]", full_group["data_formats"]) def test_resolver_rejects_empty_targets() -> None: From c9ccf060811b7f955eb0547208d93e500e83493a Mon Sep 17 00:00:00 2001 From: Will Manning Date: Sat, 21 Nov 2026 09:21:27 -0500 Subject: [PATCH 16/44] Count the Parquet footer and rewrite stale cached Parquet compress-bench now records zstd Parquet's whole file, footer included, as it does for Vortex and DuckDB's Snappy Parquet. The Vortex query suite and statpopgen write their Parquet again when a cached file is not zstd. Signed-off-by: Will Manning --- benchmarks/compress-bench/src/parquet.rs | 10 ++-- vortex-bench/src/conversions.rs | 10 ++-- vortex-bench/src/statpopgen/download_vcf.rs | 5 ++ vortex-bench/src/utils/parquet.rs | 56 +++++++++++++++++++++ vortex-bench/src/vortex_queries.rs | 9 +++- 5 files changed, 77 insertions(+), 13 deletions(-) diff --git a/benchmarks/compress-bench/src/parquet.rs b/benchmarks/compress-bench/src/parquet.rs index 438900d67c4..50ba20474dc 100644 --- a/benchmarks/compress-bench/src/parquet.rs +++ b/benchmarks/compress-bench/src/parquet.rs @@ -136,7 +136,7 @@ impl Compressor for ParquetCompressor { } /// Write `batches` to `buf` as one Parquet file the way DataFusion's `ParquetSink` does with its -/// default options, returning the bytes written before the footer. +/// default options, returning the file's size, footer included, as the other formats count theirs. /// /// Batches are split at the writer's `max_row_group_row_count`, the same row-group boundaries a /// sequential `ArrowWriter` produces. Every leaf column of the open row group is encoded by its own @@ -185,11 +185,11 @@ pub async fn parquet_compress_write( } serialize.await??; - let n_bytes = writer.bytes_written(); writer.close()?; output.flush_into(&mut parts, 0); - buf.reserve_exact(parts.iter().map(Vec::len).sum()); + let n_bytes = parts.iter().map(Vec::len).sum(); + buf.reserve_exact(n_bytes); for part in parts { buf.extend_from_slice(&part); } @@ -491,13 +491,15 @@ mod tests { let compression = Compression::ZSTD(ZstdLevel::try_new(3)?); let mut parallel = Vec::new(); - parquet_compress_write( + let size = parquet_compress_write( batches.clone(), Arc::clone(&schema), compression, &mut parallel, ) .await?; + // The size counts the whole file, footer included. + assert_eq!(size, parallel.len()); let parallel = Bytes::from(parallel); let mut sequential = Vec::new(); diff --git a/vortex-bench/src/conversions.rs b/vortex-bench/src/conversions.rs index 2760345379c..243c07712e5 100644 --- a/vortex-bench/src/conversions.rs +++ b/vortex-bench/src/conversions.rs @@ -16,7 +16,6 @@ use parquet::arrow::ParquetRecordBatchStreamBuilder; use parquet::arrow::arrow_reader::ArrowReaderMetadata; use parquet::arrow::arrow_reader::ArrowReaderOptions; use parquet::arrow::async_reader::ParquetRecordBatchStream; -use parquet::basic::Compression; use parquet::file::metadata::KeyValue; use parquet::file::metadata::ParquetMetaData; use sysinfo::System; @@ -73,6 +72,7 @@ use crate::CompactionStrategy; use crate::Format; use crate::SESSION; use crate::utils::file::idempotent_async; +use crate::utils::parquet::is_zstd; use crate::utils::parquet::parquet_writer_properties; /// Memory budget per concurrent conversion stream in GB. This is somewhat arbitary. @@ -442,12 +442,7 @@ pub async fn add_geoparquet_metadata( .file_metadata() .key_value_metadata() .is_some_and(|kvs| kvs.iter().any(|kv| kv.key == "geo")); - let zstd = metadata - .row_groups() - .iter() - .flat_map(|row_group| row_group.columns()) - .all(|column| matches!(column.compression(), Compression::ZSTD(_))); - if already_tagged && zstd { + if already_tagged && is_zstd(metadata) { return Ok(()); } @@ -588,6 +583,7 @@ mod tests { use arrow_schema::Field; use arrow_schema::Schema; use parquet::arrow::ArrowWriter; + use parquet::basic::Compression; use parquet::file::properties::WriterProperties; use parquet::file::reader::FileReader as _; use parquet::file::reader::SerializedFileReader; diff --git a/vortex-bench/src/statpopgen/download_vcf.rs b/vortex-bench/src/statpopgen/download_vcf.rs index b04dfcde5d8..c3788804742 100644 --- a/vortex-bench/src/statpopgen/download_vcf.rs +++ b/vortex-bench/src/statpopgen/download_vcf.rs @@ -38,6 +38,7 @@ use super::StatPopGenBenchmark; use crate::idempotent_async; use crate::statpopgen::builder::GnomADBuilder; use crate::statpopgen::schema::schema_from_vcf_header; +use crate::utils::parquet::is_zstd_file; use crate::utils::parquet::parquet_writer_properties; // DuckDB parallelizes parquet at row-group granularity. Each of our rows are quite big (~4000 @@ -56,6 +57,10 @@ impl StatPopGenBenchmark { StatPopGenBenchmark::FILE_NAME ); let parquet_output_path = self.parquet_path()?; + // A file written before the benchmark wrote zstd is written again. + if parquet_output_path.exists() && !is_zstd_file(&parquet_output_path)? { + std::fs::remove_file(&parquet_output_path)?; + } idempotent_async( &parquet_output_path, diff --git a/vortex-bench/src/utils/parquet.rs b/vortex-bench/src/utils/parquet.rs index 3fa62e42e26..37a206008d0 100644 --- a/vortex-bench/src/utils/parquet.rs +++ b/vortex-bench/src/utils/parquet.rs @@ -3,8 +3,13 @@ //! Shared Parquet writer settings for generated benchmark data. +use std::fs::File; +use std::path::Path; + use parquet::basic::Compression; use parquet::basic::ZstdLevel; +use parquet::file::metadata::ParquetMetaData; +use parquet::file::metadata::ParquetMetaDataReader; use parquet::file::properties::WriterProperties; use parquet::file::properties::WriterPropertiesBuilder; @@ -27,3 +32,54 @@ pub fn parquet_writer_properties() -> WriterPropertiesBuilder { // zstd too little context to compress repeating columns. .set_data_page_row_count_limit(usize::MAX) } + +/// Return whether every column chunk in `metadata` is zstd. +pub fn is_zstd(metadata: &ParquetMetaData) -> bool { + metadata + .row_groups() + .iter() + .flat_map(|row_group| row_group.columns()) + .all(|column| matches!(column.compression(), Compression::ZSTD(_))) +} + +/// Return whether every column chunk of the Parquet file at `path` is zstd. It reads only the +/// footer. A benchmark uses it to rewrite data that it cached before it wrote zstd. +pub fn is_zstd_file(path: &Path) -> anyhow::Result { + let metadata = ParquetMetaDataReader::new().parse_and_finish(&File::open(path)?)?; + Ok(is_zstd(&metadata)) +} + +#[cfg(test)] +mod tests { + use std::sync::Arc; + + use arrow_array::Int64Array; + use arrow_array::RecordBatch; + use parquet::arrow::ArrowWriter; + + use super::*; + + fn write(path: &Path, props: Option) -> anyhow::Result<()> { + let batch = RecordBatch::try_from_iter([( + "x", + Arc::new(Int64Array::from_iter_values(0..1000)) as _, + )])?; + let mut writer = ArrowWriter::try_new(File::create(path)?, batch.schema(), props)?; + writer.write(&batch)?; + writer.close()?; + Ok(()) + } + + #[test] + fn zstd_file_check_reads_the_codec() -> anyhow::Result<()> { + let dir = tempfile::tempdir()?; + let uncompressed = dir.path().join("uncompressed.parquet"); + let zstd = dir.path().join("zstd.parquet"); + write(&uncompressed, None)?; + write(&zstd, Some(parquet_writer_properties().build()))?; + + assert!(!is_zstd_file(&uncompressed)?); + assert!(is_zstd_file(&zstd)?); + Ok(()) + } +} diff --git a/vortex-bench/src/vortex_queries.rs b/vortex-bench/src/vortex_queries.rs index 63e9a658068..02012a3e1cb 100644 --- a/vortex-bench/src/vortex_queries.rs +++ b/vortex-bench/src/vortex_queries.rs @@ -23,6 +23,7 @@ use crate::Format; use crate::TableSpec; use crate::bench_dir; use crate::resolve_data_url; +use crate::utils::parquet::is_zstd_file; // Path to script that creates Parquet data const INIT_SQL: &str = "init.sql"; @@ -124,8 +125,12 @@ impl Benchmark for VortexBenchmark { let parquet_file = parquet_dir.join("test.parquet"); if parquet_file.exists() { - debug!("Parquet data present in {}", parquet_dir.display()); - return Ok(()); + if is_zstd_file(&parquet_file)? { + debug!("Parquet data present in {}", parquet_dir.display()); + return Ok(()); + } + // Data generated before the suite wrote zstd. Write it again. + fs::remove_file(&parquet_file)?; } let init_path = self.queries_dir.join(INIT_SQL); From 8ca376c3479a90f11cff761436c9e57266ff3009 Mon Sep 17 00:00:00 2001 From: Will Manning Date: Sat, 21 Nov 2026 09:36:36 -0500 Subject: [PATCH 17/44] TEMPORARY: query DuckDB's Parquet with zstd in TPC-H SF10 on this PR Adds a parquet-duckdb-zstd format: the base Parquet written again by the duckdb CLI with zstd level 3. Beside parquet (parquet-rs, zstd) and parquet-snappy (DuckDB, Snappy), it separates the writer's effect from the codec's. Revert before merge. Signed-off-by: Will Manning --- .../bench_orchestrator/ci_matrix/catalog.py | 6 ++-- .../bench_orchestrator/ci_matrix/render.py | 1 + .../bench_orchestrator/config.py | 3 ++ bench-orchestrator/tests/test_matrix.py | 4 +-- benchmarks/datafusion-bench/src/lib.rs | 4 ++- benchmarks/duckdb-bench/src/lib.rs | 1 + scripts/capture-file-sizes.py | 2 ++ scripts/compare-benchmark-jsons.py | 9 +++--- vortex-bench/src/bin/data-gen.rs | 7 +++++ vortex-bench/src/lib.rs | 6 ++++ vortex-bench/src/parquet_copies.rs | 28 +++++++++++++++++-- 11 files changed, 60 insertions(+), 11 deletions(-) diff --git a/bench-orchestrator/bench_orchestrator/ci_matrix/catalog.py b/bench-orchestrator/bench_orchestrator/ci_matrix/catalog.py index 30a5ca735b8..9c861d28927 100644 --- a/bench-orchestrator/bench_orchestrator/ci_matrix/catalog.py +++ b/bench-orchestrator/bench_orchestrator/ci_matrix/catalog.py @@ -68,6 +68,8 @@ ) # Parquet as DuckDB writes it by default, queried beside zstd Parquet where bench compares the two. SNAPPY_TARGETS = df(Format.PARQUET_SNAPPY) | duck(Format.PARQUET_SNAPPY) +# TEMPORARY: DuckDB's Parquet with zstd, to tell the writer's effect from the codec's on this PR. +DUCKDB_ZSTD_TARGETS = df(Format.PARQUET_DUCKDB_ZSTD) | duck(Format.PARQUET_DUCKDB_ZSTD) # Vortex targets name an integration (`file`, `datasource`) and a scan engine (`v1`, `v2`); see # `BenchmarkTarget`. Declared targets run the file integration on the suite's default engine. @@ -218,7 +220,7 @@ def _tpcds_sf100_job(target: BenchmarkTarget) -> str: scale_factor=10.0, iterations=10, runs={ - "pr": Coverage(DEFAULT_TARGETS | SNAPPY_TARGETS), # TEMPORARY: compare the Parquet variants on this PR + "pr": Coverage(DEFAULT_TARGETS | SNAPPY_TARGETS | DUCKDB_ZSTD_TARGETS), # TEMPORARY "pr-compact": COMPACT, "pr-full": FULL_PR, "develop": FULL_LOCAL_WITH_SNAPPY, @@ -234,7 +236,7 @@ def _tpcds_sf100_job(target: BenchmarkTarget) -> str: local_dir="vortex-bench/data/tpch/10.0", remote_key="tpch/10.0", runs={ - "pr": Coverage(DEFAULT_TARGETS | SNAPPY_TARGETS), # TEMPORARY: compare the Parquet variants on this PR + "pr": Coverage(DEFAULT_TARGETS | SNAPPY_TARGETS | DUCKDB_ZSTD_TARGETS), # TEMPORARY "pr-compact": COMPACT, "pr-full": STANDARD, "develop": STANDARD_WITH_SNAPPY, diff --git a/bench-orchestrator/bench_orchestrator/ci_matrix/render.py b/bench-orchestrator/bench_orchestrator/ci_matrix/render.py index a4d3c18759b..d32e86fa107 100644 --- a/bench-orchestrator/bench_orchestrator/ci_matrix/render.py +++ b/bench-orchestrator/bench_orchestrator/ci_matrix/render.py @@ -12,6 +12,7 @@ _FORMAT_ORDER = ( Format.PARQUET, Format.PARQUET_SNAPPY, + Format.PARQUET_DUCKDB_ZSTD, Format.VORTEX, Format.VORTEX_COMPACT, Format.VORTEX_SPATIAL_NATIVE, diff --git a/bench-orchestrator/bench_orchestrator/config.py b/bench-orchestrator/bench_orchestrator/config.py index ae695b2b44f..527978e5066 100644 --- a/bench-orchestrator/bench_orchestrator/config.py +++ b/bench-orchestrator/bench_orchestrator/config.py @@ -43,6 +43,7 @@ class Format(Enum): PARQUET = "parquet" # The base Parquet files as DuckDB writes them, with Snappy, which `data-gen` writes beside them. PARQUET_SNAPPY = "parquet-snappy" + PARQUET_DUCKDB_ZSTD = "parquet-duckdb-zstd" VORTEX = "vortex" VORTEX_COMPACT = "vortex-compact" VORTEX_SPATIAL_NATIVE = "vortex-spatial-native" @@ -105,6 +106,7 @@ class Benchmark(Enum): Engine.DATAFUSION: [ Format.PARQUET, Format.PARQUET_SNAPPY, + Format.PARQUET_DUCKDB_ZSTD, Format.VORTEX, Format.VORTEX_COMPACT, Format.LANCE, @@ -112,6 +114,7 @@ class Benchmark(Enum): Engine.DUCKDB: [ Format.PARQUET, Format.PARQUET_SNAPPY, + Format.PARQUET_DUCKDB_ZSTD, Format.VORTEX, Format.VORTEX_COMPACT, Format.VORTEX_SPATIAL_NATIVE, diff --git a/bench-orchestrator/tests/test_matrix.py b/bench-orchestrator/tests/test_matrix.py index f2373856404..dd10b4a0f85 100644 --- a/bench-orchestrator/tests/test_matrix.py +++ b/bench-orchestrator/tests/test_matrix.py @@ -288,9 +288,9 @@ def test_pr_full_covers_pr() -> None: pr = _groups("pr") pr_full = _groups("pr-full") - # TEMPORARY: this PR runs TPC-H SF=10 Snappy targets in `pr` only, to compare the Parquet variants. + # TEMPORARY: this PR runs TPC-H SF=10 DuckDB Parquet targets in `pr` only, to compare the Parquet variants. def no_snappy(values: set) -> set: - return {v for v in values if "parquet-snappy" not in v} + return {v for v in values if "parquet-snappy" not in v and "parquet-duckdb-zstd" not in v} for benchmark_id, group in pr.items(): full_group = pr_full[benchmark_id] diff --git a/benchmarks/datafusion-bench/src/lib.rs b/benchmarks/datafusion-bench/src/lib.rs index 8ebee6129f7..d772a40e5f8 100644 --- a/benchmarks/datafusion-bench/src/lib.rs +++ b/benchmarks/datafusion-bench/src/lib.rs @@ -103,7 +103,9 @@ pub fn format_to_df_format(format: Format, scan_v2: bool) -> anyhow::Result Arc::new(CsvFormat::default()) as _, - Format::Parquet | Format::ParquetSnappy => Arc::new(ParquetFormat::new()), + Format::Parquet | Format::ParquetSnappy | Format::ParquetDuckdbZstd => { + Arc::new(ParquetFormat::new()) + } Format::OnDiskVortex | Format::VortexCompact | Format::VortexSpatialNative => { Arc::new(VortexFormat::new_with_options(SESSION.clone(), options)) } diff --git a/benchmarks/duckdb-bench/src/lib.rs b/benchmarks/duckdb-bench/src/lib.rs index 324a7646fe4..670e39cbf99 100644 --- a/benchmarks/duckdb-bench/src/lib.rs +++ b/benchmarks/duckdb-bench/src/lib.rs @@ -207,6 +207,7 @@ impl DuckClient { let object_type = match file_format { Format::Parquet | Format::ParquetSnappy + | Format::ParquetDuckdbZstd | Format::OnDiskVortex | Format::VortexCompact | Format::VortexSpatialNative => "VIEW", diff --git a/scripts/capture-file-sizes.py b/scripts/capture-file-sizes.py index 88b1ea508ae..d26b7d6ad14 100644 --- a/scripts/capture-file-sizes.py +++ b/scripts/capture-file-sizes.py @@ -56,6 +56,8 @@ def main() -> None: # benchmarks write it, and the dataset's own files where the suite prescribes them, as # ClickBench's are Snappy. "parquet-snappy", + # Parquet as DuckDB writes it, but with zstd level 3. + "parquet-duckdb-zstd", "vortex-compact", "vortex-file-compressed", "vortex-spatial-native", diff --git a/scripts/compare-benchmark-jsons.py b/scripts/compare-benchmark-jsons.py index bde7c9d8b14..2e68d8a822c 100644 --- a/scripts/compare-benchmark-jsons.py +++ b/scripts/compare-benchmark-jsons.py @@ -1283,10 +1283,11 @@ def format_report_help() -> str: "vortex-compact": 1, "parquet": 2, "parquet-snappy": 3, - "lance": 4, - "duckdb": 5, - "arrow": 6, - "litdata": 7, + "parquet-duckdb-zstd": 4, + "lance": 5, + "duckdb": 6, + "arrow": 7, + "litdata": 8, } UNIT_ORDER = { diff --git a/vortex-bench/src/bin/data-gen.rs b/vortex-bench/src/bin/data-gen.rs index faa66608b5d..7a818f873a8 100644 --- a/vortex-bench/src/bin/data-gen.rs +++ b/vortex-bench/src/bin/data-gen.rs @@ -25,6 +25,7 @@ use vortex_bench::conversions::convert_parquet_directory_to_vortex; use vortex_bench::create_benchmark; use vortex_bench::generate_duckdb_registration_sql; use vortex_bench::parquet_copies::SizeFormat; +use vortex_bench::parquet_copies::write_duckdb_zstd_parquet_directory; use vortex_bench::parquet_copies::write_size_format; use vortex_bench::parquet_copies::write_snappy_parquet_directory; use vortex_bench::setup_logging_and_tracing_with_format; @@ -104,6 +105,12 @@ async fn main() -> anyhow::Result<()> { .await??; } + if args.formats.contains(&Format::ParquetDuckdbZstd) { + let base_path = base_path.clone(); + tokio::task::spawn_blocking(move || write_duckdb_zstd_parquet_directory(&base_path)) + .await??; + } + if args .formats .iter() diff --git a/vortex-bench/src/lib.rs b/vortex-bench/src/lib.rs index ff085fe907f..60ee0092abe 100644 --- a/vortex-bench/src/lib.rs +++ b/vortex-bench/src/lib.rs @@ -223,6 +223,10 @@ pub enum Format { #[clap(name = "parquet-snappy")] #[serde(rename = "parquet-snappy")] ParquetSnappy, + /// Parquet as DuckDB writes it, but with zstd level 3. Only suites that list it generate it. + #[clap(name = "parquet-duckdb-zstd")] + #[serde(rename = "parquet-duckdb-zstd")] + ParquetDuckdbZstd, #[clap(name = "vortex")] #[serde(rename = "vortex")] OnDiskVortex, @@ -279,6 +283,7 @@ impl Format { Format::Csv => "csv", Format::Parquet => "parquet", Format::ParquetSnappy => "parquet-snappy", + Format::ParquetDuckdbZstd => "parquet-duckdb-zstd", Format::OnDiskVortex => "vortex-file-compressed", Format::VortexCompact => "vortex-compact", Format::VortexSpatialNative => "vortex-spatial-native", @@ -294,6 +299,7 @@ impl Format { Format::Csv => "csv", Format::Parquet => "parquet", Format::ParquetSnappy => "parquet", + Format::ParquetDuckdbZstd => "parquet", Format::OnDiskVortex => "vortex", Format::VortexCompact => "vortex", Format::VortexSpatialNative => "vortex", diff --git a/vortex-bench/src/parquet_copies.rs b/vortex-bench/src/parquet_copies.rs index 75760827c16..ccac635c51e 100644 --- a/vortex-bench/src/parquet_copies.rs +++ b/vortex-bench/src/parquet_copies.rs @@ -9,6 +9,8 @@ //! an analytics engine writes it for speed, where the base files are zstd level 3 for size. The //! query engines read it like Parquet. `data-gen --formats parquet-snappy` writes it with the //! `duckdb` CLI. +//! - [`Format::ParquetDuckdbZstd`]: the same rows as DuckDB writes them by default, but with zstd +//! level 3. Beside the two others, it tells the writer's effect from the codec's. //! - [`SizeFormat::ArrowIpc`]: uncompressed Arrow IPC, which no query reads. `data-gen //! --size-formats arrow-ipc` writes it only so that `scripts/capture-file-sizes.py` records its //! size. Lance is also written for size only, by `lance-bench --data-only`, because only that @@ -59,6 +61,16 @@ pub fn write_snappy_parquet_directory(base_path: &Path) -> Result<()> { ) } +/// Write every Parquet file in `{base_path}/parquet/` again with DuckDB and zstd level 3, to +/// `{base_path}/parquet-duckdb-zstd/`. See [`write_duckdb_zstd_parquet`]. +pub fn write_duckdb_zstd_parquet_directory(base_path: &Path) -> Result<()> { + copy_parquet_directory( + base_path, + Format::ParquetDuckdbZstd, + write_duckdb_zstd_parquet, + ) +} + /// Write each Parquet file in `{base_path}/parquet/` with `write`, to `{base_path}/{format}/`. /// /// The write is idempotent: an output file that exists is not written again. @@ -112,8 +124,20 @@ fn write_arrow_ipc(input: &Path, output: &Path) -> Result<()> { /// codec is DuckDB's default, so the file is what a DuckDB user gets. The codec is named because /// it is the one the `parquet-snappy` name promises, and DuckDB's default could change. pub fn write_duckdb_snappy_parquet(input: &Path, output: &Path) -> Result<()> { + write_duckdb_parquet(input, output, "COMPRESSION snappy") +} + +/// Write the Parquet file `input` again as DuckDB writes Parquet, but with zstd level 3: the +/// codec and level of the base files, with every other setting at DuckDB's default. +pub fn write_duckdb_zstd_parquet(input: &Path, output: &Path) -> Result<()> { + write_duckdb_parquet(input, output, "COMPRESSION zstd, COMPRESSION_LEVEL 3") +} + +/// Write the Parquet file `input` to `output` with the `duckdb` CLI, with the `COPY` options +/// `codec`. +fn write_duckdb_parquet(input: &Path, output: &Path, codec: &str) -> Result<()> { let sql = format!( - "COPY (FROM read_parquet({})) TO {} (FORMAT parquet, COMPRESSION snappy)", + "COPY (FROM read_parquet({})) TO {} (FORMAT parquet, {codec})", sql_string(input)?, sql_string(output)?, ); @@ -121,7 +145,7 @@ pub fn write_duckdb_snappy_parquet(input: &Path, output: &Path) -> Result<()> { .arg("-c") .arg(&sql) .output() - .context("running the duckdb CLI, which writes parquet-snappy")?; + .context("running the duckdb CLI, which writes DuckDB's Parquet")?; if !result.status.success() { bail!( "the duckdb CLI failed: {}", From 6f5e01b014f3a2fa5bc0753624588774fb8a624c Mon Sep 17 00:00:00 2001 From: Will Manning Date: Sat, 21 Nov 2026 10:36:58 -0500 Subject: [PATCH 18/44] TEMPORARY: query DuckDB's zstd Parquet in 1,048,576-row groups on this PR Adds a parquet-duckdb-zstd-1m format: parquet-duckdb-zstd with ROW_GROUP_SIZE 1048576, the row group size of the base TPC-H files. DuckDB's writer was faster than parquet-rs on NVMe and slower on S3. This format tells whether the row group size causes that. Revert before merge. Signed-off-by: Will Manning --- .../bench_orchestrator/ci_matrix/catalog.py | 4 +++- .../bench_orchestrator/ci_matrix/render.py | 1 + .../bench_orchestrator/config.py | 3 +++ bench-orchestrator/tests/test_matrix.py | 2 +- benchmarks/datafusion-bench/src/lib.rs | 7 +++--- benchmarks/duckdb-bench/src/lib.rs | 1 + scripts/capture-file-sizes.py | 2 ++ scripts/compare-benchmark-jsons.py | 9 ++++---- vortex-bench/src/bin/data-gen.rs | 7 ++++++ vortex-bench/src/lib.rs | 6 +++++ vortex-bench/src/parquet_copies.rs | 23 +++++++++++++++++++ 11 files changed, 56 insertions(+), 9 deletions(-) diff --git a/bench-orchestrator/bench_orchestrator/ci_matrix/catalog.py b/bench-orchestrator/bench_orchestrator/ci_matrix/catalog.py index 9c861d28927..172f01fe4f5 100644 --- a/bench-orchestrator/bench_orchestrator/ci_matrix/catalog.py +++ b/bench-orchestrator/bench_orchestrator/ci_matrix/catalog.py @@ -69,7 +69,9 @@ # Parquet as DuckDB writes it by default, queried beside zstd Parquet where bench compares the two. SNAPPY_TARGETS = df(Format.PARQUET_SNAPPY) | duck(Format.PARQUET_SNAPPY) # TEMPORARY: DuckDB's Parquet with zstd, to tell the writer's effect from the codec's on this PR. -DUCKDB_ZSTD_TARGETS = df(Format.PARQUET_DUCKDB_ZSTD) | duck(Format.PARQUET_DUCKDB_ZSTD) +DUCKDB_ZSTD_TARGETS = df(Format.PARQUET_DUCKDB_ZSTD, Format.PARQUET_DUCKDB_ZSTD_1M) | duck( + Format.PARQUET_DUCKDB_ZSTD, Format.PARQUET_DUCKDB_ZSTD_1M +) # Vortex targets name an integration (`file`, `datasource`) and a scan engine (`v1`, `v2`); see # `BenchmarkTarget`. Declared targets run the file integration on the suite's default engine. diff --git a/bench-orchestrator/bench_orchestrator/ci_matrix/render.py b/bench-orchestrator/bench_orchestrator/ci_matrix/render.py index d32e86fa107..ed251a94670 100644 --- a/bench-orchestrator/bench_orchestrator/ci_matrix/render.py +++ b/bench-orchestrator/bench_orchestrator/ci_matrix/render.py @@ -13,6 +13,7 @@ Format.PARQUET, Format.PARQUET_SNAPPY, Format.PARQUET_DUCKDB_ZSTD, + Format.PARQUET_DUCKDB_ZSTD_1M, Format.VORTEX, Format.VORTEX_COMPACT, Format.VORTEX_SPATIAL_NATIVE, diff --git a/bench-orchestrator/bench_orchestrator/config.py b/bench-orchestrator/bench_orchestrator/config.py index 527978e5066..5ff8990e55f 100644 --- a/bench-orchestrator/bench_orchestrator/config.py +++ b/bench-orchestrator/bench_orchestrator/config.py @@ -44,6 +44,7 @@ class Format(Enum): # The base Parquet files as DuckDB writes them, with Snappy, which `data-gen` writes beside them. PARQUET_SNAPPY = "parquet-snappy" PARQUET_DUCKDB_ZSTD = "parquet-duckdb-zstd" + PARQUET_DUCKDB_ZSTD_1M = "parquet-duckdb-zstd-1m" VORTEX = "vortex" VORTEX_COMPACT = "vortex-compact" VORTEX_SPATIAL_NATIVE = "vortex-spatial-native" @@ -107,6 +108,7 @@ class Benchmark(Enum): Format.PARQUET, Format.PARQUET_SNAPPY, Format.PARQUET_DUCKDB_ZSTD, + Format.PARQUET_DUCKDB_ZSTD_1M, Format.VORTEX, Format.VORTEX_COMPACT, Format.LANCE, @@ -115,6 +117,7 @@ class Benchmark(Enum): Format.PARQUET, Format.PARQUET_SNAPPY, Format.PARQUET_DUCKDB_ZSTD, + Format.PARQUET_DUCKDB_ZSTD_1M, Format.VORTEX, Format.VORTEX_COMPACT, Format.VORTEX_SPATIAL_NATIVE, diff --git a/bench-orchestrator/tests/test_matrix.py b/bench-orchestrator/tests/test_matrix.py index dd10b4a0f85..4f1afc9d896 100644 --- a/bench-orchestrator/tests/test_matrix.py +++ b/bench-orchestrator/tests/test_matrix.py @@ -290,7 +290,7 @@ def test_pr_full_covers_pr() -> None: # TEMPORARY: this PR runs TPC-H SF=10 DuckDB Parquet targets in `pr` only, to compare the Parquet variants. def no_snappy(values: set) -> set: - return {v for v in values if "parquet-snappy" not in v and "parquet-duckdb-zstd" not in v} + return {v for v in values if "parquet-snappy" not in str(v) and "parquet-duckdb-zstd" not in str(v)} for benchmark_id, group in pr.items(): full_group = pr_full[benchmark_id] diff --git a/benchmarks/datafusion-bench/src/lib.rs b/benchmarks/datafusion-bench/src/lib.rs index d772a40e5f8..9f818b4c714 100644 --- a/benchmarks/datafusion-bench/src/lib.rs +++ b/benchmarks/datafusion-bench/src/lib.rs @@ -103,9 +103,10 @@ pub fn format_to_df_format(format: Format, scan_v2: bool) -> anyhow::Result Arc::new(CsvFormat::default()) as _, - Format::Parquet | Format::ParquetSnappy | Format::ParquetDuckdbZstd => { - Arc::new(ParquetFormat::new()) - } + Format::Parquet + | Format::ParquetSnappy + | Format::ParquetDuckdbZstd + | Format::ParquetDuckdbZstd1m => Arc::new(ParquetFormat::new()), Format::OnDiskVortex | Format::VortexCompact | Format::VortexSpatialNative => { Arc::new(VortexFormat::new_with_options(SESSION.clone(), options)) } diff --git a/benchmarks/duckdb-bench/src/lib.rs b/benchmarks/duckdb-bench/src/lib.rs index 670e39cbf99..12abcc0a8b2 100644 --- a/benchmarks/duckdb-bench/src/lib.rs +++ b/benchmarks/duckdb-bench/src/lib.rs @@ -208,6 +208,7 @@ impl DuckClient { Format::Parquet | Format::ParquetSnappy | Format::ParquetDuckdbZstd + | Format::ParquetDuckdbZstd1m | Format::OnDiskVortex | Format::VortexCompact | Format::VortexSpatialNative => "VIEW", diff --git a/scripts/capture-file-sizes.py b/scripts/capture-file-sizes.py index d26b7d6ad14..74dc3bc1c10 100644 --- a/scripts/capture-file-sizes.py +++ b/scripts/capture-file-sizes.py @@ -58,6 +58,8 @@ def main() -> None: "parquet-snappy", # Parquet as DuckDB writes it, but with zstd level 3. "parquet-duckdb-zstd", + # The same, in row groups of 1,048,576 rows, as parquet-rs writes TPC-H. + "parquet-duckdb-zstd-1m", "vortex-compact", "vortex-file-compressed", "vortex-spatial-native", diff --git a/scripts/compare-benchmark-jsons.py b/scripts/compare-benchmark-jsons.py index 2e68d8a822c..0edeb03e5af 100644 --- a/scripts/compare-benchmark-jsons.py +++ b/scripts/compare-benchmark-jsons.py @@ -1284,10 +1284,11 @@ def format_report_help() -> str: "parquet": 2, "parquet-snappy": 3, "parquet-duckdb-zstd": 4, - "lance": 5, - "duckdb": 6, - "arrow": 7, - "litdata": 8, + "parquet-duckdb-zstd-1m": 5, + "lance": 6, + "duckdb": 7, + "arrow": 8, + "litdata": 9, } UNIT_ORDER = { diff --git a/vortex-bench/src/bin/data-gen.rs b/vortex-bench/src/bin/data-gen.rs index 7a818f873a8..fdd89a5af08 100644 --- a/vortex-bench/src/bin/data-gen.rs +++ b/vortex-bench/src/bin/data-gen.rs @@ -25,6 +25,7 @@ use vortex_bench::conversions::convert_parquet_directory_to_vortex; use vortex_bench::create_benchmark; use vortex_bench::generate_duckdb_registration_sql; use vortex_bench::parquet_copies::SizeFormat; +use vortex_bench::parquet_copies::write_duckdb_zstd_1m_parquet_directory; use vortex_bench::parquet_copies::write_duckdb_zstd_parquet_directory; use vortex_bench::parquet_copies::write_size_format; use vortex_bench::parquet_copies::write_snappy_parquet_directory; @@ -111,6 +112,12 @@ async fn main() -> anyhow::Result<()> { .await??; } + if args.formats.contains(&Format::ParquetDuckdbZstd1m) { + let base_path = base_path.clone(); + tokio::task::spawn_blocking(move || write_duckdb_zstd_1m_parquet_directory(&base_path)) + .await??; + } + if args .formats .iter() diff --git a/vortex-bench/src/lib.rs b/vortex-bench/src/lib.rs index 60ee0092abe..e36be69a77b 100644 --- a/vortex-bench/src/lib.rs +++ b/vortex-bench/src/lib.rs @@ -227,6 +227,10 @@ pub enum Format { #[clap(name = "parquet-duckdb-zstd")] #[serde(rename = "parquet-duckdb-zstd")] ParquetDuckdbZstd, + /// [`Format::ParquetDuckdbZstd`] in row groups of 1,048,576 rows, as parquet-rs writes TPC-H. + #[clap(name = "parquet-duckdb-zstd-1m")] + #[serde(rename = "parquet-duckdb-zstd-1m")] + ParquetDuckdbZstd1m, #[clap(name = "vortex")] #[serde(rename = "vortex")] OnDiskVortex, @@ -284,6 +288,7 @@ impl Format { Format::Parquet => "parquet", Format::ParquetSnappy => "parquet-snappy", Format::ParquetDuckdbZstd => "parquet-duckdb-zstd", + Format::ParquetDuckdbZstd1m => "parquet-duckdb-zstd-1m", Format::OnDiskVortex => "vortex-file-compressed", Format::VortexCompact => "vortex-compact", Format::VortexSpatialNative => "vortex-spatial-native", @@ -300,6 +305,7 @@ impl Format { Format::Parquet => "parquet", Format::ParquetSnappy => "parquet", Format::ParquetDuckdbZstd => "parquet", + Format::ParquetDuckdbZstd1m => "parquet", Format::OnDiskVortex => "vortex", Format::VortexCompact => "vortex", Format::VortexSpatialNative => "vortex", diff --git a/vortex-bench/src/parquet_copies.rs b/vortex-bench/src/parquet_copies.rs index ccac635c51e..f2f61e71128 100644 --- a/vortex-bench/src/parquet_copies.rs +++ b/vortex-bench/src/parquet_copies.rs @@ -11,6 +11,8 @@ //! `duckdb` CLI. //! - [`Format::ParquetDuckdbZstd`]: the same rows as DuckDB writes them by default, but with zstd //! level 3. Beside the two others, it tells the writer's effect from the codec's. +//! - [`Format::ParquetDuckdbZstd1m`]: the same, but in row groups of 1,048,576 rows, the row group +//! size of the base TPC-H files. It tells the row group size's effect from the rest of the writer's. //! - [`SizeFormat::ArrowIpc`]: uncompressed Arrow IPC, which no query reads. `data-gen //! --size-formats arrow-ipc` writes it only so that `scripts/capture-file-sizes.py` records its //! size. Lance is also written for size only, by `lance-bench --data-only`, because only that @@ -71,6 +73,17 @@ pub fn write_duckdb_zstd_parquet_directory(base_path: &Path) -> Result<()> { ) } +/// Write every Parquet file in `{base_path}/parquet/` again with DuckDB, zstd level 3, and row +/// groups of 1,048,576 rows, to `{base_path}/parquet-duckdb-zstd-1m/`. See +/// [`write_duckdb_zstd_1m_parquet`]. +pub fn write_duckdb_zstd_1m_parquet_directory(base_path: &Path) -> Result<()> { + copy_parquet_directory( + base_path, + Format::ParquetDuckdbZstd1m, + write_duckdb_zstd_1m_parquet, + ) +} + /// Write each Parquet file in `{base_path}/parquet/` with `write`, to `{base_path}/{format}/`. /// /// The write is idempotent: an output file that exists is not written again. @@ -133,6 +146,16 @@ pub fn write_duckdb_zstd_parquet(input: &Path, output: &Path) -> Result<()> { write_duckdb_parquet(input, output, "COMPRESSION zstd, COMPRESSION_LEVEL 3") } +/// Write the Parquet file `input` again as [`write_duckdb_zstd_parquet`] does, but in row groups of +/// 1,048,576 rows, which is how parquet-rs writes the base TPC-H files. +pub fn write_duckdb_zstd_1m_parquet(input: &Path, output: &Path) -> Result<()> { + write_duckdb_parquet( + input, + output, + "COMPRESSION zstd, COMPRESSION_LEVEL 3, ROW_GROUP_SIZE 1048576", + ) +} + /// Write the Parquet file `input` to `output` with the `duckdb` CLI, with the `COPY` options /// `codec`. fn write_duckdb_parquet(input: &Path, output: &Path, codec: &str) -> Result<()> { From 283ad8ab24e360a772800f3e9d2a1c49677ee311 Mon Sep 17 00:00:00 2001 From: Will Manning Date: Sat, 21 Nov 2026 11:34:26 -0500 Subject: [PATCH 19/44] Revert "TEMPORARY: query DuckDB's zstd Parquet in 1,048,576-row groups on this PR" This reverts commit 6f5e01b014f3a2fa5bc0753624588774fb8a624c. Signed-off-by: Will Manning --- .../bench_orchestrator/ci_matrix/catalog.py | 4 +--- .../bench_orchestrator/ci_matrix/render.py | 1 - .../bench_orchestrator/config.py | 3 --- bench-orchestrator/tests/test_matrix.py | 2 +- benchmarks/datafusion-bench/src/lib.rs | 7 +++--- benchmarks/duckdb-bench/src/lib.rs | 1 - scripts/capture-file-sizes.py | 2 -- scripts/compare-benchmark-jsons.py | 9 ++++---- vortex-bench/src/bin/data-gen.rs | 7 ------ vortex-bench/src/lib.rs | 6 ----- vortex-bench/src/parquet_copies.rs | 23 ------------------- 11 files changed, 9 insertions(+), 56 deletions(-) diff --git a/bench-orchestrator/bench_orchestrator/ci_matrix/catalog.py b/bench-orchestrator/bench_orchestrator/ci_matrix/catalog.py index 172f01fe4f5..9c861d28927 100644 --- a/bench-orchestrator/bench_orchestrator/ci_matrix/catalog.py +++ b/bench-orchestrator/bench_orchestrator/ci_matrix/catalog.py @@ -69,9 +69,7 @@ # Parquet as DuckDB writes it by default, queried beside zstd Parquet where bench compares the two. SNAPPY_TARGETS = df(Format.PARQUET_SNAPPY) | duck(Format.PARQUET_SNAPPY) # TEMPORARY: DuckDB's Parquet with zstd, to tell the writer's effect from the codec's on this PR. -DUCKDB_ZSTD_TARGETS = df(Format.PARQUET_DUCKDB_ZSTD, Format.PARQUET_DUCKDB_ZSTD_1M) | duck( - Format.PARQUET_DUCKDB_ZSTD, Format.PARQUET_DUCKDB_ZSTD_1M -) +DUCKDB_ZSTD_TARGETS = df(Format.PARQUET_DUCKDB_ZSTD) | duck(Format.PARQUET_DUCKDB_ZSTD) # Vortex targets name an integration (`file`, `datasource`) and a scan engine (`v1`, `v2`); see # `BenchmarkTarget`. Declared targets run the file integration on the suite's default engine. diff --git a/bench-orchestrator/bench_orchestrator/ci_matrix/render.py b/bench-orchestrator/bench_orchestrator/ci_matrix/render.py index ed251a94670..d32e86fa107 100644 --- a/bench-orchestrator/bench_orchestrator/ci_matrix/render.py +++ b/bench-orchestrator/bench_orchestrator/ci_matrix/render.py @@ -13,7 +13,6 @@ Format.PARQUET, Format.PARQUET_SNAPPY, Format.PARQUET_DUCKDB_ZSTD, - Format.PARQUET_DUCKDB_ZSTD_1M, Format.VORTEX, Format.VORTEX_COMPACT, Format.VORTEX_SPATIAL_NATIVE, diff --git a/bench-orchestrator/bench_orchestrator/config.py b/bench-orchestrator/bench_orchestrator/config.py index 5ff8990e55f..527978e5066 100644 --- a/bench-orchestrator/bench_orchestrator/config.py +++ b/bench-orchestrator/bench_orchestrator/config.py @@ -44,7 +44,6 @@ class Format(Enum): # The base Parquet files as DuckDB writes them, with Snappy, which `data-gen` writes beside them. PARQUET_SNAPPY = "parquet-snappy" PARQUET_DUCKDB_ZSTD = "parquet-duckdb-zstd" - PARQUET_DUCKDB_ZSTD_1M = "parquet-duckdb-zstd-1m" VORTEX = "vortex" VORTEX_COMPACT = "vortex-compact" VORTEX_SPATIAL_NATIVE = "vortex-spatial-native" @@ -108,7 +107,6 @@ class Benchmark(Enum): Format.PARQUET, Format.PARQUET_SNAPPY, Format.PARQUET_DUCKDB_ZSTD, - Format.PARQUET_DUCKDB_ZSTD_1M, Format.VORTEX, Format.VORTEX_COMPACT, Format.LANCE, @@ -117,7 +115,6 @@ class Benchmark(Enum): Format.PARQUET, Format.PARQUET_SNAPPY, Format.PARQUET_DUCKDB_ZSTD, - Format.PARQUET_DUCKDB_ZSTD_1M, Format.VORTEX, Format.VORTEX_COMPACT, Format.VORTEX_SPATIAL_NATIVE, diff --git a/bench-orchestrator/tests/test_matrix.py b/bench-orchestrator/tests/test_matrix.py index 4f1afc9d896..dd10b4a0f85 100644 --- a/bench-orchestrator/tests/test_matrix.py +++ b/bench-orchestrator/tests/test_matrix.py @@ -290,7 +290,7 @@ def test_pr_full_covers_pr() -> None: # TEMPORARY: this PR runs TPC-H SF=10 DuckDB Parquet targets in `pr` only, to compare the Parquet variants. def no_snappy(values: set) -> set: - return {v for v in values if "parquet-snappy" not in str(v) and "parquet-duckdb-zstd" not in str(v)} + return {v for v in values if "parquet-snappy" not in v and "parquet-duckdb-zstd" not in v} for benchmark_id, group in pr.items(): full_group = pr_full[benchmark_id] diff --git a/benchmarks/datafusion-bench/src/lib.rs b/benchmarks/datafusion-bench/src/lib.rs index 9f818b4c714..d772a40e5f8 100644 --- a/benchmarks/datafusion-bench/src/lib.rs +++ b/benchmarks/datafusion-bench/src/lib.rs @@ -103,10 +103,9 @@ pub fn format_to_df_format(format: Format, scan_v2: bool) -> anyhow::Result Arc::new(CsvFormat::default()) as _, - Format::Parquet - | Format::ParquetSnappy - | Format::ParquetDuckdbZstd - | Format::ParquetDuckdbZstd1m => Arc::new(ParquetFormat::new()), + Format::Parquet | Format::ParquetSnappy | Format::ParquetDuckdbZstd => { + Arc::new(ParquetFormat::new()) + } Format::OnDiskVortex | Format::VortexCompact | Format::VortexSpatialNative => { Arc::new(VortexFormat::new_with_options(SESSION.clone(), options)) } diff --git a/benchmarks/duckdb-bench/src/lib.rs b/benchmarks/duckdb-bench/src/lib.rs index 12abcc0a8b2..670e39cbf99 100644 --- a/benchmarks/duckdb-bench/src/lib.rs +++ b/benchmarks/duckdb-bench/src/lib.rs @@ -208,7 +208,6 @@ impl DuckClient { Format::Parquet | Format::ParquetSnappy | Format::ParquetDuckdbZstd - | Format::ParquetDuckdbZstd1m | Format::OnDiskVortex | Format::VortexCompact | Format::VortexSpatialNative => "VIEW", diff --git a/scripts/capture-file-sizes.py b/scripts/capture-file-sizes.py index 74dc3bc1c10..d26b7d6ad14 100644 --- a/scripts/capture-file-sizes.py +++ b/scripts/capture-file-sizes.py @@ -58,8 +58,6 @@ def main() -> None: "parquet-snappy", # Parquet as DuckDB writes it, but with zstd level 3. "parquet-duckdb-zstd", - # The same, in row groups of 1,048,576 rows, as parquet-rs writes TPC-H. - "parquet-duckdb-zstd-1m", "vortex-compact", "vortex-file-compressed", "vortex-spatial-native", diff --git a/scripts/compare-benchmark-jsons.py b/scripts/compare-benchmark-jsons.py index 0edeb03e5af..2e68d8a822c 100644 --- a/scripts/compare-benchmark-jsons.py +++ b/scripts/compare-benchmark-jsons.py @@ -1284,11 +1284,10 @@ def format_report_help() -> str: "parquet": 2, "parquet-snappy": 3, "parquet-duckdb-zstd": 4, - "parquet-duckdb-zstd-1m": 5, - "lance": 6, - "duckdb": 7, - "arrow": 8, - "litdata": 9, + "lance": 5, + "duckdb": 6, + "arrow": 7, + "litdata": 8, } UNIT_ORDER = { diff --git a/vortex-bench/src/bin/data-gen.rs b/vortex-bench/src/bin/data-gen.rs index fdd89a5af08..7a818f873a8 100644 --- a/vortex-bench/src/bin/data-gen.rs +++ b/vortex-bench/src/bin/data-gen.rs @@ -25,7 +25,6 @@ use vortex_bench::conversions::convert_parquet_directory_to_vortex; use vortex_bench::create_benchmark; use vortex_bench::generate_duckdb_registration_sql; use vortex_bench::parquet_copies::SizeFormat; -use vortex_bench::parquet_copies::write_duckdb_zstd_1m_parquet_directory; use vortex_bench::parquet_copies::write_duckdb_zstd_parquet_directory; use vortex_bench::parquet_copies::write_size_format; use vortex_bench::parquet_copies::write_snappy_parquet_directory; @@ -112,12 +111,6 @@ async fn main() -> anyhow::Result<()> { .await??; } - if args.formats.contains(&Format::ParquetDuckdbZstd1m) { - let base_path = base_path.clone(); - tokio::task::spawn_blocking(move || write_duckdb_zstd_1m_parquet_directory(&base_path)) - .await??; - } - if args .formats .iter() diff --git a/vortex-bench/src/lib.rs b/vortex-bench/src/lib.rs index e36be69a77b..60ee0092abe 100644 --- a/vortex-bench/src/lib.rs +++ b/vortex-bench/src/lib.rs @@ -227,10 +227,6 @@ pub enum Format { #[clap(name = "parquet-duckdb-zstd")] #[serde(rename = "parquet-duckdb-zstd")] ParquetDuckdbZstd, - /// [`Format::ParquetDuckdbZstd`] in row groups of 1,048,576 rows, as parquet-rs writes TPC-H. - #[clap(name = "parquet-duckdb-zstd-1m")] - #[serde(rename = "parquet-duckdb-zstd-1m")] - ParquetDuckdbZstd1m, #[clap(name = "vortex")] #[serde(rename = "vortex")] OnDiskVortex, @@ -288,7 +284,6 @@ impl Format { Format::Parquet => "parquet", Format::ParquetSnappy => "parquet-snappy", Format::ParquetDuckdbZstd => "parquet-duckdb-zstd", - Format::ParquetDuckdbZstd1m => "parquet-duckdb-zstd-1m", Format::OnDiskVortex => "vortex-file-compressed", Format::VortexCompact => "vortex-compact", Format::VortexSpatialNative => "vortex-spatial-native", @@ -305,7 +300,6 @@ impl Format { Format::Parquet => "parquet", Format::ParquetSnappy => "parquet", Format::ParquetDuckdbZstd => "parquet", - Format::ParquetDuckdbZstd1m => "parquet", Format::OnDiskVortex => "vortex", Format::VortexCompact => "vortex", Format::VortexSpatialNative => "vortex", diff --git a/vortex-bench/src/parquet_copies.rs b/vortex-bench/src/parquet_copies.rs index f2f61e71128..ccac635c51e 100644 --- a/vortex-bench/src/parquet_copies.rs +++ b/vortex-bench/src/parquet_copies.rs @@ -11,8 +11,6 @@ //! `duckdb` CLI. //! - [`Format::ParquetDuckdbZstd`]: the same rows as DuckDB writes them by default, but with zstd //! level 3. Beside the two others, it tells the writer's effect from the codec's. -//! - [`Format::ParquetDuckdbZstd1m`]: the same, but in row groups of 1,048,576 rows, the row group -//! size of the base TPC-H files. It tells the row group size's effect from the rest of the writer's. //! - [`SizeFormat::ArrowIpc`]: uncompressed Arrow IPC, which no query reads. `data-gen //! --size-formats arrow-ipc` writes it only so that `scripts/capture-file-sizes.py` records its //! size. Lance is also written for size only, by `lance-bench --data-only`, because only that @@ -73,17 +71,6 @@ pub fn write_duckdb_zstd_parquet_directory(base_path: &Path) -> Result<()> { ) } -/// Write every Parquet file in `{base_path}/parquet/` again with DuckDB, zstd level 3, and row -/// groups of 1,048,576 rows, to `{base_path}/parquet-duckdb-zstd-1m/`. See -/// [`write_duckdb_zstd_1m_parquet`]. -pub fn write_duckdb_zstd_1m_parquet_directory(base_path: &Path) -> Result<()> { - copy_parquet_directory( - base_path, - Format::ParquetDuckdbZstd1m, - write_duckdb_zstd_1m_parquet, - ) -} - /// Write each Parquet file in `{base_path}/parquet/` with `write`, to `{base_path}/{format}/`. /// /// The write is idempotent: an output file that exists is not written again. @@ -146,16 +133,6 @@ pub fn write_duckdb_zstd_parquet(input: &Path, output: &Path) -> Result<()> { write_duckdb_parquet(input, output, "COMPRESSION zstd, COMPRESSION_LEVEL 3") } -/// Write the Parquet file `input` again as [`write_duckdb_zstd_parquet`] does, but in row groups of -/// 1,048,576 rows, which is how parquet-rs writes the base TPC-H files. -pub fn write_duckdb_zstd_1m_parquet(input: &Path, output: &Path) -> Result<()> { - write_duckdb_parquet( - input, - output, - "COMPRESSION zstd, COMPRESSION_LEVEL 3, ROW_GROUP_SIZE 1048576", - ) -} - /// Write the Parquet file `input` to `output` with the `duckdb` CLI, with the `COPY` options /// `codec`. fn write_duckdb_parquet(input: &Path, output: &Path, codec: &str) -> Result<()> { From ffbfc5b205afdb275aff05944d5f68ec00d3224a Mon Sep 17 00:00:00 2001 From: Will Manning Date: Sat, 21 Nov 2026 11:34:26 -0500 Subject: [PATCH 20/44] Revert "TEMPORARY: query DuckDB's Parquet with zstd in TPC-H SF10 on this PR" This reverts commit 8ca376c3479a90f11cff761436c9e57266ff3009. Signed-off-by: Will Manning --- .../bench_orchestrator/ci_matrix/catalog.py | 6 ++-- .../bench_orchestrator/ci_matrix/render.py | 1 - .../bench_orchestrator/config.py | 3 -- bench-orchestrator/tests/test_matrix.py | 4 +-- benchmarks/datafusion-bench/src/lib.rs | 4 +-- benchmarks/duckdb-bench/src/lib.rs | 1 - scripts/capture-file-sizes.py | 2 -- scripts/compare-benchmark-jsons.py | 9 +++--- vortex-bench/src/bin/data-gen.rs | 7 ----- vortex-bench/src/lib.rs | 6 ---- vortex-bench/src/parquet_copies.rs | 28 ++----------------- 11 files changed, 11 insertions(+), 60 deletions(-) diff --git a/bench-orchestrator/bench_orchestrator/ci_matrix/catalog.py b/bench-orchestrator/bench_orchestrator/ci_matrix/catalog.py index 9c861d28927..30a5ca735b8 100644 --- a/bench-orchestrator/bench_orchestrator/ci_matrix/catalog.py +++ b/bench-orchestrator/bench_orchestrator/ci_matrix/catalog.py @@ -68,8 +68,6 @@ ) # Parquet as DuckDB writes it by default, queried beside zstd Parquet where bench compares the two. SNAPPY_TARGETS = df(Format.PARQUET_SNAPPY) | duck(Format.PARQUET_SNAPPY) -# TEMPORARY: DuckDB's Parquet with zstd, to tell the writer's effect from the codec's on this PR. -DUCKDB_ZSTD_TARGETS = df(Format.PARQUET_DUCKDB_ZSTD) | duck(Format.PARQUET_DUCKDB_ZSTD) # Vortex targets name an integration (`file`, `datasource`) and a scan engine (`v1`, `v2`); see # `BenchmarkTarget`. Declared targets run the file integration on the suite's default engine. @@ -220,7 +218,7 @@ def _tpcds_sf100_job(target: BenchmarkTarget) -> str: scale_factor=10.0, iterations=10, runs={ - "pr": Coverage(DEFAULT_TARGETS | SNAPPY_TARGETS | DUCKDB_ZSTD_TARGETS), # TEMPORARY + "pr": Coverage(DEFAULT_TARGETS | SNAPPY_TARGETS), # TEMPORARY: compare the Parquet variants on this PR "pr-compact": COMPACT, "pr-full": FULL_PR, "develop": FULL_LOCAL_WITH_SNAPPY, @@ -236,7 +234,7 @@ def _tpcds_sf100_job(target: BenchmarkTarget) -> str: local_dir="vortex-bench/data/tpch/10.0", remote_key="tpch/10.0", runs={ - "pr": Coverage(DEFAULT_TARGETS | SNAPPY_TARGETS | DUCKDB_ZSTD_TARGETS), # TEMPORARY + "pr": Coverage(DEFAULT_TARGETS | SNAPPY_TARGETS), # TEMPORARY: compare the Parquet variants on this PR "pr-compact": COMPACT, "pr-full": STANDARD, "develop": STANDARD_WITH_SNAPPY, diff --git a/bench-orchestrator/bench_orchestrator/ci_matrix/render.py b/bench-orchestrator/bench_orchestrator/ci_matrix/render.py index d32e86fa107..a4d3c18759b 100644 --- a/bench-orchestrator/bench_orchestrator/ci_matrix/render.py +++ b/bench-orchestrator/bench_orchestrator/ci_matrix/render.py @@ -12,7 +12,6 @@ _FORMAT_ORDER = ( Format.PARQUET, Format.PARQUET_SNAPPY, - Format.PARQUET_DUCKDB_ZSTD, Format.VORTEX, Format.VORTEX_COMPACT, Format.VORTEX_SPATIAL_NATIVE, diff --git a/bench-orchestrator/bench_orchestrator/config.py b/bench-orchestrator/bench_orchestrator/config.py index 527978e5066..ae695b2b44f 100644 --- a/bench-orchestrator/bench_orchestrator/config.py +++ b/bench-orchestrator/bench_orchestrator/config.py @@ -43,7 +43,6 @@ class Format(Enum): PARQUET = "parquet" # The base Parquet files as DuckDB writes them, with Snappy, which `data-gen` writes beside them. PARQUET_SNAPPY = "parquet-snappy" - PARQUET_DUCKDB_ZSTD = "parquet-duckdb-zstd" VORTEX = "vortex" VORTEX_COMPACT = "vortex-compact" VORTEX_SPATIAL_NATIVE = "vortex-spatial-native" @@ -106,7 +105,6 @@ class Benchmark(Enum): Engine.DATAFUSION: [ Format.PARQUET, Format.PARQUET_SNAPPY, - Format.PARQUET_DUCKDB_ZSTD, Format.VORTEX, Format.VORTEX_COMPACT, Format.LANCE, @@ -114,7 +112,6 @@ class Benchmark(Enum): Engine.DUCKDB: [ Format.PARQUET, Format.PARQUET_SNAPPY, - Format.PARQUET_DUCKDB_ZSTD, Format.VORTEX, Format.VORTEX_COMPACT, Format.VORTEX_SPATIAL_NATIVE, diff --git a/bench-orchestrator/tests/test_matrix.py b/bench-orchestrator/tests/test_matrix.py index dd10b4a0f85..f2373856404 100644 --- a/bench-orchestrator/tests/test_matrix.py +++ b/bench-orchestrator/tests/test_matrix.py @@ -288,9 +288,9 @@ def test_pr_full_covers_pr() -> None: pr = _groups("pr") pr_full = _groups("pr-full") - # TEMPORARY: this PR runs TPC-H SF=10 DuckDB Parquet targets in `pr` only, to compare the Parquet variants. + # TEMPORARY: this PR runs TPC-H SF=10 Snappy targets in `pr` only, to compare the Parquet variants. def no_snappy(values: set) -> set: - return {v for v in values if "parquet-snappy" not in v and "parquet-duckdb-zstd" not in v} + return {v for v in values if "parquet-snappy" not in v} for benchmark_id, group in pr.items(): full_group = pr_full[benchmark_id] diff --git a/benchmarks/datafusion-bench/src/lib.rs b/benchmarks/datafusion-bench/src/lib.rs index d772a40e5f8..8ebee6129f7 100644 --- a/benchmarks/datafusion-bench/src/lib.rs +++ b/benchmarks/datafusion-bench/src/lib.rs @@ -103,9 +103,7 @@ pub fn format_to_df_format(format: Format, scan_v2: bool) -> anyhow::Result Arc::new(CsvFormat::default()) as _, - Format::Parquet | Format::ParquetSnappy | Format::ParquetDuckdbZstd => { - Arc::new(ParquetFormat::new()) - } + Format::Parquet | Format::ParquetSnappy => Arc::new(ParquetFormat::new()), Format::OnDiskVortex | Format::VortexCompact | Format::VortexSpatialNative => { Arc::new(VortexFormat::new_with_options(SESSION.clone(), options)) } diff --git a/benchmarks/duckdb-bench/src/lib.rs b/benchmarks/duckdb-bench/src/lib.rs index 670e39cbf99..324a7646fe4 100644 --- a/benchmarks/duckdb-bench/src/lib.rs +++ b/benchmarks/duckdb-bench/src/lib.rs @@ -207,7 +207,6 @@ impl DuckClient { let object_type = match file_format { Format::Parquet | Format::ParquetSnappy - | Format::ParquetDuckdbZstd | Format::OnDiskVortex | Format::VortexCompact | Format::VortexSpatialNative => "VIEW", diff --git a/scripts/capture-file-sizes.py b/scripts/capture-file-sizes.py index d26b7d6ad14..88b1ea508ae 100644 --- a/scripts/capture-file-sizes.py +++ b/scripts/capture-file-sizes.py @@ -56,8 +56,6 @@ def main() -> None: # benchmarks write it, and the dataset's own files where the suite prescribes them, as # ClickBench's are Snappy. "parquet-snappy", - # Parquet as DuckDB writes it, but with zstd level 3. - "parquet-duckdb-zstd", "vortex-compact", "vortex-file-compressed", "vortex-spatial-native", diff --git a/scripts/compare-benchmark-jsons.py b/scripts/compare-benchmark-jsons.py index 2e68d8a822c..bde7c9d8b14 100644 --- a/scripts/compare-benchmark-jsons.py +++ b/scripts/compare-benchmark-jsons.py @@ -1283,11 +1283,10 @@ def format_report_help() -> str: "vortex-compact": 1, "parquet": 2, "parquet-snappy": 3, - "parquet-duckdb-zstd": 4, - "lance": 5, - "duckdb": 6, - "arrow": 7, - "litdata": 8, + "lance": 4, + "duckdb": 5, + "arrow": 6, + "litdata": 7, } UNIT_ORDER = { diff --git a/vortex-bench/src/bin/data-gen.rs b/vortex-bench/src/bin/data-gen.rs index 7a818f873a8..faa66608b5d 100644 --- a/vortex-bench/src/bin/data-gen.rs +++ b/vortex-bench/src/bin/data-gen.rs @@ -25,7 +25,6 @@ use vortex_bench::conversions::convert_parquet_directory_to_vortex; use vortex_bench::create_benchmark; use vortex_bench::generate_duckdb_registration_sql; use vortex_bench::parquet_copies::SizeFormat; -use vortex_bench::parquet_copies::write_duckdb_zstd_parquet_directory; use vortex_bench::parquet_copies::write_size_format; use vortex_bench::parquet_copies::write_snappy_parquet_directory; use vortex_bench::setup_logging_and_tracing_with_format; @@ -105,12 +104,6 @@ async fn main() -> anyhow::Result<()> { .await??; } - if args.formats.contains(&Format::ParquetDuckdbZstd) { - let base_path = base_path.clone(); - tokio::task::spawn_blocking(move || write_duckdb_zstd_parquet_directory(&base_path)) - .await??; - } - if args .formats .iter() diff --git a/vortex-bench/src/lib.rs b/vortex-bench/src/lib.rs index 60ee0092abe..ff085fe907f 100644 --- a/vortex-bench/src/lib.rs +++ b/vortex-bench/src/lib.rs @@ -223,10 +223,6 @@ pub enum Format { #[clap(name = "parquet-snappy")] #[serde(rename = "parquet-snappy")] ParquetSnappy, - /// Parquet as DuckDB writes it, but with zstd level 3. Only suites that list it generate it. - #[clap(name = "parquet-duckdb-zstd")] - #[serde(rename = "parquet-duckdb-zstd")] - ParquetDuckdbZstd, #[clap(name = "vortex")] #[serde(rename = "vortex")] OnDiskVortex, @@ -283,7 +279,6 @@ impl Format { Format::Csv => "csv", Format::Parquet => "parquet", Format::ParquetSnappy => "parquet-snappy", - Format::ParquetDuckdbZstd => "parquet-duckdb-zstd", Format::OnDiskVortex => "vortex-file-compressed", Format::VortexCompact => "vortex-compact", Format::VortexSpatialNative => "vortex-spatial-native", @@ -299,7 +294,6 @@ impl Format { Format::Csv => "csv", Format::Parquet => "parquet", Format::ParquetSnappy => "parquet", - Format::ParquetDuckdbZstd => "parquet", Format::OnDiskVortex => "vortex", Format::VortexCompact => "vortex", Format::VortexSpatialNative => "vortex", diff --git a/vortex-bench/src/parquet_copies.rs b/vortex-bench/src/parquet_copies.rs index ccac635c51e..75760827c16 100644 --- a/vortex-bench/src/parquet_copies.rs +++ b/vortex-bench/src/parquet_copies.rs @@ -9,8 +9,6 @@ //! an analytics engine writes it for speed, where the base files are zstd level 3 for size. The //! query engines read it like Parquet. `data-gen --formats parquet-snappy` writes it with the //! `duckdb` CLI. -//! - [`Format::ParquetDuckdbZstd`]: the same rows as DuckDB writes them by default, but with zstd -//! level 3. Beside the two others, it tells the writer's effect from the codec's. //! - [`SizeFormat::ArrowIpc`]: uncompressed Arrow IPC, which no query reads. `data-gen //! --size-formats arrow-ipc` writes it only so that `scripts/capture-file-sizes.py` records its //! size. Lance is also written for size only, by `lance-bench --data-only`, because only that @@ -61,16 +59,6 @@ pub fn write_snappy_parquet_directory(base_path: &Path) -> Result<()> { ) } -/// Write every Parquet file in `{base_path}/parquet/` again with DuckDB and zstd level 3, to -/// `{base_path}/parquet-duckdb-zstd/`. See [`write_duckdb_zstd_parquet`]. -pub fn write_duckdb_zstd_parquet_directory(base_path: &Path) -> Result<()> { - copy_parquet_directory( - base_path, - Format::ParquetDuckdbZstd, - write_duckdb_zstd_parquet, - ) -} - /// Write each Parquet file in `{base_path}/parquet/` with `write`, to `{base_path}/{format}/`. /// /// The write is idempotent: an output file that exists is not written again. @@ -124,20 +112,8 @@ fn write_arrow_ipc(input: &Path, output: &Path) -> Result<()> { /// codec is DuckDB's default, so the file is what a DuckDB user gets. The codec is named because /// it is the one the `parquet-snappy` name promises, and DuckDB's default could change. pub fn write_duckdb_snappy_parquet(input: &Path, output: &Path) -> Result<()> { - write_duckdb_parquet(input, output, "COMPRESSION snappy") -} - -/// Write the Parquet file `input` again as DuckDB writes Parquet, but with zstd level 3: the -/// codec and level of the base files, with every other setting at DuckDB's default. -pub fn write_duckdb_zstd_parquet(input: &Path, output: &Path) -> Result<()> { - write_duckdb_parquet(input, output, "COMPRESSION zstd, COMPRESSION_LEVEL 3") -} - -/// Write the Parquet file `input` to `output` with the `duckdb` CLI, with the `COPY` options -/// `codec`. -fn write_duckdb_parquet(input: &Path, output: &Path, codec: &str) -> Result<()> { let sql = format!( - "COPY (FROM read_parquet({})) TO {} (FORMAT parquet, {codec})", + "COPY (FROM read_parquet({})) TO {} (FORMAT parquet, COMPRESSION snappy)", sql_string(input)?, sql_string(output)?, ); @@ -145,7 +121,7 @@ fn write_duckdb_parquet(input: &Path, output: &Path, codec: &str) -> Result<()> .arg("-c") .arg(&sql) .output() - .context("running the duckdb CLI, which writes DuckDB's Parquet")?; + .context("running the duckdb CLI, which writes parquet-snappy")?; if !result.status.success() { bail!( "the duckdb CLI failed: {}", From 0bcc141b632b4f2a1668f1e07aaeaaab7d48994c Mon Sep 17 00:00:00 2001 From: Will Manning Date: Sat, 21 Nov 2026 11:34:26 -0500 Subject: [PATCH 21/44] Revert "TEMPORARY: run TPC-H SF10 Snappy targets in the pr preset" This reverts commit e0e95b1de142f20c374ec600e48dced804d7d39f. Signed-off-by: Will Manning --- .../bench_orchestrator/ci_matrix/catalog.py | 3 +-- bench-orchestrator/tests/test_matrix.py | 10 +++------- 2 files changed, 4 insertions(+), 9 deletions(-) diff --git a/bench-orchestrator/bench_orchestrator/ci_matrix/catalog.py b/bench-orchestrator/bench_orchestrator/ci_matrix/catalog.py index 30a5ca735b8..6ea58400558 100644 --- a/bench-orchestrator/bench_orchestrator/ci_matrix/catalog.py +++ b/bench-orchestrator/bench_orchestrator/ci_matrix/catalog.py @@ -218,7 +218,7 @@ def _tpcds_sf100_job(target: BenchmarkTarget) -> str: scale_factor=10.0, iterations=10, runs={ - "pr": Coverage(DEFAULT_TARGETS | SNAPPY_TARGETS), # TEMPORARY: compare the Parquet variants on this PR + "pr": DEFAULT, "pr-compact": COMPACT, "pr-full": FULL_PR, "develop": FULL_LOCAL_WITH_SNAPPY, @@ -234,7 +234,6 @@ def _tpcds_sf100_job(target: BenchmarkTarget) -> str: local_dir="vortex-bench/data/tpch/10.0", remote_key="tpch/10.0", runs={ - "pr": Coverage(DEFAULT_TARGETS | SNAPPY_TARGETS), # TEMPORARY: compare the Parquet variants on this PR "pr-compact": COMPACT, "pr-full": STANDARD, "develop": STANDARD_WITH_SNAPPY, diff --git a/bench-orchestrator/tests/test_matrix.py b/bench-orchestrator/tests/test_matrix.py index f2373856404..caa30bf522a 100644 --- a/bench-orchestrator/tests/test_matrix.py +++ b/bench-orchestrator/tests/test_matrix.py @@ -58,6 +58,7 @@ if benchmark_id not in { "clickbench-sorted-nvme", + "tpch-s3-10", "statpopgen", "fineweb-s3", "appian-nvme", @@ -288,15 +289,10 @@ def test_pr_full_covers_pr() -> None: pr = _groups("pr") pr_full = _groups("pr-full") - # TEMPORARY: this PR runs TPC-H SF=10 Snappy targets in `pr` only, to compare the Parquet variants. - def no_snappy(values: set) -> set: - return {v for v in values if "parquet-snappy" not in v} - for benchmark_id, group in pr.items(): full_group = pr_full[benchmark_id] - targets = no_snappy(cast("set[object]", group["targets"])) - assert targets <= cast("set[object]", full_group["targets"]) - assert no_snappy(cast("set[str]", group["data_formats"])) <= cast("set[str]", full_group["data_formats"]) + assert cast("set[object]", group["targets"]) <= cast("set[object]", full_group["targets"]) + assert cast("set[str]", group["data_formats"]) <= cast("set[str]", full_group["data_formats"]) def test_resolver_rejects_empty_targets() -> None: From 754d9c6546da388a674a0e28ac661105a37a933f Mon Sep 17 00:00:00 2001 From: Will Manning Date: Sat, 21 Nov 2026 11:34:26 -0500 Subject: [PATCH 22/44] Revert "Query Snappy Parquet in TPC-H SF10 on NVMe and S3 on develop" This reverts commit 48bcff483fd7044e78526ef995f08910046d8349. Signed-off-by: Will Manning --- .../bench_orchestrator/ci_matrix/catalog.py | 10 ++-------- bench-orchestrator/tests/test_matrix.py | 14 -------------- 2 files changed, 2 insertions(+), 22 deletions(-) diff --git a/bench-orchestrator/bench_orchestrator/ci_matrix/catalog.py b/bench-orchestrator/bench_orchestrator/ci_matrix/catalog.py index 6ea58400558..aaf2fd58c10 100644 --- a/bench-orchestrator/bench_orchestrator/ci_matrix/catalog.py +++ b/bench-orchestrator/bench_orchestrator/ci_matrix/catalog.py @@ -66,8 +66,6 @@ Format.PARQUET, Format.VORTEX_COMPACT, ) -# Parquet as DuckDB writes it by default, queried beside zstd Parquet where bench compares the two. -SNAPPY_TARGETS = df(Format.PARQUET_SNAPPY) | duck(Format.PARQUET_SNAPPY) # Vortex targets name an integration (`file`, `datasource`) and a scan engine (`v1`, `v2`); see # `BenchmarkTarget`. Declared targets run the file integration on the suite's default engine. @@ -100,10 +98,6 @@ def with_all_scans(coverage: Coverage) -> Coverage: STANDARD_WITH_DUCKDB_TARGETS | df(Format.PARQUET_SNAPPY, Format.LANCE) | duck(Format.PARQUET_SNAPPY), size_formats=(SizeFormat.ARROW_IPC,), ) -# TPC-H SF=10 queries Snappy Parquet on NVMe and S3, so bench can compare the two Parquet variants -# where file size matters most for speed: S3 reads every byte over the network. -FULL_LOCAL_WITH_SNAPPY = Coverage(FULL_LOCAL_TARGETS | SNAPPY_TARGETS) -STANDARD_WITH_SNAPPY = Coverage(STANDARD_TARGETS | SNAPPY_TARGETS) DATAFUSION_VORTEX = Coverage(DATAFUSION_VORTEX_TARGETS) COMPACT = Coverage(COMPACT_TARGETS) JOB_DUCKDB = Coverage(duck(Format.PARQUET, Format.VORTEX, Format.DUCKDB)) @@ -221,7 +215,7 @@ def _tpcds_sf100_job(target: BenchmarkTarget) -> str: "pr": DEFAULT, "pr-compact": COMPACT, "pr-full": FULL_PR, - "develop": FULL_LOCAL_WITH_SNAPPY, + "develop": FULL_LOCAL, }, ), BenchmarkCase( @@ -236,7 +230,7 @@ def _tpcds_sf100_job(target: BenchmarkTarget) -> str: runs={ "pr-compact": COMPACT, "pr-full": STANDARD, - "develop": STANDARD_WITH_SNAPPY, + "develop": STANDARD, }, ), BenchmarkCase( diff --git a/bench-orchestrator/tests/test_matrix.py b/bench-orchestrator/tests/test_matrix.py index caa30bf522a..24994322bed 100644 --- a/bench-orchestrator/tests/test_matrix.py +++ b/bench-orchestrator/tests/test_matrix.py @@ -348,20 +348,6 @@ def test_develop_tpcds_sf1_queries_snappy_parquet_and_lance() -> None: assert "lance" not in entry["data_formats"] -@pytest.mark.parametrize("case_id", ("tpch-nvme-10", "tpch-s3-10")) -def test_develop_tpch_sf10_queries_both_parquet_variants(case_id: str) -> None: - entry = {entry["id"]: entry for entry in _entries("develop")}[case_id] - targets = {(target["engine"], target["format"]) for target in entry["targets"]} - - assert { - ("datafusion", "parquet"), - ("duckdb", "parquet"), - ("datafusion", "parquet-snappy"), - ("duckdb", "parquet-snappy"), - } <= targets - assert entry["data_formats"][:2] == ["parquet", "parquet-snappy"] - - def test_resolver_rejects_a_size_only_format_that_a_target_reads() -> None: benchmark = replace( CATALOG.benchmarks[0], From 3d619c0ea381b8727ebf9532212128e50522cf60 Mon Sep 17 00:00:00 2001 From: Will Manning Date: Sat, 21 Nov 2026 11:46:15 -0500 Subject: [PATCH 23/44] Write Snappy Parquet only for sizes, and size row groups by storage Snappy Parquet is now a size-only format: data-gen writes it from the base Parquet with `--size-formats parquet-snappy`, and no query reads it. TPC-DS SF1 still queries Lance on DataFusion. TPC-H, TPC-DS, and nested TPC-H write Parquet in row groups of 122,880 rows (DuckDB's default) for local disk, and 1,048,576 rows (parquet-rs's default) for S3. The CI matrix passes `--opt row-group-rows=1048576` to data-gen for S3 entries. In a TPC-H SF10 test, each size was the faster one on its storage. Signed-off-by: Will Manning --- .github/workflows/sql-bench-matrix.yml | 1 + AGENTS.md | 7 ++- .../bench_orchestrator/ci_matrix/catalog.py | 8 +-- .../bench_orchestrator/ci_matrix/render.py | 9 ++- .../bench_orchestrator/config.py | 10 ++-- bench-orchestrator/tests/test_matrix.py | 25 +++++--- benchmarks/compress-bench/src/main.rs | 2 +- benchmarks/datafusion-bench/src/lib.rs | 2 +- benchmarks/duckdb-bench/src/lib.rs | 1 - vortex-bench/README.md | 12 +++- vortex-bench/src/bin/data-gen.rs | 7 --- vortex-bench/src/lib.rs | 28 +++++---- vortex-bench/src/parquet_copies.rs | 60 ++++++++++--------- vortex-bench/src/tpcds/tpcds_benchmark.rs | 16 ++++- vortex-bench/src/tpcds/tpcdsgen.rs | 16 ++--- vortex-bench/src/tpch/benchmark.rs | 12 +++- vortex-bench/src/tpch/tpchgen.rs | 21 ++++--- vortex-bench/src/tpch_nested/mod.rs | 12 +++- vortex-bench/src/utils/parquet.rs | 8 +++ 19 files changed, 170 insertions(+), 87 deletions(-) diff --git a/.github/workflows/sql-bench-matrix.yml b/.github/workflows/sql-bench-matrix.yml index 9bad1becaeb..c7b4d8da3ac 100644 --- a/.github/workflows/sql-bench-matrix.yml +++ b/.github/workflows/sql-bench-matrix.yml @@ -224,6 +224,7 @@ jobs: uv run --project bench-orchestrator vx-bench prepare-data "${{ matrix.subcommand }}" \ --formats-json '${{ toJSON(matrix.data_formats) }}' \ ${S3_CACHE:+--s3-cache "$S3_CACHE"} \ + ${{ matrix.row_group_rows && format('--opt row-group-rows={0}', matrix.row_group_rows) || '' }} \ ${{ matrix.scale_factor && format('--opt scale-factor={0}', matrix.scale_factor) || '' }} # setup-benchmark.sh pins every running process to the housekeeping CPUs, so it waits for diff --git a/AGENTS.md b/AGENTS.md index f599201dd24..ece89a00f96 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -231,7 +231,12 @@ These CI checks are the ones most often missed when adding files rather than edi - DuckDB: `(FORMAT parquet, COMPRESSION zstd, COMPRESSION_LEVEL 3)` - tpchgen-cli: `parquet --compression='ZSTD(3)'` - Benchmarks that deliberately compare Parquet codecs, such as the GPU compress benchmark's - `--codec`, are exempt. + `--codec` and the `parquet-snappy` copy that `data-gen --size-formats` writes only for its + size, are exempt. +- Generated Parquet that queries read from local disk has row groups of 122,880 rows + (`LOCAL_ROW_GROUP_ROWS`, DuckDB's default). Generated Parquet that queries read from S3 has + row groups of 1,048,576 rows (`S3_ROW_GROUP_ROWS`, parquet-rs's default): the CI matrix passes + `--opt row-group-rows=1048576` to `data-gen` for S3 entries. ## Common Mistakes diff --git a/bench-orchestrator/bench_orchestrator/ci_matrix/catalog.py b/bench-orchestrator/bench_orchestrator/ci_matrix/catalog.py index aaf2fd58c10..a4fb4f38273 100644 --- a/bench-orchestrator/bench_orchestrator/ci_matrix/catalog.py +++ b/bench-orchestrator/bench_orchestrator/ci_matrix/catalog.py @@ -92,11 +92,11 @@ def with_all_scans(coverage: Coverage) -> Coverage: ) STANDARD_WITH_DUCKDB = Coverage(STANDARD_WITH_DUCKDB_TARGETS) # TPC-DS SF1 is the SQL data that bench.vortex.dev's File Sizes summary ranks, so develop has every -# format `compress-bench` measures. It queries Snappy Parquet on both engines and Lance on -# DataFusion, and writes Arrow IPC only for its size. They are small and fast at SF1. +# format `compress-bench` measures. It queries Lance on DataFusion, and writes Snappy Parquet and +# Arrow IPC only for their sizes. They are small and fast at SF1. STANDARD_WITH_DUCKDB_AND_SIZE_FORMATS = Coverage( - STANDARD_WITH_DUCKDB_TARGETS | df(Format.PARQUET_SNAPPY, Format.LANCE) | duck(Format.PARQUET_SNAPPY), - size_formats=(SizeFormat.ARROW_IPC,), + STANDARD_WITH_DUCKDB_TARGETS | df(Format.LANCE), + size_formats=(SizeFormat.PARQUET_SNAPPY, SizeFormat.ARROW_IPC), ) DATAFUSION_VORTEX = Coverage(DATAFUSION_VORTEX_TARGETS) COMPACT = Coverage(COMPACT_TARGETS) diff --git a/bench-orchestrator/bench_orchestrator/ci_matrix/render.py b/bench-orchestrator/bench_orchestrator/ci_matrix/render.py index a4d3c18759b..8b30c501efc 100644 --- a/bench-orchestrator/bench_orchestrator/ci_matrix/render.py +++ b/bench-orchestrator/bench_orchestrator/ci_matrix/render.py @@ -4,14 +4,15 @@ """Render declarative benchmark coverage as GitHub Actions matrices.""" from ..config import Benchmark, BenchmarkTarget, Engine, Format, Integration, ScanEngine, SizeFormat -from .model import BenchmarkCase, Catalog, Coverage, ScanCoverage +from .model import BenchmarkCase, Catalog, Coverage, ScanCoverage, Storage from .targets import TargetSet from .validate import validate_catalog _NOT_GENERATED = frozenset({Format.LANCE}) +# vortex-bench's `S3_ROW_GROUP_ROWS`: parquet-rs's default. +S3_ROW_GROUP_ROWS = 1024 * 1024 _FORMAT_ORDER = ( Format.PARQUET, - Format.PARQUET_SNAPPY, Format.VORTEX, Format.VORTEX_COMPACT, Format.VORTEX_SPATIAL_NATIVE, @@ -115,6 +116,10 @@ def _matrix_entry( if benchmark.remote_key is not None: # A distinct key per entry: each S3 entry clears and re-uploads its own copy of the data. entry["remote_key"] = benchmark.remote_key + suffix + if benchmark.storage is Storage.S3: + # Generated Parquet that queries read from S3 has larger row groups than the default, so + # it needs fewer requests to object storage. Suites that query published files ignore it. + entry["row_group_rows"] = str(S3_ROW_GROUP_ROWS) return entry diff --git a/bench-orchestrator/bench_orchestrator/config.py b/bench-orchestrator/bench_orchestrator/config.py index ae695b2b44f..478956fd38f 100644 --- a/bench-orchestrator/bench_orchestrator/config.py +++ b/bench-orchestrator/bench_orchestrator/config.py @@ -41,8 +41,6 @@ class Format(Enum): """Data formats for benchmarks.""" PARQUET = "parquet" - # The base Parquet files as DuckDB writes them, with Snappy, which `data-gen` writes beside them. - PARQUET_SNAPPY = "parquet-snappy" VORTEX = "vortex" VORTEX_COMPACT = "vortex-compact" VORTEX_SPATIAL_NATIVE = "vortex-spatial-native" @@ -73,10 +71,12 @@ class ScanEngine(Enum): class SizeFormat(Enum): """A format a benchmark writes only to record its file sizes. No query reads it. - `vx-bench write-size-formats` writes Arrow IPC with `data-gen --size-formats`, and Lance with - `lance-bench --data-only`. + `vx-bench write-size-formats` writes Snappy Parquet and Arrow IPC with `data-gen --size-formats`, + and Lance with `lance-bench --data-only`. """ + # The base Parquet files as DuckDB writes them, with Snappy. + PARQUET_SNAPPY = "parquet-snappy" ARROW_IPC = "arrow-ipc" LANCE = "lance" @@ -104,14 +104,12 @@ class Benchmark(Enum): ENGINE_FORMATS: dict[Engine, list[Format]] = { Engine.DATAFUSION: [ Format.PARQUET, - Format.PARQUET_SNAPPY, Format.VORTEX, Format.VORTEX_COMPACT, Format.LANCE, ], Engine.DUCKDB: [ Format.PARQUET, - Format.PARQUET_SNAPPY, Format.VORTEX, Format.VORTEX_COMPACT, Format.VORTEX_SPATIAL_NATIVE, diff --git a/bench-orchestrator/tests/test_matrix.py b/bench-orchestrator/tests/test_matrix.py index 24994322bed..3d95f131135 100644 --- a/bench-orchestrator/tests/test_matrix.py +++ b/bench-orchestrator/tests/test_matrix.py @@ -200,6 +200,18 @@ def test_every_s3_entry_has_its_own_remote_key(preset: str) -> None: assert len(keys) == len(set(keys)) +@pytest.mark.parametrize("preset", ["develop", "nightly", "pr-full", "pr-all"]) +def test_only_s3_entries_generate_parquet_with_large_row_groups(preset: str) -> None: + entries = _entries(preset) + + assert any("remote_key" in entry for entry in entries) + for entry in entries: + if "remote_key" in entry: + assert entry["row_group_rows"] == "1048576" + else: + assert "row_group_rows" not in entry + + def test_tpcds_sf100_runs_one_target_per_job() -> None: nightly = [ entry for entry in _entries("nightly") if str(entry["id"]).startswith("tpcds-") and "-100-" in str(entry["id"]) @@ -330,22 +342,19 @@ def test_only_develop_tpcds_sf1_writes_size_only_formats(preset: str) -> None: writers = {entry["id"]: entry["size_formats"] for entry in _entries(preset) if entry["size_formats"]} if preset == "develop": - assert writers == {"tpcds-nvme": ["arrow-ipc"]} + assert writers == {"tpcds-nvme": ["parquet-snappy", "arrow-ipc"]} else: assert writers == {} -def test_develop_tpcds_sf1_queries_snappy_parquet_and_lance() -> None: +def test_develop_tpcds_sf1_queries_lance_but_not_snappy_parquet() -> None: entry = {entry["id"]: entry for entry in _entries("develop")}["tpcds-nvme"] targets = {(target["engine"], target["format"]) for target in entry["targets"]} - assert { - ("datafusion", "parquet-snappy"), - ("duckdb", "parquet-snappy"), - ("datafusion", "lance"), - } <= targets - assert entry["data_formats"][:2] == ["parquet", "parquet-snappy"] + assert ("datafusion", "lance") in targets + assert not any(fmt == "parquet-snappy" for _, fmt in targets) assert "lance" not in entry["data_formats"] + assert "parquet-snappy" not in entry["data_formats"] def test_resolver_rejects_a_size_only_format_that_a_target_reads() -> None: diff --git a/benchmarks/compress-bench/src/main.rs b/benchmarks/compress-bench/src/main.rs index 5c1342b99d6..11d7d2eb11f 100644 --- a/benchmarks/compress-bench/src/main.rs +++ b/benchmarks/compress-bench/src/main.rs @@ -62,7 +62,7 @@ use vortex_bench::statpopgen::StatPopGenBenchmark; use vortex_bench::v3; /// The size record name of Parquet as DuckDB writes it, with Snappy, beside `parquet`, which is -/// zstd level 3. It is the same writer that `data-gen --formats parquet-snappy` uses. +/// zstd level 3. It is the same writer that `data-gen --size-formats parquet-snappy` uses. const PARQUET_SNAPPY_FORMAT: &str = "parquet-snappy"; #[derive(Parser, Debug)] diff --git a/benchmarks/datafusion-bench/src/lib.rs b/benchmarks/datafusion-bench/src/lib.rs index 8ebee6129f7..5f0b1a6800e 100644 --- a/benchmarks/datafusion-bench/src/lib.rs +++ b/benchmarks/datafusion-bench/src/lib.rs @@ -103,7 +103,7 @@ pub fn format_to_df_format(format: Format, scan_v2: bool) -> anyhow::Result Arc::new(CsvFormat::default()) as _, - Format::Parquet | Format::ParquetSnappy => Arc::new(ParquetFormat::new()), + Format::Parquet => Arc::new(ParquetFormat::new()), Format::OnDiskVortex | Format::VortexCompact | Format::VortexSpatialNative => { Arc::new(VortexFormat::new_with_options(SESSION.clone(), options)) } diff --git a/benchmarks/duckdb-bench/src/lib.rs b/benchmarks/duckdb-bench/src/lib.rs index 324a7646fe4..a5c90ce3c23 100644 --- a/benchmarks/duckdb-bench/src/lib.rs +++ b/benchmarks/duckdb-bench/src/lib.rs @@ -206,7 +206,6 @@ impl DuckClient { let object_type = match file_format { Format::Parquet - | Format::ParquetSnappy | Format::OnDiskVortex | Format::VortexCompact | Format::VortexSpatialNative => "VIEW", diff --git a/vortex-bench/README.md b/vortex-bench/README.md index 8c040e3fa29..e904b7f0750 100644 --- a/vortex-bench/README.md +++ b/vortex-bench/README.md @@ -52,7 +52,17 @@ the common writers are different: - `tpchgen-cli`: writes Snappy by default. Use `parquet --compression='ZSTD(3)'`. Benchmarks that compare Parquet codecs on purpose, such as the compress-bench `--gpu-parquet-codec` -option, are exempt. +option and the `parquet-snappy` copy that `data-gen --size-formats` writes only for its size, are +exempt. + +## Parquet row groups + +TPC-H, TPC-DS, and nested TPC-H write Parquet in row groups of 122,880 rows, DuckDB's default. +In our tests, these smaller row groups were faster from local disk, because they give the query +engines more units of work to run in parallel. The benchmarks that read from S3 use row groups of +1,048,576 rows, parquet-rs's default, which need fewer requests to object storage. Pass +`--opt row-group-rows=1048576` to `data-gen` to generate data for S3. Data that is already +generated is not written again, so delete it first to change its row groups. ## Memory allocators diff --git a/vortex-bench/src/bin/data-gen.rs b/vortex-bench/src/bin/data-gen.rs index faa66608b5d..e630193b25b 100644 --- a/vortex-bench/src/bin/data-gen.rs +++ b/vortex-bench/src/bin/data-gen.rs @@ -26,7 +26,6 @@ use vortex_bench::create_benchmark; use vortex_bench::generate_duckdb_registration_sql; use vortex_bench::parquet_copies::SizeFormat; use vortex_bench::parquet_copies::write_size_format; -use vortex_bench::parquet_copies::write_snappy_parquet_directory; use vortex_bench::setup_logging_and_tracing_with_format; #[derive(Parser)] @@ -98,12 +97,6 @@ async fn main() -> anyhow::Result<()> { convert_parquet_directory_to_vortex(&base_path, CompactionStrategy::Compact).await?; } - if args.formats.contains(&Format::ParquetSnappy) { - let base_path = base_path.clone(); - tokio::task::spawn_blocking(move || write_snappy_parquet_directory(&base_path)) - .await??; - } - if args .formats .iter() diff --git a/vortex-bench/src/lib.rs b/vortex-bench/src/lib.rs index ff085fe907f..e0da88ffb8e 100644 --- a/vortex-bench/src/lib.rs +++ b/vortex-bench/src/lib.rs @@ -218,11 +218,6 @@ pub enum Format { Csv, #[clap(name = "parquet")] Parquet, - /// Parquet as DuckDB writes it, with Snappy: the base Parquet files written again by the - /// `duckdb` CLI. Only suites that list it generate it. - #[clap(name = "parquet-snappy")] - #[serde(rename = "parquet-snappy")] - ParquetSnappy, #[clap(name = "vortex")] #[serde(rename = "vortex")] OnDiskVortex, @@ -278,7 +273,6 @@ impl Format { Format::ArrowIpc => "arrow-ipc", Format::Csv => "csv", Format::Parquet => "parquet", - Format::ParquetSnappy => "parquet-snappy", Format::OnDiskVortex => "vortex-file-compressed", Format::VortexCompact => "vortex-compact", Format::VortexSpatialNative => "vortex-spatial-native", @@ -293,7 +287,6 @@ impl Format { Format::ArrowIpc => "arrow", Format::Csv => "csv", Format::Parquet => "parquet", - Format::ParquetSnappy => "parquet", Format::OnDiskVortex => "vortex", Format::VortexCompact => "vortex", Format::VortexSpatialNative => "vortex", @@ -447,6 +440,18 @@ const DEFAULT_SCALE_FACTOR: &str = "1.0"; const SCALE_FACTOR_KEY: &str = "scale-factor"; const REMOTE_DATA_KEY: &str = "remote-data-dir"; +/// Rows in each row group of the Parquet that TPC-H, TPC-DS, and nested TPC-H generate. The +/// default is [`LOCAL_ROW_GROUP_ROWS`]; the benchmarks read from S3 use [`S3_ROW_GROUP_ROWS`]. +/// +/// [`LOCAL_ROW_GROUP_ROWS`]: utils::parquet::LOCAL_ROW_GROUP_ROWS +/// [`S3_ROW_GROUP_ROWS`]: utils::parquet::S3_ROW_GROUP_ROWS +const ROW_GROUP_ROWS_KEY: &str = "row-group-rows"; + +/// The `row-group-rows` option, or [`utils::parquet::LOCAL_ROW_GROUP_ROWS`]. +fn row_group_rows(opts: &Opts) -> usize { + opts.get_as::(ROW_GROUP_ROWS_KEY) + .unwrap_or(utils::parquet::LOCAL_ROW_GROUP_ROWS) +} /// Factory function to create a benchmark instance from CLI arguments. pub fn create_benchmark(b: BenchmarkArg, opts: &Opts) -> anyhow::Result> { @@ -471,13 +476,15 @@ pub fn create_benchmark(b: BenchmarkArg, opts: &Opts) -> anyhow::Result { let scale_factor = opts.get(SCALE_FACTOR_KEY).unwrap_or(DEFAULT_SCALE_FACTOR); let remote_data_dir = opts.get_as::(REMOTE_DATA_KEY); - let benchmark = TpcHBenchmark::new(scale_factor.to_string(), remote_data_dir)?; + let benchmark = TpcHBenchmark::new(scale_factor.to_string(), remote_data_dir)? + .with_row_group_rows(row_group_rows(opts)); Ok(Box::new(benchmark) as _) } BenchmarkArg::TpcDS => { let scale_factor = opts.get(SCALE_FACTOR_KEY).unwrap_or(DEFAULT_SCALE_FACTOR); let remote_data_dir = opts.get_as::(REMOTE_DATA_KEY); - let benchmark = TpcDsBenchmark::new(scale_factor.to_string(), remote_data_dir)?; + let benchmark = TpcDsBenchmark::new(scale_factor.to_string(), remote_data_dir)? + .with_row_group_rows(row_group_rows(opts)); Ok(Box::new(benchmark) as _) } BenchmarkArg::TpcHNested => { @@ -486,7 +493,8 @@ pub fn create_benchmark(b: BenchmarkArg, opts: &Opts) -> anyhow::Result("shape").unwrap_or_default(); let remote_data_dir = opts.get_as::(REMOTE_DATA_KEY); let benchmark = - TpcHNestedBenchmark::new(scale_factor.to_string(), shape, remote_data_dir)?; + TpcHNestedBenchmark::new(scale_factor.to_string(), shape, remote_data_dir)? + .with_row_group_rows(row_group_rows(opts)); Ok(Box::new(benchmark) as _) } BenchmarkArg::StatPopGen => { diff --git a/vortex-bench/src/parquet_copies.rs b/vortex-bench/src/parquet_copies.rs index 75760827c16..afb9144c432 100644 --- a/vortex-bench/src/parquet_copies.rs +++ b/vortex-bench/src/parquet_copies.rs @@ -4,15 +4,17 @@ //! Copies of a benchmark's base Parquet files in other formats, one output file for each input //! file, in a directory of the format's name beside the base `parquet` directory. //! -//! - [`Format::ParquetSnappy`]: the same rows as DuckDB writes them by default, with Snappy, +//! No query reads these copies. `data-gen --size-formats` writes them only so that +//! `scripts/capture-file-sizes.py` records their sizes. +//! +//! - [`SizeFormat::ParquetSnappy`]: the same rows as DuckDB writes them by default, with Snappy, //! DuckDB's row groups, and its dictionaries, statistics, and Bloom filters. This is Parquet as //! an analytics engine writes it for speed, where the base files are zstd level 3 for size. The -//! query engines read it like Parquet. `data-gen --formats parquet-snappy` writes it with the -//! `duckdb` CLI. -//! - [`SizeFormat::ArrowIpc`]: uncompressed Arrow IPC, which no query reads. `data-gen -//! --size-formats arrow-ipc` writes it only so that `scripts/capture-file-sizes.py` records its -//! size. Lance is also written for size only, by `lance-bench --data-only`, because only that -//! binary depends on Lance. +//! `duckdb` CLI writes it. +//! - [`SizeFormat::ArrowIpc`]: uncompressed Arrow IPC. +//! +//! Lance is also written for size only, by `lance-bench --data-only`, because only that binary +//! depends on Lance. use std::fs; use std::fs::File; @@ -35,6 +37,9 @@ use crate::idempotent; /// A format that is written only to record its file size. No query reads it. #[derive(Clone, Copy, Debug, PartialEq, Eq, ValueEnum)] pub enum SizeFormat { + /// Parquet as DuckDB writes it, with Snappy. See [`write_duckdb_snappy_parquet`]. + #[clap(name = "parquet-snappy")] + ParquetSnappy, /// Uncompressed Arrow IPC, as `compress-bench` writes it. #[clap(name = "arrow-ipc")] ArrowIpc, @@ -43,32 +48,33 @@ pub enum SizeFormat { /// Write `format` from the base Parquet files in `base_path`. pub fn write_size_format(base_path: &Path, format: SizeFormat) -> Result<()> { match format { - SizeFormat::ArrowIpc => { - copy_parquet_directory(base_path, Format::ArrowIpc, write_arrow_ipc) - } + SizeFormat::ParquetSnappy => copy_parquet_directory( + base_path, + "parquet-snappy", + Format::Parquet.ext(), + write_duckdb_snappy_parquet, + ), + SizeFormat::ArrowIpc => copy_parquet_directory( + base_path, + Format::ArrowIpc.name(), + Format::ArrowIpc.ext(), + write_arrow_ipc, + ), } } -/// Write every Parquet file in `{base_path}/parquet/` again with DuckDB, to -/// `{base_path}/parquet-snappy/`. See [`write_duckdb_snappy_parquet`]. -pub fn write_snappy_parquet_directory(base_path: &Path) -> Result<()> { - copy_parquet_directory( - base_path, - Format::ParquetSnappy, - write_duckdb_snappy_parquet, - ) -} - -/// Write each Parquet file in `{base_path}/parquet/` with `write`, to `{base_path}/{format}/`. +/// Write each Parquet file in `{base_path}/parquet/` with `write`, to `{base_path}/{name}/`, with +/// the extension `ext`. /// /// The write is idempotent: an output file that exists is not written again. fn copy_parquet_directory( base_path: &Path, - format: Format, + name: &str, + ext: &str, write: fn(&Path, &Path) -> Result<()>, ) -> Result<()> { let parquet_dir = base_path.join(Format::Parquet.name()); - let output_dir = base_path.join(format.name()); + let output_dir = base_path.join(name); let mut inputs = fs::read_dir(&parquet_dir) .with_context(|| format!("reading {}", parquet_dir.display()))? .map(|entry| entry.map(|entry| entry.path())) @@ -79,7 +85,7 @@ fn copy_parquet_directory( info!( "Writing {} files as {} in {}", inputs.len(), - format.name(), + name, output_dir.display() ); for input in inputs { @@ -88,9 +94,9 @@ fn copy_parquet_directory( .context("a Parquet file has no name")? .to_os_string(); let mut output = output_dir.join(stem); - output.set_extension(format.ext()); + output.set_extension(ext); idempotent(output.as_path(), |temp| write(&input, temp)) - .with_context(|| format!("writing {} as {}", input.display(), format.name()))?; + .with_context(|| format!("writing {} as {}", input.display(), name))?; } Ok(()) } @@ -189,7 +195,7 @@ mod tests { let base = tempfile::tempdir()?; let expected = write_base(base.path(), 1000, 300)?; - write_snappy_parquet_directory(base.path())?; + write_size_format(base.path(), SizeFormat::ParquetSnappy)?; let output = base.path().join("parquet-snappy").join("t.parquet"); let metadata = SerializedFileReader::new(File::open(&output)?)? diff --git a/vortex-bench/src/tpcds/tpcds_benchmark.rs b/vortex-bench/src/tpcds/tpcds_benchmark.rs index dd1e6c2997f..93b820f9338 100644 --- a/vortex-bench/src/tpcds/tpcds_benchmark.rs +++ b/vortex-bench/src/tpcds/tpcds_benchmark.rs @@ -16,12 +16,14 @@ use crate::IdempotentPath; use crate::TableSpec; use crate::tpcds::tpcds_queries; use crate::tpcds::tpcdsgen::generate_tpcds; +use crate::utils::parquet::LOCAL_ROW_GROUP_ROWS; use crate::utils::split; /// TPC-DS benchmark implementation pub struct TpcDsBenchmark { pub scale_factor: String, pub data_url: Url, + row_group_rows: usize, } impl TpcDsBenchmark { @@ -29,9 +31,16 @@ impl TpcDsBenchmark { Ok(Self { scale_factor: scale_factor.clone(), data_url: Self::create_data_url(use_remote_data_dir.as_deref(), &scale_factor)?, + row_group_rows: LOCAL_ROW_GROUP_ROWS, }) } + /// Generate Parquet in row groups of `row_group_rows` rows. + pub fn with_row_group_rows(mut self, row_group_rows: usize) -> Self { + self.row_group_rows = row_group_rows; + self + } + fn create_data_url(remote_data_dir: Option<&str>, scale_factor: &str) -> Result { match remote_data_dir { None => { @@ -77,7 +86,12 @@ impl Benchmark for TpcDsBenchmark { Format::Parquet ); - generate_tpcds(base_data_dir, self.scale_factor.clone()).await?; + generate_tpcds( + base_data_dir, + self.scale_factor.clone(), + self.row_group_rows, + ) + .await?; Ok(()) } diff --git a/vortex-bench/src/tpcds/tpcdsgen.rs b/vortex-bench/src/tpcds/tpcdsgen.rs index 83ebb0191e0..6c98f152303 100644 --- a/vortex-bench/src/tpcds/tpcdsgen.rs +++ b/vortex-bench/src/tpcds/tpcdsgen.rs @@ -64,9 +64,6 @@ use crate::utils::split; const BATCH_SIZE: usize = 8192 * 16; -/// Matches the row group size of DuckDB's Parquet writer, which previously generated this data. -const ROW_GROUP_SIZE: usize = 122_880; - /// Source rows generated by one task. The sales tables emit one row per line item, about a dozen /// per source row, so a chunk holds up to roughly one row group. const SOURCE_ROWS_PER_CHUNK: u64 = 8 * 1024; @@ -76,9 +73,14 @@ const SOURCE_ROWS_PER_CHUNK: u64 = 8 * 1024; /// Large tables are split into files of about [`split::TARGET_FILE_COMPRESSED_BYTES`], named by /// [`split::part_file_name`]; every other table is a single `{table}_0001.parquet`. The files hold /// the same data and schema as `tpcgen-cli tpcds parquet` of the same `tpcdsgen` version, which -/// generates the SQL logic test data. Tables are written one at a time, each split into chunks of -/// source rows that are generated and encoded in parallel. Already generated tables are skipped. -pub async fn generate_tpcds(base_dir: PathBuf, scale_factor: String) -> Result { +/// generates the SQL logic test data, in row groups of `row_group_rows` rows. Tables are written +/// one at a time, each split into chunks of source rows that are generated and encoded in +/// parallel. Already generated tables are skipped. +pub async fn generate_tpcds( + base_dir: PathBuf, + scale_factor: String, + row_group_rows: usize, +) -> Result { let output_dir = base_dir.join(Format::Parquet.name()); fs::create_dir_all(&output_dir)?; @@ -113,7 +115,7 @@ pub async fn generate_tpcds(base_dir: PathBuf, scale_factor: String) -> Result

Self { + self.row_group_rows = row_group_rows; + self + } + fn create_data_url(remote_data_dir: Option<&str>, scale_factor: &str) -> anyhow::Result { match remote_data_dir { None => { @@ -94,7 +103,8 @@ impl Benchmark for TpcHBenchmark { .to_file_path() .map_err(|_| anyhow::anyhow!("Invalid file URL: {}", self.data_url.as_str()))?; - let options = TpchGenOptions::new(self.scale_factor.clone(), base_data_dir); + let options = TpchGenOptions::new(self.scale_factor.clone(), base_data_dir) + .with_row_group_rows(self.row_group_rows); tpchgen::generate_tpch_tables(options).await?; diff --git a/vortex-bench/src/tpch/tpchgen.rs b/vortex-bench/src/tpch/tpchgen.rs index 6ba124109f1..03e75865608 100644 --- a/vortex-bench/src/tpch/tpchgen.rs +++ b/vortex-bench/src/tpch/tpchgen.rs @@ -47,13 +47,10 @@ use crate::IdempotentPath; use crate::SESSION; use crate::tpch::nest::NestedBatchReader; use crate::utils::file::idempotent_async; +use crate::utils::parquet::LOCAL_ROW_GROUP_ROWS; use crate::utils::parquet::parquet_writer_properties; use crate::utils::split; -/// The parquet-rs default, kept explicit so the shared writer settings do not change the -/// parallelism of existing TPC-H Parquet benchmarks. -const ROW_GROUP_SIZE: usize = 1024 * 1024; - // Compressed size of each TPC-H table at scale factor 1, used to split tables into files of about // `split::TARGET_FILE_COMPRESSED_BYTES`: the mean of the Parquet and default Vortex sizes, measured at // scale factor 10. Every table but nation and region scales linearly with the scale factor. At @@ -89,6 +86,8 @@ pub struct TpchGenOptions { pub batch_size: usize, /// Shape of the generated tables pub shape: TableShape, + /// Rows in each Parquet row group + pub row_group_rows: usize, } impl Default for TpchGenOptions { @@ -99,6 +98,7 @@ impl Default for TpchGenOptions { format: Format::Parquet, batch_size: 8192 * 64, shape: TableShape::Flat, + row_group_rows: LOCAL_ROW_GROUP_ROWS, } } } @@ -126,6 +126,11 @@ impl TpchGenOptions { self.shape = shape; self } + + pub fn with_row_group_rows(mut self, row_group_rows: usize) -> Self { + self.row_group_rows = row_group_rows; + self + } } /// Generate all TPC-H tables for a single scale factor @@ -318,11 +323,11 @@ fn generate_table_file( } /// Number of parts generated in parallel for a table written as one Parquet file. -fn table_num_parts(generator: TableGenerator, scale_factor: f64) -> usize { +fn table_num_parts(generator: TableGenerator, scale_factor: f64, row_group_rows: usize) -> usize { let rows = usize::try_from(generator.estimated_rows(scale_factor)).unwrap_or(1); get_available_parallelism() .unwrap_or(1) - .min(rows.div_ceil(ROW_GROUP_SIZE)) + .min(rows.div_ceil(row_group_rows)) .max(1) } @@ -347,7 +352,7 @@ async fn write_parquet( } let scale_factor = options.scale_factor.parse::()?; - let gen_parts = table_num_parts(generator, scale_factor); + let gen_parts = table_num_parts(generator, scale_factor, options.row_group_rows); write_parquet_parts(generator, options, gen_parts, output).await } @@ -386,7 +391,7 @@ fn write_parquet_file( let iter = create_batch_iterator(generator, options, part, num_parts)?; let schema = iter.schema(); let props = parquet_writer_properties() - .set_max_row_group_row_count(Some(ROW_GROUP_SIZE)) + .set_max_row_group_row_count(Some(options.row_group_rows)) .build(); let mut writer = ArrowWriter::try_new(fs::File::create(output)?, schema, Some(props))?; for batch in iter { diff --git a/vortex-bench/src/tpch_nested/mod.rs b/vortex-bench/src/tpch_nested/mod.rs index 4a92e733443..bf7f8b09bde 100644 --- a/vortex-bench/src/tpch_nested/mod.rs +++ b/vortex-bench/src/tpch_nested/mod.rs @@ -48,6 +48,7 @@ use crate::tpch::schema::SUPPLIER; use crate::tpch::tpchgen; use crate::tpch::tpchgen::TableShape; use crate::tpch::tpchgen::TpchGenOptions; +use crate::utils::parquet::LOCAL_ROW_GROUP_ROWS; use crate::utils::split; /// How each table's non-key columns are nested. @@ -122,6 +123,7 @@ pub struct TpcHNestedBenchmark { pub scale_factor: String, pub shape: Shape, data_url: Url, + row_group_rows: usize, } impl TpcHNestedBenchmark { @@ -153,8 +155,15 @@ impl TpcHNestedBenchmark { scale_factor, shape, data_url, + row_group_rows: LOCAL_ROW_GROUP_ROWS, }) } + + /// Generate Parquet in row groups of `row_group_rows` rows. + pub fn with_row_group_rows(mut self, row_group_rows: usize) -> Self { + self.row_group_rows = row_group_rows; + self + } } #[async_trait::async_trait] @@ -178,7 +187,8 @@ impl Benchmark for TpcHNestedBenchmark { .map_err(|_| anyhow::anyhow!("Invalid file URL: {}", self.data_url.as_str()))?; let options = TpchGenOptions::new(self.scale_factor.clone(), base_data_dir) - .with_shape(self.shape.table_shape()); + .with_shape(self.shape.table_shape()) + .with_row_group_rows(self.row_group_rows); tpchgen::generate_tpch_tables(options).await?; diff --git a/vortex-bench/src/utils/parquet.rs b/vortex-bench/src/utils/parquet.rs index 37a206008d0..fdbc20848f8 100644 --- a/vortex-bench/src/utils/parquet.rs +++ b/vortex-bench/src/utils/parquet.rs @@ -13,6 +13,14 @@ use parquet::file::metadata::ParquetMetaDataReader; use parquet::file::properties::WriterProperties; use parquet::file::properties::WriterPropertiesBuilder; +/// Rows in each row group of generated benchmark Parquet that queries read from local disk: +/// DuckDB's default. Small row groups give the query engines more units of work to run in parallel. +pub const LOCAL_ROW_GROUP_ROWS: usize = 122_880; + +/// Rows in each row group of generated benchmark Parquet that queries read from S3: parquet-rs's +/// default. Large row groups need fewer requests to object storage. +pub const S3_ROW_GROUP_ROWS: usize = 1024 * 1024; + /// Columns whose dictionary outgrows this fall back to plain encoding. The parquet-rs default /// (1 MiB) keeps dictionaries for unique keys, which compress far worse than plain values. A small /// limit approximates the per-column choice that DuckDB's writer makes. From 78551cffe3a56e7bd739e29abba55fd24d054b61 Mon Sep 17 00:00:00 2001 From: Will Manning Date: Sat, 21 Nov 2026 11:49:24 -0500 Subject: [PATCH 24/44] Record Snappy Parquet sizes only in compress-bench TPC-DS SF1 no longer writes Snappy Parquet for its size, so data-gen loses the `parquet-snappy` size format and the file-size capture stops looking for its directory. compress-bench still records the size of Parquet as DuckDB writes it with Snappy. TPC-DS SF1 still writes Arrow IPC for its size and queries Lance on DataFusion. Signed-off-by: Will Manning --- AGENTS.md | 3 +-- .../bench_orchestrator/ci_matrix/catalog.py | 8 +++---- .../bench_orchestrator/config.py | 6 ++--- bench-orchestrator/tests/test_matrix.py | 6 ++--- benchmarks/compress-bench/src/main.rs | 2 +- scripts/capture-file-sizes.py | 8 +++---- scripts/tests/test_benchmark_reporting.py | 2 -- vortex-bench/README.md | 3 +-- vortex-bench/src/parquet_copies.rs | 23 +++++-------------- 9 files changed, 20 insertions(+), 41 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index ece89a00f96..d62df9c310c 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -231,8 +231,7 @@ These CI checks are the ones most often missed when adding files rather than edi - DuckDB: `(FORMAT parquet, COMPRESSION zstd, COMPRESSION_LEVEL 3)` - tpchgen-cli: `parquet --compression='ZSTD(3)'` - Benchmarks that deliberately compare Parquet codecs, such as the GPU compress benchmark's - `--codec` and the `parquet-snappy` copy that `data-gen --size-formats` writes only for its - size, are exempt. + `--codec` and the Snappy Parquet whose size `compress-bench` records, are exempt. - Generated Parquet that queries read from local disk has row groups of 122,880 rows (`LOCAL_ROW_GROUP_ROWS`, DuckDB's default). Generated Parquet that queries read from S3 has row groups of 1,048,576 rows (`S3_ROW_GROUP_ROWS`, parquet-rs's default): the CI matrix passes diff --git a/bench-orchestrator/bench_orchestrator/ci_matrix/catalog.py b/bench-orchestrator/bench_orchestrator/ci_matrix/catalog.py index a4fb4f38273..9569730d912 100644 --- a/bench-orchestrator/bench_orchestrator/ci_matrix/catalog.py +++ b/bench-orchestrator/bench_orchestrator/ci_matrix/catalog.py @@ -91,12 +91,12 @@ def with_all_scans(coverage: Coverage) -> Coverage: data_formats=(Format.PARQUET, Format.VORTEX, Format.VORTEX_COMPACT, Format.DUCKDB), ) STANDARD_WITH_DUCKDB = Coverage(STANDARD_WITH_DUCKDB_TARGETS) -# TPC-DS SF1 is the SQL data that bench.vortex.dev's File Sizes summary ranks, so develop has every -# format `compress-bench` measures. It queries Lance on DataFusion, and writes Snappy Parquet and -# Arrow IPC only for their sizes. They are small and fast at SF1. +# TPC-DS SF1 is the SQL data that bench.vortex.dev's File Sizes summary ranks, so develop also +# records the sizes of Lance and Arrow IPC there. It queries Lance on DataFusion, and writes Arrow +# IPC only for its size. Both are small and fast at SF1. STANDARD_WITH_DUCKDB_AND_SIZE_FORMATS = Coverage( STANDARD_WITH_DUCKDB_TARGETS | df(Format.LANCE), - size_formats=(SizeFormat.PARQUET_SNAPPY, SizeFormat.ARROW_IPC), + size_formats=(SizeFormat.ARROW_IPC,), ) DATAFUSION_VORTEX = Coverage(DATAFUSION_VORTEX_TARGETS) COMPACT = Coverage(COMPACT_TARGETS) diff --git a/bench-orchestrator/bench_orchestrator/config.py b/bench-orchestrator/bench_orchestrator/config.py index 478956fd38f..a1bc98871c9 100644 --- a/bench-orchestrator/bench_orchestrator/config.py +++ b/bench-orchestrator/bench_orchestrator/config.py @@ -71,12 +71,10 @@ class ScanEngine(Enum): class SizeFormat(Enum): """A format a benchmark writes only to record its file sizes. No query reads it. - `vx-bench write-size-formats` writes Snappy Parquet and Arrow IPC with `data-gen --size-formats`, - and Lance with `lance-bench --data-only`. + `vx-bench write-size-formats` writes Arrow IPC with `data-gen --size-formats`, and Lance with + `lance-bench --data-only`. """ - # The base Parquet files as DuckDB writes them, with Snappy. - PARQUET_SNAPPY = "parquet-snappy" ARROW_IPC = "arrow-ipc" LANCE = "lance" diff --git a/bench-orchestrator/tests/test_matrix.py b/bench-orchestrator/tests/test_matrix.py index 3d95f131135..7ca0987def4 100644 --- a/bench-orchestrator/tests/test_matrix.py +++ b/bench-orchestrator/tests/test_matrix.py @@ -342,19 +342,17 @@ def test_only_develop_tpcds_sf1_writes_size_only_formats(preset: str) -> None: writers = {entry["id"]: entry["size_formats"] for entry in _entries(preset) if entry["size_formats"]} if preset == "develop": - assert writers == {"tpcds-nvme": ["parquet-snappy", "arrow-ipc"]} + assert writers == {"tpcds-nvme": ["arrow-ipc"]} else: assert writers == {} -def test_develop_tpcds_sf1_queries_lance_but_not_snappy_parquet() -> None: +def test_develop_tpcds_sf1_queries_lance() -> None: entry = {entry["id"]: entry for entry in _entries("develop")}["tpcds-nvme"] targets = {(target["engine"], target["format"]) for target in entry["targets"]} assert ("datafusion", "lance") in targets - assert not any(fmt == "parquet-snappy" for _, fmt in targets) assert "lance" not in entry["data_formats"] - assert "parquet-snappy" not in entry["data_formats"] def test_resolver_rejects_a_size_only_format_that_a_target_reads() -> None: diff --git a/benchmarks/compress-bench/src/main.rs b/benchmarks/compress-bench/src/main.rs index 11d7d2eb11f..85f055f0b8d 100644 --- a/benchmarks/compress-bench/src/main.rs +++ b/benchmarks/compress-bench/src/main.rs @@ -62,7 +62,7 @@ use vortex_bench::statpopgen::StatPopGenBenchmark; use vortex_bench::v3; /// The size record name of Parquet as DuckDB writes it, with Snappy, beside `parquet`, which is -/// zstd level 3. It is the same writer that `data-gen --size-formats parquet-snappy` uses. +/// zstd level 3. const PARQUET_SNAPPY_FORMAT: &str = "parquet-snappy"; #[derive(Parser, Debug)] diff --git a/scripts/capture-file-sizes.py b/scripts/capture-file-sizes.py index 88b1ea508ae..ec2d56e2c11 100644 --- a/scripts/capture-file-sizes.py +++ b/scripts/capture-file-sizes.py @@ -50,12 +50,10 @@ def main() -> None: "duckdb", "lance", "litdata", + # A format is named by its directory, not by its codec: `parquet` is the suite's base + # Parquet, which is zstd level 3 where the benchmarks write it, and the dataset's own files + # where the suite prescribes them, as ClickBench's are Snappy. "parquet", - # Parquet as DuckDB writes it, with Snappy. A format is named by its directory, not by - # its codec: `parquet` is the suite's base Parquet, which is zstd level 3 where the - # benchmarks write it, and the dataset's own files where the suite prescribes them, as - # ClickBench's are Snappy. - "parquet-snappy", "vortex-compact", "vortex-file-compressed", "vortex-spatial-native", diff --git a/scripts/tests/test_benchmark_reporting.py b/scripts/tests/test_benchmark_reporting.py index 803fc5f3206..74a3d8787c6 100644 --- a/scripts/tests/test_benchmark_reporting.py +++ b/scripts/tests/test_benchmark_reporting.py @@ -941,7 +941,6 @@ def test_capture_file_sizes_names_parquet_by_its_directory(tmp_path: Path) -> No files = { # ClickBench's own files are Snappy, and they are its `parquet`. ("clickbench_partitioned", "parquet", "hits_0.parquet"): 40, - ("clickbench_partitioned", "parquet-snappy", "hits_0.parquet"): 50, ("clickbench_partitioned", "arrow-ipc", "hits_0.arrow"): 80, } for parts, size in files.items(): @@ -971,7 +970,6 @@ def test_capture_file_sizes_names_parquet_by_its_directory(tmp_path: Path) -> No assert sorted((r["file_size"]["format"], r["value"]) for r in records) == [ ("arrow-ipc", 80), ("parquet", 40), - ("parquet-snappy", 50), ] diff --git a/vortex-bench/README.md b/vortex-bench/README.md index e904b7f0750..8daa0939e9e 100644 --- a/vortex-bench/README.md +++ b/vortex-bench/README.md @@ -52,8 +52,7 @@ the common writers are different: - `tpchgen-cli`: writes Snappy by default. Use `parquet --compression='ZSTD(3)'`. Benchmarks that compare Parquet codecs on purpose, such as the compress-bench `--gpu-parquet-codec` -option and the `parquet-snappy` copy that `data-gen --size-formats` writes only for its size, are -exempt. +option and the Snappy Parquet whose size compress-bench records, are exempt. ## Parquet row groups diff --git a/vortex-bench/src/parquet_copies.rs b/vortex-bench/src/parquet_copies.rs index afb9144c432..6eca1158469 100644 --- a/vortex-bench/src/parquet_copies.rs +++ b/vortex-bench/src/parquet_copies.rs @@ -7,14 +7,11 @@ //! No query reads these copies. `data-gen --size-formats` writes them only so that //! `scripts/capture-file-sizes.py` records their sizes. //! -//! - [`SizeFormat::ParquetSnappy`]: the same rows as DuckDB writes them by default, with Snappy, -//! DuckDB's row groups, and its dictionaries, statistics, and Bloom filters. This is Parquet as -//! an analytics engine writes it for speed, where the base files are zstd level 3 for size. The -//! `duckdb` CLI writes it. //! - [`SizeFormat::ArrowIpc`]: uncompressed Arrow IPC. //! //! Lance is also written for size only, by `lance-bench --data-only`, because only that binary -//! depends on Lance. +//! depends on Lance. [`write_duckdb_snappy_parquet`] writes the Snappy Parquet whose size +//! `compress-bench` records. use std::fs; use std::fs::File; @@ -37,9 +34,6 @@ use crate::idempotent; /// A format that is written only to record its file size. No query reads it. #[derive(Clone, Copy, Debug, PartialEq, Eq, ValueEnum)] pub enum SizeFormat { - /// Parquet as DuckDB writes it, with Snappy. See [`write_duckdb_snappy_parquet`]. - #[clap(name = "parquet-snappy")] - ParquetSnappy, /// Uncompressed Arrow IPC, as `compress-bench` writes it. #[clap(name = "arrow-ipc")] ArrowIpc, @@ -48,12 +42,6 @@ pub enum SizeFormat { /// Write `format` from the base Parquet files in `base_path`. pub fn write_size_format(base_path: &Path, format: SizeFormat) -> Result<()> { match format { - SizeFormat::ParquetSnappy => copy_parquet_directory( - base_path, - "parquet-snappy", - Format::Parquet.ext(), - write_duckdb_snappy_parquet, - ), SizeFormat::ArrowIpc => copy_parquet_directory( base_path, Format::ArrowIpc.name(), @@ -115,7 +103,8 @@ fn write_arrow_ipc(input: &Path, output: &Path) -> Result<()> { /// Write the Parquet file `input` again as DuckDB writes Parquet: `COPY ... (FORMAT parquet, /// COMPRESSION snappy)` in the `duckdb` CLI, which must be on `PATH`. Every setting other than the -/// codec is DuckDB's default, so the file is what a DuckDB user gets. The codec is named because +/// codec is DuckDB's default, so the file is what a DuckDB user gets: DuckDB's row groups, and its +/// dictionaries, statistics, and Bloom filters. The codec is named because /// it is the one the `parquet-snappy` name promises, and DuckDB's default could change. pub fn write_duckdb_snappy_parquet(input: &Path, output: &Path) -> Result<()> { let sql = format!( @@ -195,9 +184,9 @@ mod tests { let base = tempfile::tempdir()?; let expected = write_base(base.path(), 1000, 300)?; - write_size_format(base.path(), SizeFormat::ParquetSnappy)?; + let output = base.path().join("t.snappy.parquet"); + write_duckdb_snappy_parquet(&base.path().join("parquet").join("t.parquet"), &output)?; - let output = base.path().join("parquet-snappy").join("t.parquet"); let metadata = SerializedFileReader::new(File::open(&output)?)? .metadata() .clone(); From 50a3ed4cea655e9daff4dd59c87775d7303c447c Mon Sep 17 00:00:00 2001 From: Will Manning Date: Sat, 21 Nov 2026 11:57:10 -0500 Subject: [PATCH 25/44] Generate Parquet again when its row groups change The TPC-H and TPC-DS generators skip files that exist, so Parquet generated before with other row groups stayed. A marker file beside the `parquet` directory, `parquet.row-group-rows`, now records the row groups of its files. If the marker is missing or records another size, the generator removes the directory and writes it again. Signed-off-by: Will Manning --- vortex-bench/README.md | 5 +-- vortex-bench/src/tpcds/tpcdsgen.rs | 3 +- vortex-bench/src/tpch/tpchgen.rs | 7 ++++ vortex-bench/src/utils/parquet.rs | 51 ++++++++++++++++++++++++++++++ 4 files changed, 63 insertions(+), 3 deletions(-) diff --git a/vortex-bench/README.md b/vortex-bench/README.md index 8daa0939e9e..1ae47d9b724 100644 --- a/vortex-bench/README.md +++ b/vortex-bench/README.md @@ -60,8 +60,9 @@ TPC-H, TPC-DS, and nested TPC-H write Parquet in row groups of 122,880 rows, Duc In our tests, these smaller row groups were faster from local disk, because they give the query engines more units of work to run in parallel. The benchmarks that read from S3 use row groups of 1,048,576 rows, parquet-rs's default, which need fewer requests to object storage. Pass -`--opt row-group-rows=1048576` to `data-gen` to generate data for S3. Data that is already -generated is not written again, so delete it first to change its row groups. +`--opt row-group-rows=1048576` to `data-gen` to generate data for S3. The file +`parquet.row-group-rows`, beside the `parquet` directory, records the row groups of its files. +`data-gen` removes and generates again Parquet whose row groups are different or not recorded. ## Memory allocators diff --git a/vortex-bench/src/tpcds/tpcdsgen.rs b/vortex-bench/src/tpcds/tpcdsgen.rs index 6c98f152303..495d3b279ce 100644 --- a/vortex-bench/src/tpcds/tpcdsgen.rs +++ b/vortex-bench/src/tpcds/tpcdsgen.rs @@ -60,6 +60,7 @@ use vortex::utils::parallelism::get_available_parallelism; use crate::Format; use crate::utils::file::temp_download_filepath; use crate::utils::parquet::parquet_writer_properties; +use crate::utils::parquet::prepare_parquet_dir; use crate::utils::split; const BATCH_SIZE: usize = 8192 * 16; @@ -82,7 +83,7 @@ pub async fn generate_tpcds( row_group_rows: usize, ) -> Result { let output_dir = base_dir.join(Format::Parquet.name()); - fs::create_dir_all(&output_dir)?; + prepare_parquet_dir(&output_dir, row_group_rows)?; let scale_factor: f64 = scale_factor.parse()?; // Follow the C `dsdgen` reference rather than the Trino Java port, like `tpcgen-cli` does. diff --git a/vortex-bench/src/tpch/tpchgen.rs b/vortex-bench/src/tpch/tpchgen.rs index 03e75865608..52fa1405e44 100644 --- a/vortex-bench/src/tpch/tpchgen.rs +++ b/vortex-bench/src/tpch/tpchgen.rs @@ -49,6 +49,7 @@ use crate::tpch::nest::NestedBatchReader; use crate::utils::file::idempotent_async; use crate::utils::parquet::LOCAL_ROW_GROUP_ROWS; use crate::utils::parquet::parquet_writer_properties; +use crate::utils::parquet::prepare_parquet_dir; use crate::utils::split; // Compressed size of each TPC-H table at scale factor 1, used to split tables into files of about @@ -136,6 +137,12 @@ impl TpchGenOptions { /// Generate all TPC-H tables for a single scale factor pub async fn generate_tpch_tables(options: TpchGenOptions) -> Result<()> { fs::create_dir_all(&options.output_dir)?; + if matches!(options.format, Format::Parquet | Format::OnDiskDuckDB) { + prepare_parquet_dir( + &options.output_dir.join(Format::Parquet.name()), + options.row_group_rows, + )?; + } let scale_factor = options.scale_factor.parse::()?; let mut all_futures = Vec::new(); diff --git a/vortex-bench/src/utils/parquet.rs b/vortex-bench/src/utils/parquet.rs index fdbc20848f8..05527d06201 100644 --- a/vortex-bench/src/utils/parquet.rs +++ b/vortex-bench/src/utils/parquet.rs @@ -3,6 +3,7 @@ //! Shared Parquet writer settings for generated benchmark data. +use std::fs; use std::fs::File; use std::path::Path; @@ -12,6 +13,7 @@ use parquet::file::metadata::ParquetMetaData; use parquet::file::metadata::ParquetMetaDataReader; use parquet::file::properties::WriterProperties; use parquet::file::properties::WriterPropertiesBuilder; +use tracing::info; /// Rows in each row group of generated benchmark Parquet that queries read from local disk: /// DuckDB's default. Small row groups give the query engines more units of work to run in parallel. @@ -42,6 +44,29 @@ pub fn parquet_writer_properties() -> WriterPropertiesBuilder { } /// Return whether every column chunk in `metadata` is zstd. +/// Make `parquet_dir` ready for generated Parquet in row groups of `row_group_rows` rows. +/// +/// The generators do not write a file that exists, so Parquet generated before with other row +/// groups would stay. A marker file beside the directory, `parquet.row-group-rows`, records the +/// row groups its files have. If the directory exists and the marker is missing or records another +/// size, this removes the directory, so that the generator writes it again. +pub fn prepare_parquet_dir(parquet_dir: &Path, row_group_rows: usize) -> anyhow::Result<()> { + let marker = parquet_dir.with_extension("row-group-rows"); + let recorded = fs::read_to_string(&marker) + .ok() + .and_then(|text| text.trim().parse::().ok()); + if parquet_dir.exists() && recorded != Some(row_group_rows) { + info!( + "Removing {}: its row groups are not {row_group_rows} rows", + parquet_dir.display() + ); + fs::remove_dir_all(parquet_dir)?; + } + fs::create_dir_all(parquet_dir)?; + fs::write(&marker, row_group_rows.to_string())?; + Ok(()) +} + pub fn is_zstd(metadata: &ParquetMetaData) -> bool { metadata .row_groups() @@ -78,6 +103,32 @@ mod tests { Ok(()) } + #[test] + fn parquet_with_other_row_groups_is_generated_again() -> anyhow::Result<()> { + let base = tempfile::tempdir()?; + let parquet_dir = base.path().join("parquet"); + let file = parquet_dir.join("t.parquet"); + + // Parquet without a marker, as generated before the marker existed. + fs::create_dir_all(&parquet_dir)?; + fs::write(&file, b"old")?; + prepare_parquet_dir(&parquet_dir, LOCAL_ROW_GROUP_ROWS)?; + assert!(!file.exists()); + + fs::write(&file, b"local")?; + prepare_parquet_dir(&parquet_dir, LOCAL_ROW_GROUP_ROWS)?; + assert!(file.exists()); + + prepare_parquet_dir(&parquet_dir, S3_ROW_GROUP_ROWS)?; + assert!(parquet_dir.exists()); + assert!(!file.exists()); + assert_eq!( + fs::read_to_string(base.path().join("parquet.row-group-rows"))?, + S3_ROW_GROUP_ROWS.to_string() + ); + Ok(()) + } + #[test] fn zstd_file_check_reads_the_codec() -> anyhow::Result<()> { let dir = tempfile::tempdir()?; From cfc00b36bb577f54285f101f3d908ea8e58a248c Mon Sep 17 00:00:00 2001 From: Will Manning Date: Sat, 21 Nov 2026 12:06:16 -0500 Subject: [PATCH 26/44] Remove converted formats with Parquet whose row groups changed The Vortex conversions skip files that exist, so Vortex converted from the old Parquet stayed when the Parquet was generated again. When the row-group marker is missing or records another size, the generators now remove every format directory beside `parquet`, not only `parquet`. Signed-off-by: Will Manning --- vortex-bench/README.md | 3 ++- vortex-bench/src/utils/parquet.rs | 26 +++++++++++++++++++++----- 2 files changed, 23 insertions(+), 6 deletions(-) diff --git a/vortex-bench/README.md b/vortex-bench/README.md index 1ae47d9b724..fa0f2c3f47c 100644 --- a/vortex-bench/README.md +++ b/vortex-bench/README.md @@ -62,7 +62,8 @@ engines more units of work to run in parallel. The benchmarks that read from S3 1,048,576 rows, parquet-rs's default, which need fewer requests to object storage. Pass `--opt row-group-rows=1048576` to `data-gen` to generate data for S3. The file `parquet.row-group-rows`, beside the `parquet` directory, records the row groups of its files. -`data-gen` removes and generates again Parquet whose row groups are different or not recorded. +`data-gen` removes and generates again Parquet whose row groups are different or not recorded, +and the formats converted from it. ## Memory allocators diff --git a/vortex-bench/src/utils/parquet.rs b/vortex-bench/src/utils/parquet.rs index 05527d06201..c00e5ce5b55 100644 --- a/vortex-bench/src/utils/parquet.rs +++ b/vortex-bench/src/utils/parquet.rs @@ -49,18 +49,28 @@ pub fn parquet_writer_properties() -> WriterPropertiesBuilder { /// The generators do not write a file that exists, so Parquet generated before with other row /// groups would stay. A marker file beside the directory, `parquet.row-group-rows`, records the /// row groups its files have. If the directory exists and the marker is missing or records another -/// size, this removes the directory, so that the generator writes it again. +/// size, this removes it, so that the generator writes it again. It also removes the other format +/// directories beside it, such as `vortex-file-compressed`, because they were converted from the +/// old Parquet and their conversions skip files that exist. pub fn prepare_parquet_dir(parquet_dir: &Path, row_group_rows: usize) -> anyhow::Result<()> { let marker = parquet_dir.with_extension("row-group-rows"); let recorded = fs::read_to_string(&marker) .ok() .and_then(|text| text.trim().parse::().ok()); if parquet_dir.exists() && recorded != Some(row_group_rows) { + let data_dir = parquet_dir + .parent() + .ok_or_else(|| anyhow::anyhow!("{} has no parent", parquet_dir.display()))?; info!( - "Removing {}: its row groups are not {row_group_rows} rows", - parquet_dir.display() + "Removing the data in {}: its Parquet row groups are not {row_group_rows} rows", + data_dir.display() ); - fs::remove_dir_all(parquet_dir)?; + for entry in fs::read_dir(data_dir)? { + let path = entry?.path(); + if path.is_dir() { + fs::remove_dir_all(path)?; + } + } } fs::create_dir_all(parquet_dir)?; fs::write(&marker, row_group_rows.to_string())?; @@ -108,12 +118,18 @@ mod tests { let base = tempfile::tempdir()?; let parquet_dir = base.path().join("parquet"); let file = parquet_dir.join("t.parquet"); + let vortex_dir = base.path().join("vortex-file-compressed"); + let converted = vortex_dir.join("t.vortex"); - // Parquet without a marker, as generated before the marker existed. + // Parquet without a marker, as generated before the marker existed, and a file converted + // from it. fs::create_dir_all(&parquet_dir)?; fs::write(&file, b"old")?; + fs::create_dir_all(&vortex_dir)?; + fs::write(&converted, b"old")?; prepare_parquet_dir(&parquet_dir, LOCAL_ROW_GROUP_ROWS)?; assert!(!file.exists()); + assert!(!converted.exists()); fs::write(&file, b"local")?; prepare_parquet_dir(&parquet_dir, LOCAL_ROW_GROUP_ROWS)?; From d7a62f4393aa9f898ed65da6517d941c35bd459a Mon Sep 17 00:00:00 2001 From: Will Manning Date: Sat, 21 Nov 2026 12:15:12 -0500 Subject: [PATCH 27/44] Say where the l_comment dataset's row-group size comes from The comment said it matched the TPC-H generator, which now writes 122,880-row groups for local data. The size stays at 1,048,576 rows, the default of compress-bench's own Parquet writer. Signed-off-by: Will Manning --- vortex-bench/src/datasets/tpch_l_comment.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/vortex-bench/src/datasets/tpch_l_comment.rs b/vortex-bench/src/datasets/tpch_l_comment.rs index 4b7b3301f58..8b1c41596fc 100644 --- a/vortex-bench/src/datasets/tpch_l_comment.rs +++ b/vortex-bench/src/datasets/tpch_l_comment.rs @@ -37,7 +37,9 @@ async fn ensure_lineitem(format: Format) -> Result { TpchSf1Table::LineItem.path(format).await } -/// Rows per row group in the `l_comment` Parquet file, the same as the TPC-H generator writes. +/// Rows per row group in the `l_comment` Parquet file: parquet-rs's default, which compress-bench's +/// own Parquet writer also uses. The TPC-H generator's row groups depend on the storage that the +/// queries read from, so this file does not copy the row groups of `lineitem`. const L_COMMENT_ROW_GROUP_ROWS: usize = 1024 * 1024; /// Path of a Parquet file that holds only the `l_comment` column of TPC-H SF=1 `lineitem`. From 6f19d4331ce3b951513bc27399d14078a8b983f0 Mon Sep 17 00:00:00 2001 From: Will Manning Date: Sat, 21 Nov 2026 12:42:44 -0500 Subject: [PATCH 28/44] Put is_zstd's doc comment back on is_zstd Signed-off-by: Will Manning --- vortex-bench/src/utils/parquet.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/vortex-bench/src/utils/parquet.rs b/vortex-bench/src/utils/parquet.rs index c00e5ce5b55..df60c75dc53 100644 --- a/vortex-bench/src/utils/parquet.rs +++ b/vortex-bench/src/utils/parquet.rs @@ -43,7 +43,6 @@ pub fn parquet_writer_properties() -> WriterPropertiesBuilder { .set_data_page_row_count_limit(usize::MAX) } -/// Return whether every column chunk in `metadata` is zstd. /// Make `parquet_dir` ready for generated Parquet in row groups of `row_group_rows` rows. /// /// The generators do not write a file that exists, so Parquet generated before with other row @@ -77,6 +76,7 @@ pub fn prepare_parquet_dir(parquet_dir: &Path, row_group_rows: usize) -> anyhow: Ok(()) } +/// Return whether every column chunk in `metadata` is zstd. pub fn is_zstd(metadata: &ParquetMetaData) -> bool { metadata .row_groups() From 76d5500d790a181fe0278e1360cb467bdcb703d3 Mon Sep 17 00:00:00 2001 From: Will Manning Date: Sat, 21 Nov 2026 12:58:43 -0500 Subject: [PATCH 29/44] Read random access Parquet with a page index, the taxi data included The taxi data was the published NYC TLC file, which has no page index. Without the offset index, parquet-rs decodes every page of a column chunk to read one row, so Parquet lookups on taxi did much more work than the benchmark describes. The taxi data is now the published file written again with `random_access_writer_properties`, the writer of the synthetic datasets. That writer now sets its layout explicitly: zstd level 3, page statistics, data pages of at most 1 MiB and about 20,000 rows, and row groups of at most 1,048,576 rows, parquet-rs's defaults. The reader now stops with an error on a file without the offset index, because parquet-rs accepts such a file silently. Signed-off-by: Will Manning --- benchmarks/random-access-bench/README.md | 7 ++ vortex-bench/src/datasets/taxi_data.rs | 17 ++++- vortex-bench/src/random_access/mod.rs | 83 +++++++++++++++++++++++- vortex-bench/src/random_access/take.rs | 10 ++- 4 files changed, 112 insertions(+), 5 deletions(-) diff --git a/benchmarks/random-access-bench/README.md b/benchmarks/random-access-bench/README.md index 3e3a6f0c883..c9fe09a096b 100644 --- a/benchmarks/random-access-bench/README.md +++ b/benchmarks/random-access-bench/README.md @@ -14,6 +14,13 @@ touched row group into a `RowSelection`, so with the page index parquet-rs fetch only the pages holding those rows; row groups are read concurrently, and local files go through `object_store`'s `LocalFileSystem`, as DataFusion reads them. +Every Parquet file is written by parquet-rs with zstd level 3 and parquet-rs's default layout: +a page index, data pages of at most 1 MiB and about 20,000 rows, and row groups of at most +1,048,576 rows (`random_access_writer_properties` in `vortex-bench/src/random_access/mod.rs`). +The taxi data is the published NYC TLC file written again in this layout, because the published +file has no page index. The benchmark stops with an error on a Parquet file without the offset +index. + Two access patterns are generated with a fixed seed (see [`src/main.rs`](./src/main.rs)): - **correlated**: several clusters of consecutive indices scattered across the dataset, diff --git a/vortex-bench/src/datasets/taxi_data.rs b/vortex-bench/src/datasets/taxi_data.rs index 3800c5b5749..3238b47451b 100644 --- a/vortex-bench/src/datasets/taxi_data.rs +++ b/vortex-bench/src/datasets/taxi_data.rs @@ -21,10 +21,12 @@ use crate::SESSION; use crate::conversions::parquet_to_vortex_chunks; use crate::datasets::Dataset; use crate::datasets::data_downloads::download_data; +use crate::idempotent; use crate::idempotent_async; use crate::random_access::BenchDataset; use crate::random_access::data_path; use crate::random_access::parquet_to_arrow_file; +use crate::random_access::write_random_access_parquet; /// Dataset identifier used for data path generation. pub const DATASET: &str = "taxi"; @@ -67,7 +69,7 @@ impl BenchDataset for TaxiData { } Format::OnDiskVortex => taxi_data_vortex().await, Format::VortexCompact => taxi_data_vortex_compact().await, - Format::Parquet => taxi_data_parquet().await, + Format::Parquet => taxi_random_access_parquet().await, other => anyhow::bail!("Random access bench not implemented for {other}"), } } @@ -80,6 +82,19 @@ pub async fn taxi_data_parquet() -> Result { download_data(taxi_parquet_fpath, taxi_data_url).await } +/// The taxi data as the random access benchmark reads it: the published file written again with +/// [`random_access_writer_properties`](crate::random_access::random_access_writer_properties), +/// because the published file has no page index. +pub async fn taxi_random_access_parquet() -> Result { + let published = taxi_data_parquet().await?; + tokio::task::spawn_blocking(move || { + idempotent(&data_path(DATASET, Format::Parquet), |output| { + write_random_access_parquet(&published, output) + }) + }) + .await? +} + pub async fn fetch_taxi_data() -> Result { let vortex_data = taxi_data_vortex().await?; Ok(SESSION diff --git a/vortex-bench/src/random_access/mod.rs b/vortex-bench/src/random_access/mod.rs index e7ff4c7a41a..c09b3f5cc4f 100644 --- a/vortex-bench/src/random_access/mod.rs +++ b/vortex-bench/src/random_access/mod.rs @@ -9,14 +9,17 @@ use std::sync::Arc; use anyhow::Result; use anyhow::anyhow; use arrow_array::RecordBatch; +use arrow_array::RecordBatchReader; use arrow_ipc::writer::FileWriter; use async_trait::async_trait; use object_store::ObjectStore; use object_store::aws::AmazonS3Builder; use object_store::path::Path as ObjectStorePath; +use parquet::arrow::ArrowWriter; use parquet::arrow::arrow_reader::ParquetRecordBatchReaderBuilder; use parquet::basic::Compression; use parquet::basic::ZstdLevel; +use parquet::file::properties::EnabledStatistics; use parquet::file::properties::WriterProperties; use url::Url; use vortex::array::ArrayRef; @@ -82,16 +85,45 @@ pub fn parquet_to_arrow_file(parquet_path: PathBuf, arrow_path: String) -> Resul }) } -/// Parquet writer properties for the synthetic random-access datasets. +/// Parquet writer properties for every random-access dataset, the taxi data included. /// -/// Compression is zstd level 3, matching every other benchmark data generator; parquet-rs would -/// otherwise write these files uncompressed. Row group and page sizes are left at their defaults. +/// Compression is zstd level 3, like every other benchmark data generator; parquet-rs would +/// otherwise write these files uncompressed. The other settings are parquet-rs's defaults, set +/// here so that a change of default cannot change the benchmark: +/// +/// - Page statistics, so each file has a page index: the column index and the offset index. With +/// the offset index, a lookup fetches and decodes only the pages that hold the requested rows. +/// - Data pages of at most 1 MiB and about 20,000 rows, so a lookup decodes a small page. +/// parquet-rs checks the row limit after every 1,024 rows, so full pages hold 20,480 rows. +/// - Row groups of at most 1,048,576 rows. pub fn random_access_writer_properties() -> Result { Ok(WriterProperties::builder() .set_compression(Compression::ZSTD(ZstdLevel::try_new(3)?)) + .set_statistics_enabled(EnabledStatistics::Page) + .set_data_page_row_count_limit(20_000) + .set_data_page_size_limit(1024 * 1024) + .set_max_row_group_row_count(Some(1024 * 1024)) .build()) } +/// Write the Parquet file `input` again with [`random_access_writer_properties`]. +/// +/// A published file can lack the page index, and without it parquet-rs must decode every page of +/// a column chunk to read one row. +pub fn write_random_access_parquet(input: &Path, output: &Path) -> Result<()> { + let reader = ParquetRecordBatchReaderBuilder::try_new(File::open(input)?)?.build()?; + let mut writer = ArrowWriter::try_new( + File::create(output)?, + reader.schema(), + Some(random_access_writer_properties()?), + )?; + for batch in reader { + writer.write(&batch?)?; + } + writer.close()?; + Ok(()) +} + /// A remote directory holding the same layout as the local benchmark data directory. /// /// Random access datasets are always materialized locally first, then uploaded verbatim, so a @@ -194,8 +226,53 @@ pub trait RandomAccessor: Send + Sync { #[cfg(test)] mod tests { + use arrow_array::Int64Array; + use parquet::file::metadata::PageIndexPolicy; + use parquet::file::metadata::ParquetMetaDataReader; + use super::*; + #[test] + fn rewritten_parquet_has_a_page_index_and_small_pages() -> Result<()> { + let dir = tempfile::tempdir()?; + let input = dir.path().join("published.parquet"); + let output = dir.path().join("random-access.parquet"); + + // A file without a page index, like the published taxi data. + let batch = RecordBatch::try_from_iter([( + "x", + Arc::new(Int64Array::from_iter_values(0..100_000)) as _, + )])?; + let props = WriterProperties::builder() + .set_statistics_enabled(EnabledStatistics::None) + .set_offset_index_disabled(true) + .build(); + let mut writer = ArrowWriter::try_new(File::create(&input)?, batch.schema(), Some(props))?; + writer.write(&batch)?; + writer.close()?; + let published = ParquetMetaDataReader::new() + .with_page_index_policy(PageIndexPolicy::Optional) + .parse_and_finish(&File::open(&input)?)?; + assert!(published.offset_index().is_none()); + + write_random_access_parquet(&input, &output)?; + + let metadata = ParquetMetaDataReader::new() + .with_page_index_policy(PageIndexPolicy::Required) + .parse_and_finish(&File::open(&output)?)?; + assert!(metadata.column_index().is_some()); + let offset_index = metadata + .offset_index() + .ok_or_else(|| anyhow!("no offset index"))?; + let pages = offset_index[0][0].page_locations(); + assert!(pages.len() >= 5); + for pair in pages.windows(2) { + // parquet-rs checks the 20,000-row limit after every 1,024 rows. + assert!(pair[1].first_row_index - pair[0].first_row_index <= 20_480); + } + Ok(()) + } + fn remote(url: &str) -> Result { // `from_env` needs no credentials to construct the client. RemoteDataDir::try_new(Url::parse(url)?) diff --git a/vortex-bench/src/random_access/take.rs b/vortex-bench/src/random_access/take.rs index abb2fc340b0..6d3f10dfeaf 100644 --- a/vortex-bench/src/random_access/take.rs +++ b/vortex-bench/src/random_access/take.rs @@ -291,11 +291,19 @@ impl ParquetRandomAccessor { } /// Parse the Parquet footer, including the page index, from any async reader. +/// +/// parquet-rs returns no page index, and no error, for a file that has none at all. Without the +/// offset index every lookup would decode whole column chunks, so this returns an error instead. async fn load_metadata( reader: &mut T, ) -> anyhow::Result { let options = ArrowReaderOptions::new().with_page_index_policy(PageIndexPolicy::Required); - Ok(ArrowReaderMetadata::load_async(reader, options).await?) + let metadata = ArrowReaderMetadata::load_async(reader, options).await?; + anyhow::ensure!( + metadata.metadata().offset_index().is_some(), + "the Parquet file has no offset index; write it with `random_access_writer_properties`" + ); + Ok(metadata) } /// The rows to read from one row group: runs of consecutive row-group-local indices. From 89bd5ca05c7f7992c4bbc313de186541db438d7a Mon Sep 17 00:00:00 2001 From: Will Manning Date: Sat, 21 Nov 2026 13:09:54 -0500 Subject: [PATCH 30/44] Say which suites the row-group rule covers The rule named all generated Parquet that queries read. It covers the SQL data of TPC-H, TPC-DS, and nested TPC-H. The random access benchmark writes its own layout on both storages: a page index and small pages, so the row-group size matters little, and the S3 job reads the files that the local job prepares. Signed-off-by: Will Manning --- AGENTS.md | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index d62df9c310c..e5a1a8ed899 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -232,10 +232,14 @@ These CI checks are the ones most often missed when adding files rather than edi - tpchgen-cli: `parquet --compression='ZSTD(3)'` - Benchmarks that deliberately compare Parquet codecs, such as the GPU compress benchmark's `--codec` and the Snappy Parquet whose size `compress-bench` records, are exempt. -- Generated Parquet that queries read from local disk has row groups of 122,880 rows - (`LOCAL_ROW_GROUP_ROWS`, DuckDB's default). Generated Parquet that queries read from S3 has - row groups of 1,048,576 rows (`S3_ROW_GROUP_ROWS`, parquet-rs's default): the CI matrix passes +- The Parquet that TPC-H, TPC-DS, and nested TPC-H generate for SQL queries has row groups of + 122,880 rows (`LOCAL_ROW_GROUP_ROWS`, DuckDB's default) on local disk, and 1,048,576 rows + (`S3_ROW_GROUP_ROWS`, parquet-rs's default) on S3: the CI matrix passes `--opt row-group-rows=1048576` to `data-gen` for S3 entries. +- The random access benchmark writes all its Parquet with `random_access_writer_properties`, on + local disk and S3 alike: a page index and pages of about 20,000 rows. A lookup reads only the + pages that hold its rows, so the row-group size matters little, and the S3 job reads the same + files that the local job prepares. ## Common Mistakes From 9f12a81c72fe1763bd722a1fa2948a23d65b7f5a Mon Sep 17 00:00:00 2001 From: Will Manning Date: Sat, 21 Nov 2026 13:48:53 -0500 Subject: [PATCH 31/44] Write JOB, Polar Signals, and SpatialBench Parquet with the shared config The three suites wrote Parquet with parquet-rs defaults and zstd 3, in 1,048,576-row groups. They now use parquet_writer_properties() with 122,880-row groups, as TPC-H, TPC-DS, and nested TPC-H do on local disk. JOB and Polar Signals regenerate stale data through the row-group marker. SpatialBench keeps its directory, because its zone files come from outside. Signed-off-by: Will Manning --- AGENTS.md | 10 ++++++---- vortex-bench/README.md | 7 ++++--- vortex-bench/src/job/mod.rs | 14 ++++++++------ vortex-bench/src/polarsignals/benchmark.rs | 5 +++++ vortex-bench/src/polarsignals/data.rs | 9 ++++----- .../src/spatialbench/datagen/spatial_sort.rs | 9 ++++----- vortex-bench/src/spatialbench/datagen/wkb.rs | 7 +++++++ vortex-bench/src/utils/parquet.rs | 2 +- 8 files changed, 39 insertions(+), 24 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index e5a1a8ed899..5c78f37f95b 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -232,10 +232,12 @@ These CI checks are the ones most often missed when adding files rather than edi - tpchgen-cli: `parquet --compression='ZSTD(3)'` - Benchmarks that deliberately compare Parquet codecs, such as the GPU compress benchmark's `--codec` and the Snappy Parquet whose size `compress-bench` records, are exempt. -- The Parquet that TPC-H, TPC-DS, and nested TPC-H generate for SQL queries has row groups of - 122,880 rows (`LOCAL_ROW_GROUP_ROWS`, DuckDB's default) on local disk, and 1,048,576 rows - (`S3_ROW_GROUP_ROWS`, parquet-rs's default) on S3: the CI matrix passes - `--opt row-group-rows=1048576` to `data-gen` for S3 entries. +- The SQL benchmarks that write Parquet with parquet-rs (TPC-H, TPC-DS, nested TPC-H, JOB, + Polar Signals, and SpatialBench) use `parquet_writer_properties()`, with row groups of 122,880 + rows (`LOCAL_ROW_GROUP_ROWS`, DuckDB's default) on local disk. TPC-H, TPC-DS, and nested TPC-H + also run on S3, with row groups of 1,048,576 rows (`S3_ROW_GROUP_ROWS`, parquet-rs's default): + the CI matrix passes `--opt row-group-rows=1048576` to `data-gen` for S3 entries. The suites + that DuckDB's `COPY` writes get DuckDB's 122,880-row groups by default. - The random access benchmark writes all its Parquet with `random_access_writer_properties`, on local disk and S3 alike: a page index and pages of about 20,000 rows. A lookup reads only the pages that hold its rows, so the row-group size matters little, and the S3 job reads the same diff --git a/vortex-bench/README.md b/vortex-bench/README.md index fa0f2c3f47c..2af5a4f55fb 100644 --- a/vortex-bench/README.md +++ b/vortex-bench/README.md @@ -56,14 +56,15 @@ option and the Snappy Parquet whose size compress-bench records, are exempt. ## Parquet row groups -TPC-H, TPC-DS, and nested TPC-H write Parquet in row groups of 122,880 rows, DuckDB's default. -In our tests, these smaller row groups were faster from local disk, because they give the query +TPC-H, TPC-DS, nested TPC-H, JOB, Polar Signals, and SpatialBench write Parquet in row groups of +122,880 rows, DuckDB's default. In our tests, these smaller row groups were faster from local disk, because they give the query engines more units of work to run in parallel. The benchmarks that read from S3 use row groups of 1,048,576 rows, parquet-rs's default, which need fewer requests to object storage. Pass `--opt row-group-rows=1048576` to `data-gen` to generate data for S3. The file `parquet.row-group-rows`, beside the `parquet` directory, records the row groups of its files. `data-gen` removes and generates again Parquet whose row groups are different or not recorded, -and the formats converted from it. +and the formats converted from it. SpatialBench keeps its `parquet` directory, because the `zone` +files in it come from outside: delete its generated files by hand to write them again. ## Memory allocators diff --git a/vortex-bench/src/job/mod.rs b/vortex-bench/src/job/mod.rs index 0071a6d4343..05641f0c2ca 100644 --- a/vortex-bench/src/job/mod.rs +++ b/vortex-bench/src/job/mod.rs @@ -17,9 +17,6 @@ use anyhow::Context; use glob::Pattern; use parquet::arrow::ArrowWriter; use parquet::arrow::arrow_reader::ParquetRecordBatchReaderBuilder; -use parquet::basic::Compression; -use parquet::basic::ZstdLevel; -use parquet::file::properties::WriterProperties; use tracing::info; use url::Url; use vortex::error::VortexExpect; @@ -31,6 +28,9 @@ use crate::TableSpec; use crate::datasets::data_downloads::download_many; use crate::utils::file::idempotent; use crate::utils::file::resolve_data_url; +use crate::utils::parquet::LOCAL_ROW_GROUP_ROWS; +use crate::utils::parquet::parquet_writer_properties; +use crate::utils::parquet::prepare_parquet_dir; /// Release that hosts DuckDB's JOB Parquet files, as referenced by DuckDB's /// `benchmark/imdb/init/load.sql`. Each table lives at `{UPSTREAM_BASE_URL}/job_{table}.parquet`. @@ -116,6 +116,7 @@ impl Benchmark for JobBenchmark { let base_dir = self.base_dir()?; let parquet_dir = base_dir.join(Format::Parquet.name()); + prepare_parquet_dir(&parquet_dir, LOCAL_ROW_GROUP_ROWS)?; let missing: Vec<&str> = TABLES .iter() .copied() @@ -189,15 +190,16 @@ impl Benchmark for JobBenchmark { } } -/// Rewrite the upstream Parquet file at `src` to `dst` with zstd level 3 compression. +/// Rewrite the upstream Parquet file at `src` to `dst` with `parquet_writer_properties`, in +/// local row groups. fn reencode_parquet(src: &Path, dst: &Path) -> anyhow::Result { idempotent(dst, |tmp| { let builder = ParquetRecordBatchReaderBuilder::try_new( File::open(src).with_context(|| format!("opening {}", src.display()))?, )?; let schema = Arc::clone(builder.schema()); - let props = WriterProperties::builder() - .set_compression(Compression::ZSTD(ZstdLevel::try_new(3)?)) + let props = parquet_writer_properties() + .set_max_row_group_row_count(Some(LOCAL_ROW_GROUP_ROWS)) .build(); let mut writer = ArrowWriter::try_new(File::create(tmp)?, schema, Some(props))?; for batch in builder.build()? { diff --git a/vortex-bench/src/polarsignals/benchmark.rs b/vortex-bench/src/polarsignals/benchmark.rs index d1097e83bd1..c6756c6e8a1 100644 --- a/vortex-bench/src/polarsignals/benchmark.rs +++ b/vortex-bench/src/polarsignals/benchmark.rs @@ -16,6 +16,8 @@ use crate::Format; use crate::IdempotentPath; use crate::TableSpec; use crate::idempotent; +use crate::utils::parquet::LOCAL_ROW_GROUP_ROWS; +use crate::utils::parquet::prepare_parquet_dir; use crate::workspace_root; const FILE_NAME: &str = "stacktraces"; @@ -88,6 +90,9 @@ impl Benchmark for PolarSignalsBenchmark { let n_rows = self.n_rows; let parquet_path = self.parquet_path()?; + if let Some(parquet_dir) = parquet_path.parent() { + prepare_parquet_dir(parquet_dir, LOCAL_ROW_GROUP_ROWS)?; + } idempotent(&parquet_path, |tmp_path| { tracing::info!( n_rows, diff --git a/vortex-bench/src/polarsignals/data.rs b/vortex-bench/src/polarsignals/data.rs index b3a792d9f2c..b07532d07f2 100644 --- a/vortex-bench/src/polarsignals/data.rs +++ b/vortex-bench/src/polarsignals/data.rs @@ -20,9 +20,6 @@ use arrow_schema::DataType; use arrow_schema::Field; use arrow_schema::Schema; use parquet::arrow::ArrowWriter; -use parquet::basic::Compression; -use parquet::basic::ZstdLevel; -use parquet::file::properties::WriterProperties; use rand::RngExt; use rand::SeedableRng; use rand::rngs::StdRng; @@ -36,6 +33,8 @@ use super::schema::UInt64DictBuilder; use super::schema::label_fields; use super::schema::lines_fields; use super::schema::location_fields; +use crate::utils::parquet::LOCAL_ROW_GROUP_ROWS; +use crate::utils::parquet::parquet_writer_properties; pub const BASE_TIMESTAMP_NS: i64 = 0; @@ -142,8 +141,8 @@ pub fn generate_polarsignals_parquet(n_rows: usize, output_path: &Path) -> Resul let label_sets = Arc::new(label_sets); let file = std::fs::File::create(output_path)?; - let props = WriterProperties::builder() - .set_compression(Compression::ZSTD(ZstdLevel::try_new(3)?)) + let props = parquet_writer_properties() + .set_max_row_group_row_count(Some(LOCAL_ROW_GROUP_ROWS)) .build(); let mut writer = ArrowWriter::try_new(file, Arc::clone(&schema), Some(props))?; diff --git a/vortex-bench/src/spatialbench/datagen/spatial_sort.rs b/vortex-bench/src/spatialbench/datagen/spatial_sort.rs index 1be22cfbe59..90c6f6dc000 100644 --- a/vortex-bench/src/spatialbench/datagen/spatial_sort.rs +++ b/vortex-bench/src/spatialbench/datagen/spatial_sort.rs @@ -37,15 +37,14 @@ use geoarrow::datatypes::Metadata; use geoarrow::datatypes::WkbType; use parquet::arrow::AsyncArrowWriter; use parquet::arrow::ParquetRecordBatchStreamBuilder; -use parquet::basic::Compression; -use parquet::basic::ZstdLevel; use parquet::file::metadata::KeyValue; -use parquet::file::properties::WriterProperties; use tokio::fs::File as TokioFile; use tracing::info; use super::table::Table; use super::wkb::geoparquet_metadata; +use crate::utils::parquet::LOCAL_ROW_GROUP_ROWS; +use crate::utils::parquet::parquet_writer_properties; /// Parquet metadata marker: this file is already spatially sorted (makes the step idempotent). const SORTED_KEY: &str = "vortex_spatial_sorted"; @@ -143,8 +142,8 @@ async fn sort_part(path: &Path, table: Table, geom_col: &str) -> anyhow::Result< let num_rows = sorted.num_rows(); let tmp_path = path.with_extension("parquet.sorttmp"); - let props = WriterProperties::builder() - .set_compression(Compression::ZSTD(ZstdLevel::try_new(3)?)) + let props = parquet_writer_properties() + .set_max_row_group_row_count(Some(LOCAL_ROW_GROUP_ROWS)) .build(); let mut writer = AsyncArrowWriter::try_new(TokioFile::create(&tmp_path).await?, schema, Some(props))?; diff --git a/vortex-bench/src/spatialbench/datagen/wkb.rs b/vortex-bench/src/spatialbench/datagen/wkb.rs index d9f92e11168..d7b53c626bf 100644 --- a/vortex-bench/src/spatialbench/datagen/wkb.rs +++ b/vortex-bench/src/spatialbench/datagen/wkb.rs @@ -32,6 +32,8 @@ use tracing::info; use super::table::Table; use crate::Format; use crate::utils::file::idempotent_async; +use crate::utils::parquet::DICTIONARY_PAGE_SIZE_LIMIT; +use crate::utils::parquet::LOCAL_ROW_GROUP_ROWS; /// Batch size matching the TPC-H generator's streaming batches. const BATCH_SIZE: usize = 8192 * 64; @@ -93,8 +95,13 @@ pub async fn generate_tables(scale_factor: &str, output_dir: PathBuf) -> Result< let schema = Arc::clone(iter.schema()); let file = TokioFile::create(&path).await?; + // `parquet_writer_properties`'s settings, in the parquet version this writer + // takes. let props = WriterProperties::builder() .set_compression(Compression::ZSTD(ZstdLevel::try_new(3)?)) + .set_dictionary_page_size_limit(DICTIONARY_PAGE_SIZE_LIMIT) + .set_data_page_row_count_limit(usize::MAX) + .set_max_row_group_size(LOCAL_ROW_GROUP_ROWS) .build(); let mut writer = AsyncArrowWriter::try_new(file, schema, Some(props))?; for batch in iter { diff --git a/vortex-bench/src/utils/parquet.rs b/vortex-bench/src/utils/parquet.rs index df60c75dc53..389db80b29b 100644 --- a/vortex-bench/src/utils/parquet.rs +++ b/vortex-bench/src/utils/parquet.rs @@ -26,7 +26,7 @@ pub const S3_ROW_GROUP_ROWS: usize = 1024 * 1024; /// Columns whose dictionary outgrows this fall back to plain encoding. The parquet-rs default /// (1 MiB) keeps dictionaries for unique keys, which compress far worse than plain values. A small /// limit approximates the per-column choice that DuckDB's writer makes. -const DICTIONARY_PAGE_SIZE_LIMIT: usize = 64 * 1024; +pub const DICTIONARY_PAGE_SIZE_LIMIT: usize = 64 * 1024; /// Writer settings for generated benchmark Parquet: zstd level 3, pages bounded by bytes only, /// and small dictionaries. From 34797dd5d50c00147f9a416ae86a72aef2cc1b24 Mon Sep 17 00:00:00 2001 From: Will Manning Date: Sat, 21 Nov 2026 14:01:25 -0500 Subject: [PATCH 32/44] Generate SpatialBench Parquet again when its row groups change SpatialBench skipped existing Parquet, so files cached with the old 1,048,576-row groups kept that layout. It now uses the row-group marker, like the other generators, but keeps the zone files, which come from outside. Signed-off-by: Will Manning --- vortex-bench/README.md | 14 ++++---- vortex-bench/src/spatialbench/benchmark.rs | 13 +++++++ vortex-bench/src/utils/parquet.rs | 40 ++++++++++++++++++++++ 3 files changed, 60 insertions(+), 7 deletions(-) diff --git a/vortex-bench/README.md b/vortex-bench/README.md index 2af5a4f55fb..4e8c602b298 100644 --- a/vortex-bench/README.md +++ b/vortex-bench/README.md @@ -57,14 +57,14 @@ option and the Snappy Parquet whose size compress-bench records, are exempt. ## Parquet row groups TPC-H, TPC-DS, nested TPC-H, JOB, Polar Signals, and SpatialBench write Parquet in row groups of -122,880 rows, DuckDB's default. In our tests, these smaller row groups were faster from local disk, because they give the query -engines more units of work to run in parallel. The benchmarks that read from S3 use row groups of -1,048,576 rows, parquet-rs's default, which need fewer requests to object storage. Pass -`--opt row-group-rows=1048576` to `data-gen` to generate data for S3. The file +122,880 rows, DuckDB's default. In our tests, these smaller row groups were faster from local disk, +because they give the query engines more units of work to run in parallel. The benchmarks that read +from S3 use row groups of 1,048,576 rows, parquet-rs's default, which need fewer requests to object +storage. Pass `--opt row-group-rows=1048576` to `data-gen` to generate data for S3. The file `parquet.row-group-rows`, beside the `parquet` directory, records the row groups of its files. -`data-gen` removes and generates again Parquet whose row groups are different or not recorded, -and the formats converted from it. SpatialBench keeps its `parquet` directory, because the `zone` -files in it come from outside: delete its generated files by hand to write them again. +`data-gen` removes and generates again Parquet whose row groups are different or not recorded, and +the formats converted from it. SpatialBench keeps its `zone` files, which come from outside, and +writes the rest again. ## Memory allocators diff --git a/vortex-bench/src/spatialbench/benchmark.rs b/vortex-bench/src/spatialbench/benchmark.rs index 693a174eae1..40627302825 100644 --- a/vortex-bench/src/spatialbench/benchmark.rs +++ b/vortex-bench/src/spatialbench/benchmark.rs @@ -16,6 +16,8 @@ use crate::TableSpec; use crate::spatialbench::datagen; use crate::spatialbench::datagen::Table; use crate::utils::file::resolve_data_url; +use crate::utils::parquet::LOCAL_ROW_GROUP_ROWS; +use crate::utils::parquet::prepare_parquet_dir_keeping; use crate::workspace_root; /// Data-dir subfolder for the native-geometry Vortex files (the `vortex-spatial-native` lane). @@ -88,6 +90,17 @@ impl Benchmark for SpatialBenchBenchmark { .data_url .to_file_path() .map_err(|_| anyhow::anyhow!("Invalid file URL: {}", self.data_url.as_str()))?; + // Generate the tables again if their row groups are not local ones. The `zone` files come + // from outside, so they stay. + let zone_prefix = format!("{}_", Table::Zone.name()); + prepare_parquet_dir_keeping( + &base_data_dir.join(Format::Parquet.name()), + LOCAL_ROW_GROUP_ROWS, + |path| { + path.file_name() + .is_some_and(|name| name.to_string_lossy().starts_with(&zone_prefix)) + }, + )?; datagen::generate_tables(&self.scale_factor, base_data_dir.clone()).await?; // `zone` is externally sourced (SpatialBench directly generates it), so restore its diff --git a/vortex-bench/src/utils/parquet.rs b/vortex-bench/src/utils/parquet.rs index 389db80b29b..6edce35a91d 100644 --- a/vortex-bench/src/utils/parquet.rs +++ b/vortex-bench/src/utils/parquet.rs @@ -52,6 +52,16 @@ pub fn parquet_writer_properties() -> WriterPropertiesBuilder { /// directories beside it, such as `vortex-file-compressed`, because they were converted from the /// old Parquet and their conversions skip files that exist. pub fn prepare_parquet_dir(parquet_dir: &Path, row_group_rows: usize) -> anyhow::Result<()> { + prepare_parquet_dir_keeping(parquet_dir, row_group_rows, |_| false) +} + +/// [`prepare_parquet_dir`], but it keeps the entries of `parquet_dir` for which `keep` returns +/// true, such as input files that no generator writes. +pub fn prepare_parquet_dir_keeping( + parquet_dir: &Path, + row_group_rows: usize, + keep: impl Fn(&Path) -> bool, +) -> anyhow::Result<()> { let marker = parquet_dir.with_extension("row-group-rows"); let recorded = fs::read_to_string(&marker) .ok() @@ -66,8 +76,19 @@ pub fn prepare_parquet_dir(parquet_dir: &Path, row_group_rows: usize) -> anyhow: ); for entry in fs::read_dir(data_dir)? { let path = entry?.path(); + if path.is_dir() && path != parquet_dir { + fs::remove_dir_all(path)?; + } + } + for entry in fs::read_dir(parquet_dir)? { + let path = entry?.path(); + if keep(&path) { + continue; + } if path.is_dir() { fs::remove_dir_all(path)?; + } else { + fs::remove_file(path)?; } } } @@ -145,6 +166,25 @@ mod tests { Ok(()) } + #[test] + fn kept_inputs_stay_when_parquet_is_generated_again() -> anyhow::Result<()> { + let base = tempfile::tempdir()?; + let parquet_dir = base.path().join("parquet"); + let generated = parquet_dir.join("trip_0.parquet"); + let input = parquet_dir.join("zone_0.parquet"); + let vortex_dir = base.path().join("vortex-file-compressed"); + fs::create_dir_all(&parquet_dir)?; + fs::write(&generated, b"old")?; + fs::write(&input, b"input")?; + fs::create_dir_all(&vortex_dir)?; + + prepare_parquet_dir_keeping(&parquet_dir, LOCAL_ROW_GROUP_ROWS, |path| path == input)?; + assert!(!generated.exists()); + assert!(input.exists()); + assert!(!vortex_dir.exists()); + Ok(()) + } + #[test] fn zstd_file_check_reads_the_codec() -> anyhow::Result<()> { let dir = tempfile::tempdir()?; From f6d749e629850f83364e2f4b8518fdea98f308e8 Mon Sep 17 00:00:00 2001 From: Will Manning Date: Sat, 21 Nov 2026 14:10:15 -0500 Subject: [PATCH 33/44] Write SpatialBench zone files in local row groups The GeoParquet rewrite of the outside zone files left the row-group limit at parquet-rs's 1,048,576 rows. It now uses 122,880-row groups, like the rest of the local SpatialBench data, and also rewrites a tagged zstd file whose row groups are larger. Signed-off-by: Will Manning --- vortex-bench/src/conversions.rs | 52 +++++++++++++++++++++++++++++---- 1 file changed, 47 insertions(+), 5 deletions(-) diff --git a/vortex-bench/src/conversions.rs b/vortex-bench/src/conversions.rs index 243c07712e5..c2091e40a73 100644 --- a/vortex-bench/src/conversions.rs +++ b/vortex-bench/src/conversions.rs @@ -72,6 +72,7 @@ use crate::CompactionStrategy; use crate::Format; use crate::SESSION; use crate::utils::file::idempotent_async; +use crate::utils::parquet::LOCAL_ROW_GROUP_ROWS; use crate::utils::parquet::is_zstd; use crate::utils::parquet::parquet_writer_properties; @@ -430,8 +431,9 @@ pub async fn write_parquet_as_vortex( /// Add GeoParquet `geo` file metadata to externally-sourced parquet we don't generate (e.g. SpatialBench `zone`). /// -/// The file is rewritten with zstd unless it already has both the metadata and zstd, so a file -/// tagged before the benchmarks wrote zstd is compressed too. +/// The file is rewritten with the shared Parquet settings, in local row groups, unless it already +/// has the metadata, zstd, and no row group larger than a local one. So a file tagged before the +/// benchmarks wrote zstd or local row groups is written again too. pub async fn add_geoparquet_metadata( parquet_path: &Path, geoparquet_json: &str, @@ -442,7 +444,11 @@ pub async fn add_geoparquet_metadata( .file_metadata() .key_value_metadata() .is_some_and(|kvs| kvs.iter().any(|kv| kv.key == "geo")); - if already_tagged && is_zstd(metadata) { + let local_row_groups = metadata + .row_groups() + .iter() + .all(|row_group| row_group.num_rows() <= LOCAL_ROW_GROUP_ROWS as i64); + if already_tagged && is_zstd(metadata) && local_row_groups { return Ok(()); } @@ -450,8 +456,10 @@ pub async fn add_geoparquet_metadata( let mut reader = builder.build()?; let tmp_path = parquet_path.with_extension("parquet.tmp"); - // Rewrite with the zstd settings every benchmark writes, not parquet-rs's default (none). - let props = parquet_writer_properties().build(); + // The settings every benchmark writes, not parquet-rs's defaults (no compression). + let props = parquet_writer_properties() + .set_max_row_group_row_count(Some(LOCAL_ROW_GROUP_ROWS)) + .build(); let mut writer = AsyncArrowWriter::try_new(File::create(&tmp_path).await?, schema, Some(props))?; while let Some(batch) = reader.try_next().await? { @@ -615,6 +623,40 @@ mod tests { Ok(()) } + #[tokio::test] + async fn geoparquet_tagging_rewrites_large_row_groups_as_local_ones() -> anyhow::Result<()> { + let dir = tempfile::tempdir()?; + let path = dir.path().join("zone.parquet"); + let schema = Arc::new(Schema::new(vec![Field::new("id", DataType::Int64, false)])); + let batch = RecordBatch::try_new( + Arc::clone(&schema), + vec![Arc::new(Int64Array::from_iter_values(0..200_000))], + )?; + // Tagged and zstd, but in one row group larger than a local one. + let props = parquet_writer_properties() + .set_max_row_group_row_count(Some(1024 * 1024)) + .set_key_value_metadata(Some(vec![KeyValue::new( + "geo".to_string(), + Some("{}".to_string()), + )])) + .build(); + let mut writer = ArrowWriter::try_new(fs::File::create(&path)?, schema, Some(props))?; + writer.write(&batch)?; + writer.close()?; + + add_geoparquet_metadata(&path, "{}").await?; + + let reader = SerializedFileReader::new(fs::File::open(&path)?)?; + let rows: Vec = reader + .metadata() + .row_groups() + .iter() + .map(|row_group| row_group.num_rows()) + .collect(); + assert_eq!(rows, vec![122_880, 200_000 - 122_880]); + Ok(()) + } + #[tokio::test] async fn geoparquet_tagging_recompresses_a_tagged_uncompressed_file() -> anyhow::Result<()> { let dir = tempfile::tempdir()?; From 8f04eb8d44423b89779dfa91e76b7cedb44a9442 Mon Sep 17 00:00:00 2001 From: Will Manning Date: Sat, 21 Nov 2026 14:22:42 -0500 Subject: [PATCH 34/44] Write all benchmark Parquet with one set of writer settings parquet_writer_properties() was bounded pages by bytes only, while random access had its own settings with 20,000-row pages. All parquet-rs writers of benchmark data, compress-bench and random access included, now use parquet_writer_properties(): zstd 3, 64 KiB dictionaries, a page index, and parquet-rs's default pages of at most 1 MiB and about 20,000 rows. Only the row-group size differs. On TPC-H SF10 from local disk, the 20,000-row pages had the same total size (2,322 MiB) and the same timings within 3% on DataFusion and DuckDB. On random access they made lookups up to 4 times faster. The marker beside a parquet directory is now parquet.layout and records a layout version with the row groups, so a settings change regenerates local data. The random access CI data cache key covers the shared settings. Signed-off-by: Will Manning --- .github/workflows/develop-bench.yml | 1 + .github/workflows/pr-bench-runner.yml | 1 + AGENTS.md | 19 +++--- benchmarks/compress-bench/src/parquet.rs | 7 +- benchmarks/random-access-bench/README.md | 6 +- benchmarks/string-bench/src/lib.rs | 8 +-- vortex-bench/README.md | 25 ++++--- vortex-bench/src/datasets/feature_vectors.rs | 2 +- vortex-bench/src/datasets/nested_lists.rs | 2 +- vortex-bench/src/datasets/nested_structs.rs | 2 +- vortex-bench/src/datasets/sparse_wide.rs | 8 +-- vortex-bench/src/random_access/mod.rs | 39 +++++------ vortex-bench/src/spatialbench/datagen/wkb.rs | 7 +- vortex-bench/src/utils/parquet.rs | 70 ++++++++++++++------ 14 files changed, 108 insertions(+), 89 deletions(-) diff --git a/.github/workflows/develop-bench.yml b/.github/workflows/develop-bench.yml index bc5fd97d1a6..5667b0701af 100644 --- a/.github/workflows/develop-bench.yml +++ b/.github/workflows/develop-bench.yml @@ -207,6 +207,7 @@ jobs: hashFiles( 'vortex-bench/src/datasets/**', 'vortex-bench/src/random_access/**', + 'vortex-bench/src/utils/parquet.rs', 'scripts/litdata-random-access.py', 'benchmarks/random-access-bench/src/litdata.rs') }} diff --git a/.github/workflows/pr-bench-runner.yml b/.github/workflows/pr-bench-runner.yml index fd1fcd0e4d2..2ed54bdc360 100644 --- a/.github/workflows/pr-bench-runner.yml +++ b/.github/workflows/pr-bench-runner.yml @@ -214,6 +214,7 @@ jobs: hashFiles( 'vortex-bench/src/datasets/**', 'vortex-bench/src/random_access/**', + 'vortex-bench/src/utils/parquet.rs', 'scripts/litdata-random-access.py', 'benchmarks/random-access-bench/src/litdata.rs') }} diff --git a/AGENTS.md b/AGENTS.md index 5c78f37f95b..9a4d2f89052 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -232,16 +232,15 @@ These CI checks are the ones most often missed when adding files rather than edi - tpchgen-cli: `parquet --compression='ZSTD(3)'` - Benchmarks that deliberately compare Parquet codecs, such as the GPU compress benchmark's `--codec` and the Snappy Parquet whose size `compress-bench` records, are exempt. -- The SQL benchmarks that write Parquet with parquet-rs (TPC-H, TPC-DS, nested TPC-H, JOB, - Polar Signals, and SpatialBench) use `parquet_writer_properties()`, with row groups of 122,880 - rows (`LOCAL_ROW_GROUP_ROWS`, DuckDB's default) on local disk. TPC-H, TPC-DS, and nested TPC-H - also run on S3, with row groups of 1,048,576 rows (`S3_ROW_GROUP_ROWS`, parquet-rs's default): - the CI matrix passes `--opt row-group-rows=1048576` to `data-gen` for S3 entries. The suites - that DuckDB's `COPY` writes get DuckDB's 122,880-row groups by default. -- The random access benchmark writes all its Parquet with `random_access_writer_properties`, on - local disk and S3 alike: a page index and pages of about 20,000 rows. A lookup reads only the - pages that hold its rows, so the row-group size matters little, and the S3 job reads the same - files that the local job prepares. +- Every parquet-rs writer of benchmark data uses `parquet_writer_properties()` in + `vortex-bench/src/utils/parquet.rs`: zstd level 3, 64 KiB dictionaries, a page index, and + parquet-rs's default pages of at most 1 MiB and about 20,000 rows. Only the row-group size + differs. SQL data has row groups of 122,880 rows (`LOCAL_ROW_GROUP_ROWS`, DuckDB's default) on + local disk and 1,048,576 rows (`S3_ROW_GROUP_ROWS`, parquet-rs's default) on S3: the CI matrix + passes `--opt row-group-rows=1048576` to `data-gen` for S3 entries. Random access uses the S3 + size on local disk too, because its S3 job reads the files that its local job prepares. When a + setting changes, raise `LAYOUT_VERSION` so that local data is generated again. The suites that + DuckDB's `COPY` writes get DuckDB's 122,880-row groups by default. ## Common Mistakes diff --git a/benchmarks/compress-bench/src/parquet.rs b/benchmarks/compress-bench/src/parquet.rs index 50ba20474dc..a9d9b982e17 100644 --- a/benchmarks/compress-bench/src/parquet.rs +++ b/benchmarks/compress-bench/src/parquet.rs @@ -29,7 +29,6 @@ use parquet::basic::Compression; use parquet::basic::ZstdLevel; use parquet::file::metadata::RowGroupMetaData; use parquet::file::properties::DEFAULT_MAX_ROW_GROUP_ROW_COUNT; -use parquet::file::properties::WriterProperties; use tokio::sync::mpsc; use tokio::task::JoinHandle; use vortex_bench::Format; @@ -39,6 +38,7 @@ use vortex_bench::compress::Compressor; use vortex_bench::compress::Uncompressed; use vortex_bench::compress::read_projection; use vortex_bench::parquet_copies::write_duckdb_snappy_parquet; +use vortex_bench::utils::parquet::parquet_writer_properties; /// Compressor implementation for Parquet format with ZSTD level 3 compression. pub struct ParquetCompressor { @@ -149,7 +149,7 @@ pub async fn parquet_compress_write( compression: Compression, buf: &mut Vec, ) -> anyhow::Result { - let writer_properties = WriterProperties::builder() + let writer_properties = parquet_writer_properties() .set_compression(compression) .build(); let max_rows = writer_properties @@ -454,6 +454,7 @@ mod tests { use arrow_schema::DataType; use arrow_schema::Field; use parquet::file::metadata::ParquetMetaData; + use parquet::file::properties::WriterProperties; use rstest::rstest; use super::*; @@ -503,7 +504,7 @@ mod tests { let parallel = Bytes::from(parallel); let mut sequential = Vec::new(); - let props = WriterProperties::builder() + let props = parquet_writer_properties() .set_compression(compression) .build(); let mut writer = ArrowWriter::try_new(&mut sequential, Arc::clone(&schema), Some(props))?; diff --git a/benchmarks/random-access-bench/README.md b/benchmarks/random-access-bench/README.md index c9fe09a096b..21b276f4750 100644 --- a/benchmarks/random-access-bench/README.md +++ b/benchmarks/random-access-bench/README.md @@ -14,9 +14,9 @@ touched row group into a `RowSelection`, so with the page index parquet-rs fetch only the pages holding those rows; row groups are read concurrently, and local files go through `object_store`'s `LocalFileSystem`, as DataFusion reads them. -Every Parquet file is written by parquet-rs with zstd level 3 and parquet-rs's default layout: -a page index, data pages of at most 1 MiB and about 20,000 rows, and row groups of at most -1,048,576 rows (`random_access_writer_properties` in `vortex-bench/src/random_access/mod.rs`). +Every Parquet file is written by parquet-rs with the settings of all generated benchmark Parquet +(`parquet_writer_properties` in `vortex-bench/src/utils/parquet.rs`): zstd level 3, a page index, +and data pages of at most 1 MiB and about 20,000 rows, in row groups of at most 1,048,576 rows. The taxi data is the published NYC TLC file written again in this layout, because the published file has no page index. The benchmark stops with an error on a Parquet file without the offset index. diff --git a/benchmarks/string-bench/src/lib.rs b/benchmarks/string-bench/src/lib.rs index 19d0a99439e..96c61ece349 100644 --- a/benchmarks/string-bench/src/lib.rs +++ b/benchmarks/string-bench/src/lib.rs @@ -34,9 +34,6 @@ use parquet::arrow::ArrowWriter; use parquet::arrow::ParquetRecordBatchStreamBuilder; use parquet::arrow::ProjectionMask; use parquet::arrow::async_reader; -use parquet::basic::Compression; -use parquet::basic::ZstdLevel; -use parquet::file::properties::WriterProperties; use tokio::fs::File; use url::Url; use vortex::VortexSessionDefault; @@ -58,6 +55,7 @@ use vortex_bench::datasets::data_downloads::download_data; use vortex_bench::datasets::tpch_l_comment::TPCHLCommentCanonical; use vortex_bench::enable_unstable_encodings; use vortex_bench::idempotent_async; +use vortex_bench::utils::parquet::parquet_writer_properties; use vortex_cloud::hf::make_hf_store_from_url; use vortex_fsst::FSST; use vortex_onpair::Config; @@ -453,9 +451,7 @@ async fn cache_hf_column(source: &HfColumn) -> Result { } let mut reader = builder.build()?; - let props = WriterProperties::builder() - .set_compression(Compression::ZSTD(ZstdLevel::try_new(3)?)) - .build(); + let props = parquet_writer_properties().build(); let mut writer = ArrowWriter::try_new( std::fs::File::create(&tmp)?, Arc::clone(reader.schema()), diff --git a/vortex-bench/README.md b/vortex-bench/README.md index 4e8c602b298..41f7209dfdc 100644 --- a/vortex-bench/README.md +++ b/vortex-bench/README.md @@ -54,17 +54,20 @@ the common writers are different: Benchmarks that compare Parquet codecs on purpose, such as the compress-bench `--gpu-parquet-codec` option and the Snappy Parquet whose size compress-bench records, are exempt. -## Parquet row groups - -TPC-H, TPC-DS, nested TPC-H, JOB, Polar Signals, and SpatialBench write Parquet in row groups of -122,880 rows, DuckDB's default. In our tests, these smaller row groups were faster from local disk, -because they give the query engines more units of work to run in parallel. The benchmarks that read -from S3 use row groups of 1,048,576 rows, parquet-rs's default, which need fewer requests to object -storage. Pass `--opt row-group-rows=1048576` to `data-gen` to generate data for S3. The file -`parquet.row-group-rows`, beside the `parquet` directory, records the row groups of its files. -`data-gen` removes and generates again Parquet whose row groups are different or not recorded, and -the formats converted from it. SpatialBench keeps its `zone` files, which come from outside, and -writes the rest again. +## Parquet layout + +All Parquet the benchmarks generate uses the same writer settings, `parquet_writer_properties` in +`src/utils/parquet.rs`: zstd level 3, 64 KiB dictionaries, a page index, and pages of at most 1 MiB +and about 20,000 rows. Only the row groups differ. TPC-H, TPC-DS, nested TPC-H, JOB, Polar Signals, +and SpatialBench write Parquet in row groups of 122,880 rows, DuckDB's default. In our tests, these +smaller row groups were faster from local disk, because they give the query engines more units of +work to run in parallel. The benchmarks that read from S3 use row groups of 1,048,576 rows, +parquet-rs's default, which need fewer requests to object storage. Pass `--opt +row-group-rows=1048576` to `data-gen` to generate data for S3. The file `parquet.layout`, beside the +`parquet` directory, records the layout of its files: the row groups, and a version of the other +writer settings. `data-gen` removes and generates again Parquet whose layout is different or not +recorded, and the formats converted from it. SpatialBench keeps its `zone` files, which come from +outside, and writes the rest again. ## Memory allocators diff --git a/vortex-bench/src/datasets/feature_vectors.rs b/vortex-bench/src/datasets/feature_vectors.rs index d1aae6dfe78..afe7ebaf739 100644 --- a/vortex-bench/src/datasets/feature_vectors.rs +++ b/vortex-bench/src/datasets/feature_vectors.rs @@ -90,7 +90,7 @@ pub async fn feature_vectors_parquet() -> Result { let mut writer = ArrowWriter::try_new( file, Arc::clone(&schema), - Some(random_access_writer_properties()?), + Some(random_access_writer_properties()), )?; let mut rng = StdRng::seed_from_u64(42); diff --git a/vortex-bench/src/datasets/nested_lists.rs b/vortex-bench/src/datasets/nested_lists.rs index 05a8a9690dd..b5312d1bdf1 100644 --- a/vortex-bench/src/datasets/nested_lists.rs +++ b/vortex-bench/src/datasets/nested_lists.rs @@ -86,7 +86,7 @@ pub async fn nested_lists_parquet() -> Result { let mut writer = ArrowWriter::try_new( file, Arc::clone(&schema), - Some(random_access_writer_properties()?), + Some(random_access_writer_properties()), )?; let mut rng = StdRng::seed_from_u64(42); diff --git a/vortex-bench/src/datasets/nested_structs.rs b/vortex-bench/src/datasets/nested_structs.rs index 4ebe6493cd8..b29e671c6ad 100644 --- a/vortex-bench/src/datasets/nested_structs.rs +++ b/vortex-bench/src/datasets/nested_structs.rs @@ -101,7 +101,7 @@ pub async fn nested_structs_parquet() -> Result { let mut writer = ArrowWriter::try_new( file, Arc::clone(&schema), - Some(random_access_writer_properties()?), + Some(random_access_writer_properties()), )?; let mut rng = StdRng::seed_from_u64(42); diff --git a/vortex-bench/src/datasets/sparse_wide.rs b/vortex-bench/src/datasets/sparse_wide.rs index a0b7229518c..07f52995e72 100644 --- a/vortex-bench/src/datasets/sparse_wide.rs +++ b/vortex-bench/src/datasets/sparse_wide.rs @@ -13,9 +13,6 @@ use arrow_array::cast::AsArray; use arrow_schema::Field; use async_trait::async_trait; use parquet::arrow::ArrowWriter; -use parquet::basic::Compression; -use parquet::basic::ZstdLevel; -use parquet::file::properties::WriterProperties; use rand::RngExt; use rand::SeedableRng; use rand::rngs::StdRng; @@ -39,6 +36,7 @@ use crate::IdempotentPath; use crate::SESSION; use crate::datasets::Dataset; use crate::idempotent_async; +use crate::utils::parquet::parquet_writer_properties; /// Synthetic sparse-wide workloads in the compression benchmark's CPU suite. #[derive(Clone, Copy)] @@ -187,9 +185,7 @@ fn write_parquet(path: &Path, array: ArrayRef, ctx: &mut ExecutionCtx) -> Result let root = Field::new_struct("", schema.fields, false); let arrow = array.execute_arrow(Some(&root), ctx)?; let batch = RecordBatch::from(arrow.as_struct()); - let properties = WriterProperties::builder() - .set_compression(Compression::ZSTD(ZstdLevel::try_new(3)?)) - .build(); + let properties = parquet_writer_properties().build(); let mut writer = ArrowWriter::try_new(File::create(path)?, batch.schema(), Some(properties))?; writer.write(&batch)?; writer.close()?; diff --git a/vortex-bench/src/random_access/mod.rs b/vortex-bench/src/random_access/mod.rs index c09b3f5cc4f..082a4c6e358 100644 --- a/vortex-bench/src/random_access/mod.rs +++ b/vortex-bench/src/random_access/mod.rs @@ -17,9 +17,6 @@ use object_store::aws::AmazonS3Builder; use object_store::path::Path as ObjectStorePath; use parquet::arrow::ArrowWriter; use parquet::arrow::arrow_reader::ParquetRecordBatchReaderBuilder; -use parquet::basic::Compression; -use parquet::basic::ZstdLevel; -use parquet::file::properties::EnabledStatistics; use parquet::file::properties::WriterProperties; use url::Url; use vortex::array::ArrayRef; @@ -27,6 +24,8 @@ use vortex::array::ArrayRef; use crate::Format; use crate::data_dir; use crate::idempotent; +use crate::utils::parquet::S3_ROW_GROUP_ROWS; +use crate::utils::parquet::parquet_writer_properties; pub mod take; @@ -85,25 +84,14 @@ pub fn parquet_to_arrow_file(parquet_path: PathBuf, arrow_path: String) -> Resul }) } -/// Parquet writer properties for every random-access dataset, the taxi data included. -/// -/// Compression is zstd level 3, like every other benchmark data generator; parquet-rs would -/// otherwise write these files uncompressed. The other settings are parquet-rs's defaults, set -/// here so that a change of default cannot change the benchmark: -/// -/// - Page statistics, so each file has a page index: the column index and the offset index. With -/// the offset index, a lookup fetches and decodes only the pages that hold the requested rows. -/// - Data pages of at most 1 MiB and about 20,000 rows, so a lookup decodes a small page. -/// parquet-rs checks the row limit after every 1,024 rows, so full pages hold 20,480 rows. -/// - Row groups of at most 1,048,576 rows. -pub fn random_access_writer_properties() -> Result { - Ok(WriterProperties::builder() - .set_compression(Compression::ZSTD(ZstdLevel::try_new(3)?)) - .set_statistics_enabled(EnabledStatistics::Page) - .set_data_page_row_count_limit(20_000) - .set_data_page_size_limit(1024 * 1024) - .set_max_row_group_row_count(Some(1024 * 1024)) - .build()) +/// Writer properties for every random-access dataset, the taxi data included: the shared +/// [`parquet_writer_properties`], whose page index and small pages let a lookup read only the +/// pages that hold its rows, in row groups of [`S3_ROW_GROUP_ROWS`]. The row groups are the S3 +/// size on local disk too, because the S3 job reads the files that the local job prepares. +pub fn random_access_writer_properties() -> WriterProperties { + parquet_writer_properties() + .set_max_row_group_row_count(Some(S3_ROW_GROUP_ROWS)) + .build() } /// Write the Parquet file `input` again with [`random_access_writer_properties`]. @@ -115,7 +103,7 @@ pub fn write_random_access_parquet(input: &Path, output: &Path) -> Result<()> { let mut writer = ArrowWriter::try_new( File::create(output)?, reader.schema(), - Some(random_access_writer_properties()?), + Some(random_access_writer_properties()), )?; for batch in reader { writer.write(&batch?)?; @@ -227,8 +215,11 @@ pub trait RandomAccessor: Send + Sync { #[cfg(test)] mod tests { use arrow_array::Int64Array; + use parquet::basic::Compression; + use parquet::basic::ZstdLevel; use parquet::file::metadata::PageIndexPolicy; use parquet::file::metadata::ParquetMetaDataReader; + use parquet::file::properties::EnabledStatistics; use super::*; @@ -318,7 +309,7 @@ mod tests { #[test] fn generated_parquet_is_zstd_level_3() -> Result<()> { - let props = random_access_writer_properties()?; + let props = random_access_writer_properties(); assert_eq!( props.compression(&"embedding".into()), Compression::ZSTD(ZstdLevel::try_new(3)?) diff --git a/vortex-bench/src/spatialbench/datagen/wkb.rs b/vortex-bench/src/spatialbench/datagen/wkb.rs index d7b53c626bf..7a851001a9e 100644 --- a/vortex-bench/src/spatialbench/datagen/wkb.rs +++ b/vortex-bench/src/spatialbench/datagen/wkb.rs @@ -23,6 +23,7 @@ use spatialbench_arrow::TripArrow; use spatialbench_parquet::arrow::AsyncArrowWriter; use spatialbench_parquet::basic::Compression; use spatialbench_parquet::basic::ZstdLevel; +use spatialbench_parquet::file::properties::EnabledStatistics; use spatialbench_parquet::file::properties::WriterProperties; use spatialbench_parquet::format::KeyValue; use tokio::fs::File as TokioFile; @@ -32,6 +33,8 @@ use tracing::info; use super::table::Table; use crate::Format; use crate::utils::file::idempotent_async; +use crate::utils::parquet::DATA_PAGE_ROW_COUNT_LIMIT; +use crate::utils::parquet::DATA_PAGE_SIZE_LIMIT; use crate::utils::parquet::DICTIONARY_PAGE_SIZE_LIMIT; use crate::utils::parquet::LOCAL_ROW_GROUP_ROWS; @@ -100,7 +103,9 @@ pub async fn generate_tables(scale_factor: &str, output_dir: PathBuf) -> Result< let props = WriterProperties::builder() .set_compression(Compression::ZSTD(ZstdLevel::try_new(3)?)) .set_dictionary_page_size_limit(DICTIONARY_PAGE_SIZE_LIMIT) - .set_data_page_row_count_limit(usize::MAX) + .set_statistics_enabled(EnabledStatistics::Page) + .set_data_page_size_limit(DATA_PAGE_SIZE_LIMIT) + .set_data_page_row_count_limit(DATA_PAGE_ROW_COUNT_LIMIT) .set_max_row_group_size(LOCAL_ROW_GROUP_ROWS) .build(); let mut writer = AsyncArrowWriter::try_new(file, schema, Some(props))?; diff --git a/vortex-bench/src/utils/parquet.rs b/vortex-bench/src/utils/parquet.rs index 6edce35a91d..d130cab03dd 100644 --- a/vortex-bench/src/utils/parquet.rs +++ b/vortex-bench/src/utils/parquet.rs @@ -11,6 +11,7 @@ use parquet::basic::Compression; use parquet::basic::ZstdLevel; use parquet::file::metadata::ParquetMetaData; use parquet::file::metadata::ParquetMetaDataReader; +use parquet::file::properties::EnabledStatistics; use parquet::file::properties::WriterProperties; use parquet::file::properties::WriterPropertiesBuilder; use tracing::info; @@ -28,29 +29,54 @@ pub const S3_ROW_GROUP_ROWS: usize = 1024 * 1024; /// limit approximates the per-column choice that DuckDB's writer makes. pub const DICTIONARY_PAGE_SIZE_LIMIT: usize = 64 * 1024; -/// Writer settings for generated benchmark Parquet: zstd level 3, pages bounded by bytes only, -/// and small dictionaries. +/// Most rows in a data page: parquet-rs's default. parquet-rs checks it after every 1,024 rows, so +/// full pages hold 20,480 rows. +pub const DATA_PAGE_ROW_COUNT_LIMIT: usize = 20_000; + +/// Most bytes in a data page: parquet-rs's default. +pub const DATA_PAGE_SIZE_LIMIT: usize = 1024 * 1024; + +/// The version of the layout that [`parquet_writer_properties`] writes. Raise it when a setting +/// changes, so that [`prepare_parquet_dir`] removes local data in the old layout. +const LAYOUT_VERSION: u32 = 2; + +/// Writer settings for all Parquet that the benchmarks generate: +/// +/// - zstd level 3. parquet-rs's default is no compression. +/// - Dictionaries of at most [`DICTIONARY_PAGE_SIZE_LIMIT`]. +/// - Page statistics, so each file has a page index: the column index and the offset index. With +/// the offset index, a point lookup fetches and decodes only the pages that hold its rows. +/// - Data pages of at most [`DATA_PAGE_SIZE_LIMIT`] and about [`DATA_PAGE_ROW_COUNT_LIMIT`] rows. /// -/// Row group size is left to the caller. +/// The page settings are parquet-rs's defaults, set here so that a change of default cannot change +/// the benchmarks. Against pages bounded by bytes only, the row limit made random access lookups +/// up to 4 times faster, and cost no space or scan time on TPC-H SF10. +/// +/// Row group size is left to the caller: [`LOCAL_ROW_GROUP_ROWS`] or [`S3_ROW_GROUP_ROWS`]. pub fn parquet_writer_properties() -> WriterPropertiesBuilder { WriterProperties::builder() .set_compression(Compression::ZSTD( ZstdLevel::try_new(3).unwrap_or_else(|_| unreachable!("3 is a valid zstd level")), )) .set_dictionary_page_size_limit(DICTIONARY_PAGE_SIZE_LIMIT) - // The default 20,000-row page limit splits row groups into many small pages, which gives - // zstd too little context to compress repeating columns. - .set_data_page_row_count_limit(usize::MAX) + .set_statistics_enabled(EnabledStatistics::Page) + .set_data_page_size_limit(DATA_PAGE_SIZE_LIMIT) + .set_data_page_row_count_limit(DATA_PAGE_ROW_COUNT_LIMIT) +} + +/// The text of the marker beside a `parquet` directory for row groups of `row_group_rows` rows. +fn layout(row_group_rows: usize) -> String { + format!("layout {LAYOUT_VERSION}, row groups of {row_group_rows} rows\n") } /// Make `parquet_dir` ready for generated Parquet in row groups of `row_group_rows` rows. /// -/// The generators do not write a file that exists, so Parquet generated before with other row -/// groups would stay. A marker file beside the directory, `parquet.row-group-rows`, records the -/// row groups its files have. If the directory exists and the marker is missing or records another -/// size, this removes it, so that the generator writes it again. It also removes the other format -/// directories beside it, such as `vortex-file-compressed`, because they were converted from the -/// old Parquet and their conversions skip files that exist. +/// The generators do not write a file that exists, so Parquet generated before in another layout +/// would stay. A marker file beside the directory, `parquet.layout`, records the layout of its +/// files: the [`LAYOUT_VERSION`] and the row groups. If the directory exists and the marker is +/// missing or records another layout, this removes it, so that the generator writes it again. It +/// also removes the other format directories beside it, such as `vortex-file-compressed`, because +/// they were converted from the old Parquet and their conversions skip files that exist. pub fn prepare_parquet_dir(parquet_dir: &Path, row_group_rows: usize) -> anyhow::Result<()> { prepare_parquet_dir_keeping(parquet_dir, row_group_rows, |_| false) } @@ -62,17 +88,17 @@ pub fn prepare_parquet_dir_keeping( row_group_rows: usize, keep: impl Fn(&Path) -> bool, ) -> anyhow::Result<()> { - let marker = parquet_dir.with_extension("row-group-rows"); - let recorded = fs::read_to_string(&marker) - .ok() - .and_then(|text| text.trim().parse::().ok()); - if parquet_dir.exists() && recorded != Some(row_group_rows) { + let marker = parquet_dir.with_extension("layout"); + let layout = layout(row_group_rows); + let recorded = fs::read_to_string(&marker).ok(); + if parquet_dir.exists() && recorded.as_deref() != Some(layout.as_str()) { let data_dir = parquet_dir .parent() .ok_or_else(|| anyhow::anyhow!("{} has no parent", parquet_dir.display()))?; info!( - "Removing the data in {}: its Parquet row groups are not {row_group_rows} rows", - data_dir.display() + "Removing the data in {}: its Parquet layout is not {}", + data_dir.display(), + layout.trim() ); for entry in fs::read_dir(data_dir)? { let path = entry?.path(); @@ -93,7 +119,7 @@ pub fn prepare_parquet_dir_keeping( } } fs::create_dir_all(parquet_dir)?; - fs::write(&marker, row_group_rows.to_string())?; + fs::write(&marker, layout)?; Ok(()) } @@ -160,8 +186,8 @@ mod tests { assert!(parquet_dir.exists()); assert!(!file.exists()); assert_eq!( - fs::read_to_string(base.path().join("parquet.row-group-rows"))?, - S3_ROW_GROUP_ROWS.to_string() + fs::read_to_string(base.path().join("parquet.layout"))?, + layout(S3_ROW_GROUP_ROWS) ); Ok(()) } From ae74dc45eddf03c03b639140be9f343cbb8e7941 Mon Sep 17 00:00:00 2001 From: Will Manning Date: Sat, 21 Nov 2026 14:32:46 -0500 Subject: [PATCH 35/44] Record the Parquet layout version in each generated file Each file that parquet_writer_properties() writes now records LAYOUT_VERSION in its file metadata. The random access generators remove a cached file without the current version before they skip existing files, and the SpatialBench zone rewrite rewrites a zone file without it, so a settings change reaches files that no directory marker covers. Also make LAYOUT_VERSION public: a public doc comment links to it, which failed the docs build. Signed-off-by: Will Manning --- vortex-bench/src/conversions.rs | 47 ++++++++++++--- vortex-bench/src/datasets/feature_vectors.rs | 3 + vortex-bench/src/datasets/nested_lists.rs | 3 + vortex-bench/src/datasets/nested_structs.rs | 3 + vortex-bench/src/datasets/taxi_data.rs | 5 +- vortex-bench/src/spatialbench/datagen/wkb.rs | 6 ++ vortex-bench/src/utils/parquet.rs | 62 +++++++++++++++++++- 7 files changed, 118 insertions(+), 11 deletions(-) diff --git a/vortex-bench/src/conversions.rs b/vortex-bench/src/conversions.rs index c2091e40a73..6ab0e956be8 100644 --- a/vortex-bench/src/conversions.rs +++ b/vortex-bench/src/conversions.rs @@ -73,6 +73,7 @@ use crate::Format; use crate::SESSION; use crate::utils::file::idempotent_async; use crate::utils::parquet::LOCAL_ROW_GROUP_ROWS; +use crate::utils::parquet::has_current_layout; use crate::utils::parquet::is_zstd; use crate::utils::parquet::parquet_writer_properties; @@ -432,8 +433,8 @@ pub async fn write_parquet_as_vortex( /// Add GeoParquet `geo` file metadata to externally-sourced parquet we don't generate (e.g. SpatialBench `zone`). /// /// The file is rewritten with the shared Parquet settings, in local row groups, unless it already -/// has the metadata, zstd, and no row group larger than a local one. So a file tagged before the -/// benchmarks wrote zstd or local row groups is written again too. +/// has the metadata, zstd, no row group larger than a local one, and the current layout version. +/// So a file tagged before a change of the shared settings is written again too. pub async fn add_geoparquet_metadata( parquet_path: &Path, geoparquet_json: &str, @@ -448,7 +449,7 @@ pub async fn add_geoparquet_metadata( .row_groups() .iter() .all(|row_group| row_group.num_rows() <= LOCAL_ROW_GROUP_ROWS as i64); - if already_tagged && is_zstd(metadata) && local_row_groups { + if already_tagged && is_zstd(metadata) && local_row_groups && has_current_layout(metadata) { return Ok(()); } @@ -597,6 +598,8 @@ mod tests { use parquet::file::reader::SerializedFileReader; use super::*; + use crate::utils::parquet::LAYOUT_KEY; + use crate::utils::parquet::LAYOUT_VERSION; #[tokio::test] async fn geoparquet_tagging_rewrites_an_uncompressed_file_with_zstd() -> anyhow::Result<()> { @@ -632,13 +635,13 @@ mod tests { Arc::clone(&schema), vec![Arc::new(Int64Array::from_iter_values(0..200_000))], )?; - // Tagged and zstd, but in one row group larger than a local one. + // Tagged, zstd, and in the current layout, but in one row group larger than a local one. let props = parquet_writer_properties() .set_max_row_group_row_count(Some(1024 * 1024)) - .set_key_value_metadata(Some(vec![KeyValue::new( - "geo".to_string(), - Some("{}".to_string()), - )])) + .set_key_value_metadata(Some(vec![ + KeyValue::new("geo".to_string(), Some("{}".to_string())), + KeyValue::new(LAYOUT_KEY.to_string(), LAYOUT_VERSION.to_string()), + ])) .build(); let mut writer = ArrowWriter::try_new(fs::File::create(&path)?, schema, Some(props))?; writer.write(&batch)?; @@ -657,6 +660,34 @@ mod tests { Ok(()) } + #[tokio::test] + async fn geoparquet_tagging_rewrites_a_file_in_an_old_layout() -> anyhow::Result<()> { + let dir = tempfile::tempdir()?; + let path = dir.path().join("zone.parquet"); + let schema = Arc::new(Schema::new(vec![Field::new("id", DataType::Int64, false)])); + let batch = RecordBatch::try_new( + Arc::clone(&schema), + vec![Arc::new(Int64Array::from_iter_values(0..1000))], + )?; + // Tagged, zstd, and in local row groups, but with no layout version. + let props = parquet_writer_properties() + .set_max_row_group_row_count(Some(LOCAL_ROW_GROUP_ROWS)) + .set_key_value_metadata(Some(vec![KeyValue::new( + "geo".to_string(), + Some("{}".to_string()), + )])) + .build(); + let mut writer = ArrowWriter::try_new(fs::File::create(&path)?, schema, Some(props))?; + writer.write(&batch)?; + writer.close()?; + + add_geoparquet_metadata(&path, "{}").await?; + + let reader = SerializedFileReader::new(fs::File::open(&path)?)?; + assert!(has_current_layout(reader.metadata())); + Ok(()) + } + #[tokio::test] async fn geoparquet_tagging_recompresses_a_tagged_uncompressed_file() -> anyhow::Result<()> { let dir = tempfile::tempdir()?; diff --git a/vortex-bench/src/datasets/feature_vectors.rs b/vortex-bench/src/datasets/feature_vectors.rs index afe7ebaf739..3eebc867be7 100644 --- a/vortex-bench/src/datasets/feature_vectors.rs +++ b/vortex-bench/src/datasets/feature_vectors.rs @@ -21,12 +21,14 @@ use rand::rngs::StdRng; use crate::CompactionStrategy; use crate::Format; +use crate::IdempotentPath; use crate::conversions::write_parquet_as_vortex; use crate::idempotent_async; use crate::random_access::BenchDataset; use crate::random_access::data_path; use crate::random_access::parquet_to_arrow_file; use crate::random_access::random_access_writer_properties; +use crate::utils::parquet::remove_stale_parquet; /// Dataset identifier used for data path generation. pub const DATASET: &str = "feature_vectors"; @@ -71,6 +73,7 @@ const BATCH_SIZE: usize = 100_000; /// Schema: `id: Int64, embedding: FixedSizeList`. /// This simulates a table of embedding vectors, common in ML workloads. pub async fn feature_vectors_parquet() -> Result { + remove_stale_parquet(&data_path(DATASET, Format::Parquet).to_data_path())?; idempotent_async( data_path(DATASET, Format::Parquet), |temp_path| async move { diff --git a/vortex-bench/src/datasets/nested_lists.rs b/vortex-bench/src/datasets/nested_lists.rs index b5312d1bdf1..96b9cfdeae1 100644 --- a/vortex-bench/src/datasets/nested_lists.rs +++ b/vortex-bench/src/datasets/nested_lists.rs @@ -20,12 +20,14 @@ use rand::rngs::StdRng; use crate::CompactionStrategy; use crate::Format; +use crate::IdempotentPath; use crate::conversions::write_parquet_as_vortex; use crate::idempotent_async; use crate::random_access::BenchDataset; use crate::random_access::data_path; use crate::random_access::parquet_to_arrow_file; use crate::random_access::random_access_writer_properties; +use crate::utils::parquet::remove_stale_parquet; /// Dataset identifier used for data path generation. pub const DATASET: &str = "nested_lists"; @@ -70,6 +72,7 @@ const BATCH_SIZE: usize = 100_000; /// Schema: `id: Int64, values: List`. /// Each row contains a variable-length list of 1 to 20 random integers. pub async fn nested_lists_parquet() -> Result { + remove_stale_parquet(&data_path(DATASET, Format::Parquet).to_data_path())?; idempotent_async( data_path(DATASET, Format::Parquet), |temp_path| async move { diff --git a/vortex-bench/src/datasets/nested_structs.rs b/vortex-bench/src/datasets/nested_structs.rs index b29e671c6ad..d5ebf246b7f 100644 --- a/vortex-bench/src/datasets/nested_structs.rs +++ b/vortex-bench/src/datasets/nested_structs.rs @@ -21,12 +21,14 @@ use rand::rngs::StdRng; use crate::CompactionStrategy; use crate::Format; +use crate::IdempotentPath; use crate::conversions::write_parquet_as_vortex; use crate::idempotent_async; use crate::random_access::BenchDataset; use crate::random_access::data_path; use crate::random_access::parquet_to_arrow_file; use crate::random_access::random_access_writer_properties; +use crate::utils::parquet::remove_stale_parquet; /// Dataset identifier used for data path generation. pub const DATASET: &str = "nested_structs"; @@ -79,6 +81,7 @@ const BATCH_SIZE: usize = 100_000; /// } /// ``` pub async fn nested_structs_parquet() -> Result { + remove_stale_parquet(&data_path(DATASET, Format::Parquet).to_data_path())?; idempotent_async( data_path(DATASET, Format::Parquet), |temp_path| async move { diff --git a/vortex-bench/src/datasets/taxi_data.rs b/vortex-bench/src/datasets/taxi_data.rs index 3238b47451b..af562b251dc 100644 --- a/vortex-bench/src/datasets/taxi_data.rs +++ b/vortex-bench/src/datasets/taxi_data.rs @@ -27,6 +27,7 @@ use crate::random_access::BenchDataset; use crate::random_access::data_path; use crate::random_access::parquet_to_arrow_file; use crate::random_access::write_random_access_parquet; +use crate::utils::parquet::remove_stale_parquet; /// Dataset identifier used for data path generation. pub const DATASET: &str = "taxi"; @@ -88,7 +89,9 @@ pub async fn taxi_data_parquet() -> Result { pub async fn taxi_random_access_parquet() -> Result { let published = taxi_data_parquet().await?; tokio::task::spawn_blocking(move || { - idempotent(&data_path(DATASET, Format::Parquet), |output| { + let path = data_path(DATASET, Format::Parquet); + remove_stale_parquet(&path.to_data_path())?; + idempotent(&path, |output| { write_random_access_parquet(&published, output) }) }) diff --git a/vortex-bench/src/spatialbench/datagen/wkb.rs b/vortex-bench/src/spatialbench/datagen/wkb.rs index 7a851001a9e..6231b895a0b 100644 --- a/vortex-bench/src/spatialbench/datagen/wkb.rs +++ b/vortex-bench/src/spatialbench/datagen/wkb.rs @@ -36,6 +36,8 @@ use crate::utils::file::idempotent_async; use crate::utils::parquet::DATA_PAGE_ROW_COUNT_LIMIT; use crate::utils::parquet::DATA_PAGE_SIZE_LIMIT; use crate::utils::parquet::DICTIONARY_PAGE_SIZE_LIMIT; +use crate::utils::parquet::LAYOUT_KEY; +use crate::utils::parquet::LAYOUT_VERSION; use crate::utils::parquet::LOCAL_ROW_GROUP_ROWS; /// Batch size matching the TPC-H generator's streaming batches. @@ -107,6 +109,10 @@ pub async fn generate_tables(scale_factor: &str, output_dir: PathBuf) -> Result< .set_data_page_size_limit(DATA_PAGE_SIZE_LIMIT) .set_data_page_row_count_limit(DATA_PAGE_ROW_COUNT_LIMIT) .set_max_row_group_size(LOCAL_ROW_GROUP_ROWS) + .set_key_value_metadata(Some(vec![KeyValue::new( + LAYOUT_KEY.to_string(), + LAYOUT_VERSION.to_string(), + )])) .build(); let mut writer = AsyncArrowWriter::try_new(file, schema, Some(props))?; for batch in iter { diff --git a/vortex-bench/src/utils/parquet.rs b/vortex-bench/src/utils/parquet.rs index d130cab03dd..0a95d574f6a 100644 --- a/vortex-bench/src/utils/parquet.rs +++ b/vortex-bench/src/utils/parquet.rs @@ -9,6 +9,7 @@ use std::path::Path; use parquet::basic::Compression; use parquet::basic::ZstdLevel; +use parquet::file::metadata::KeyValue; use parquet::file::metadata::ParquetMetaData; use parquet::file::metadata::ParquetMetaDataReader; use parquet::file::properties::EnabledStatistics; @@ -37,8 +38,13 @@ pub const DATA_PAGE_ROW_COUNT_LIMIT: usize = 20_000; pub const DATA_PAGE_SIZE_LIMIT: usize = 1024 * 1024; /// The version of the layout that [`parquet_writer_properties`] writes. Raise it when a setting -/// changes, so that [`prepare_parquet_dir`] removes local data in the old layout. -const LAYOUT_VERSION: u32 = 2; +/// changes, so that local data in the old layout is generated again: [`prepare_parquet_dir`] +/// removes a directory in the old layout, and [`remove_stale_parquet`] removes a file. +pub const LAYOUT_VERSION: u32 = 2; + +/// The key of the file metadata entry in which each generated Parquet file records the +/// [`LAYOUT_VERSION`] it was written in. +pub const LAYOUT_KEY: &str = "vortex_bench_layout"; /// Writer settings for all Parquet that the benchmarks generate: /// @@ -47,6 +53,8 @@ const LAYOUT_VERSION: u32 = 2; /// - Page statistics, so each file has a page index: the column index and the offset index. With /// the offset index, a point lookup fetches and decodes only the pages that hold its rows. /// - Data pages of at most [`DATA_PAGE_SIZE_LIMIT`] and about [`DATA_PAGE_ROW_COUNT_LIMIT`] rows. +/// - The [`LAYOUT_VERSION`] in the file metadata, under [`LAYOUT_KEY`]. A caller that sets its own +/// key-value metadata on the builder replaces it, so append other entries to the writer instead. /// /// The page settings are parquet-rs's defaults, set here so that a change of default cannot change /// the benchmarks. Against pages bounded by bytes only, the row limit made random access lookups @@ -62,6 +70,40 @@ pub fn parquet_writer_properties() -> WriterPropertiesBuilder { .set_statistics_enabled(EnabledStatistics::Page) .set_data_page_size_limit(DATA_PAGE_SIZE_LIMIT) .set_data_page_row_count_limit(DATA_PAGE_ROW_COUNT_LIMIT) + .set_key_value_metadata(Some(vec![KeyValue::new( + LAYOUT_KEY.to_string(), + LAYOUT_VERSION.to_string(), + )])) +} + +/// Return whether `metadata` records the current [`LAYOUT_VERSION`]. +pub fn has_current_layout(metadata: &ParquetMetaData) -> bool { + let version = LAYOUT_VERSION.to_string(); + metadata + .file_metadata() + .key_value_metadata() + .is_some_and(|kvs| { + kvs.iter() + .any(|kv| kv.key == LAYOUT_KEY && kv.value.as_deref() == Some(version.as_str())) + }) +} + +/// Remove the generated Parquet file at `path` if it exists and does not record the current +/// [`LAYOUT_VERSION`], so that its generator, which skips a file that exists, writes it again. It +/// reads only the footer. +pub fn remove_stale_parquet(path: &Path) -> anyhow::Result<()> { + let Ok(file) = File::open(path) else { + return Ok(()); + }; + let metadata = ParquetMetaDataReader::new().parse_and_finish(&file)?; + if !has_current_layout(&metadata) { + info!( + "Removing {}: it was not written in Parquet layout {LAYOUT_VERSION}", + path.display() + ); + fs::remove_file(path)?; + } + Ok(()) } /// The text of the marker beside a `parquet` directory for row groups of `row_group_rows` rows. @@ -160,6 +202,22 @@ mod tests { Ok(()) } + #[test] + fn parquet_in_an_old_layout_is_removed() -> anyhow::Result<()> { + let dir = tempfile::tempdir()?; + let old = dir.path().join("old.parquet"); + let current = dir.path().join("current.parquet"); + write(&old, Some(WriterProperties::builder().build()))?; + write(¤t, Some(parquet_writer_properties().build()))?; + + remove_stale_parquet(&old)?; + remove_stale_parquet(¤t)?; + remove_stale_parquet(&dir.path().join("missing.parquet"))?; + assert!(!old.exists()); + assert!(current.exists()); + Ok(()) + } + #[test] fn parquet_with_other_row_groups_is_generated_again() -> anyhow::Result<()> { let base = tempfile::tempdir()?; From 6872cb4e9dea7b471a5bc695c9b668bf141a69fc Mon Sep 17 00:00:00 2001 From: Will Manning Date: Sat, 21 Nov 2026 14:50:20 -0500 Subject: [PATCH 36/44] Generate cached benchmark Parquet again in a new layout sparse-wide, the TPC-H l_comment file, string-bench's Hugging Face columns, and statpopgen's gnomAD file skip a Parquet file that exists. Each now removes a file that does not record the current layout version first, so a change to the shared writer settings reaches them too. statpopgen's zstd check is replaced: a file without zstd also lacks the stamp. Signed-off-by: Will Manning --- benchmarks/string-bench/src/lib.rs | 7 +++++-- vortex-bench/src/datasets/sparse_wide.rs | 2 ++ vortex-bench/src/datasets/tpch_l_comment.rs | 8 +++++--- vortex-bench/src/statpopgen/download_vcf.rs | 8 +++----- 4 files changed, 15 insertions(+), 10 deletions(-) diff --git a/benchmarks/string-bench/src/lib.rs b/benchmarks/string-bench/src/lib.rs index 96c61ece349..d33e530d0eb 100644 --- a/benchmarks/string-bench/src/lib.rs +++ b/benchmarks/string-bench/src/lib.rs @@ -56,6 +56,7 @@ use vortex_bench::datasets::tpch_l_comment::TPCHLCommentCanonical; use vortex_bench::enable_unstable_encodings; use vortex_bench::idempotent_async; use vortex_bench::utils::parquet::parquet_writer_properties; +use vortex_bench::utils::parquet::remove_stale_parquet; use vortex_cloud::hf::make_hf_store_from_url; use vortex_fsst::FSST; use vortex_onpair::Config; @@ -436,10 +437,12 @@ pub async fn load_hf_column(source: &HfColumn, ctx: &mut ExecutionCtx) -> Result /// Read `source`'s rows over HTTP and cache just that column as a local /// zstd-compressed parquet file under `vortex-bench/data/string-bench/`. /// -/// The cache file is named after the column, so changing a source's URL or row -/// cap needs the stale file deleted. +/// A cache file in an older Parquet layout is written again. The cache file is +/// named after the column, so changing a source's URL or row cap still needs the +/// stale file deleted. async fn cache_hf_column(source: &HfColumn) -> Result { let cache_path = format!("string-bench/{}.parquet", source.name.replace('/', "_")); + remove_stale_parquet(&cache_path.to_data_path())?; idempotent_async(cache_path, |tmp| async move { let (store, path) = make_hf_store_from_url(&Url::parse(source.url)?)?; let builder = ParquetRecordBatchStreamBuilder::new(ObjectReader::new(store, path)).await?; diff --git a/vortex-bench/src/datasets/sparse_wide.rs b/vortex-bench/src/datasets/sparse_wide.rs index 07f52995e72..1e3c3354226 100644 --- a/vortex-bench/src/datasets/sparse_wide.rs +++ b/vortex-bench/src/datasets/sparse_wide.rs @@ -37,6 +37,7 @@ use crate::SESSION; use crate::datasets::Dataset; use crate::idempotent_async; use crate::utils::parquet::parquet_writer_properties; +use crate::utils::parquet::remove_stale_parquet; /// Synthetic sparse-wide workloads in the compression benchmark's CPU suite. #[derive(Clone, Copy)] @@ -171,6 +172,7 @@ impl Dataset for SparseWide { async fn to_parquet_path(&self) -> Result { let path = format!("sparse_wide/v1/{}.parquet", self.name()).to_data_path(); + remove_stale_parquet(&path)?; idempotent_async(path, |temp_path| async move { let mut ctx = SESSION.create_execution_ctx(); let array = self.to_vortex_array(&mut ctx).await?; diff --git a/vortex-bench/src/datasets/tpch_l_comment.rs b/vortex-bench/src/datasets/tpch_l_comment.rs index 8b1c41596fc..40817876e8c 100644 --- a/vortex-bench/src/datasets/tpch_l_comment.rs +++ b/vortex-bench/src/datasets/tpch_l_comment.rs @@ -24,11 +24,13 @@ use vortex::expr::pack; use vortex::file::OpenOptionsSessionExt; use crate::Format; +use crate::IdempotentPath; use crate::SESSION; use crate::datasets::Dataset; use crate::datasets::tpch_sf1::TpchSf1Table; use crate::idempotent; use crate::utils::parquet::parquet_writer_properties; +use crate::utils::parquet::remove_stale_parquet; pub struct TPCHLCommentChunked; @@ -49,9 +51,9 @@ const L_COMMENT_ROW_GROUP_ROWS: usize = 1024 * 1024; async fn l_comment_parquet() -> Result { let lineitem = ensure_lineitem(Format::Parquet).await?; tokio::task::spawn_blocking(move || { - idempotent(&"tpch-l_comment/1.0/l_comment.parquet", |output| { - write_l_comment(&lineitem, output) - }) + let path = "tpch-l_comment/1.0/l_comment.parquet"; + remove_stale_parquet(&path.to_data_path())?; + idempotent(&path, |output| write_l_comment(&lineitem, output)) }) .await? } diff --git a/vortex-bench/src/statpopgen/download_vcf.rs b/vortex-bench/src/statpopgen/download_vcf.rs index c3788804742..823b1315652 100644 --- a/vortex-bench/src/statpopgen/download_vcf.rs +++ b/vortex-bench/src/statpopgen/download_vcf.rs @@ -38,8 +38,8 @@ use super::StatPopGenBenchmark; use crate::idempotent_async; use crate::statpopgen::builder::GnomADBuilder; use crate::statpopgen::schema::schema_from_vcf_header; -use crate::utils::parquet::is_zstd_file; use crate::utils::parquet::parquet_writer_properties; +use crate::utils::parquet::remove_stale_parquet; // DuckDB parallelizes parquet at row-group granularity. Each of our rows are quite big (~4000 // genotypes each with tens of bytes of data). @@ -57,10 +57,8 @@ impl StatPopGenBenchmark { StatPopGenBenchmark::FILE_NAME ); let parquet_output_path = self.parquet_path()?; - // A file written before the benchmark wrote zstd is written again. - if parquet_output_path.exists() && !is_zstd_file(&parquet_output_path)? { - std::fs::remove_file(&parquet_output_path)?; - } + // A file written in an older Parquet layout is written again. + remove_stale_parquet(&parquet_output_path)?; idempotent_async( &parquet_output_path, From 7c885be3c3fd500a9a158ea4bc68696f176a78a5 Mon Sep 17 00:00:00 2001 From: Will Manning Date: Sat, 21 Nov 2026 14:58:53 -0500 Subject: [PATCH 37/44] Keep the layout version in concatenated TPC-H Parquet The TPC-H generator writes a large table in parts and then joins them into one file. The joining writer started from empty properties, so the file lost the parts' key-value metadata: the layout version and the Arrow schema. It now copies the first part's metadata. Signed-off-by: Will Manning --- vortex-bench/src/tpch/tpchgen.rs | 57 ++++++++++++++++++++++++++++---- 1 file changed, 51 insertions(+), 6 deletions(-) diff --git a/vortex-bench/src/tpch/tpchgen.rs b/vortex-bench/src/tpch/tpchgen.rs index 52fa1405e44..b8f0e01e5be 100644 --- a/vortex-bench/src/tpch/tpchgen.rs +++ b/vortex-bench/src/tpch/tpchgen.rs @@ -421,12 +421,15 @@ fn concat_parquet_parts(parts: &[PathBuf], output: &Path) -> Result<()> { }) .collect::>>()?; - let root_schema = inputs[0].1.file_metadata().schema_descr().root_schema_ptr(); - let mut writer = SerializedFileWriter::new( - fs::File::create(output)?, - root_schema, - Arc::new(WriterProperties::builder().build()), - )?; + let file_metadata = inputs[0].1.file_metadata(); + let root_schema = file_metadata.schema_descr().root_schema_ptr(); + // The parts' key-value metadata holds the Arrow schema and the layout version, which + // `remove_stale_parquet` reads, so the whole file keeps it. + let props = WriterProperties::builder() + .set_key_value_metadata(file_metadata.key_value_metadata().cloned()) + .build(); + let mut writer = + SerializedFileWriter::new(fs::File::create(output)?, root_schema, Arc::new(props))?; for (input, metadata) in &inputs { let column_indexes = metadata.column_index(); @@ -598,3 +601,45 @@ impl FileWriter for VortexWriter { Ok(()) } } + +#[cfg(test)] +mod tests { + use arrow_array::Int64Array; + use parquet::arrow::ARROW_SCHEMA_META_KEY; + + use super::*; + use crate::utils::parquet::has_current_layout; + + #[test] + fn concatenated_parts_keep_the_file_metadata() -> Result<()> { + let dir = tempfile::tempdir()?; + let parts = (0..2) + .map(|part| -> Result { + let path = dir.path().join(format!("t.part{part}")); + let batch = RecordBatch::try_from_iter([( + "x", + Arc::new(Int64Array::from_iter_values(0..1000)) as _, + )])?; + let props = parquet_writer_properties().build(); + let mut writer = + ArrowWriter::try_new(fs::File::create(&path)?, batch.schema(), Some(props))?; + writer.write(&batch)?; + writer.close()?; + Ok(path) + }) + .collect::>>()?; + let output = dir.path().join("t.parquet"); + concat_parquet_parts(&parts, &output)?; + + let metadata = ParquetMetaDataReader::new().parse_and_finish(&fs::File::open(&output)?)?; + assert_eq!(metadata.file_metadata().num_rows(), 2000); + assert!(has_current_layout(&metadata)); + assert!( + metadata + .file_metadata() + .key_value_metadata() + .is_some_and(|kvs| kvs.iter().any(|kv| kv.key == ARROW_SCHEMA_META_KEY)) + ); + Ok(()) + } +} From 644fbb904980533361fb01e9bf5a7f4e9e43a567 Mon Sep 17 00:00:00 2001 From: Will Manning Date: Sat, 21 Nov 2026 14:59:24 -0500 Subject: [PATCH 38/44] Pass S3 row groups to the benchmark run, not only to data generation A fork PR has no AWS credentials, so it runs an S3 entry on local data. The run started the benchmark with the default row groups, which did not match the generated data's marker, so the benchmark removed the data and could not generate it again. Both run steps now pass the entry's row groups. Signed-off-by: Will Manning --- .github/workflows/sql-bench-matrix.yml | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/.github/workflows/sql-bench-matrix.yml b/.github/workflows/sql-bench-matrix.yml index c7b4d8da3ac..d6c27818fc0 100644 --- a/.github/workflows/sql-bench-matrix.yml +++ b/.github/workflows/sql-bench-matrix.yml @@ -256,6 +256,8 @@ jobs: - name: Setup benchmark environment run: sudo bash scripts/setup-benchmark.sh + # The run steps pass the same row groups as "Generate data". A fork PR runs an S3 entry + # here, on local data, and a benchmark that expects other row groups removes that data. - name: Run ${{ matrix.name }} benchmark if: matrix.remote_key == null || github.event.pull_request.head.repo.fork == true shell: bash @@ -272,6 +274,7 @@ jobs: --ingest-jsonl results.ingest.jsonl \ --no-build \ ${{ matrix.iterations && format('--iterations {0}', matrix.iterations) || '' }} \ + ${{ matrix.row_group_rows && format('--opt row-group-rows={0}', matrix.row_group_rows) || '' }} \ ${{ matrix.scale_factor && format('--opt scale-factor={0}', matrix.scale_factor) || '' }} - name: Run ${{ matrix.name }} benchmark (remote) @@ -292,6 +295,7 @@ jobs: --ingest-jsonl results.ingest.jsonl \ --no-build \ ${{ matrix.iterations && format('--iterations {0}', matrix.iterations) || '' }} \ + ${{ matrix.row_group_rows && format('--opt row-group-rows={0}', matrix.row_group_rows) || '' }} \ --opt remote-data-dir="$REMOTE_STORAGE" \ ${{ matrix.scale_factor && format('--opt scale-factor={0}', matrix.scale_factor) || '' }} From c7814a22f5f2517f438910aac96b962133fba0a5 Mon Sep 17 00:00:00 2001 From: Will Manning Date: Sat, 21 Nov 2026 15:14:02 -0500 Subject: [PATCH 39/44] Write parquet-snappy with the same settings as parquet compress-bench recorded parquet-snappy as DuckDB writes Parquet, with DuckDB's row groups, pages, dictionaries, and Bloom filters, so its size differed from parquet's by more than the codec. It now writes the same batches with the same parquet-rs writer and settings as parquet, with Snappy in place of zstd level 3. A test checks that only the codec differs. The DuckDB CLI writer goes away. Signed-off-by: Will Manning --- .github/actions/setup-duckdb/action.yml | 2 +- benchmarks/compress-bench/README.md | 3 +- benchmarks/compress-bench/src/main.rs | 18 +++-- benchmarks/compress-bench/src/parquet.rs | 84 ++++++++++++++++++++---- vortex-bench/src/parquet_copies.rs | 81 +---------------------- 5 files changed, 87 insertions(+), 101 deletions(-) diff --git a/.github/actions/setup-duckdb/action.yml b/.github/actions/setup-duckdb/action.yml index 6d39d077b16..ff033c3f243 100644 --- a/.github/actions/setup-duckdb/action.yml +++ b/.github/actions/setup-duckdb/action.yml @@ -3,7 +3,7 @@ description: "Download the DuckDB CLI and put it on PATH" inputs: duckdb_version: # Keep this on the DuckDB minor version that `vortex-duckdb/build.rs` links (2.0), so the CLI - # that writes `parquet-snappy` and the `duckdb` database matches the DuckDB the queries run on. + # that writes the `duckdb` database matches the DuckDB the queries run on. description: "Version of the DuckDB CLI" default: "2.0.1" runs: diff --git a/benchmarks/compress-bench/README.md b/benchmarks/compress-bench/README.md index c9e3009349c..ba55e7f0337 100644 --- a/benchmarks/compress-bench/README.md +++ b/benchmarks/compress-bench/README.md @@ -10,7 +10,8 @@ without codec cost. Its file size provides the approximately 1x baseline for com ratios. Parquet provides the established reference for a compressed columnar representation. The suite also records the file size of two formats that it does not time: Parquet with Snappy -(`parquet-snappy`), beside the timed Parquet with zstd level 3, and Vortex with the compact +(`parquet-snappy`), written with the same settings as the timed Parquet except for the codec, +which is zstd level 3 in the timed Parquet, and Vortex with the compact strategy (`vortex-compact`), as the SQL benchmarks write it. Each is one write per dataset, and neither runs in GPU mode. bench shows these sizes in its `File Sizes` group. diff --git a/benchmarks/compress-bench/src/main.rs b/benchmarks/compress-bench/src/main.rs index 85f055f0b8d..da9d551215a 100644 --- a/benchmarks/compress-bench/src/main.rs +++ b/benchmarks/compress-bench/src/main.rs @@ -17,7 +17,7 @@ use compress_bench::gpu::GpuOptions; use compress_bench::gpu::compressor as gpu_compressor; use compress_bench::parquet::ParquetCompressor; use compress_bench::parquet::arrow_uncompressed_size; -use compress_bench::parquet::duckdb_snappy_parquet_size; +use compress_bench::parquet::snappy_parquet_size; use compress_bench::vortex::VortexCompressor; use compress_bench::vortex::vortex_compact_size; use futures::FutureExt; @@ -61,8 +61,8 @@ use vortex_bench::setup_logging_and_tracing_with_format; use vortex_bench::statpopgen::StatPopGenBenchmark; use vortex_bench::v3; -/// The size record name of Parquet as DuckDB writes it, with Snappy, beside `parquet`, which is -/// zstd level 3. +/// The size record name of Parquet with Snappy, beside `parquet`, which is zstd level 3. Every +/// other writer setting is the same. const PARQUET_SNAPPY_FORMAT: &str = "parquet-snappy"; #[derive(Parser, Debug)] @@ -461,8 +461,8 @@ async fn run_compress( Ok(()) } -/// Size records of the size-only formats, one untimed write each: DuckDB's Snappy Parquet beside -/// `parquet`, and compact Vortex beside `vortex`. +/// Size records of the size-only formats, one untimed write each: Snappy Parquet beside `parquet`, +/// and compact Vortex beside `vortex`. async fn size_only_records( parquet_path: &Path, formats: &[Format], @@ -473,9 +473,13 @@ async fn size_only_records( ) -> anyhow::Result> { let mut records = Vec::new(); if formats.contains(&Format::Parquet) { - let snappy_size = duckdb_snappy_parquet_size(parquet_path) + let input = get_compressor(Format::Parquet, mode)? + .load(parquet_path) + .await + .with_context(|| format!("loading {bench_name} for Snappy Parquet"))?; + let snappy_size = snappy_parquet_size(&input) .await - .with_context(|| format!("writing {bench_name} as Snappy Parquet with DuckDB"))?; + .with_context(|| format!("writing {bench_name} as Snappy Parquet"))?; records.push(v3::named_compression_size_record( v3_dataset, v3_variant, diff --git a/benchmarks/compress-bench/src/parquet.rs b/benchmarks/compress-bench/src/parquet.rs index a9d9b982e17..28803d3993e 100644 --- a/benchmarks/compress-bench/src/parquet.rs +++ b/benchmarks/compress-bench/src/parquet.rs @@ -37,7 +37,6 @@ use vortex_bench::compress::CompressedData; use vortex_bench::compress::Compressor; use vortex_bench::compress::Uncompressed; use vortex_bench::compress::read_projection; -use vortex_bench::parquet_copies::write_duckdb_snappy_parquet; use vortex_bench::utils::parquet::parquet_writer_properties; /// Compressor implementation for Parquet format with ZSTD level 3 compression. @@ -61,17 +60,18 @@ impl Default for ParquetCompressor { } } -/// Return the size of the Parquet file `parquet_path` written again by DuckDB, with Snappy. See -/// [`write_duckdb_snappy_parquet`]. -pub async fn duckdb_snappy_parquet_size(parquet_path: &Path) -> anyhow::Result { - let parquet_path = parquet_path.to_path_buf(); - tokio::task::spawn_blocking(move || { - let dir = tempfile::tempdir()?; - let output = dir.path().join("snappy.parquet"); - write_duckdb_snappy_parquet(&parquet_path, &output)?; - Ok(std::fs::metadata(&output)?.len()) - }) - .await? +/// Return the size of `input` written as Parquet with Snappy. Every other setting is the one that +/// [`ParquetCompressor`] writes with, so the size differs from `parquet`'s only by the codec. +pub async fn snappy_parquet_size(input: &Uncompressed) -> anyhow::Result { + let (schema, batches) = input.arrow()?; + let size = parquet_compress_write( + batches.to_vec(), + Arc::clone(schema), + Compression::SNAPPY, + &mut Vec::new(), + ) + .await?; + Ok(size as u64) } /// Return the Arrow memory size after decoding the input Parquet file. @@ -533,6 +533,66 @@ mod tests { Ok(()) } + /// `parquet-snappy` differs from `parquet` only by the codec: the same row groups, pages, + /// encodings, and file metadata. + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn snappy_parquet_differs_only_by_the_codec() -> anyhow::Result<()> { + let batches = vec![batch(0, 50_000)?]; + let schema = batches[0].schema(); + let mut metadata = Vec::new(); + for compression in [ + Compression::ZSTD(ZstdLevel::try_new(3)?), + Compression::SNAPPY, + ] { + let mut buf = Vec::new(); + parquet_compress_write(batches.clone(), Arc::clone(&schema), compression, &mut buf) + .await?; + let options = ArrowReaderOptions::new().with_page_index(true); + metadata.push(ArrowReaderMetadata::load(&Bytes::from(buf), options)?); + } + let (zstd, snappy) = (metadata[0].metadata(), metadata[1].metadata()); + + assert_eq!(row_group_rows(zstd), row_group_rows(snappy)); + assert_eq!( + zstd.file_metadata().key_value_metadata(), + snappy.file_metadata().key_value_metadata() + ); + // The same pages: each page of each column chunk starts at the same row. + let page_starts = |metadata: &ParquetMetaData| -> Vec>> { + metadata + .offset_index() + .into_iter() + .flatten() + .map(|row_group| { + row_group + .iter() + .map(|column| { + column + .page_locations() + .iter() + .map(|page| page.first_row_index) + .collect() + }) + .collect() + }) + .collect() + }; + assert!(!page_starts(zstd).is_empty()); + assert_eq!(page_starts(zstd), page_starts(snappy)); + for (z, s) in zstd.row_groups().iter().zip(snappy.row_groups()) { + for (z, s) in z.columns().iter().zip(s.columns()) { + assert!(matches!(z.compression(), Compression::ZSTD(_))); + assert_eq!(s.compression(), Compression::SNAPPY); + assert_eq!( + z.encodings().collect::>(), + s.encodings().collect::>() + ); + assert_eq!(z.num_values(), s.num_values()); + } + } + Ok(()) + } + #[rstest] #[case::small_file(1000, 4, vec![vec![0, 1, 2]])] #[case::one_partition_per_row_group(200_000, 4, vec![vec![0], vec![1], vec![2]])] diff --git a/vortex-bench/src/parquet_copies.rs b/vortex-bench/src/parquet_copies.rs index 6eca1158469..05fae7f42ca 100644 --- a/vortex-bench/src/parquet_copies.rs +++ b/vortex-bench/src/parquet_copies.rs @@ -10,19 +10,16 @@ //! - [`SizeFormat::ArrowIpc`]: uncompressed Arrow IPC. //! //! Lance is also written for size only, by `lance-bench --data-only`, because only that binary -//! depends on Lance. [`write_duckdb_snappy_parquet`] writes the Snappy Parquet whose size -//! `compress-bench` records. +//! depends on Lance. use std::fs; use std::fs::File; use std::io::BufWriter; use std::path::Path; -use std::process::Command; use std::sync::Arc; use anyhow::Context; use anyhow::Result; -use anyhow::bail; use arrow_ipc::writer::FileWriter; use clap::ValueEnum; use parquet::arrow::arrow_reader::ParquetRecordBatchReaderBuilder; @@ -101,39 +98,6 @@ fn write_arrow_ipc(input: &Path, output: &Path) -> Result<()> { Ok(()) } -/// Write the Parquet file `input` again as DuckDB writes Parquet: `COPY ... (FORMAT parquet, -/// COMPRESSION snappy)` in the `duckdb` CLI, which must be on `PATH`. Every setting other than the -/// codec is DuckDB's default, so the file is what a DuckDB user gets: DuckDB's row groups, and its -/// dictionaries, statistics, and Bloom filters. The codec is named because -/// it is the one the `parquet-snappy` name promises, and DuckDB's default could change. -pub fn write_duckdb_snappy_parquet(input: &Path, output: &Path) -> Result<()> { - let sql = format!( - "COPY (FROM read_parquet({})) TO {} (FORMAT parquet, COMPRESSION snappy)", - sql_string(input)?, - sql_string(output)?, - ); - let result = Command::new("duckdb") - .arg("-c") - .arg(&sql) - .output() - .context("running the duckdb CLI, which writes parquet-snappy")?; - if !result.status.success() { - bail!( - "the duckdb CLI failed: {}", - String::from_utf8_lossy(&result.stderr) - ); - } - Ok(()) -} - -/// `path` as a SQL string literal. -fn sql_string(path: &Path) -> Result { - let path = path - .to_str() - .with_context(|| format!("{} is not UTF-8", path.display()))?; - Ok(format!("'{}'", path.replace('\'', "''"))) -} - #[cfg(test)] mod tests { use arrow_array::Int64Array; @@ -144,9 +108,6 @@ mod tests { use arrow_schema::Field; use arrow_schema::Schema; use parquet::arrow::ArrowWriter; - use parquet::basic::Compression; - use parquet::file::reader::FileReader as _; - use parquet::file::reader::SerializedFileReader; use super::*; use crate::utils::parquet::parquet_writer_properties; @@ -178,46 +139,6 @@ mod tests { Ok(batch) } - #[test] - #[ignore = "needs the duckdb CLI on PATH, which the benchmark runners install"] - fn snappy_parquet_is_duckdbs_parquet_with_the_same_rows() -> Result<()> { - let base = tempfile::tempdir()?; - let expected = write_base(base.path(), 1000, 300)?; - - let output = base.path().join("t.snappy.parquet"); - write_duckdb_snappy_parquet(&base.path().join("parquet").join("t.parquet"), &output)?; - - let metadata = SerializedFileReader::new(File::open(&output)?)? - .metadata() - .clone(); - assert!( - metadata - .file_metadata() - .created_by() - .is_some_and(|created_by| created_by.starts_with("DuckDB")) - ); - // DuckDB's own row groups, not the base file's 300 rows. - assert_eq!(metadata.num_row_groups(), 1); - for column in metadata.row_groups().iter().flat_map(|rg| rg.columns()) { - assert_eq!(column.compression(), Compression::SNAPPY); - } - let reader = ParquetRecordBatchReaderBuilder::try_new(File::open(&output)?)?.build()?; - let batches = reader.collect::, _>>()?; - let actual = arrow_select::concat::concat_batches(&batches[0].schema(), &batches)?; - assert_eq!(actual.num_rows(), expected.num_rows()); - assert_eq!(actual.columns(), expected.columns()); - Ok(()) - } - - #[test] - fn sql_strings_escape_quotes() -> Result<()> { - assert_eq!( - sql_string(Path::new("/data/o'brien.parquet"))?, - "'/data/o''brien.parquet'" - ); - Ok(()) - } - #[test] fn arrow_ipc_holds_the_same_rows() -> Result<()> { let base = tempfile::tempdir()?; From aff33cb182de11731721f5481a8648db2a4ab55c Mon Sep 17 00:00:00 2001 From: Will Manning Date: Sat, 21 Nov 2026 15:14:16 -0500 Subject: [PATCH 40/44] Read the page index with the current parquet-rs API in the Snappy test Signed-off-by: Will Manning --- benchmarks/compress-bench/src/parquet.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/benchmarks/compress-bench/src/parquet.rs b/benchmarks/compress-bench/src/parquet.rs index 28803d3993e..71d12714032 100644 --- a/benchmarks/compress-bench/src/parquet.rs +++ b/benchmarks/compress-bench/src/parquet.rs @@ -453,6 +453,7 @@ mod tests { use arrow_array::StringArray; use arrow_schema::DataType; use arrow_schema::Field; + use parquet::file::metadata::PageIndexPolicy; use parquet::file::metadata::ParquetMetaData; use parquet::file::properties::WriterProperties; use rstest::rstest; @@ -547,7 +548,8 @@ mod tests { let mut buf = Vec::new(); parquet_compress_write(batches.clone(), Arc::clone(&schema), compression, &mut buf) .await?; - let options = ArrowReaderOptions::new().with_page_index(true); + let options = + ArrowReaderOptions::new().with_page_index_policy(PageIndexPolicy::Required); metadata.push(ArrowReaderMetadata::load(&Bytes::from(buf), options)?); } let (zstd, snappy) = (metadata[0].metadata(), metadata[1].metadata()); From 2addb48c444bf2ed0ca1788eb5127c9f826b12e5 Mon Sep 17 00:00:00 2001 From: Will Manning Date: Sat, 21 Nov 2026 15:34:01 -0500 Subject: [PATCH 41/44] Record Snappy Parquet's size on TPC-DS at SF1 bench ranks file sizes over the compress-bench datasets and TPC-DS at SF1. compress-bench recorded parquet-snappy, but TPC-DS did not, so it ranked as a partial format. data-gen gets a parquet-snappy size-only format: each base Parquet file written again with the shared settings and its own row groups, with Snappy in place of zstd level 3. Develop's TPC-DS SF1 entry writes it, and capture-file-sizes records it. Signed-off-by: Will Manning --- AGENTS.md | 3 +- .../bench_orchestrator/ci_matrix/catalog.py | 7 +- .../bench_orchestrator/config.py | 6 +- bench-orchestrator/tests/test_matrix.py | 2 +- scripts/capture-file-sizes.py | 2 + vortex-bench/README.md | 3 +- vortex-bench/src/parquet_copies.rs | 82 ++++++++++++++++++- 7 files changed, 95 insertions(+), 10 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 9a4d2f89052..003df93ec1f 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -231,7 +231,8 @@ These CI checks are the ones most often missed when adding files rather than edi - DuckDB: `(FORMAT parquet, COMPRESSION zstd, COMPRESSION_LEVEL 3)` - tpchgen-cli: `parquet --compression='ZSTD(3)'` - Benchmarks that deliberately compare Parquet codecs, such as the GPU compress benchmark's - `--codec` and the Snappy Parquet whose size `compress-bench` records, are exempt. + `--codec` and the Snappy Parquet whose size `compress-bench` and TPC-DS at SF1 record, are + exempt. - Every parquet-rs writer of benchmark data uses `parquet_writer_properties()` in `vortex-bench/src/utils/parquet.rs`: zstd level 3, 64 KiB dictionaries, a page index, and parquet-rs's default pages of at most 1 MiB and about 20,000 rows. Only the row-group size diff --git a/bench-orchestrator/bench_orchestrator/ci_matrix/catalog.py b/bench-orchestrator/bench_orchestrator/ci_matrix/catalog.py index 9569730d912..e9e104081e9 100644 --- a/bench-orchestrator/bench_orchestrator/ci_matrix/catalog.py +++ b/bench-orchestrator/bench_orchestrator/ci_matrix/catalog.py @@ -92,11 +92,12 @@ def with_all_scans(coverage: Coverage) -> Coverage: ) STANDARD_WITH_DUCKDB = Coverage(STANDARD_WITH_DUCKDB_TARGETS) # TPC-DS SF1 is the SQL data that bench.vortex.dev's File Sizes summary ranks, so develop also -# records the sizes of Lance and Arrow IPC there. It queries Lance on DataFusion, and writes Arrow -# IPC only for its size. Both are small and fast at SF1. +# records the sizes of Lance, Arrow IPC, and Snappy Parquet there, the formats compress-bench also +# records. It queries Lance on DataFusion, and writes Arrow IPC and Snappy Parquet only for their +# sizes. All three are small and fast at SF1. STANDARD_WITH_DUCKDB_AND_SIZE_FORMATS = Coverage( STANDARD_WITH_DUCKDB_TARGETS | df(Format.LANCE), - size_formats=(SizeFormat.ARROW_IPC,), + size_formats=(SizeFormat.ARROW_IPC, SizeFormat.PARQUET_SNAPPY), ) DATAFUSION_VORTEX = Coverage(DATAFUSION_VORTEX_TARGETS) COMPACT = Coverage(COMPACT_TARGETS) diff --git a/bench-orchestrator/bench_orchestrator/config.py b/bench-orchestrator/bench_orchestrator/config.py index a1bc98871c9..77b62c9c9d7 100644 --- a/bench-orchestrator/bench_orchestrator/config.py +++ b/bench-orchestrator/bench_orchestrator/config.py @@ -71,12 +71,14 @@ class ScanEngine(Enum): class SizeFormat(Enum): """A format a benchmark writes only to record its file sizes. No query reads it. - `vx-bench write-size-formats` writes Arrow IPC with `data-gen --size-formats`, and Lance with - `lance-bench --data-only`. + `vx-bench write-size-formats` writes Arrow IPC and Snappy Parquet with `data-gen --size-formats`, + and Lance with `lance-bench --data-only`. """ ARROW_IPC = "arrow-ipc" LANCE = "lance" + # The base Parquet with Snappy in place of zstd level 3, and every other writer setting the same. + PARQUET_SNAPPY = "parquet-snappy" class Benchmark(Enum): diff --git a/bench-orchestrator/tests/test_matrix.py b/bench-orchestrator/tests/test_matrix.py index 7ca0987def4..50b4481c8b7 100644 --- a/bench-orchestrator/tests/test_matrix.py +++ b/bench-orchestrator/tests/test_matrix.py @@ -342,7 +342,7 @@ def test_only_develop_tpcds_sf1_writes_size_only_formats(preset: str) -> None: writers = {entry["id"]: entry["size_formats"] for entry in _entries(preset) if entry["size_formats"]} if preset == "develop": - assert writers == {"tpcds-nvme": ["arrow-ipc"]} + assert writers == {"tpcds-nvme": ["arrow-ipc", "parquet-snappy"]} else: assert writers == {} diff --git a/scripts/capture-file-sizes.py b/scripts/capture-file-sizes.py index ec2d56e2c11..30f12a09b63 100644 --- a/scripts/capture-file-sizes.py +++ b/scripts/capture-file-sizes.py @@ -54,6 +54,8 @@ def main() -> None: # Parquet, which is zstd level 3 where the benchmarks write it, and the dataset's own files # where the suite prescribes them, as ClickBench's are Snappy. "parquet", + # The base Parquet with Snappy in place of zstd level 3, written only for its size. + "parquet-snappy", "vortex-compact", "vortex-file-compressed", "vortex-spatial-native", diff --git a/vortex-bench/README.md b/vortex-bench/README.md index 41f7209dfdc..0c134a076b7 100644 --- a/vortex-bench/README.md +++ b/vortex-bench/README.md @@ -52,7 +52,8 @@ the common writers are different: - `tpchgen-cli`: writes Snappy by default. Use `parquet --compression='ZSTD(3)'`. Benchmarks that compare Parquet codecs on purpose, such as the compress-bench `--gpu-parquet-codec` -option and the Snappy Parquet whose size compress-bench records, are exempt. +option and the Snappy Parquet whose size compress-bench and TPC-DS at SF1 record +(`parquet-snappy`), are exempt. ## Parquet layout diff --git a/vortex-bench/src/parquet_copies.rs b/vortex-bench/src/parquet_copies.rs index 05fae7f42ca..1a548fd789d 100644 --- a/vortex-bench/src/parquet_copies.rs +++ b/vortex-bench/src/parquet_copies.rs @@ -8,6 +8,9 @@ //! `scripts/capture-file-sizes.py` records their sizes. //! //! - [`SizeFormat::ArrowIpc`]: uncompressed Arrow IPC. +//! - [`SizeFormat::ParquetSnappy`]: the base Parquet with Snappy in place of zstd level 3, and +//! every other writer setting the same. `compress-bench` records the same format for its +//! datasets. //! //! Lance is also written for size only, by `lance-bench --data-only`, because only that binary //! depends on Lance. @@ -22,11 +25,14 @@ use anyhow::Context; use anyhow::Result; use arrow_ipc::writer::FileWriter; use clap::ValueEnum; +use parquet::arrow::ArrowWriter; use parquet::arrow::arrow_reader::ParquetRecordBatchReaderBuilder; +use parquet::basic::Compression; use tracing::info; use crate::Format; use crate::idempotent; +use crate::utils::parquet::parquet_writer_properties; /// A format that is written only to record its file size. No query reads it. #[derive(Clone, Copy, Debug, PartialEq, Eq, ValueEnum)] @@ -34,6 +40,9 @@ pub enum SizeFormat { /// Uncompressed Arrow IPC, as `compress-bench` writes it. #[clap(name = "arrow-ipc")] ArrowIpc, + /// The base Parquet with Snappy in place of zstd level 3. + #[clap(name = "parquet-snappy")] + ParquetSnappy, } /// Write `format` from the base Parquet files in `base_path`. @@ -45,9 +54,18 @@ pub fn write_size_format(base_path: &Path, format: SizeFormat) -> Result<()> { Format::ArrowIpc.ext(), write_arrow_ipc, ), + SizeFormat::ParquetSnappy => copy_parquet_directory( + base_path, + PARQUET_SNAPPY_DIR, + Format::Parquet.ext(), + write_snappy_parquet, + ), } } +/// The directory of [`SizeFormat::ParquetSnappy`], beside the base `parquet` directory. +const PARQUET_SNAPPY_DIR: &str = "parquet-snappy"; + /// Write each Parquet file in `{base_path}/parquet/` with `write`, to `{base_path}/{name}/`, with /// the extension `ext`. /// @@ -98,6 +116,30 @@ fn write_arrow_ipc(input: &Path, output: &Path) -> Result<()> { Ok(()) } +/// Write the Parquet file `input` again with Snappy. Every other setting is the shared writer's, +/// and the row groups are the input's, so the file differs from `input` only by its codec. +fn write_snappy_parquet(input: &Path, output: &Path) -> Result<()> { + let builder = ParquetRecordBatchReaderBuilder::try_new(File::open(input)?)?; + // Every row group but the last is full, so the first holds the input's row group size. + let row_group_rows = builder + .metadata() + .row_groups() + .first() + .map(|row_group| row_group.num_rows()) + .context("the Parquet file has no row groups")?; + let schema = Arc::clone(builder.schema()); + let props = parquet_writer_properties() + .set_compression(Compression::SNAPPY) + .set_max_row_group_row_count(Some(usize::try_from(row_group_rows)?)) + .build(); + let mut writer = ArrowWriter::try_new(File::create(output)?, schema, Some(props))?; + for batch in builder.build()? { + writer.write(&batch?)?; + } + writer.close()?; + Ok(()) +} + #[cfg(test)] mod tests { use arrow_array::Int64Array; @@ -107,10 +149,10 @@ mod tests { use arrow_schema::DataType; use arrow_schema::Field; use arrow_schema::Schema; - use parquet::arrow::ArrowWriter; + use parquet::file::metadata::ParquetMetaData; use super::*; - use crate::utils::parquet::parquet_writer_properties; + use crate::utils::parquet::has_current_layout; /// Write `rows` rows to `{base}/parquet/t.parquet`, in row groups of `row_group_rows`. fn write_base(base: &Path, rows: i64, row_group_rows: usize) -> Result { @@ -139,6 +181,42 @@ mod tests { Ok(batch) } + #[test] + fn snappy_parquet_differs_from_the_base_only_by_the_codec() -> Result<()> { + let base = tempfile::tempdir()?; + let expected = write_base(base.path(), 1000, 300)?; + + write_size_format(base.path(), SizeFormat::ParquetSnappy)?; + + let read = |path: &Path| -> Result<_> { + Ok(ParquetRecordBatchReaderBuilder::try_new(File::open(path)?)?) + }; + let input = read(&base.path().join("parquet").join("t.parquet"))?; + let output = read(&base.path().join("parquet-snappy").join("t.parquet"))?; + let rows = |metadata: &ParquetMetaData| -> Vec { + metadata + .row_groups() + .iter() + .map(|rg| rg.num_rows()) + .collect() + }; + assert_eq!(rows(output.metadata()), rows(input.metadata())); + assert_eq!(rows(input.metadata()), vec![300, 300, 300, 100]); + assert!(has_current_layout(output.metadata())); + for column in output + .metadata() + .row_groups() + .iter() + .flat_map(|rg| rg.columns()) + { + assert_eq!(column.compression(), Compression::SNAPPY); + } + let batches = output.build()?.collect::, _>>()?; + let actual = arrow_select::concat::concat_batches(&expected.schema(), &batches)?; + assert_eq!(actual, expected); + Ok(()) + } + #[test] fn arrow_ipc_holds_the_same_rows() -> Result<()> { let base = tempfile::tempdir()?; From 911d6aa88bdbe512f988652f6b2f1797bd89d005 Mon Sep 17 00:00:00 2001 From: Will Manning Date: Sat, 21 Nov 2026 15:44:08 -0500 Subject: [PATCH 42/44] Write the struct-list compression datasets with the shared Parquet config StructListOfInts wrote its Parquet input with parquet-rs's defaults and kept a cached file in any layout. It now uses parquet_writer_properties() and writes a cached file in an older layout again, like the other compression datasets. Signed-off-by: Will Manning --- vortex-bench/src/datasets/struct_list_of_ints.rs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/vortex-bench/src/datasets/struct_list_of_ints.rs b/vortex-bench/src/datasets/struct_list_of_ints.rs index 50abc12f8dd..0490eeb2b25 100644 --- a/vortex-bench/src/datasets/struct_list_of_ints.rs +++ b/vortex-bench/src/datasets/struct_list_of_ints.rs @@ -33,6 +33,8 @@ use crate::IdempotentPath; use crate::SESSION; use crate::datasets::Dataset; use crate::idempotent_async; +use crate::utils::parquet::parquet_writer_properties; +use crate::utils::parquet::remove_stale_parquet; /// Creates a randomly generated struct array, where each field is a list of /// i64 of size one. @@ -134,6 +136,7 @@ impl Dataset for StructListOfInts { async fn to_parquet_path(&self) -> Result { let parquet_path = format!("struct_list_of_ints/{}", self.parquet_filename()).to_data_path(); + remove_stale_parquet(&parquet_path)?; idempotent_async(&parquet_path, |temp_path| async move { // Generate the data @@ -157,7 +160,7 @@ impl Dataset for StructListOfInts { writer = Some(ArrowWriter::try_new( file.try_clone()?, batch.schema(), - None, + Some(parquet_writer_properties().build()), )?); } writer.as_mut().unwrap().write(&batch)?; From 9997597ad11a4644fa6108129a433d8fa6c8de6a Mon Sep 17 00:00:00 2001 From: Will Manning Date: Sat, 21 Nov 2026 15:51:12 -0500 Subject: [PATCH 43/44] Read view types as plain types for Arrow IPC and compress-bench The TPC-H and TPC-DS generators write Utf8View columns. Since the concatenated TPC-H files keep their Arrow schema, compress-bench read them as Utf8View. The Arrow IPC writer writes every buffer that a view array refers to, and batches from one Parquet reader share buffers, so TPC-H's Arrow IPC files grew by up to 20 times. TPC-DS's new Arrow IPC sizes had the same problem. compress-bench's Arrow input and the size-only Arrow IPC copies now read Utf8View as Utf8 and BinaryView as Binary, as develop's input was. Signed-off-by: Will Manning --- vortex-bench/src/compress/mod.rs | 8 +-- vortex-bench/src/parquet_copies.rs | 6 +- vortex-bench/src/utils/parquet.rs | 92 +++++++++++++++++++++++++++++- 3 files changed, 97 insertions(+), 9 deletions(-) diff --git a/vortex-bench/src/compress/mod.rs b/vortex-bench/src/compress/mod.rs index 43d8d22328b..96316d53b67 100644 --- a/vortex-bench/src/compress/mod.rs +++ b/vortex-bench/src/compress/mod.rs @@ -4,7 +4,6 @@ use std::any::Any; use std::borrow::Cow; use std::fmt; -use std::fs::File; use std::path::Path; use std::sync::Arc; use std::time::Duration; @@ -17,7 +16,6 @@ use arrow_schema::Schema; use async_trait::async_trait; use bytes::Bytes; use clap::ValueEnum; -use parquet::arrow::arrow_reader::ParquetRecordBatchReaderBuilder; use serde::Serialize; use tempfile::NamedTempFile; use tempfile::TempDir; @@ -28,6 +26,7 @@ use vortex::utils::aliases::hash_map::HashMap; use crate::Format; use crate::measurements::CompressionTimingMeasurement; use crate::measurements::CustomUnitMeasurement; +use crate::utils::parquet::plain_arrow_reader; /// Number of top-level columns in the wide-table decompression projection benchmark. pub const READ_PROJECTION_ROOT_COLUMNS: usize = 100_000; @@ -112,9 +111,10 @@ pub enum Uncompressed { } impl Uncompressed { - /// Read a Parquet file into Arrow record batches. + /// Read a Parquet file into Arrow record batches, with view types read as plain types + /// ([`plain_arrow_reader`]). pub fn read_arrow(parquet_path: &Path) -> Result { - let builder = ParquetRecordBatchReaderBuilder::try_new(File::open(parquet_path)?)?; + let builder = plain_arrow_reader(parquet_path)?; let schema = Arc::clone(builder.schema()); let batches = builder.build()?.collect::, _>>()?; diff --git a/vortex-bench/src/parquet_copies.rs b/vortex-bench/src/parquet_copies.rs index 1a548fd789d..ab5dcbfcfee 100644 --- a/vortex-bench/src/parquet_copies.rs +++ b/vortex-bench/src/parquet_copies.rs @@ -33,6 +33,7 @@ use tracing::info; use crate::Format; use crate::idempotent; use crate::utils::parquet::parquet_writer_properties; +use crate::utils::parquet::plain_arrow_reader; /// A format that is written only to record its file size. No query reads it. #[derive(Clone, Copy, Debug, PartialEq, Eq, ValueEnum)] @@ -104,9 +105,10 @@ fn copy_parquet_directory( Ok(()) } -/// Write the Parquet file `input` as an uncompressed Arrow IPC file. +/// Write the Parquet file `input` as an uncompressed Arrow IPC file, with view types written as +/// plain types ([`plain_arrow_reader`]). fn write_arrow_ipc(input: &Path, output: &Path) -> Result<()> { - let reader = ParquetRecordBatchReaderBuilder::try_new(File::open(input)?)?; + let reader = plain_arrow_reader(input)?; let schema = Arc::clone(reader.schema()); let mut writer = FileWriter::try_new(BufWriter::new(File::create(output)?), &schema)?; for batch in reader.build()? { diff --git a/vortex-bench/src/utils/parquet.rs b/vortex-bench/src/utils/parquet.rs index 0a95d574f6a..b94de3d64e8 100644 --- a/vortex-bench/src/utils/parquet.rs +++ b/vortex-bench/src/utils/parquet.rs @@ -6,7 +6,15 @@ use std::fs; use std::fs::File; use std::path::Path; - +use std::sync::Arc; + +use arrow_schema::DataType; +use arrow_schema::Field; +use arrow_schema::FieldRef; +use arrow_schema::Schema; +use parquet::arrow::arrow_reader::ArrowReaderMetadata; +use parquet::arrow::arrow_reader::ArrowReaderOptions; +use parquet::arrow::arrow_reader::ParquetRecordBatchReaderBuilder; use parquet::basic::Compression; use parquet::basic::ZstdLevel; use parquet::file::metadata::KeyValue; @@ -181,12 +189,69 @@ pub fn is_zstd_file(path: &Path) -> anyhow::Result { Ok(is_zstd(&metadata)) } +/// A reader for the Parquet file at `path` that reads Arrow's view types as their plain types: +/// `Utf8View` as `Utf8`, and `BinaryView` as `Binary`. +/// +/// The TPC-H and TPC-DS generators write `Utf8View` columns, and the Parquet file keeps that type +/// in its Arrow schema. An Arrow IPC writer writes every buffer that a view array refers to, and +/// the batches that a Parquet reader returns share their buffers, so an IPC file written from +/// view arrays holds the same bytes many times. Arrow IPC sizes are of the plain types. +pub fn plain_arrow_reader(path: &Path) -> anyhow::Result> { + let file = File::open(path)?; + let metadata = ArrowReaderMetadata::load(&file, ArrowReaderOptions::new())?; + let schema = schema_without_views(metadata.schema()); + if schema == **metadata.schema() { + return Ok(ParquetRecordBatchReaderBuilder::new_with_metadata( + file, metadata, + )); + } + let metadata = ArrowReaderMetadata::try_new( + Arc::clone(metadata.metadata()), + ArrowReaderOptions::new().with_schema(Arc::new(schema)), + )?; + Ok(ParquetRecordBatchReaderBuilder::new_with_metadata( + file, metadata, + )) +} + +fn schema_without_views(schema: &Schema) -> Schema { + Schema::new_with_metadata( + schema + .fields() + .iter() + .map(field_without_views) + .collect::>(), + schema.metadata().clone(), + ) +} + +fn field_without_views(field: &FieldRef) -> FieldRef { + Arc::new(Field::clone(field).with_data_type(type_without_views(field.data_type()))) +} + +fn type_without_views(data_type: &DataType) -> DataType { + match data_type { + DataType::Utf8View => DataType::Utf8, + DataType::BinaryView => DataType::Binary, + DataType::List(field) => DataType::List(field_without_views(field)), + DataType::LargeList(field) => DataType::LargeList(field_without_views(field)), + DataType::FixedSizeList(field, size) => { + DataType::FixedSizeList(field_without_views(field), *size) + } + DataType::Struct(fields) => { + DataType::Struct(fields.iter().map(field_without_views).collect()) + } + DataType::Map(field, sorted) => DataType::Map(field_without_views(field), *sorted), + other => other.clone(), + } +} + #[cfg(test)] mod tests { - use std::sync::Arc; - use arrow_array::Int64Array; use arrow_array::RecordBatch; + use arrow_array::StringViewArray; + use arrow_array::cast::AsArray; use parquet::arrow::ArrowWriter; use super::*; @@ -202,6 +267,27 @@ mod tests { Ok(()) } + #[test] + fn the_plain_reader_reads_view_types_as_plain_types() -> anyhow::Result<()> { + let dir = tempfile::tempdir()?; + let path = dir.path().join("views.parquet"); + let strings = ["a short one", "a string longer than twelve bytes"]; + let batch = RecordBatch::try_from_iter([( + "s", + Arc::new(StringViewArray::from_iter_values(strings)) as _, + )])?; + let mut writer = ArrowWriter::try_new(File::create(&path)?, batch.schema(), None)?; + writer.write(&batch)?; + writer.close()?; + + let builder = plain_arrow_reader(&path)?; + assert_eq!(builder.schema().field(0).data_type(), &DataType::Utf8); + let read = builder.build()?.collect::, _>>()?; + let column = read[0].column(0).as_string::(); + assert_eq!(column.iter().flatten().collect::>(), strings); + Ok(()) + } + #[test] fn parquet_in_an_old_layout_is_removed() -> anyhow::Result<()> { let dir = tempfile::tempdir()?; From 3b15172cfea0e1c917037cf5456fcd77a218149e Mon Sep 17 00:00:00 2001 From: Will Manning Date: Sat, 21 Nov 2026 16:02:56 -0500 Subject: [PATCH 44/44] Measure the uncompressed size in the representation compress-bench loads arrow_uncompressed_size still read view types, and Arrow's memory size counts a shared buffer once in every batch that refers to it. It now reads through plain_arrow_reader, like the compression input, so each ratio divides by the size of the data the formats compressed. Signed-off-by: Will Manning --- benchmarks/compress-bench/src/parquet.rs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/benchmarks/compress-bench/src/parquet.rs b/benchmarks/compress-bench/src/parquet.rs index 71d12714032..5c7a7838b33 100644 --- a/benchmarks/compress-bench/src/parquet.rs +++ b/benchmarks/compress-bench/src/parquet.rs @@ -1,7 +1,6 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors -use std::fs::File; use std::io::Write; use std::path::Path; use std::sync::Arc; @@ -38,6 +37,7 @@ use vortex_bench::compress::Compressor; use vortex_bench::compress::Uncompressed; use vortex_bench::compress::read_projection; use vortex_bench::utils::parquet::parquet_writer_properties; +use vortex_bench::utils::parquet::plain_arrow_reader; /// Compressor implementation for Parquet format with ZSTD level 3 compression. pub struct ParquetCompressor { @@ -74,10 +74,10 @@ pub async fn snappy_parquet_size(input: &Uncompressed) -> anyhow::Result { Ok(size as u64) } -/// Return the Arrow memory size after decoding the input Parquet file. +/// Return the Arrow memory size after decoding the input Parquet file, in the representation that +/// [`Uncompressed::read_arrow`] loads: view types read as plain types. pub fn arrow_uncompressed_size(parquet_path: &Path) -> anyhow::Result { - let file = File::open(parquet_path)?; - let reader = ParquetRecordBatchReaderBuilder::try_new(file)?.build()?; + let reader = plain_arrow_reader(parquet_path)?.build()?; let mut total = 0u64; for batch in reader {