diff --git a/.github/workflows/pr-bench-dispatch.yml b/.github/workflows/pr-bench-dispatch.yml index 4a6ff0b584d..240eb71ba55 100644 --- a/.github/workflows/pr-bench-dispatch.yml +++ b/.github/workflows/pr-bench-dispatch.yml @@ -189,3 +189,21 @@ jobs: secrets: inherit with: matrix_preset: "pr-full" + + remove-sql-scan-label: + runs-on: ubuntu-latest + timeout-minutes: 10 + if: github.event.label.name == 'action/bench-scan' + steps: + - uses: actions-ecosystem/action-remove-labels@2ce5d41b4b6aa8503e285553f75ed56e0a40bae0 # v1 + if: github.event.pull_request.head.repo.full_name == 'vortex-data/vortex' + with: + labels: action/bench-scan + fail_on_error: true + + sql-scan-bench: + needs: remove-sql-scan-label + uses: ./.github/workflows/pr-bench-sql.yml + secrets: inherit + with: + matrix_preset: "pr-scan" diff --git a/.github/workflows/pr-bench-sql.yml b/.github/workflows/pr-bench-sql.yml index 40789d631a8..e0b6e4590b2 100644 --- a/.github/workflows/pr-bench-sql.yml +++ b/.github/workflows/pr-bench-sql.yml @@ -26,6 +26,7 @@ on: default: "pr" options: - "pr" + - "pr-scan" - "pr-compact" - "pr-all" - "pr-full" diff --git a/.github/workflows/sql-bench-matrix.yml b/.github/workflows/sql-bench-matrix.yml index 7a5ca5f86fe..eda55e47275 100644 --- a/.github/workflows/sql-bench-matrix.yml +++ b/.github/workflows/sql-bench-matrix.yml @@ -23,6 +23,7 @@ jobs: contents: read outputs: benchmark_matrix: ${{ steps.resolve.outputs.benchmark_matrix }} + comment_groups: ${{ steps.resolve.outputs.comment_groups }} steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 with: @@ -42,6 +43,10 @@ jobs: matrix="$(uv run --project bench-orchestrator vx-bench matrix "$MATRIX_PRESET")" echo "benchmark_matrix=$matrix" >> "$GITHUB_OUTPUT" + # A case runs as one entry per scan when it covers every scan; its PR comment collects + # the entries of its `group` into one table. + groups="$(jq -c '[group_by(.group)[] | {group: .[0].group, name: .[0].group_name, ids: map(.id)}]' <<<"$matrix")" + echo "comment_groups=$groups" >> "$GITHUB_OUTPUT" build: timeout-minutes: 60 @@ -292,8 +297,9 @@ jobs: # 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: + # Every entry of a case generates the same data, so only the case's default entry records it. - name: Capture file sizes - if: matrix.remote_key == null + if: matrix.remote_key == null && matrix.records_data shell: bash run: | uv run --no-project scripts/capture-file-sizes.py \ @@ -309,7 +315,7 @@ jobs: # dumped, then one file of every table is kept, plus more partitions weighted by size up to a # line budget. Observability only, so it never fails the benchmark or holds up its job. - name: Dump sampled file trees - if: ${{ !cancelled() && matrix.remote_key == null }} + if: ${{ !cancelled() && matrix.remote_key == null && matrix.records_data }} continue-on-error: true timeout-minutes: 20 shell: bash @@ -320,56 +326,27 @@ jobs: --seed ${{ inputs.mode == 'pr' && github.event.pull_request.head.sha || github.sha }} \ -o file-trees - # "Fetch baseline" reads the file-size records "Capture file sizes" appends, so it waits for them. - - parallel: - - name: Upload sampled file trees - if: ${{ !cancelled() && matrix.remote_key == null }} - continue-on-error: true - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 - with: - name: file-trees-${{ inputs.matrix_preset }}-${{ matrix.id }} - path: file-trees/ - retention-days: 5 - if-no-files-found: ignore - - name: Fetch baseline from the benchmarks database - if: inputs.mode == 'pr' - uses: ./.github/actions/fetch-bench-baseline - with: - role-arn: ${{ vars.GH_BENCH_READ_ROLE_ARN }} - region: ${{ vars.RDS_BENCH_REGION }} - endpoint: ${{ vars.RDS_BENCH_INSTANCE_ENDPOINT }} - database: ${{ vars.RDS_BENCH_DB_NAME }} - - - name: Compare results - if: inputs.mode == 'pr' - shell: bash - run: | - set -Eeu -o pipefail -x - - uv run --no-project scripts/compare-benchmark-jsons.py base.ingest.jsonl results.json \ - "${{ matrix.name }}" --pr-records results.ingest.jsonl > comment.md - cat comment.md >> "$GITHUB_STEP_SUMMARY" - - - name: Comment PR - if: inputs.mode == 'pr' && github.event.pull_request.head.repo.fork == false - uses: thollander/actions-comment-pull-request@24bffb9b452ba05a4f3f77933840a6a841d1b32b # v3 + - name: Upload sampled file trees + if: ${{ !cancelled() && matrix.remote_key == null && matrix.records_data }} + continue-on-error: true + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 with: - file-path: comment.md - # There is exactly one comment per comment-tag. If a comment with this tag already exists, - # this action will *update* the comment instead of posting a new comment. The preset is - # part of the tag because presets overlap on benchmark ids (`pr` and `pr-compact` share - # nine) and can run concurrently, so a preset-less tag would let them clobber each other. - comment-tag: bench-pr-comment-${{ matrix.id }}-${{ inputs.matrix_preset }} + name: file-trees-${{ inputs.matrix_preset }}-${{ matrix.id }} + path: file-trees/ + retention-days: 5 + if-no-files-found: ignore - - name: Comment PR on failure - if: failure() && inputs.mode == 'pr' && github.event.pull_request.head.repo.fork == false - uses: thollander/actions-comment-pull-request@24bffb9b452ba05a4f3f77933840a6a841d1b32b # v3 + # The `comment` job compares and comments once per case, over every entry of the case. + - name: Upload results for the PR comment + if: ${{ !cancelled() && inputs.mode == 'pr' }} + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 with: - message: | - # ๐Ÿšจ๐Ÿšจ๐ŸšจโŒโŒโŒ SQL BENCHMARK FAILED โŒโŒโŒ๐Ÿšจ๐Ÿšจ๐Ÿšจ - - Benchmark `${{ matrix.name }}` (${{ inputs.matrix_preset }}) failed! Check the [workflow run](${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}) for details. - comment-tag: bench-pr-comment-${{ matrix.id }}-${{ inputs.matrix_preset }} + name: sql-results-${{ inputs.matrix_preset }}--${{ matrix.group }}--${{ matrix.id }} + path: | + results.json + results.ingest.jsonl + retention-days: 5 + if-no-files-found: ignore # v4 (Postgres) ingest -- the REQUIRED benchmark-results pipeline feeding the live # benchmarks website (see develop-bench.yml for the full rationale); a failure here fails the @@ -436,3 +413,97 @@ jobs: separate-directories: true delete-merged: true retention-days: 5 + + # One comment per case: the entries of a case run on machines of their own, one per Vortex scan, + # and their results are compared here against one baseline, so the comment shows every scan side + # by side and names any entry that did not report. + comment: + needs: [resolve-matrix, bench] + if: ${{ !cancelled() && inputs.mode == 'pr' }} + timeout-minutes: 15 + strategy: + fail-fast: false + matrix: + include: ${{ fromJSON(needs.resolve-matrix.outputs.comment_groups) }} + runs-on: >- + ${{ github.repository == 'vortex-data/vortex' + && format('runs-on={0}/region=us-east-1/runner=amd64-ci-small/image=ubuntu26-full-x64-pre-v2/tag=comment-{1}{2}', github.run_id, matrix.group, github.event.pull_request.head.repo.fork == false && '/extras=s3-cache' || '') + || 'ubuntu-latest' }} + steps: + # `extras=s3-cache` points the artifact API at the RunsOn proxy, which only this action wires up. + - uses: runs-on/action@v2 + if: github.event.pull_request.head.repo.fork == false + # The baseline is the newest develop commit reachable from the PR head, which needs full history. + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + ref: ${{ github.event.pull_request.head.sha }} + fetch-depth: 0 + persist-credentials: false + - name: Install uv + uses: spiraldb/actions/.github/actions/setup-uv@a746510eafaa926484c354541cfc49b2ec06cc63 # 0.18.6 + with: + sync: false + - name: Download results + uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8 + with: + pattern: sql-results-${{ inputs.matrix_preset }}--${{ matrix.group }}--* + path: entries + - name: Merge results + id: merge + shell: bash + env: + IDS: ${{ toJSON(matrix.ids) }} + run: | + set -Eeuo pipefail + : > results.json + : > results.ingest.jsonl + missing=() + while read -r id; do + dir="entries/sql-results-${{ inputs.matrix_preset }}--${{ matrix.group }}--${id}" + if [[ -s "$dir/results.ingest.jsonl" ]]; then + cat "$dir/results.ingest.jsonl" >> results.ingest.jsonl + cat "$dir/results.json" >> results.json 2>/dev/null || true + else + missing+=("\`${id}\`") + fi + done < <(jq -r '.[]' <<<"$IDS") + echo "missing=${missing[*]}" >> "$GITHUB_OUTPUT" + echo "reported=$([[ -s results.ingest.jsonl ]] && echo true || echo false)" >> "$GITHUB_OUTPUT" + - name: Fetch baseline from the benchmarks database + if: steps.merge.outputs.reported == 'true' + uses: ./.github/actions/fetch-bench-baseline + with: + role-arn: ${{ vars.GH_BENCH_READ_ROLE_ARN }} + region: ${{ vars.RDS_BENCH_REGION }} + endpoint: ${{ vars.RDS_BENCH_INSTANCE_ENDPOINT }} + database: ${{ vars.RDS_BENCH_DB_NAME }} + - name: Compare results + shell: bash + env: + MISSING: ${{ steps.merge.outputs.missing }} + REPORTED: ${{ steps.merge.outputs.reported }} + RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }} + run: | + set -Eeu -o pipefail -x + : > comment.md + if [[ -n "$MISSING" ]]; then + echo "# ๐Ÿšจ๐Ÿšจ๐ŸšจโŒโŒโŒ SQL BENCHMARK FAILED โŒโŒโŒ๐Ÿšจ๐Ÿšจ๐Ÿšจ" >> comment.md + echo >> comment.md + echo "Benchmark \`${{ matrix.name }}\` (${{ inputs.matrix_preset }}) has entries that did not report: ${MISSING}. Check the [workflow run](${RUN_URL}) for details." >> comment.md + echo >> comment.md + fi + if [[ "$REPORTED" == "true" ]]; then + uv run --no-project scripts/compare-benchmark-jsons.py base.ingest.jsonl results.json \ + "${{ matrix.name }}" --pr-records results.ingest.jsonl >> comment.md + fi + cat comment.md >> "$GITHUB_STEP_SUMMARY" + - name: Comment PR + if: github.event.pull_request.head.repo.fork == false + uses: thollander/actions-comment-pull-request@24bffb9b452ba05a4f3f77933840a6a841d1b32b # v3 + with: + file-path: comment.md + # There is exactly one comment per comment-tag. If a comment with this tag already exists, + # this action will *update* the comment instead of posting a new comment. The preset is + # part of the tag because presets overlap on benchmark ids (`pr` and `pr-compact` share + # nine) and can run concurrently, so a preset-less tag would let them clobber each other. + comment-tag: bench-pr-comment-${{ matrix.group }}-${{ inputs.matrix_preset }} diff --git a/bench-orchestrator/README.md b/bench-orchestrator/README.md index 19ce9f08ecd..035473d6a53 100644 --- a/bench-orchestrator/README.md +++ b/bench-orchestrator/README.md @@ -159,11 +159,19 @@ vx-bench clean --older-than "30 days" [options] ## CI Benchmark Matrices CI benchmark coverage lives in `bench_orchestrator/ci_matrix/catalog.py`. This is the only file to -edit when changing what runs in the `develop`, `pr`, `pr-compact`, `pr-all`, `pr-full`, or -`nightly` presets. The remaining modules in `ci_matrix` model, validate, and render that catalog as +edit when changing what runs in the `develop`, `pr`, `pr-scan`, `pr-compact`, `pr-all`, `pr-full`, +or `nightly` presets. The remaining modules in `ci_matrix` model, validate, and render that catalog as the JSON expected by GitHub Actions. `pr-all` is not declared per benchmark: it is derived as the union of each benchmark's `pr`, `pr-compact`, and `pr-full` coverage. +Vortex targets name an integration (`file` or `datasource`) and a scan engine (`v1` or `v2`). A +coverage made with `with_all_scans` runs every valid combination, and each combination becomes a +matrix entry of its own, `{id}-{engine}-{integration}-{scan}`, on its own machine. The default +entry keeps the case's id. Every entry of a case shares its `group`, and the PR comment job merges +a group's results into one table. `nightly` covers every scan on every benchmark; `develop` and +`pr-scan` cover them on ClickBench and TPC-H SF=1 on NVMe. The other PR presets run the default +scans only. + When adding coverage, update the benchmark declarations and the expected preset membership in `tests/test_matrix.py`. diff --git a/bench-orchestrator/bench_orchestrator/ci_matrix/catalog.py b/bench-orchestrator/bench_orchestrator/ci_matrix/catalog.py index 6a0ac476c0d..e905cd85c91 100644 --- a/bench-orchestrator/bench_orchestrator/ci_matrix/catalog.py +++ b/bench-orchestrator/bench_orchestrator/ci_matrix/catalog.py @@ -9,18 +9,25 @@ from dataclasses import replace -from ..config import Benchmark, Engine, Format -from .model import BenchmarkCase, Catalog, Coverage, Storage +from ..config import Benchmark, BenchmarkTarget, Engine, Format, Integration, ScanEngine +from .model import BenchmarkCase, Catalog, Coverage, ScanCoverage, Storage from .render import merge_coverage -from .targets import df, duck, targets +from .targets import TargetSet, df, duck PRESETS = { - "develop": "Every regular SQL benchmark at full target coverage.", + "develop": ( + "Every regular SQL benchmark at full target coverage, and every Vortex scan on ClickBench and " + "TPC-H SF=1 on NVMe." + ), "pr": "The quicker pull-request SQL benchmark matrix (action/bench-sql).", "pr-compact": "Pull-request SQL benchmarks for Vortex Compact plus Parquet controls.", + "pr-scan": ( + "ClickBench and TPC-H SF=1 on NVMe with every Vortex integration and scan engine, one machine " + "per combination (action/bench-scan)." + ), "pr-all": "The union of the pr, pr-compact and pr-full matrices (action/bench-all).", - "pr-full": "Every regular SQL benchmark at full PR target coverage (action/bench-sql-extended).", - "nightly": "SF=100 TPC-H and nested TPC-H, and SF=10/100 TPC-DS, on NVMe and S3 at default targets.", + "pr-full": ("Every regular SQL benchmark at full PR target coverage (action/bench-sql-extended)."), + "nightly": "SF=100 TPC-H and nested TPC-H, and SF=10/100 TPC-DS, on NVMe and S3, with every Vortex scan.", } # Reusable target coverage @@ -60,6 +67,18 @@ Format.VORTEX_COMPACT, ) +# Vortex targets name an integration (`file`, `datasource`) and a scan engine (`v1`, `v2`); see +# `BenchmarkTarget`. Declared targets run the file integration on the suite's default engine. +# `ScanCoverage.ALL` adds every other valid combination for the `vortex` format: DataFusion file-v1 and +# datasource-v1 beside file-v2, and DuckDB file-v1 beside file-v2, on V2 suites. Each combination runs +# as a matrix entry, and so a machine, of its own, so covering them all adds machines, not wall time. + + +def with_all_scans(coverage: Coverage) -> Coverage: + """Run every valid integration and scan engine combination for the `vortex` format.""" + return replace(coverage, scans=ScanCoverage.ALL) + + DEFAULT = Coverage(DEFAULT_TARGETS) STANDARD = Coverage(STANDARD_TARGETS) FULL_LOCAL = Coverage(FULL_LOCAL_TARGETS) @@ -78,29 +97,51 @@ # Concrete benchmark cases -# TPC-DS SF=100 runs one engine/format target per job, each on its own machine, so a single slow -# target cannot push the others past the job timeout and lose their results. +# TPC-DS SF=100 runs one target per job, each on its own machine, so a single slow target cannot +# push the others past the job timeout and lose their results. TPCDS_SF100_TARGETS = ( - (Engine.DATAFUSION, Format.PARQUET, "DataFusion", "Parquet"), - (Engine.DATAFUSION, Format.VORTEX, "DataFusion", "Vortex"), - (Engine.DUCKDB, Format.PARQUET, "DuckDB", "Parquet"), - (Engine.DUCKDB, Format.VORTEX, "DuckDB", "Vortex"), + (BenchmarkTarget(Engine.DATAFUSION, Format.PARQUET), "DataFusion, Parquet"), + (BenchmarkTarget(Engine.DATAFUSION, Format.VORTEX), "DataFusion, Vortex"), + (BenchmarkTarget(Engine.DUCKDB, Format.PARQUET), "DuckDB, Parquet"), + (BenchmarkTarget(Engine.DUCKDB, Format.VORTEX), "DuckDB, Vortex"), + ( + BenchmarkTarget(Engine.DATAFUSION, Format.VORTEX, Integration.FILE, ScanEngine.V1), + "DataFusion, Vortex, file v1", + ), + ( + BenchmarkTarget(Engine.DATAFUSION, Format.VORTEX, Integration.DATASOURCE, ScanEngine.V1), + "DataFusion, Vortex, datasource v1", + ), + ( + BenchmarkTarget(Engine.DUCKDB, Format.VORTEX, Integration.FILE, ScanEngine.V1), + "DuckDB, Vortex, file v1", + ), ) + + +def _tpcds_sf100_job(target: BenchmarkTarget) -> str: + """Name a TPC-DS SF=100 job after its target; default-scan targets keep their original names.""" + job = f"{target.engine.value}-{target.format.value}" + if target.scan is not None: + job += f"-{target.integration.value}-{target.scan.value}" + return job + + TPCDS_SF100_CASES = tuple( BenchmarkCase( - id=f"tpcds-{storage.value}-100-{engine.value}-{fmt.value}", + id=f"tpcds-{storage.value}-100-{_tpcds_sf100_job(target)}", benchmark=Benchmark.TPCDS, - name=f"TPC-DS SF=100 on {storage.value.upper()} ({engine_name}, {fmt_name})", + name=f"TPC-DS SF=100 on {storage.value.upper()} ({label})", storage=storage, scale_factor=100.0, iterations=3, local_dir="vortex-bench/data/tpcds/100.0" if storage is Storage.S3 else None, # A distinct key per job: each job clears and re-uploads its own copy of the data. - remote_key=f"tpcds/100.0-{engine.value}-{fmt.value}" if storage is Storage.S3 else None, - runs={"nightly": Coverage(targets(engine, fmt))}, + remote_key=f"tpcds/100.0-{_tpcds_sf100_job(target)}" if storage is Storage.S3 else None, + runs={"nightly": Coverage(TargetSet((target,)))}, ) for storage in (Storage.NVME, Storage.S3) - for engine, fmt, engine_name, fmt_name in TPCDS_SF100_TARGETS + for target, label in TPCDS_SF100_TARGETS ) BENCHMARKS = ( @@ -111,9 +152,10 @@ dataset_dir="clickbench_partitioned", runs={ "pr": DEFAULT, + "pr-scan": with_all_scans(DEFAULT), "pr-compact": COMPACT, "pr-full": DEFAULT_WITH_DUCKDB_PR_FULL, - "develop": FULL_LOCAL, + "develop": with_all_scans(FULL_LOCAL), }, ), BenchmarkCase( @@ -134,9 +176,10 @@ iterations=10, runs={ "pr": DEFAULT, + "pr-scan": with_all_scans(DEFAULT), "pr-compact": COMPACT, "pr-full": FULL_PR, - "develop": FULL_LOCAL, + "develop": with_all_scans(FULL_LOCAL), }, ), BenchmarkCase( @@ -344,6 +387,22 @@ ), ) +# Presets whose every benchmark runs every valid integration and scan engine combination. TPC-DS +# SF=100 lists its targets one per job already, see `TPCDS_SF100_TARGETS`. PR presets other than +# `pr-scan` keep the default scans, so the extra machines are opt-in. +ALL_SCAN_PRESETS = ("nightly",) + + +def _with_all_scan_presets(benchmark: BenchmarkCase) -> BenchmarkCase: + if benchmark in TPCDS_SF100_CASES: + return benchmark + runs = { + preset: with_all_scans(coverage) if preset in ALL_SCAN_PRESETS else coverage + for preset, coverage in benchmark.runs.items() + } + return replace(benchmark, runs=runs) + + PR_ALL_SOURCES = ("pr", "pr-compact", "pr-full") @@ -351,7 +410,10 @@ def _with_pr_all(benchmark: BenchmarkCase) -> BenchmarkCase: sources = [benchmark.runs[preset] for preset in PR_ALL_SOURCES if preset in benchmark.runs] if not sources: return benchmark - return replace(benchmark, runs={**benchmark.runs, "pr-all": merge_coverage(sources)}) + return replace(benchmark, runs={**benchmark.runs, "pr-all": merge_coverage(benchmark.benchmark, sources)}) -CATALOG = Catalog(presets=PRESETS, benchmarks=tuple(map(_with_pr_all, BENCHMARKS))) +CATALOG = Catalog( + presets=PRESETS, + benchmarks=tuple(_with_pr_all(_with_all_scan_presets(benchmark)) for benchmark in BENCHMARKS), +) diff --git a/bench-orchestrator/bench_orchestrator/ci_matrix/model.py b/bench-orchestrator/bench_orchestrator/ci_matrix/model.py index 8889f46116e..b30537ae500 100644 --- a/bench-orchestrator/bench_orchestrator/ci_matrix/model.py +++ b/bench-orchestrator/bench_orchestrator/ci_matrix/model.py @@ -4,10 +4,10 @@ """Data model for declarative CI benchmark coverage.""" from collections.abc import Mapping -from dataclasses import dataclass +from dataclasses import dataclass, replace from enum import Enum -from ..config import Benchmark, Format +from ..config import SCAN_COMBINATIONS, Benchmark, BenchmarkTarget, Format from .targets import TargetSet @@ -18,12 +18,44 @@ class Storage(Enum): S3 = "s3" +class ScanCoverage(Enum): + """Which integration and scan engine combinations a coverage runs for its Vortex targets.""" + + # Each Vortex target as declared: the file integration on the suite's default scan engine, + # unless the target names others. + DEFAULT = "default" + # The declared targets plus every other valid combination for the `vortex` format. Each + # combination runs as a matrix entry of its own, see `render`. + ALL = "all" + + @dataclass(frozen=True) class Coverage: """Targets and generated formats for one benchmark in one preset.""" targets: TargetSet data_formats: tuple[Format, ...] | None = None + scans: ScanCoverage = ScanCoverage.DEFAULT + + def resolved_targets(self, benchmark: Benchmark) -> TargetSet: + """Return the targets this coverage runs in `benchmark`, with every scan engine named. + + Combinations the suite cannot run, such as v2 on a list-layout suite, are left out of the + added ones; a declared target the suite cannot run stays in and fails validation. + """ + resolved = [target.resolved(benchmark) for target in self.targets] + if self.scans is ScanCoverage.DEFAULT: + return TargetSet(tuple(resolved)) + + alternates: list[BenchmarkTarget] = [] + for target in resolved: + if target.format is not Format.VORTEX: + continue + for integration, scan in SCAN_COMBINATIONS: + candidate = replace(target, integration=integration, scan=scan) + if candidate not in resolved and candidate.is_supported(benchmark): + alternates.append(candidate) + return TargetSet(tuple(resolved) + tuple(alternates)) @dataclass(frozen=True) diff --git a/bench-orchestrator/bench_orchestrator/ci_matrix/render.py b/bench-orchestrator/bench_orchestrator/ci_matrix/render.py index 5a6f462fed3..d74b9ee90a7 100644 --- a/bench-orchestrator/bench_orchestrator/ci_matrix/render.py +++ b/bench-orchestrator/bench_orchestrator/ci_matrix/render.py @@ -3,8 +3,8 @@ """Render declarative benchmark coverage as GitHub Actions matrices.""" -from ..config import Format -from .model import BenchmarkCase, Catalog, Coverage +from ..config import Benchmark, BenchmarkTarget, Engine, Format, Integration, ScanEngine +from .model import BenchmarkCase, Catalog, Coverage, ScanCoverage from .targets import TargetSet from .validate import validate_catalog @@ -19,32 +19,82 @@ ) -def _data_formats(coverage: Coverage) -> list[Format]: +def _data_formats(coverage: Coverage, targets: TargetSet) -> list[Format]: if coverage.data_formats is not None: return list(coverage.data_formats) - present = {target.format for target in coverage.targets} + present = {target.format for target in targets} return [fmt for fmt in _FORMAT_ORDER if fmt in present and fmt not in _NOT_GENERATED] -def merge_coverage(coverages: list[Coverage]) -> Coverage: - """Union several coverages: every target and every generated data format.""" +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() for coverage in coverages: - targets = targets | coverage.targets - formats.update(_data_formats(coverage)) - return Coverage(targets, data_formats=tuple(fmt for fmt in _FORMAT_ORDER if fmt in formats)) + resolved = coverage.resolved_targets(benchmark) + targets = targets | resolved + formats.update(_data_formats(coverage, resolved)) + 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) -def _matrix_entry(benchmark: BenchmarkCase, coverage: Coverage) -> dict[str, object]: +ScanGroup = tuple[Engine, Integration, ScanEngine] + + +def _scan_group(target: BenchmarkTarget, benchmark: Benchmark) -> ScanGroup | None: + """Return the scan a target runs, or `None` for the default group: every target that keeps its + bare format identity, which is Parquet and the like and the file integration on the suite's + default scan engine.""" + resolved = target.resolved(benchmark) + if not resolved.is_vortex or resolved.result_format("", benchmark) == "": + return None + assert resolved.scan is not None + return (resolved.engine, resolved.integration, resolved.scan) + + +def _matrix_entries(benchmark: BenchmarkCase, coverage: Coverage) -> list[dict[str, object]]: + """Render one case's coverage, one entry per scan when it covers every scan. + + Each entry runs on a machine of its own, so the extra scans add machines rather than wall time, + and a failing scan cannot take another entry's results with it. The default group keeps the + case's id, name and history; the other scans are named `{id}-{engine}-{integration}-{scan}`. + Every entry of a case shares its `group`, which the PR comment collects into one table. + """ + targets = coverage.resolved_targets(benchmark.benchmark) + groups: dict[ScanGroup | None, list[BenchmarkTarget]] = {} + for target in targets: + group = _scan_group(target, benchmark.benchmark) if coverage.scans is ScanCoverage.ALL else None + groups.setdefault(group, []).append(target) + + entries = [] + for group, group_targets in groups.items(): + entry = _matrix_entry(benchmark, coverage, TargetSet(tuple(group_targets)), group) + entries.append(entry) + return entries + + +def _matrix_entry( + benchmark: BenchmarkCase, coverage: Coverage, targets: TargetSet, group: ScanGroup | None +) -> dict[str, object]: + suffix = "" if group is None else "-" + "-".join(axis.value for axis in group) + if group is None: + data_formats = _data_formats(coverage, targets) + else: + # A scan's entry generates only the formats its targets read. + data_formats = _data_formats(Coverage(targets), targets) entry: dict[str, object] = { - "id": benchmark.id, + "id": benchmark.id + suffix, + "group": benchmark.id, + "group_name": benchmark.name, "subcommand": benchmark.subcommand, - "name": benchmark.name, + "name": benchmark.name if group is None else f"{benchmark.name} ({' '.join(a.value for a in group)})", "dataset_dir": benchmark.data_dir_name, - "targets": [target.to_dict() for target in coverage.targets], - "data_formats": [fmt.value for fmt in _data_formats(coverage)], + "targets": [target.to_dict() for target in targets], + "data_formats": [fmt.value for fmt in data_formats], + # 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, } if benchmark.scale_factor is not None: entry["scale_factor"] = str(benchmark.scale_factor) @@ -53,7 +103,8 @@ def _matrix_entry(benchmark: BenchmarkCase, coverage: Coverage) -> dict[str, obj if benchmark.local_dir is not None: entry["local_dir"] = benchmark.local_dir if benchmark.remote_key is not None: - entry["remote_key"] = benchmark.remote_key + # 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 return entry @@ -64,6 +115,14 @@ def render_matrix(preset: str, catalog: Catalog) -> list[dict[str, object]]: raise ValueError(f"Unknown matrix preset {preset!r}. Available: {known}") validate_catalog(catalog) - return [ - _matrix_entry(benchmark, benchmark.runs[preset]) for benchmark in catalog.benchmarks if preset in benchmark.runs + entries = [ + entry + for benchmark in catalog.benchmarks + if preset in benchmark.runs + for entry in _matrix_entries(benchmark, benchmark.runs[preset]) ] + ids = [entry["id"] for entry in entries] + duplicates = sorted({entry_id for entry_id in ids if ids.count(entry_id) > 1}) + if duplicates: + raise ValueError(f"Preset {preset!r} renders duplicate matrix entry IDs: {duplicates}") + return entries diff --git a/bench-orchestrator/bench_orchestrator/ci_matrix/validate.py b/bench-orchestrator/bench_orchestrator/ci_matrix/validate.py index 5f950077a13..b07c82038ee 100644 --- a/bench-orchestrator/bench_orchestrator/ci_matrix/validate.py +++ b/bench-orchestrator/bench_orchestrator/ci_matrix/validate.py @@ -8,12 +8,16 @@ def _validate_coverage(benchmark: BenchmarkCase, preset: str, coverage: Coverage) -> None: - if len(coverage.targets) == 0: + targets = coverage.resolved_targets(benchmark.benchmark) + if len(targets) == 0: raise ValueError(f"Benchmark {benchmark.id!r} resolved to no runnable targets") - for target in coverage.targets: - if not target.is_supported(): - raise ValueError(f"Benchmark {benchmark.id!r} has unsupported target {target} in preset {preset!r}") + for target in targets: + errors = target.support_errors(benchmark.benchmark) + if errors: + raise ValueError( + f"Benchmark {benchmark.id!r} has unsupported target {target} in preset {preset!r}: {errors[0]}" + ) if target.engine not in engines_for_benchmark(benchmark.benchmark): raise ValueError(f"Benchmark {benchmark.id!r} cannot run target {target} in preset {preset!r}") if benchmark.storage is Storage.S3 and target.format is Format.LANCE: diff --git a/bench-orchestrator/bench_orchestrator/cli.py b/bench-orchestrator/bench_orchestrator/cli.py index 959eee6a26a..3ebe58bbfeb 100644 --- a/bench-orchestrator/bench_orchestrator/cli.py +++ b/bench-orchestrator/bench_orchestrator/cli.py @@ -16,6 +16,7 @@ import pandas as pd import typer from rich.console import Console +from rich.markup import escape from rich.table import Table from .ci_matrix import MATRIX_PRESETS, resolve_matrix @@ -32,11 +33,11 @@ parse_formats_json, parse_targets_json, resolve_axis_targets, - uses_scan_v2, ) from .data_cache import S3DataCache, cached_dataset from .runner.builder import BenchmarkBuilder from .runner.executor import BenchmarkExecutor +from .runner.labels import label_ingest_file, label_result_line from .storage.store import ResultStore app = typer.Typer( @@ -362,6 +363,8 @@ def run( for warning in warnings: console.print(f"[yellow]Warning: {warning}[/yellow]") + # Vortex targets without a scan engine run the suite's default; name it from here on. + targets = list(dict.fromkeys(target.resolved(benchmark) for target in targets)) if not targets: console.print("[red]No valid benchmark targets selected[/red]") raise typer.Exit(1) @@ -398,10 +401,8 @@ def run( raise typer.Exit(1) console.print(f"\n[bold]Running {benchmark.value} benchmark[/bold]") - console.print(f" Targets: {', '.join(map(str, config.targets))}") + console.print(f" Targets: {escape(', '.join(map(str, config.targets)))}") console.print(f" Iterations: {iterations}") - if any(target.engine in {Engine.DATAFUSION, Engine.DUCKDB} for target in config.targets): - console.print(f" Vortex scan: {'V2' if uses_scan_v2(benchmark) else 'V1'}") if label: console.print(f" Label: {label}") console.print() @@ -422,7 +423,8 @@ def run( for target in backend_targets: query_results: list[str] = [] - def stream(line: str) -> None: + def stream(line: str, target: BenchmarkTarget = target) -> None: + line = label_result_line(line, target, benchmark) query_results.append(line) write_result_line(line, ctx.write_raw_json, compatibility_file) @@ -451,8 +453,12 @@ def stream(line: str) -> None: runner=runner, ingest_output=part_ingest_output, on_result=stream, + integration=target.integration, + scan=target.scan, ) if part_ingest_output is not None: + if part_ingest_output.exists(): + label_ingest_file(part_ingest_output, target, benchmark) ingest_output_parts.append(part_ingest_output) elapsed = (datetime.now() - started).total_seconds() @@ -464,12 +470,12 @@ def stream(line: str) -> None: soft_wrap=True, ) - console.print(f"[green]{target}: {len(query_ids)} queries[/green]") + console.print(f"[green]{escape(str(target))}: {len(query_ids)} queries[/green]") except RuntimeError as exc: ctx.metadata.partial = True if strict_failures: raise - console.print(f"[red]{target} failed: {exc}[/red]") + console.print(f"[red]{escape(str(target))} failed: {escape(str(exc))}[/red]") soft_failures.append(str(exc)) if ingest_output is not None: diff --git a/bench-orchestrator/bench_orchestrator/comparison/reporter.py b/bench-orchestrator/bench_orchestrator/comparison/reporter.py index 3561a4d52af..a27c4053fee 100644 --- a/bench-orchestrator/bench_orchestrator/comparison/reporter.py +++ b/bench-orchestrator/bench_orchestrator/comparison/reporter.py @@ -7,6 +7,7 @@ import pandas as pd from rich.console import Console +from rich.markup import escape from rich.table import Table from rich.text import Text @@ -59,9 +60,9 @@ def pivot_comparison_table( # Add column for each comparison target for col in pivot.columns: if col == pivot.baseline: - table.add_column(f"{col} (base)", justify="right") + table.add_column(f"{escape(col)} (base)", justify="right") else: - table.add_column(col, justify="right") + table.add_column(escape(col), justify="right") # Add rows for _, row in pivot.df.iterrows(): diff --git a/bench-orchestrator/bench_orchestrator/config.py b/bench-orchestrator/bench_orchestrator/config.py index 4735f9bf767..7be6cff9e29 100644 --- a/bench-orchestrator/bench_orchestrator/config.py +++ b/bench-orchestrator/bench_orchestrator/config.py @@ -5,7 +5,7 @@ import json from collections.abc import Iterable -from dataclasses import dataclass, field +from dataclasses import dataclass, field, replace from enum import Enum from pathlib import Path from typing import Any, TypeVar @@ -48,6 +48,26 @@ class Format(Enum): LANCE = "lance" +class Integration(Enum): + """How an engine reaches Vortex files. The files on disk are the same for every integration.""" + + # File-at-a-time integration: DataFusion's `ListingTable` and `FileOpener`, DuckDB's + # `MultiFileReader`. + FILE = "file" + # A `DataSource` over the whole table: DataFusion's `VortexTable`. DuckDB has no `DataSource` + # table function yet. + DATASOURCE = "datasource" + + +class ScanEngine(Enum): + """The Vortex scan engine a target runs on.""" + + # `LayoutReader`s. + V1 = "v1" + # Planner-driven scan plans. + V2 = "v2" + + class Benchmark(Enum): """Available benchmark suites.""" @@ -93,10 +113,13 @@ class Benchmark(Enum): } -# Benchmarks whose Vortex scans still run on the V1 scan. The orchestrator runs every other -# benchmark on the planner-driven V2 scan, overriding the benchmark binaries' V1 default. -# These suites write the list layout, which the V2 scan cannot read yet. -BENCHMARK_SCAN_V1: frozenset[Benchmark] = frozenset( +# Formats whose targets name an integration and a scan engine. Other formats (Parquet, DuckDB's own +# format, Lance) are controls and comparisons, with neither axis. +VORTEX_FORMATS: frozenset[Format] = frozenset({Format.VORTEX, Format.VORTEX_COMPACT, Format.VORTEX_SPATIAL_NATIVE}) + +# Benchmarks the V2 scan cannot run yet: they write the list layout, which V2 cannot read. This is a +# constraint, not a selector; a target names its scan engine, and V2 targets are rejected here. +BENCHMARKS_WITHOUT_SCAN_V2: frozenset[Benchmark] = frozenset( { Benchmark.POLARSIGNALS, Benchmark.STATPOPGEN, @@ -104,10 +127,54 @@ class Benchmark(Enum): } ) +# The integration and scan engine combinations each engine can run on Vortex formats. Adding a +# combination here, plus its flag in `BenchmarkExecutor`, is all a new one needs. +SUPPORTED_SCANS: dict[Engine, dict[Integration, frozenset[ScanEngine]]] = { + Engine.DATAFUSION: { + Integration.FILE: frozenset({ScanEngine.V1, ScanEngine.V2}), + # `VortexTable` reaches only V1: `MultiFileDataSource` opens `LayoutReader`s. V2 needs the V2 + # scan behind `split`/`open` (#11626). + Integration.DATASOURCE: frozenset({ScanEngine.V1}), + }, + Engine.DUCKDB: { + Integration.FILE: frozenset({ScanEngine.V1, ScanEngine.V2}), + }, +} + +# Every combination in a stable order: the suite's default engine comes first wherever it is used. +SCAN_COMBINATIONS: tuple[tuple[Integration, ScanEngine], ...] = ( + (Integration.FILE, ScanEngine.V2), + (Integration.FILE, ScanEngine.V1), + (Integration.DATASOURCE, ScanEngine.V2), + (Integration.DATASOURCE, ScanEngine.V1), +) + -def uses_scan_v2(benchmark: Benchmark) -> bool: - """Return whether `benchmark` runs its Vortex scans on the V2 scan.""" - return benchmark not in BENCHMARK_SCAN_V1 +def supports_scan_v2(benchmark: Benchmark) -> bool: + """Return whether the V2 scan can run `benchmark`.""" + return benchmark not in BENCHMARKS_WITHOUT_SCAN_V2 + + +def default_scan_engine(benchmark: Benchmark) -> ScanEngine: + """Return the scan engine a Vortex target runs when it names none: V2 wherever V2 can run.""" + return ScanEngine.V2 if supports_scan_v2(benchmark) else ScanEngine.V1 + + +def scan_support_error(engine: Engine, integration: Integration, scan: ScanEngine | None) -> str | None: + """Explain why `engine` cannot scan Vortex through `integration` on `scan`, or return None.""" + integrations = SUPPORTED_SCANS.get(engine, {}) + if integration not in integrations: + if integration is Integration.DATASOURCE and engine is Engine.DUCKDB: + return "duckdb has no DataSource table function yet, so it has no datasource targets" + return f"{engine.value} has no {integration.value} integration" + if scan is not None and scan not in integrations[integration]: + if engine is Engine.DATAFUSION and integration is Integration.DATASOURCE and scan is ScanEngine.V2: + return ( + "datafusion datasource targets run only the v1 scan: MultiFileDataSource opens " + "LayoutReaders, and v2 needs the V2 scan behind split/open (#11626)" + ) + return f"{engine.value} {integration.value} targets cannot run the {scan.value} scan" + return None def engines_for_benchmark(benchmark: Benchmark) -> frozenset[Engine]: @@ -131,17 +198,35 @@ def _unique_preserve_order(values: Iterable[T]) -> list[T]: @dataclass(frozen=True) class BenchmarkTarget: - """An explicit engine/format benchmark target.""" + """An explicit benchmark target. + + Vortex targets also name an integration and a scan engine. A Vortex target without a scan + engine runs the suite's default, see `resolved`. + """ engine: Engine format: Format + integration: Integration = Integration.FILE + scan: ScanEngine | None = None def normalized(self) -> "BenchmarkTarget": """Normalize legacy lance targets onto the logical CI identity.""" if self.engine == Engine.LANCE and self.format == Format.LANCE: - return BenchmarkTarget(engine=Engine.DATAFUSION, format=Format.LANCE) + return replace(self, engine=Engine.DATAFUSION) return self + @property + def is_vortex(self) -> bool: + """Return whether this target names an integration and a scan engine.""" + return self.format in VORTEX_FORMATS + + def resolved(self, benchmark: Benchmark) -> "BenchmarkTarget": + """Fill in the scan engine a Vortex target runs in `benchmark` when it names none.""" + target = self.normalized() + if target.is_vortex and target.scan is None: + return replace(target, scan=default_scan_engine(benchmark)) + return target + @property def backend(self) -> Engine: """Return the engine whose benchmark binary should execute this target.""" @@ -154,14 +239,56 @@ def backend(self) -> Engine: return Engine.DUCKDB raise ValueError(f"Unsupported benchmark target: {target}") - def is_supported(self) -> bool: - """Return whether the logical engine supports this format.""" + def support_errors(self, benchmark: Benchmark | None = None) -> list[str]: + """Explain why this target cannot run, in `benchmark` when given; empty when it can.""" target = self.normalized() - return target.format in ENGINE_FORMATS.get(target.engine, []) + if target.format not in ENGINE_FORMATS.get(target.engine, []): + return [f"Format {target.format.value} is not supported by engine {target.engine.value}"] + if not target.is_vortex: + if target.integration is not Integration.FILE or target.scan is not None: + return [f"{target.engine.value}:{target.format.value} takes no integration or scan engine"] + return [] + error = scan_support_error(target.engine, target.integration, target.scan) + if error is not None: + return [error] + if benchmark is not None: + resolved = target.resolved(benchmark) + if resolved.scan is ScanEngine.V2 and not supports_scan_v2(benchmark): + return [f"Benchmark {benchmark.value} cannot run the v2 scan yet (list layout): {resolved}"] + error = scan_support_error(target.engine, target.integration, resolved.scan) + if error is not None: + return [error] + return [] + + def is_supported(self, benchmark: Benchmark | None = None) -> bool: + """Return whether this target can run, in `benchmark` when given.""" + return not self.support_errors(benchmark) + + def result_format(self, format_name: str, benchmark: Benchmark) -> str: + """Return the format identity results record for this target, given the binary's label. + + The benchmark binaries label results by engine and format alone, and the benchmarks + database keys rows on them. The file integration on the suite's default engine keeps the + bare format, which is the identity its history was recorded under; every other combination + appends both axes, e.g. `vortex-file-compressed [datasource, v1]`. The axes are also + recorded as fields of their own, see `runner.labels`. + """ + target = self.resolved(benchmark) + if not target.is_vortex: + return format_name + if target.integration is Integration.FILE and target.scan is default_scan_engine(benchmark): + return format_name + assert target.scan is not None + return f"{format_name} [{target.integration.value}, {target.scan.value}]" def to_dict(self) -> dict[str, str]: target = self.normalized() - return {"engine": target.engine.value, "format": target.format.value} + data = {"engine": target.engine.value, "format": target.format.value} + if target.is_vortex: + data["integration"] = target.integration.value + if target.scan is not None: + data["scan"] = target.scan.value + return data @classmethod def from_dict(cls, data: dict[str, Any]) -> "BenchmarkTarget": @@ -171,6 +298,8 @@ def from_dict(cls, data: dict[str, Any]) -> "BenchmarkTarget": target = cls( engine=Engine(data["engine"]), format=Format(data["format"]), + integration=Integration(data.get("integration", Integration.FILE.value)), + scan=ScanEngine(data["scan"]) if data.get("scan") is not None else None, ) except KeyError as exc: raise ValueError("Targets must include engine and format fields") from exc @@ -179,8 +308,17 @@ def from_dict(cls, data: dict[str, Any]) -> "BenchmarkTarget": return target.normalized() def __str__(self) -> str: + """Render the target as `engine:format`, naming both axes for Vortex targets. + + For example `datafusion:vortex [file, v2]`, or `datafusion:vortex [file]` before the scan + engine is resolved. + """ target = self.normalized() - return f"{target.engine.value}:{target.format.value}" + label = f"{target.engine.value}:{target.format.value}" + if not target.is_vortex: + return label + axes = [target.integration.value] + ([target.scan.value] if target.scan is not None else []) + return f"{label} [{', '.join(axes)}]" def parse_targets_json(value: str) -> list[BenchmarkTarget]: @@ -230,6 +368,8 @@ def resolve_axis_targets( continue for fmt in formats: target = BenchmarkTarget(engine=engine, format=fmt).normalized() + if benchmark is not None: + target = target.resolved(benchmark) if not target.is_supported(): warnings.append(f"Format {fmt.value} is not supported by engine {engine.value}") continue @@ -254,8 +394,7 @@ def validate_targets( normalized_targets = [target.normalized() for target in targets] for target in normalized_targets: - if not target.is_supported(): - errors.append(f"Format {target.format.value} is not supported by engine {target.engine.value}") + errors.extend(target.support_errors(benchmark)) if benchmark is not None and target.engine not in engines_for_benchmark(benchmark): errors.append(f"Benchmark {benchmark.value} does not support engine {target.engine.value}") diff --git a/bench-orchestrator/bench_orchestrator/runner/executor.py b/bench-orchestrator/bench_orchestrator/runner/executor.py index dcb9b1935bd..6a09e872926 100644 --- a/bench-orchestrator/bench_orchestrator/runner/executor.py +++ b/bench-orchestrator/bench_orchestrator/runner/executor.py @@ -14,10 +14,18 @@ from rich.console import Console from rich.progress import Progress, SpinnerColumn, TextColumn -from ..config import Benchmark, Engine, Format, uses_scan_v2 +from ..config import Benchmark, Engine, Format, Integration, ScanEngine, default_scan_engine console = Console() +# Arguments each backend's binary takes to run an integration. A DuckDB datasource target needs an +# entry here once DuckDB has a `DataSource` table function. +INTEGRATION_ARGS: dict[tuple[Engine, Integration], list[str]] = { + (Engine.DATAFUSION, Integration.FILE): [], + (Engine.DUCKDB, Integration.FILE): [], + (Engine.DATAFUSION, Integration.DATASOURCE): ["--scan-api", "true"], +} + @final class BenchmarkExecutor: @@ -41,8 +49,14 @@ def build_command( tracing: bool = False, runner: str | None = None, ingest_output: Path | None = None, + integration: Integration = Integration.FILE, + scan: ScanEngine | None = None, ) -> list[str]: - """Build the command used to execute a benchmark binary.""" + """Build the command used to execute a benchmark binary. + + `scan` selects the Vortex scan engine; without one the binary runs the suite's default. + """ + self._check_integration(integration) cmd = [ str(self.binary_path), benchmark.value, @@ -55,7 +69,9 @@ def build_command( if self.backend in {Engine.DATAFUSION, Engine.DUCKDB}: cmd.extend(["--formats", ",".join(fmt.value for fmt in formats)]) - cmd.extend(["--scan-v1", str(not uses_scan_v2(benchmark)).lower()]) + scan = scan if scan is not None else default_scan_engine(benchmark) + cmd.extend(["--scan-v1", str(scan is ScanEngine.V1).lower()]) + cmd.extend(INTEGRATION_ARGS.get((self.backend, integration), [])) if self.backend == Engine.DUCKDB: cmd.append("--delete-duckdb-database") @@ -87,6 +103,10 @@ def build_command( return cmd + 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 list_queries( self, benchmark: Benchmark, @@ -125,6 +145,8 @@ def run( runner: str | None = None, ingest_output: Path | None = None, on_result: Callable[[str], None] | None = None, + integration: Integration = Integration.FILE, + scan: ScanEngine | None = None, ) -> list[str]: """ Run benchmark and return results as JSON lines. @@ -136,6 +158,8 @@ def run( iterations: Number of runs per query options: Additional options (e.g., scale_factor) track_memory: Enable memory tracking + integration: How the engine reaches Vortex files + scan: The Vortex scan engine, or None for the suite's default on_result: Callback for each result line (for streaming) Returns: @@ -153,6 +177,8 @@ def run( tracing=tracing, runner=runner, ingest_output=ingest_output, + integration=integration, + scan=scan, ) if self.verbose: diff --git a/bench-orchestrator/bench_orchestrator/runner/labels.py b/bench-orchestrator/bench_orchestrator/runner/labels.py new file mode 100644 index 00000000000..a3cc2dce410 --- /dev/null +++ b/bench-orchestrator/bench_orchestrator/runner/labels.py @@ -0,0 +1,65 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright the Vortex contributors + +"""Label benchmark binary output with the target's integration and scan engine. + +The benchmark binaries label results by engine and format alone, so every Vortex target on the same +files would share one identity. Each result gets both axes as fields of their own (`integration` +and `scan_engine`), and its format identity names them too unless it is the file integration on +the suite's default engine, whose history keeps the bare format; see +`BenchmarkTarget.result_format`. +""" + +import json +from pathlib import Path +from typing import Any + +from ..config import Benchmark, BenchmarkTarget + + +def _axes(target: BenchmarkTarget, benchmark: Benchmark) -> dict[str, str]: + resolved = target.resolved(benchmark) + if not resolved.is_vortex or resolved.scan is None: + return {} + return {"integration": resolved.integration.value, "scan_engine": resolved.scan.value} + + +def _label_name(name: object, target: BenchmarkTarget, benchmark: Benchmark) -> object: + # Names have the shape `{dataset}_qNN[_memory]/{engine}:{format}`. + if isinstance(name, str) and "/" in name and ":" in name.rsplit("/", 1)[1]: + prefix, name_format = name.rsplit(":", 1) + return f"{prefix}:{target.result_format(name_format, benchmark)}" + return name + + +def label_result_line(line: str, target: BenchmarkTarget, benchmark: Benchmark) -> str: + """Label one results-JSON line (`--display-format gh-json`) for `target`.""" + axes = _axes(target, benchmark) + if not axes or not line.lstrip().startswith("{"): + return line + record: dict[str, Any] = json.loads(line) + + record_target = record.get("target") + if isinstance(record_target, dict) and isinstance(record_target.get("format"), str): + record_target["format"] = target.result_format(record_target["format"], benchmark) + record["name"] = _label_name(record.get("name"), target, benchmark) + record.update(axes) + + return json.dumps(record, separators=(",", ":")) + + +def label_ingest_file(path: Path, target: BenchmarkTarget, benchmark: Benchmark) -> None: + """Label the `--ingest-jsonl` query records in `path` for `target`, in place.""" + axes = _axes(target, benchmark) + if not axes: + return + lines = [] + for line in path.read_text(encoding="utf-8").splitlines(): + if line.strip(): + record = json.loads(line) + if record.get("kind") == "query_measurement" and isinstance(record.get("format"), str): + record["format"] = target.result_format(record["format"], benchmark) + record.update(axes) + line = json.dumps(record, separators=(",", ":")) + lines.append(line) + path.write_text("".join(f"{line}\n" for line in lines), encoding="utf-8") diff --git a/bench-orchestrator/tests/test_cli.py b/bench-orchestrator/tests/test_cli.py index ea20531df13..f7f6a0512b4 100644 --- a/bench-orchestrator/tests/test_cli.py +++ b/bench-orchestrator/tests/test_cli.py @@ -170,3 +170,73 @@ def test_format_query_reading_summarizes_runtimes() -> None: def test_format_query_reading_without_timing() -> None: memory = json.dumps({"name": "tpch_q01 memory", "unit": "bytes", "value": 1024}) assert cli_module.format_query_reading([memory]) == "no timing reported" + + +def test_run_keeps_each_scan_apart(tmp_path, monkeypatch) -> None: + run_store = ResultStore(base_dir=tmp_path / "runs") + output_path = tmp_path / "artifacts" / "results.json" + ingest_path = tmp_path / "artifacts" / "results.ingest.jsonl" + binary_path = tmp_path / "datafusion-bench" + binary_path.write_text("", encoding="utf-8") + + 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: None) + monkeypatch.setattr(BenchmarkExecutor, "list_queries", lambda self, *args, **kwargs: [1]) + + seen_scans = [] + + def fake_run(self, **kwargs: object) -> list[str]: + # The binary labels every scan identically; only the orchestrator knows the axes. + seen_scans.append((kwargs["integration"].value, kwargs["scan"].value)) + line = json.dumps( + { + "name": "tpch_q01/datafusion:vortex-file-compressed", + "unit": "ns", + "value": 100, + "all_runtimes": [100], + "target": {"engine": "datafusion", "format": "vortex-file-compressed"}, + } + ) + kwargs["on_result"](line) + record = {"kind": "query_measurement", "engine": "datafusion", "format": "vortex-file-compressed"} + kwargs["ingest_output"].write_text(json.dumps(record) + "\n", encoding="utf-8") + return [line] + + monkeypatch.setattr(BenchmarkExecutor, "run", fake_run) + + result = runner.invoke( + cli_module.app, + [ + "run", + "tpch", + "--targets-json", + '[{"engine":"datafusion","format":"vortex"},' + '{"engine":"datafusion","format":"vortex","integration":"datasource","scan":"v1"}]', + "--no-build", + "--output", + str(output_path), + "--ingest-jsonl", + str(ingest_path), + ], + ) + + assert result.exit_code == 0, result.stdout + assert seen_scans == [("file", "v2"), ("datasource", "v1")] + results = [json.loads(line) for line in output_path.read_text(encoding="utf-8").splitlines()] + assert [record["name"] for record in results] == [ + "tpch_q01/datafusion:vortex-file-compressed", + "tpch_q01/datafusion:vortex-file-compressed [datasource, v1]", + ] + assert [(record["integration"], record["scan_engine"]) for record in results] == [ + ("file", "v2"), + ("datasource", "v1"), + ] + ingest = [json.loads(line) for line in ingest_path.read_text(encoding="utf-8").splitlines()] + assert [record["format"] for record in ingest] == [ + "vortex-file-compressed", + "vortex-file-compressed [datasource, v1]", + ] + assert [record["scan_engine"] for record in ingest] == ["v2", "v1"] + assert "datafusion:vortex [file, v2]" in result.stdout + assert "datafusion:vortex [datasource, v1]" in result.stdout diff --git a/bench-orchestrator/tests/test_config.py b/bench-orchestrator/tests/test_config.py index e2b09b06141..f73b8bffaf7 100644 --- a/bench-orchestrator/tests/test_config.py +++ b/bench-orchestrator/tests/test_config.py @@ -1,11 +1,16 @@ # SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright the Vortex contributors +import pytest from bench_orchestrator.config import ( + BENCHMARKS_WITHOUT_SCAN_V2, Benchmark, BenchmarkTarget, Engine, Format, + Integration, + ScanEngine, + default_scan_engine, group_targets_by_backend, parse_formats_json, parse_targets_json, @@ -13,6 +18,8 @@ validate_targets, ) +DATASOURCE_V1 = BenchmarkTarget(Engine.DATAFUSION, Format.VORTEX, Integration.DATASOURCE, ScanEngine.V1) + def test_parse_targets_json_normalizes_and_dedupes_lance_targets() -> None: targets = parse_targets_json('[{"engine":"lance","format":"lance"},{"engine":"datafusion","format":"lance"}]') @@ -65,9 +72,10 @@ def test_resolve_axis_targets_skips_engines_a_benchmark_cannot_run() -> None: Benchmark.SPATIALBENCH, ) + # Vortex targets resolve to the suite's default scan. assert targets == [ BenchmarkTarget(engine=Engine.DUCKDB, format=Format.PARQUET), - BenchmarkTarget(engine=Engine.DUCKDB, format=Format.VORTEX), + BenchmarkTarget(Engine.DUCKDB, Format.VORTEX, Integration.FILE, ScanEngine.V2), ] assert warnings == ["Benchmark spatialbench does not support engine datafusion"] @@ -83,8 +91,8 @@ def test_resolve_axis_targets_supports_spatialbench_three_lanes() -> None: assert targets == [ BenchmarkTarget(engine=Engine.DUCKDB, format=Format.PARQUET), - BenchmarkTarget(engine=Engine.DUCKDB, format=Format.VORTEX), - BenchmarkTarget(engine=Engine.DUCKDB, format=Format.VORTEX_SPATIAL_NATIVE), + BenchmarkTarget(Engine.DUCKDB, Format.VORTEX, Integration.FILE, ScanEngine.V2), + BenchmarkTarget(Engine.DUCKDB, Format.VORTEX_SPATIAL_NATIVE, Integration.FILE, ScanEngine.V2), ] assert warnings == [] @@ -128,3 +136,110 @@ def test_group_targets_by_backend_routes_lance_to_lance_binary() -> None: def test_datafusion_package_and_binary_names_match() -> None: assert Engine.DATAFUSION.package_name == "datafusion-bench" assert Engine.DATAFUSION.binary_name == "datafusion-bench" + + +def test_scan_axes_name_the_target() -> None: + assert BenchmarkTarget(Engine.DATAFUSION, Format.VORTEX).to_dict() == { + "engine": "datafusion", + "format": "vortex", + "integration": "file", + } + assert DATASOURCE_V1.to_dict() == { + "engine": "datafusion", + "format": "vortex", + "integration": "datasource", + "scan": "v1", + } + assert str(DATASOURCE_V1) == "datafusion:vortex [datasource, v1]" + assert str(BenchmarkTarget(Engine.DATAFUSION, Format.VORTEX)) == "datafusion:vortex [file]" + assert str(BenchmarkTarget(Engine.DATAFUSION, Format.VORTEX).resolved(Benchmark.TPCH)) == ( + "datafusion:vortex [file, v2]" + ) + assert str(BenchmarkTarget(Engine.DATAFUSION, Format.PARQUET).resolved(Benchmark.TPCH)) == "datafusion:parquet" + assert parse_targets_json( + '[{"engine":"datafusion","format":"vortex"},' + '{"engine":"datafusion","format":"vortex","integration":"datasource","scan":"v1"}]' + ) == [BenchmarkTarget(Engine.DATAFUSION, Format.VORTEX), DATASOURCE_V1] + + +@pytest.mark.parametrize( + ("benchmark", "target", "result_format"), + [ + # The file integration on the suite's default scan keeps the format its history is under. + (Benchmark.TPCH, BenchmarkTarget(Engine.DATAFUSION, Format.VORTEX), "vortex-file-compressed"), + ( + Benchmark.TPCH, + BenchmarkTarget(Engine.DUCKDB, Format.VORTEX, Integration.FILE, ScanEngine.V2), + "vortex-file-compressed", + ), + (Benchmark.TPCH_NESTED, BenchmarkTarget(Engine.DUCKDB, Format.VORTEX), "vortex-file-compressed"), + ( + Benchmark.TPCH, + BenchmarkTarget(Engine.DATAFUSION, Format.VORTEX, Integration.FILE, ScanEngine.V1), + "vortex-file-compressed [file, v1]", + ), + (Benchmark.TPCH, DATASOURCE_V1, "vortex-file-compressed [datasource, v1]"), + (Benchmark.TPCH_NESTED, DATASOURCE_V1, "vortex-file-compressed [datasource, v1]"), + (Benchmark.TPCH, BenchmarkTarget(Engine.DATAFUSION, Format.PARQUET), "parquet"), + ], +) +def test_result_format_keeps_history_for_the_default_scan( + benchmark: Benchmark, target: BenchmarkTarget, result_format: str +) -> None: + assert target.result_format(result_format.split(" [", 1)[0], benchmark) == result_format + + +def test_parse_targets_json_rejects_unknown_axes() -> None: + with pytest.raises(ValueError, match="Invalid benchmark target"): + _ = parse_targets_json('[{"engine":"datafusion","format":"vortex","integration":"scan-api"}]') + with pytest.raises(ValueError, match="Invalid benchmark target"): + _ = parse_targets_json('[{"engine":"datafusion","format":"vortex","scan":"v3"}]') + + +@pytest.mark.parametrize( + ("engine", "integration", "scan", "error"), + [ + (Engine.DATAFUSION, Integration.FILE, ScanEngine.V1, None), + (Engine.DATAFUSION, Integration.FILE, ScanEngine.V2, None), + (Engine.DATAFUSION, Integration.DATASOURCE, ScanEngine.V1, None), + (Engine.DUCKDB, Integration.FILE, ScanEngine.V1, None), + (Engine.DUCKDB, Integration.FILE, ScanEngine.V2, None), + (Engine.DATAFUSION, Integration.DATASOURCE, ScanEngine.V2, "datasource targets run only the v1 scan"), + (Engine.DUCKDB, Integration.DATASOURCE, ScanEngine.V1, "duckdb has no DataSource table function yet"), + (Engine.DUCKDB, Integration.DATASOURCE, ScanEngine.V2, "duckdb has no DataSource table function yet"), + ], +) +def test_scan_combinations(engine: Engine, integration: Integration, scan: ScanEngine, error: str | None) -> None: + errors = validate_targets([BenchmarkTarget(engine, Format.VORTEX, integration, scan)], {}) + + if error is None: + assert errors == [] + else: + (message,) = errors + assert error in message + + +def test_non_vortex_targets_take_no_scan_axes() -> None: + errors = validate_targets([BenchmarkTarget(Engine.DATAFUSION, Format.PARQUET, Integration.DATASOURCE)], {}) + + assert errors == ["datafusion:parquet takes no integration or scan engine"] + + +@pytest.mark.parametrize("benchmark", list(Benchmark)) +def test_v2_scan_is_the_default_where_the_suite_supports_it(benchmark: Benchmark) -> None: + file_v2 = BenchmarkTarget(Engine.DATAFUSION, Format.VORTEX, Integration.FILE, ScanEngine.V2) + expected = ScanEngine.V1 if benchmark in BENCHMARKS_WITHOUT_SCAN_V2 else ScanEngine.V2 + + assert default_scan_engine(benchmark) is expected + assert BenchmarkTarget(Engine.DATAFUSION, Format.VORTEX).resolved(benchmark).scan is expected + assert file_v2.is_supported(benchmark) is (expected is ScanEngine.V2) + + +def test_validate_targets_rejects_v2_on_list_layouts() -> None: + errors = validate_targets( + [BenchmarkTarget(Engine.DUCKDB, Format.VORTEX, Integration.FILE, ScanEngine.V2)], + {}, + benchmark=Benchmark.TPCH_NESTED, + ) + + assert errors == ["Benchmark tpch-nested cannot run the v2 scan yet (list layout): duckdb:vortex [file, v2]"] diff --git a/bench-orchestrator/tests/test_executor.py b/bench-orchestrator/tests/test_executor.py index 067d72af3ae..709a56b1824 100644 --- a/bench-orchestrator/tests/test_executor.py +++ b/bench-orchestrator/tests/test_executor.py @@ -6,7 +6,7 @@ from pathlib import Path import pytest -from bench_orchestrator.config import BENCHMARK_SCAN_V1, Benchmark, Engine, Format +from bench_orchestrator.config import BENCHMARKS_WITHOUT_SCAN_V2, Benchmark, Engine, Format, Integration, ScanEngine from bench_orchestrator.runner.executor import BenchmarkExecutor @@ -47,21 +47,31 @@ def test_build_command_serializes_vortex_spatial_native_format() -> None: assert cmd[cmd.index("--formats") + 1] == "parquet,vortex,vortex-spatial-native" -def test_scan_v1_benchmarks_are_explicit() -> None: - assert BENCHMARK_SCAN_V1 == {Benchmark.POLARSIGNALS, Benchmark.STATPOPGEN, Benchmark.TPCH_NESTED} +def test_benchmarks_without_scan_v2_are_explicit() -> None: + assert BENCHMARKS_WITHOUT_SCAN_V2 == {Benchmark.POLARSIGNALS, Benchmark.STATPOPGEN, Benchmark.TPCH_NESTED} @pytest.mark.parametrize("engine", [Engine.DATAFUSION, Engine.DUCKDB]) @pytest.mark.parametrize("benchmark", list(Benchmark)) -def test_build_command_selects_scan_version(engine: Engine, benchmark: Benchmark) -> None: +def test_build_command_defaults_to_the_suites_scan(engine: Engine, benchmark: Benchmark) -> None: executor = BenchmarkExecutor(Path("/tmp/bench"), engine) cmd = executor.build_command(benchmark=benchmark, formats=[Format.VORTEX]) - expected = "true" if benchmark in BENCHMARK_SCAN_V1 else "false" + expected = "true" if benchmark in BENCHMARKS_WITHOUT_SCAN_V2 else "false" assert cmd[cmd.index("--scan-v1") + 1] == expected +@pytest.mark.parametrize("engine", [Engine.DATAFUSION, Engine.DUCKDB]) +@pytest.mark.parametrize(("scan", "scan_v1"), [(ScanEngine.V1, "true"), (ScanEngine.V2, "false")]) +def test_build_command_passes_the_targets_scan(engine: Engine, scan: ScanEngine, scan_v1: str) -> None: + executor = BenchmarkExecutor(Path("/tmp/bench"), engine) + + cmd = executor.build_command(benchmark=Benchmark.TPCH, formats=[Format.VORTEX], scan=scan) + + assert cmd[cmd.index("--scan-v1") + 1] == scan_v1 + + def test_build_command_omits_formats_for_lance_backend() -> None: executor = BenchmarkExecutor(Path("/tmp/lance-bench"), Engine.LANCE) @@ -130,3 +140,32 @@ def test_run_streams_logs_without_counting_them(tmp_path: Path) -> None: assert results == ['{"engine":"duckdb","format":"parquet","query":0}'] assert streamed == results + + +def test_datasource_integration_registers_vortex_table() -> None: + executor = BenchmarkExecutor(Path("/tmp/datafusion-bench"), Engine.DATAFUSION) + + cmd = executor.build_command( + benchmark=Benchmark.TPCH, formats=[Format.VORTEX], integration=Integration.DATASOURCE, scan=ScanEngine.V1 + ) + + assert cmd[cmd.index("--scan-api") + 1] == "true" + assert cmd[cmd.index("--scan-v1") + 1] == "true" + + +@pytest.mark.parametrize("engine", [Engine.DATAFUSION, Engine.DUCKDB]) +def test_file_integration_omits_the_scan_api_flag(engine: Engine) -> None: + executor = BenchmarkExecutor(Path("/tmp/bench"), engine) + + cmd = executor.build_command(benchmark=Benchmark.TPCH, formats=[Format.VORTEX]) + + assert "--scan-api" not in cmd + + +def test_datasource_integration_is_rejected_by_duckdb() -> None: + executor = BenchmarkExecutor(Path("/tmp/duckdb-bench"), Engine.DUCKDB) + + with pytest.raises(ValueError, match="duckdb cannot run the datasource integration"): + _ = executor.build_command( + benchmark=Benchmark.TPCH, formats=[Format.VORTEX], integration=Integration.DATASOURCE + ) diff --git a/bench-orchestrator/tests/test_labels.py b/bench-orchestrator/tests/test_labels.py new file mode 100644 index 00000000000..3014d790b41 --- /dev/null +++ b/bench-orchestrator/tests/test_labels.py @@ -0,0 +1,81 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright the Vortex contributors + +import json +from pathlib import Path + +import pytest +from bench_orchestrator.config import Benchmark, BenchmarkTarget, Engine, Format, Integration, ScanEngine +from bench_orchestrator.runner.labels import label_ingest_file, label_result_line + +FILE_DEFAULT = BenchmarkTarget(Engine.DATAFUSION, Format.VORTEX) +DATASOURCE_V1 = BenchmarkTarget(Engine.DATAFUSION, Format.VORTEX, Integration.DATASOURCE, ScanEngine.V1) +PARQUET = BenchmarkTarget(Engine.DATAFUSION, Format.PARQUET) + + +def _result_line(name: str, file_format: str = "vortex-file-compressed") -> str: + return json.dumps( + { + "name": name, + "storage": "nvme", + "unit": "ns", + "value": 10, + "all_runtimes": [10, 11], + "target": {"engine": "datafusion", "format": file_format}, + } + ) + + +@pytest.mark.parametrize( + "name", ["tpch_q01/datafusion:vortex-file-compressed", "tpch_q01_memory/datafusion:vortex-file-compressed"] +) +def test_label_result_line_names_both_axes(name: str) -> None: + record = json.loads(label_result_line(_result_line(name), DATASOURCE_V1, Benchmark.TPCH)) + + assert record["name"] == name + " [datasource, v1]" + assert record["target"] == {"engine": "datafusion", "format": "vortex-file-compressed [datasource, v1]"} + assert (record["integration"], record["scan_engine"]) == ("datasource", "v1") + assert record["all_runtimes"] == [10, 11] + + +@pytest.mark.parametrize(("benchmark", "scan"), [(Benchmark.TPCH, "v2"), (Benchmark.TPCH_NESTED, "v1")]) +def test_label_result_line_keeps_the_default_identity(benchmark: Benchmark, scan: str) -> None: + name = "tpch_q01/datafusion:vortex-file-compressed" + + record = json.loads(label_result_line(_result_line(name), FILE_DEFAULT, benchmark)) + + assert record["name"] == name + assert record["target"]["format"] == "vortex-file-compressed" + assert (record["integration"], record["scan_engine"]) == ("file", scan) + + +def test_label_result_line_leaves_controls_and_logs_alone() -> None: + line = _result_line("tpch_q01/datafusion:parquet", "parquet") + + assert label_result_line(line, PARQUET, Benchmark.TPCH) == line + assert label_result_line("not json", DATASOURCE_V1, Benchmark.TPCH) == "not json" + + +def test_label_ingest_file_names_both_axes(tmp_path: Path) -> None: + record = {"kind": "query_measurement", "engine": "datafusion", "format": "vortex-file-compressed", "query_idx": 1} + path = tmp_path / "part.jsonl" + path.write_text(json.dumps(record) + "\n") + + label_ingest_file(path, DATASOURCE_V1, Benchmark.TPCH) + + (line,) = path.read_text().splitlines() + assert json.loads(line) == { + **record, + "format": "vortex-file-compressed [datasource, v1]", + "integration": "datasource", + "scan_engine": "v1", + } + + +def test_label_ingest_file_leaves_controls_alone(tmp_path: Path) -> None: + path = tmp_path / "part.jsonl" + path.write_text('{"kind": "query_measurement", "format": "parquet"}\n') + + label_ingest_file(path, PARQUET, Benchmark.TPCH) + + assert path.read_text() == '{"kind": "query_measurement", "format": "parquet"}\n' diff --git a/bench-orchestrator/tests/test_matrix.py b/bench-orchestrator/tests/test_matrix.py index ed80a7e38ad..67abe1b8812 100644 --- a/bench-orchestrator/tests/test_matrix.py +++ b/bench-orchestrator/tests/test_matrix.py @@ -14,6 +14,7 @@ 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 typer.testing import CliRunner runner = CliRunner() @@ -40,7 +41,8 @@ # TPC-DS SF=10 on NVMe runs in the PR presets and nightly, not on every develop commit. PR_IDS = (*REGULAR_IDS[:7], "tpcds-nvme-10", *REGULAR_IDS[7:]) PR_FULL_IDS = (*PR_IDS[:-1], "job-nvme", "tpch-nested-nvme", "vortex-queries") -EXPECTED_IDS = { +# The benchmark cases each preset runs; a case covering every scan runs as several matrix entries. +EXPECTED_GROUPS = { "develop": DEVELOP_IDS, "pr": tuple( benchmark_id @@ -55,6 +57,7 @@ "vortex-queries", } ), + "pr-scan": ("clickbench-nvme", "tpch-nvme"), "pr-compact": COMPACT_IDS, "pr-all": PR_FULL_IDS, "pr-full": PR_FULL_IDS, @@ -66,12 +69,21 @@ *( f"tpcds-{storage}-100-{target}" for storage in ("nvme", "s3") - for target in ("datafusion-parquet", "datafusion-vortex", "duckdb-parquet", "duckdb-vortex") + for target in ( + "datafusion-parquet", + "datafusion-vortex", + "duckdb-parquet", + "duckdb-vortex", + "datafusion-vortex-file-v1", + "datafusion-vortex-datasource-v1", + "duckdb-vortex-file-v1", + ) ), "tpch-nested-nvme", "tpch-nested-s3", ), } +SCAN_SUFFIXES = ("datafusion-file-v1", "datafusion-datasource-v1", "duckdb-file-v1") def _entries(preset: str) -> list[dict[str, object]]: @@ -79,75 +91,200 @@ def _entries(preset: str) -> list[dict[str, object]]: def _targets(entry: dict[str, object]) -> set[tuple[str, str]]: + """Return an entry's targets as `(engine, format)`, with any scan axes appended to the format.""" targets = cast("list[dict[str, str]]", entry["targets"]) - return {(target["engine"], target["format"]) for target in targets} + return { + ( + target["engine"], + target["format"] + (f" [{target['integration']}, {target['scan']}]" if "integration" in target else ""), + ) + for target in targets + } + + +def _groups(preset: str) -> dict[str, dict[str, object]]: + """Merge each case's matrix entries back into one: its targets and data formats.""" + groups: dict[str, dict[str, object]] = {} + for entry in _entries(preset): + group = groups.setdefault(str(entry["group"]), {"ids": [], "targets": set(), "data_formats": set()}) + cast("list[str]", group["ids"]).append(str(entry["id"])) + cast("set[tuple[str, str]]", group["targets"]).update(_targets(entry)) + cast("set[str]", group["data_formats"]).update(cast("list[str]", entry["data_formats"])) + return groups + + +def _group_targets(preset: str) -> dict[str, set[tuple[str, str]]]: + return {group: cast("set[tuple[str, str]]", value["targets"]) for group, value in _groups(preset).items()} -@pytest.mark.parametrize(("preset", "expected_ids"), EXPECTED_IDS.items()) -def test_matrix_presets(preset: str, expected_ids: tuple[str, ...]) -> None: +ALL_SCANS = { + ("datafusion", "parquet"), + ("datafusion", "vortex [file, v2]"), + ("datafusion", "vortex [file, v1]"), + ("datafusion", "vortex [datasource, v1]"), + ("duckdb", "parquet"), + ("duckdb", "vortex [file, v2]"), + ("duckdb", "vortex [file, v1]"), +} +DEFAULT_SCANS = { + ("datafusion", "parquet"), + ("datafusion", "vortex [file, v2]"), + ("duckdb", "parquet"), + ("duckdb", "vortex [file, v2]"), +} + + +@pytest.mark.parametrize(("preset", "expected_groups"), EXPECTED_GROUPS.items()) +def test_matrix_presets(preset: str, expected_groups: tuple[str, ...]) -> None: entries = _entries(preset) ids = [entry["id"] for entry in entries] - assert tuple(ids) == expected_ids + assert tuple(_groups(preset)) == expected_groups assert len(ids) == len(set(ids)) assert all(entry["targets"] for entry in entries) assert "${{" not in json.dumps(entries) +@pytest.mark.parametrize("preset", ["pr-scan", "develop", "nightly"]) +def test_every_scan_runs_on_a_machine_of_its_own(preset: str) -> None: + groups = _groups(preset) + entries = {entry["id"]: entry for entry in _entries(preset)} + + assert groups["tpch-nvme"]["ids"] == ["tpch-nvme", *(f"tpch-nvme-{suffix}" for suffix in SCAN_SUFFIXES)] + assert ALL_SCANS <= _group_targets(preset)["tpch-nvme"] + # The default entry keeps the case's id and history and records its data; a scan's entry + # generates only the Vortex files it reads. + assert entries["tpch-nvme"]["records_data"] is True + assert ("datafusion", "vortex [file, v1]") not in _targets(entries["tpch-nvme"]) + for suffix in SCAN_SUFFIXES: + entry = entries[f"tpch-nvme-{suffix}"] + assert entry["group"] == "tpch-nvme" + assert len(_targets(entry)) == 1 + assert entry["data_formats"] == ["vortex"] + assert entry["records_data"] is False + + +def test_pr_scan_runs_every_scan_on_clickbench_and_tpch_nvme() -> None: + groups = _group_targets("pr-scan") + + assert groups == {"clickbench-nvme": ALL_SCANS, "tpch-nvme": ALL_SCANS} + + +def test_pr_runs_only_the_default_scans() -> None: + entries = _entries("pr") + + assert all(entry["id"] == entry["group"] for entry in entries) + assert _group_targets("pr")["tpch-nvme"] == DEFAULT_SCANS + + +def test_develop_runs_every_scan_where_pr_scan_compares_against_it() -> None: + groups = _group_targets("develop") + + for benchmark_id in ("clickbench-nvme", "tpch-nvme"): + assert ALL_SCANS <= groups[benchmark_id] + assert ("datafusion", "vortex [file, v1]") not in groups["tpch-nvme-10"] + + +@pytest.mark.parametrize("preset", ["develop", "nightly", "pr-full", "pr-all"]) +def test_every_s3_entry_has_its_own_remote_key(preset: str) -> None: + keys = [entry["remote_key"] for entry in _entries(preset) if "remote_key" in entry] + + assert len(keys) == len(set(keys)) + + 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"]) ] - assert len(nightly) == 8 + assert len(nightly) == 14 assert all(len(_targets(entry)) == 1 for entry in nightly) + assert {target for entry in nightly for target in _targets(entry)} == ALL_SCANS s3_keys = [entry["remote_key"] for entry in nightly if "remote_key" in entry] - assert len(s3_keys) == len(set(s3_keys)) == 4 + assert len(s3_keys) == len(set(s3_keys)) == 7 -def test_pr_target_selection() -> None: - develop = {entry["id"]: entry for entry in _entries("develop")} - pr = {entry["id"]: entry for entry in _entries("pr")} - pr_compact = {entry["id"]: entry for entry in _entries("pr-compact")} - pr_full = {entry["id"]: entry for entry in _entries("pr-full")} +def test_nightly_runs_every_scan() -> None: + groups = _group_targets("nightly") - assert _targets(pr["tpch-nvme"]) == { + assert groups["tpch-s3"] == ALL_SCANS + # Nested TPC-H reads list layouts, which the v2 scan cannot read yet. + assert groups["tpch-nested-s3"] == { ("datafusion", "parquet"), - ("datafusion", "vortex"), + ("datafusion", "vortex [file, v1]"), + ("datafusion", "vortex [datasource, v1]"), ("duckdb", "parquet"), - ("duckdb", "vortex"), + ("duckdb", "vortex [file, v1]"), } - assert ("datafusion", "lance") in _targets(develop["tpch-nvme"]) + + +def test_pr_target_selection() -> None: + develop = _group_targets("develop") + pr_compact = _groups("pr-compact") + pr_full = _group_targets("pr-full") + + assert ("datafusion", "lance") in develop["tpch-nvme"] for preset in (pr_full, develop): - assert {engine for engine, _format in _targets(preset["statpopgen"])} == {"datafusion", "duckdb"} - assert all(("datafusion", "lance") not in _targets(entry) for entry in pr_full.values()) - assert "vortex-compact" in cast("list[str]", pr_full["clickbench-nvme"]["data_formats"]) - for entry in pr_compact.values(): - targets = _targets(entry) - assert {file_format for _engine, file_format in targets} == {"parquet", "vortex-compact"} - assert set(cast("list[str]", entry["data_formats"])) == {"parquet", "vortex-compact"} + assert {engine for engine, _format in preset["statpopgen"]} == {"datafusion", "duckdb"} + assert all(("datafusion", "lance") not in targets for targets in pr_full.values()) + assert "vortex-compact" in cast("set[str]", _groups("pr-full")["clickbench-nvme"]["data_formats"]) + for group in pr_compact.values(): + targets = cast("set[tuple[str, str]]", group["targets"]) + assert {file_format.split(" [", 1)[0] for _engine, file_format in targets} == {"parquet", "vortex-compact"} + assert group["data_formats"] == {"parquet", "vortex-compact"} + + +@pytest.mark.parametrize("preset", ["pr", "pr-compact", "pr-full", "pr-all"]) +def test_only_pr_scan_adds_scans_to_pull_requests(preset: str) -> None: + # The extra scans cost a machine each, so pull requests opt in with `action/bench-scan`. + assert all(entry["id"] == entry["group"] for entry in _entries(preset)) + + +def test_nightly_runs_every_valid_scan() -> None: + for benchmark_id, targets in _group_targets("nightly").items(): + if "-100-" in benchmark_id: + continue + engines = {engine for engine, fmt in targets if fmt.startswith("vortex [")} + scans = {(engine, fmt) for engine, fmt in targets if fmt.startswith("vortex [")} + expected = {(engine, "vortex [file, v1]") for engine in engines} | ( + {("datafusion", "vortex [datasource, v1]")} if "datafusion" in engines else set() + ) + if not benchmark_id.startswith("tpch-nested"): + expected |= {(engine, "vortex [file, v2]") for engine in engines} + assert scans == expected, benchmark_id + + +def test_scan_targets_round_trip_through_targets_json() -> None: + entries = {entry["id"]: entry for entry in _entries("pr-scan")} + + (target,) = parse_targets_json(json.dumps(entries["tpch-nvme-datafusion-datasource-v1"]["targets"])) + default = parse_targets_json(json.dumps(entries["tpch-nvme"]["targets"])) + + assert target == BenchmarkTarget(Engine.DATAFUSION, Format.VORTEX, Integration.DATASOURCE, ScanEngine.V1) + assert BenchmarkTarget(Engine.DATAFUSION, Format.VORTEX, Integration.FILE, ScanEngine.V2) in default + assert BenchmarkTarget(Engine.DATAFUSION, Format.PARQUET) in default def test_pr_all_is_union_of_pr_compact_and_full() -> None: - sources = [{entry["id"]: entry for entry in _entries(preset)} for preset in ("pr", "pr-compact", "pr-full")] - pr_all = {entry["id"]: entry for entry in _entries("pr-all")} + sources = [_groups(preset) for preset in ("pr", "pr-compact", "pr-full")] + pr_all = _groups("pr-all") assert set(pr_all) == set().union(*sources) - for benchmark_id, entry in pr_all.items(): - assert _targets(entry) == set().union(*(_targets(p[benchmark_id]) for p in sources if benchmark_id in p)) + for benchmark_id, group in pr_all.items(): + assert group["targets"] == set().union(*(p[benchmark_id]["targets"] for p in sources if benchmark_id in p)) for preset in sources: if source := preset.get(benchmark_id): - assert set(cast("list[str]", source["data_formats"])) <= set(cast("list[str]", entry["data_formats"])) + assert cast("set[str]", source["data_formats"]) <= cast("set[str]", group["data_formats"]) def test_pr_full_covers_pr() -> None: - pr = {entry["id"]: entry for entry in _entries("pr")} - pr_full = {entry["id"]: entry for entry in _entries("pr-full")} + pr = _groups("pr") + pr_full = _groups("pr-full") - for benchmark_id, entry in pr.items(): - full_entry = pr_full[benchmark_id] - assert _targets(entry) <= _targets(full_entry) - assert set(cast("list[str]", entry["data_formats"])) <= set(cast("list[str]", full_entry["data_formats"])) + for benchmark_id, group in pr.items(): + full_group = pr_full[benchmark_id] + assert cast("set[object]", group["targets"]) <= cast("set[object]", full_group["targets"]) + assert cast("set[str]", group["data_formats"]) <= cast("set[str]", full_group["data_formats"]) def test_resolver_rejects_empty_targets() -> None: @@ -191,4 +328,4 @@ def test_matrix_command() -> None: def test_preset_names_are_stable() -> None: - assert set(MATRIX_PRESETS) == set(EXPECTED_IDS) + assert set(MATRIX_PRESETS) == set(EXPECTED_GROUPS) diff --git a/benchmarks/datafusion-bench/src/main.rs b/benchmarks/datafusion-bench/src/main.rs index e2acd536fdc..d5d6d328513 100644 --- a/benchmarks/datafusion-bench/src/main.rs +++ b/benchmarks/datafusion-bench/src/main.rs @@ -124,6 +124,12 @@ struct Args { #[arg(long, default_value_t = true, action = clap::ArgAction::Set)] scan_v1: bool, + /// Register Vortex tables through the Scan API (`VortexTable` over a `MultiFileDataSource`) + /// instead of a listing table, whatever `--scan-v1` says. `MultiFileDataSource` runs the V1 + /// scan. + #[arg(long, default_value_t = false, action = clap::ArgAction::Set)] + scan_api: bool, + #[arg(long = "opt", value_delimiter = ',', value_parser = value_parser!(Opt))] options: Vec, } @@ -137,6 +143,7 @@ async fn main() -> anyhow::Result<()> { let args = Args::parse(); let opts = Opts::from(args.options); let scan_v2 = !args.scan_v1; + let scan_api = args.scan_api; set_join_set_tracer(get_static_tracer())?; setup_logging_and_tracing(args.verbose, args.tracing)?; @@ -196,7 +203,8 @@ async fn main() -> anyhow::Result<()> { session.sql(&sql).await?.collect().await?; } datafusion_bench::make_object_store(&session, benchmark.data_url())?; - register_benchmark_tables(&session, benchmark, format, scan_v2).await?; + register_benchmark_tables(&session, benchmark, format, scan_v2, scan_api) + .await?; Ok((session, format)) } }, @@ -252,18 +260,14 @@ async fn main() -> anyhow::Result<()> { Ok(()) } -fn use_scan_api() -> bool { - std::env::var("VORTEX_USE_SCAN_API").is_ok_and(|v| v == "1") -} - async fn register_benchmark_tables( session: &SessionContext, benchmark: &B, format: Format, scan_v2: bool, + scan_api: bool, ) -> anyhow::Result<()> { - if !scan_v2 && use_scan_api() && matches!(format, Format::OnDiskVortex | Format::VortexCompact) - { + if scan_api && matches!(format, Format::OnDiskVortex | Format::VortexCompact) { register_v2_tables(session, benchmark, format).await } else { let benchmark_base = benchmark.data_url().join(&format!("{}/", format.name()))?; @@ -300,7 +304,7 @@ async fn register_benchmark_tables( } } -/// Register tables using the V2 `VortexTable` + `MultiFileDataSource` path. +/// Register tables using the Scan API path: a `VortexTable` over a `MultiFileDataSource`. async fn register_v2_tables( session: &SessionContext, benchmark: &B, diff --git a/docs/developer-guide/benchmarking.md b/docs/developer-guide/benchmarking.md index e26ca423b86..36899d73249 100644 --- a/docs/developer-guide/benchmarking.md +++ b/docs/developer-guide/benchmarking.md @@ -305,6 +305,12 @@ Benchmarks run automatically on all commits to `develop` and can be run on-deman - **SQL** -- `action/bench-sql` runs the `pr` preset, a quick core subset of the SQL benchmarks that includes TPC-DS SF=10 on NVMe and excludes `vortex-compact`, Clickbench Sorted, Appian, JOB, nested TPC-H, statpopgen, FineWeb on S3, TPC-H SF=10 on S3, and Vortex queries. +- **SQL Scan** -- `action/bench-scan` runs the `pr-scan` preset: ClickBench and TPC-H SF=1 on + NVMe with every valid Vortex integration and scan engine, each combination on a machine of its + own. Vortex targets name both axes, such as `datafusion:vortex [file, v2]`: the integration is + `file` (DataFusion `ListingTable`, DuckDB `MultiFileReader`) or `datasource` (DataFusion + `VortexTable` over a Vortex `DataSource`), and the scan engine is `v1` (LayoutReader) or `v2` + (plans). Use it on PRs that change either path. - **SQL Extended** -- `action/bench-sql-extended` runs the `pr-full` preset: every regular SQL benchmark, including `vortex-compact` and DuckDB-format targets. - **SQL Compact** -- `action/bench-sql-compact` runs the `pr-compact` preset, which benchmarks diff --git a/scripts/compare-benchmark-jsons.py b/scripts/compare-benchmark-jsons.py index ef2b4827e92..d8adca90adf 100644 --- a/scripts/compare-benchmark-jsons.py +++ b/scripts/compare-benchmark-jsons.py @@ -204,6 +204,7 @@ def ingest_record_row(record: dict[str, Any]) -> dict[str, Any] | None: if dims: row["dataset"] = dims row["target"] = {"engine": engine, "format": file_format} + row.update({axis: record[axis] for axis in SCAN_AXES if record.get(axis) is not None}) elif kind == "random_access_time": ext = "vortex" if str(file_format).startswith("vortex") else file_format row["name"] = f"random-access/{record['dataset']}/{ext}-{record['open_mode']}" @@ -256,6 +257,35 @@ def read_benchmark_rows(path: str) -> pd.DataFrame: return pd.DataFrame(rows) +# Fields the bench orchestrator records on Vortex SQL results: the integration (`file` or +# `datasource`) and the scan engine (`v1` or `v2`). See `BenchmarkTarget` in bench-orchestrator. +SCAN_AXES = ("integration", "scan_engine") + + +def label_scan_axes(base: pd.DataFrame, pr: pd.DataFrame) -> None: + """Name the integration and scan engine in every Vortex format that does not already. + + Only the file integration on a suite's default scan engine keeps the bare format identity, so + its history continues; every other combination already carries `[integration, scan]`. The PR + rows record both axes as fields, which label the bare format on both sides alike, so a column + never reads as a different engine than it ran. The match and merge keys are left unchanged. + """ + + if not set(SCAN_AXES) <= set(pr.columns): + return + labels = {} + for engine, file_format, integration, scan in zip( + pr["engine"], pr["file_format"], pr["integration"], pr["scan_engine"] + ): + if isinstance(integration, str) and isinstance(scan, str) and " [" not in str(file_format): + labels[(engine, file_format)] = f"{file_format} [{integration}, {scan}]" + for df in (base, pr): + df["file_format"] = [ + labels.get((engine, file_format), file_format) + for engine, file_format in zip(df["engine"], df["file_format"]) + ] + + def normalize_measurement_rows(df: pd.DataFrame) -> pd.DataFrame: """Add canonical comparison keys to benchmark measurement rows.""" @@ -776,43 +806,46 @@ def query_column_label(engine: str, file_format: str) -> str: return f"{engine}:{file_format}" -def query_column_sort_key(combo: tuple[str, str]) -> tuple[int, int, str, str]: - """Order query table columns by engine, then format, with a format's variants beside it. +# Within a format, the file integration comes before datasource and the v2 scan before v1, so +# each engine's columns start with the target its history is recorded under. +SCAN_AXIS_ORDER = {"file": 0, "datasource": 1, "v2": 0, "v1": 1} - A variant such as `vortex-file-compressed [scan-api]` sorts right after its base format. - """ + +def query_column_sort_key(combo: tuple[str, str]) -> tuple[int, int, str, tuple[int, ...], str]: + """Order query table columns by engine, then format, with a format's scan variants beside it, + e.g. `[file, v2]`, `[file, v1]`, then `[datasource, v1]`.""" engine, file_format = combo - base_format = file_format.split(" [", 1)[0] + base_format, _, axes = file_format.partition(" [") + axis_order = tuple(SCAN_AXIS_ORDER.get(axis.strip(), len(SCAN_AXIS_ORDER)) for axis in axes.rstrip("]").split(",")) return ( ENGINE_ORDER.get(engine, len(ENGINE_ORDER)), FILE_FORMAT_ORDER.get(base_format, len(FILE_FORMAT_ORDER)), engine, + axis_order if axes else (), file_format, ) -# Notes printed under the query table caption when a column of that variant is present. -FORMAT_VARIANT_NOTES = { - "scan-api": ( - "`[scan-api]` columns run DataFusion through the Scan API (`VortexTable`) on the V1 scan. " - "Compare them with their own develop times, not with the V2 `datafusion:vortex` column." - ), -} +# Printed under the query table caption when any column names an integration and scan engine. +SCAN_AXES_NOTE = ( + "Vortex columns name the integration and the scan engine: `file` reads through the engine's file " + "format (DataFusion `ListingTable`, DuckDB `MultiFileReader`), `datasource` through DataFusion's " + "`VortexTable` over a Vortex `DataSource`; `v1` and `v2` are the LayoutReader and plan scans. " + "Each column compares with its own develop times." +) def format_query_table_caption(df: pd.DataFrame, base_label: str, pr_label: str, threshold_pct: int) -> str: - """Say what the query table compares, and note any format variant its columns carry.""" + """Say what the query table compares, and what the scan axes on its Vortex columns mean.""" lines = [ f"Each cell is develop `{base_label}` โ†’ this PR `{pr_label}` (hot runs), with PR รท develop in " f"parentheses: below 1.00 is faster. Changes past ยฑ{threshold_pct}% are bold. The geomean row " "compares each target's geomean over its queries." ] - variants = { - str(file_format).split(" [", 1)[1].rstrip("]") for file_format in df["file_format"] if " [" in str(file_format) - } - lines += [FORMAT_VARIANT_NOTES[variant] for variant in sorted(variants) if variant in FORMAT_VARIANT_NOTES] + if any(" [" in str(file_format) for file_format in df["file_format"]): + lines.append(SCAN_AXES_NOTE) return "
".join(lines) @@ -1316,6 +1349,7 @@ def main() -> None: base = normalize_measurement_rows(base) pr = normalize_measurement_rows(pr) + label_scan_axes(base, pr) comparison_keys = ["name", "storage", "dataset_key", "engine", "file_format", "unit", "query"] df3 = pd.merge(base, pr, on=comparison_keys, how="right", suffixes=("_base", "_pr")) diff --git a/scripts/post-ingest.py b/scripts/post-ingest.py index 9c98668ec01..44a1126c111 100755 --- a/scripts/post-ingest.py +++ b/scripts/post-ingest.py @@ -185,6 +185,10 @@ def build_commit(sha: str, branch: str, repo_url: str, git_dir: Path | None) -> "physical_delta", "virtual_delta", "env_triple", + # The bench orchestrator's Vortex scan axes. The format identity already names + # them (see `BenchmarkTarget.result_format`), so they are validated but not stored. + "integration", + "scan_engine", } ), ), @@ -374,6 +378,8 @@ def _memory_quartet_consistent(r: dict) -> bool: ("storage", "str"), ("engine", "str"), ("format", "str"), + ("integration", "opt_str"), + ("scan_engine", "opt_str"), ("value_ns", "i64"), ("all_runtimes_ns", "i64_list"), ("peak_physical", "opt_i64"), @@ -463,6 +469,11 @@ def _validate_record_values(record: dict, kind: str, index: int) -> None: raise SystemExit( f"record {index} (query_measurement): storage must be 'nvme' or 's3', got {record['storage']!r}" ) + for field, values in (("integration", ("file", "datasource")), ("scan_engine", ("v1", "v2"))): + if record.get(field) not in (None, *values): + raise SystemExit( + f"record {index} (query_measurement): {field} must be one of {values}, got {record[field]!r}" + ) if not _memory_quartet_consistent(record): raise SystemExit( f"record {index} (query_measurement): memory fields must be populated together (all four or none)" diff --git a/scripts/tests/test_benchmark_reporting.py b/scripts/tests/test_benchmark_reporting.py index 0a44b46fa2c..1b55c84191a 100644 --- a/scripts/tests/test_benchmark_reporting.py +++ b/scripts/tests/test_benchmark_reporting.py @@ -965,29 +965,40 @@ def test_capture_file_sizes_reads_only_the_named_directory(tmp_path: Path) -> No assert [record["value"] for record in records] == [42] -def test_query_table_puts_a_format_variant_beside_its_base_format(tmp_path: Path) -> None: +def test_query_table_names_each_vortex_columns_integration_and_scan(tmp_path: Path) -> None: + # (engine, recorded format, integration, scan engine, develop ns, PR ns). The file integration on + # the default scan keeps the bare format, so develop's records carry no axes for it. targets = [ - ("duckdb", "vortex-file-compressed", 90, 90), - ("datafusion", "parquet", 100, 100), - ("datafusion", "vortex-file-compressed [scan-api]", 1_500_000, 1_200_000), - ("datafusion", "vortex-file-compressed", 80, 80), + ("duckdb", "vortex-file-compressed", "file", "v2", 90, 90), + ("datafusion", "parquet", None, None, 100, 100), + ("datafusion", "vortex-file-compressed [datasource, v1]", "datasource", "v1", 1_500_000, 1_200_000), + ("datafusion", "vortex-file-compressed [file, v1]", "file", "v1", 70, 70), + ("datafusion", "vortex-file-compressed", "file", "v2", 80, 80), + ] + base = [query_record("base-sha", 1, engine, fmt, base) for engine, fmt, _i, _s, base, _pr in targets] + pr = [ + { + **query_record("pr-sha", 1, engine, fmt, pr), + **({"integration": integration, "scan_engine": scan} if integration else {}), + } + for engine, fmt, integration, scan, _base, pr in targets ] - base = [query_record("base-sha", 1, engine, fmt, base) for engine, fmt, base, _pr in targets] - pr = [query_record("pr-sha", 1, engine, fmt, pr) for engine, fmt, _base, pr in targets] pr_results = [stored_timing_row("pr-sha", "ignored when records exist", 1)] report = render_report(tmp_path, base, pr_results, "TPC-H", pr) assert markdown_row(report, "query") == [ "query", - "datafusion:vortex", - "datafusion:vortex [scan-api]", + "datafusion:vortex [file, v2]", + "datafusion:vortex [file, v1]", + "datafusion:vortex [datasource, v1]", "datafusion:parquet", - "duckdb:vortex", + "duckdb:vortex [file, v2]", ] - assert markdown_row(report, "tpch_q01")[2] == "**1.50 โ†’ 1.20 ms (0.80)** ๐ŸŸข" - # The variant's column carries a note on what it measures. - assert "`[scan-api]` columns run DataFusion through the Scan API" in report + assert markdown_row(report, "tpch_q01")[3] == "**1.50 โ†’ 1.20 ms (0.80)** ๐ŸŸข" + # The bare default identity still matches develop's records. + assert markdown_row(report, "tpch_q01")[1] == "80.0 โ†’ 80.0 ns (1.00)" + assert "`datasource` through DataFusion's `VortexTable`" in report def test_format_duration_picks_a_readable_unit() -> None: @@ -1015,7 +1026,7 @@ def test_query_table_says_what_it_compares(tmp_path: Path) -> None: report = render_report(tmp_path, base, pr_results, "TPC-H", pr) assert "Each cell is develop `base-sha` โ†’ this PR `pr-sha` (hot runs)" in report - assert "[scan-api]" not in report + assert "`datasource` through" not in report def test_float_query_numbers_still_count_as_sql_queries() -> None: diff --git a/scripts/tests/test_post_ingest.py b/scripts/tests/test_post_ingest.py index c2c5c830c4c..5c99d3f5e8e 100644 --- a/scripts/tests/test_post_ingest.py +++ b/scripts/tests/test_post_ingest.py @@ -91,6 +91,20 @@ def test_invalid_file_size_never_starts_transaction(writer, commit, records, inv writer.ingest_postgres(object(), commit, records) +@pytest.mark.parametrize("invalid", [{"integration": "scan-api"}, {"scan_engine": "v3"}, {"integration": 1}]) +def test_invalid_scan_axes_never_start_transaction(writer, commit, records, invalid): + records[0] = {**records[0], **invalid} + with pytest.raises(SystemExit, match=r"record 0 \(query_measurement\)"): + writer.ingest_postgres(object(), commit, records) + + +def test_query_measurements_accept_scan_axes(writer, records): + record = {**records[0], "integration": "datasource", "scan_engine": "v1"} + + kind = writer._validate_record_fields(record, 0) + writer._validate_record_values(record, kind, 0) + + def test_fact_rows_apply_in_lock_order(writer, commit, records, monkeypatch): records += [{**records[0], "query_idx": idx} for idx in (2, 3)] expected_records = deepcopy(records)