diff --git a/.github/actions/setup-duckdb/action.yml b/.github/actions/setup-duckdb/action.yml index 51d920304e9..ff033c3f243 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 on the DuckDB minor version that `vortex-duckdb/build.rs` links (2.0), so the CLI + # that writes the `duckdb` database matches the DuckDB the queries run on. description: "Version of the DuckDB CLI" - default: "1.5.5" + default: "2.0.1" 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" 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/.github/workflows/sql-bench-matrix.yml b/.github/workflows/sql-bench-matrix.yml index eda55e47275..d6c27818fc0 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 @@ -255,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 @@ -271,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) @@ -291,9 +295,20 @@ 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) || '' }} + # 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/AGENTS.md b/AGENTS.md index f599201dd24..003df93ec1f 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -231,7 +231,17 @@ 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 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 + 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/bench-orchestrator/bench_orchestrator/ci_matrix/catalog.py b/bench-orchestrator/bench_orchestrator/ci_matrix/catalog.py index e905cd85c91..e9e104081e9 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,14 @@ 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 +# 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, 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 +260,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..8b30c501efc 100644 --- a/bench-orchestrator/bench_orchestrator/ci_matrix/render.py +++ b/bench-orchestrator/bench_orchestrator/ci_matrix/render.py @@ -3,12 +3,14 @@ """Render declarative benchmark coverage as GitHub Actions matrices.""" -from ..config import Benchmark, BenchmarkTarget, Engine, Format, Integration, ScanEngine -from .model import BenchmarkCase, Catalog, Coverage, ScanCoverage +from ..config import Benchmark, BenchmarkTarget, Engine, Format, Integration, ScanEngine, SizeFormat +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.VORTEX, @@ -31,12 +33,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 +104,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) @@ -105,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/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..ea1b1986f44 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[ @@ -429,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/config.py b/bench-orchestrator/bench_orchestrator/config.py index 7be6cff9e29..77b62c9c9d7 100644 --- a/bench-orchestrator/bench_orchestrator/config.py +++ b/bench-orchestrator/bench_orchestrator/config.py @@ -68,6 +68,19 @@ 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" + # 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): """Available benchmark suites.""" @@ -334,6 +347,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/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/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 f7f6a0512b4..c99221658b5 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"]', + "--opt", + "scale-factor=1.0", + ], + ) + + assert result.exit_code == 0, result.stdout + assert commands == [ + [str(data_gen), "tpcds", "--size-formats", "arrow-ipc", "--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" @@ -155,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/bench-orchestrator/tests/test_matrix.py b/bench-orchestrator/tests/test_matrix.py index 67abe1b8812..50b4481c8b7 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() @@ -192,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"]) @@ -317,6 +337,41 @@ 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", "parquet-snappy"]} + else: + assert writers == {} + + +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 "lance" not in entry["data_formats"] + + +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/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/README.md b/benchmarks/compress-bench/README.md index 8f3764823d3..ba55e7f0337 100644 --- a/benchmarks/compress-bench/README.md +++ b/benchmarks/compress-bench/README.md @@ -9,6 +9,12 @@ 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`), 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. + 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 9e6e9aeafa9..da9d551215a 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; @@ -16,7 +17,9 @@ 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::snappy_parquet_size; use compress_bench::vortex::VortexCompressor; +use compress_bench::vortex::vortex_compact_size; use futures::FutureExt; use indicatif::ProgressBar; use itertools::Itertools; @@ -58,6 +61,10 @@ use vortex_bench::setup_logging_and_tracing_with_format; use vortex_bench::statpopgen::StatPopGenBenchmark; use vortex_bench::v3; +/// 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)] #[command(version, about, long_about = None)] struct Args { @@ -454,6 +461,51 @@ async fn run_compress( Ok(()) } +/// 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], + 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 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"))?; + 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, @@ -576,6 +628,23 @@ async fn run_benchmark_for_dataset( } } + // 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")?; + 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. match mode { // The shared ratio labels name the CPU suite's codec, which the GPU run does not diff --git a/benchmarks/compress-bench/src/parquet.rs b/benchmarks/compress-bench/src/parquet.rs index 37f8b36a599..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; @@ -29,7 +28,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; @@ -38,6 +36,8 @@ use vortex_bench::compress::CompressedData; 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 { @@ -52,10 +52,6 @@ impl ParquetCompressor { ), } } - - pub fn with_compression(compression: Compression) -> Self { - Self { compression } - } } impl Default for ParquetCompressor { @@ -64,10 +60,24 @@ impl Default for ParquetCompressor { } } -/// Return the Arrow memory size after decoding the input Parquet file. +/// 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, 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 { @@ -126,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 @@ -139,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 @@ -175,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); } @@ -443,7 +453,9 @@ 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; use super::*; @@ -481,17 +493,19 @@ 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(); - 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))?; @@ -520,6 +534,67 @@ 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_policy(PageIndexPolicy::Required); + 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/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)?; diff --git a/benchmarks/lance-bench/src/main.rs b/benchmarks/lance-bench/src/main.rs index ec5209f0b11..3dd893f0e01 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, @@ -88,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(); @@ -98,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 { @@ -117,6 +143,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/benchmarks/random-access-bench/README.md b/benchmarks/random-access-bench/README.md index 3e3a6f0c883..21b276f4750 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 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. + 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/benchmarks/string-bench/src/lib.rs b/benchmarks/string-bench/src/lib.rs index 19d0a99439e..d33e530d0eb 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,8 @@ 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_bench::utils::parquet::remove_stale_parquet; use vortex_cloud::hf::make_hf_store_from_url; use vortex_fsst::FSST; use vortex_onpair::Config; @@ -438,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?; @@ -453,9 +454,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/scripts/capture-file-sizes.py b/scripts/capture-file-sizes.py index f987cbc28f9..30f12a09b63 100644 --- a/scripts/capture-file-sizes.py +++ b/scripts/capture-file-sizes.py @@ -50,7 +50,12 @@ 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", + # 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/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/scripts/tests/test_benchmark_reporting.py b/scripts/tests/test_benchmark_reporting.py index 1b55c84191a..74a3d8787c6 100644 --- a/scripts/tests/test_benchmark_reporting.py +++ b/scripts/tests/test_benchmark_reporting.py @@ -936,6 +936,43 @@ def test_summary_reports_hot_alone_when_no_row_recorded_its_runs(tmp_path: Path) assert "cold" not in summary +def test_capture_file_sizes_names_parquet_by_its_directory(tmp_path: Path) -> None: + data_dir = tmp_path / "data" + files = { + # ClickBench's own files are Snappy, and they are its `parquet`. + ("clickbench_partitioned", "parquet", "hits_0.parquet"): 40, + ("clickbench_partitioned", "arrow-ipc", "hits_0.arrow"): 80, + } + 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" + + subprocess.run( + [ + sys.executable, + str(CAPTURE_SCRIPT), + str(data_dir), + "--benchmark", + "clickbench", + "--dataset-dir", + "clickbench_partitioned", + "--commit", + "deadbeef", + "-o", + str(output_path), + ], + check=True, + ) + + records = [json.loads(line) for line in output_path.read_text(encoding="utf-8").splitlines()] + assert sorted((r["file_size"]["format"], r["value"]) for r in records) == [ + ("arrow-ipc", 80), + ("parquet", 40), + ] + + 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/README.md b/vortex-bench/README.md index 8c040e3fa29..0c134a076b7 100644 --- a/vortex-bench/README.md +++ b/vortex-bench/README.md @@ -52,7 +52,23 @@ 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 Snappy Parquet whose size compress-bench and TPC-DS at SF1 record +(`parquet-snappy`), are exempt. + +## 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/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/bin/data-gen.rs b/vortex-bench/src/bin/data-gen.rs index 61233d1e6fe..e630193b25b 100644 --- a/vortex-bench/src/bin/data-gen.rs +++ b/vortex-bench/src/bin/data-gen.rs @@ -24,6 +24,8 @@ 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::setup_logging_and_tracing_with_format; #[derive(Parser)] @@ -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 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/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/conversions.rs b/vortex-bench/src/conversions.rs index eb585a14516..6ab0e956be8 100644 --- a/vortex-bench/src/conversions.rs +++ b/vortex-bench/src/conversions.rs @@ -72,6 +72,10 @@ 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::has_current_layout; +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. const MEMORY_PER_STREAM_GB: u64 = 4; @@ -427,17 +431,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 the shared Parquet settings, in local row groups, unless it already +/// 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, ) -> 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 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 && has_current_layout(metadata) { return Ok(()); } @@ -445,7 +457,12 @@ 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)?; + // 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? { writer.write(&batch).await?; } @@ -567,3 +584,143 @@ 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::properties::WriterProperties; + use parquet::file::reader::FileReader as _; + 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<()> { + 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(()) + } + + #[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, 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())), + 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)?; + 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_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()?; + 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(()) + } +} diff --git a/vortex-bench/src/datasets/feature_vectors.rs b/vortex-bench/src/datasets/feature_vectors.rs index d1aae6dfe78..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 { @@ -90,7 +93,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..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 { @@ -86,7 +89,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..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 { @@ -101,7 +104,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..1e3c3354226 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,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; /// Synthetic sparse-wide workloads in the compression benchmark's CPU suite. #[derive(Clone, Copy)] @@ -173,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?; @@ -187,9 +187,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/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)?; diff --git a/vortex-bench/src/datasets/taxi_data.rs b/vortex-bench/src/datasets/taxi_data.rs index 3800c5b5749..af562b251dc 100644 --- a/vortex-bench/src/datasets/taxi_data.rs +++ b/vortex-bench/src/datasets/taxi_data.rs @@ -21,10 +21,13 @@ 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; +use crate::utils::parquet::remove_stale_parquet; /// Dataset identifier used for data path generation. pub const DATASET: &str = "taxi"; @@ -67,7 +70,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 +83,21 @@ 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 || { + let path = data_path(DATASET, Format::Parquet); + remove_stale_parquet(&path.to_data_path())?; + idempotent(&path, |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/datasets/tpch_l_comment.rs b/vortex-bench/src/datasets/tpch_l_comment.rs index 4b7b3301f58..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; @@ -37,7 +39,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`. @@ -47,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/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/lib.rs b/vortex-bench/src/lib.rs index 46c6d8b0250..e0da88ffb8e 100644 --- a/vortex-bench/src/lib.rs +++ b/vortex-bench/src/lib.rs @@ -55,6 +55,7 @@ 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; @@ -439,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> { @@ -463,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 => { @@ -478,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 new file mode 100644 index 00000000000..ab5dcbfcfee --- /dev/null +++ b/vortex-bench/src/parquet_copies.rs @@ -0,0 +1,236 @@ +// 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. +//! +//! No query reads these copies. `data-gen --size-formats` writes them only so that +//! `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. + +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; +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)] +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`. +pub fn write_size_format(base_path: &Path, format: SizeFormat) -> Result<()> { + match format { + SizeFormat::ArrowIpc => copy_parquet_directory( + base_path, + Format::ArrowIpc.name(), + 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`. +/// +/// The write is idempotent: an output file that exists is not written again. +fn copy_parquet_directory( + base_path: &Path, + 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(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(), + 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(ext); + idempotent(output.as_path(), |temp| write(&input, temp)) + .with_context(|| format!("writing {} as {}", input.display(), name))?; + } + Ok(()) +} + +/// 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 = 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()? { + writer.write(&batch?)?; + } + writer.finish()?; + 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; + 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::metadata::ParquetMetaData; + + use super::*; + 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 { + 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_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()?; + 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(()) + } +} 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/random_access/mod.rs b/vortex-bench/src/random_access/mod.rs index e7ff4c7a41a..082a4c6e358 100644 --- a/vortex-bench/src/random_access/mod.rs +++ b/vortex-bench/src/random_access/mod.rs @@ -9,14 +9,14 @@ 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::WriterProperties; use url::Url; use vortex::array::ArrayRef; @@ -24,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; @@ -82,14 +84,32 @@ pub fn parquet_to_arrow_file(parquet_path: PathBuf, arrow_path: String) -> Resul }) } -/// Parquet writer properties for the synthetic random-access datasets. +/// 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`]. /// -/// 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. -pub fn random_access_writer_properties() -> Result { - Ok(WriterProperties::builder() - .set_compression(Compression::ZSTD(ZstdLevel::try_new(3)?)) - .build()) +/// 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. @@ -194,8 +214,56 @@ 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::*; + #[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)?) @@ -241,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/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. 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/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..6231b895a0b 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,12 @@ 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::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. const BATCH_SIZE: usize = 8192 * 64; @@ -93,8 +100,19 @@ 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_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) + .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/statpopgen/download_vcf.rs b/vortex-bench/src/statpopgen/download_vcf.rs index fb7d99e98ee..823b1315652 100644 --- a/vortex-bench/src/statpopgen/download_vcf.rs +++ b/vortex-bench/src/statpopgen/download_vcf.rs @@ -38,6 +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::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). @@ -55,6 +57,8 @@ impl StatPopGenBenchmark { StatPopGenBenchmark::FILE_NAME ); let parquet_output_path = self.parquet_path()?; + // A file written in an older Parquet layout is written again. + remove_stale_parquet(&parquet_output_path)?; idempotent_async( &parquet_output_path, @@ -82,7 +86,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 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..495d3b279ce 100644 --- a/vortex-bench/src/tpcds/tpcdsgen.rs +++ b/vortex-bench/src/tpcds/tpcdsgen.rs @@ -60,13 +60,11 @@ 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; -/// 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,11 +74,16 @@ 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)?; + 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. @@ -113,7 +116,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..b8f0e01e5be 100644 --- a/vortex-bench/src/tpch/tpchgen.rs +++ b/vortex-bench/src/tpch/tpchgen.rs @@ -47,13 +47,11 @@ 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::parquet::prepare_parquet_dir; 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 +87,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 +99,7 @@ impl Default for TpchGenOptions { format: Format::Parquet, batch_size: 8192 * 64, shape: TableShape::Flat, + row_group_rows: LOCAL_ROW_GROUP_ROWS, } } } @@ -126,11 +127,22 @@ 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 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(); @@ -318,11 +330,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 +359,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 +398,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 { @@ -409,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(); @@ -586,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(()) + } +} 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 3fa62e42e26..b94de3d64e8 100644 --- a/vortex-bench/src/utils/parquet.rs +++ b/vortex-bench/src/utils/parquet.rs @@ -3,27 +3,368 @@ //! Shared Parquet writer settings for generated benchmark data. +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; +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; + +/// 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. -const DICTIONARY_PAGE_SIZE_LIMIT: usize = 64 * 1024; +pub const DICTIONARY_PAGE_SIZE_LIMIT: usize = 64 * 1024; + +/// 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 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 generated benchmark Parquet: zstd level 3, pages bounded by bytes only, -/// and small dictionaries. +/// Writer settings for all Parquet that the benchmarks generate: /// -/// Row group size is left to the caller. +/// - 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. +/// - 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 +/// 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) + .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. +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 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) +} + +/// [`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("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 layout is not {}", + data_dir.display(), + layout.trim() + ); + 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)?; + } + } + } + fs::create_dir_all(parquet_dir)?; + fs::write(&marker, layout)?; + Ok(()) +} + +/// 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)) +} + +/// 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 arrow_array::Int64Array; + use arrow_array::RecordBatch; + use arrow_array::StringViewArray; + use arrow_array::cast::AsArray; + 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 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()?; + 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()?; + 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, 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)?; + 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.layout"))?, + layout(S3_ROW_GROUP_ROWS) + ); + 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()?; + 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/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 { 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); 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!(), };