diff --git a/scripts/compare-benchmark-jsons.py b/scripts/compare-benchmark-jsons.py index 77d9ae9bddd..ef2b4827e92 100644 --- a/scripts/compare-benchmark-jsons.py +++ b/scripts/compare-benchmark-jsons.py @@ -65,6 +65,10 @@ FORMAT_DISPLAY_NAMES = { "vortex": "vortex-file-compressed", } +# Query table columns use the short format names targets are declared with. +FORMAT_COLUMN_NAMES = { + "vortex-file-compressed": "vortex", +} @dataclass @@ -703,6 +707,200 @@ def format_delta_cell( return f"{pr_text} / {base_text} / {change_text} {marker}" +def format_duration(value_ns: object) -> str: + """Render a nanosecond duration with three significant figures in a readable unit.""" + + if pd.isna(value_ns): + return "—" + value = float(value_ns) + for scale, unit in ((1e9, "s"), (1e6, "ms"), (1e3, "µs")): + if abs(value) >= scale: + value /= scale + break + else: + unit = "ns" + if abs(value) >= 100: + return f"{value:.0f} {unit}" + if abs(value) >= 10: + return f"{value:.1f} {unit}" + return f"{value:.2f} {unit}" + + +def format_query_cell( + base_value: object, + pr_value: object, + ratio: object, + improvement_threshold: float, + regression_threshold: float, +) -> str: + """Render one query cell as `develop → PR (PR/develop)`, bold and marked past the threshold. + + The unit is written once when both times share it, as in `131 → 118 ms (0.90)`. + """ + + if pd.isna(pr_value): + return "—" + pr_text = format_duration(pr_value) + if pd.isna(base_value): + return f"— → {pr_text}" + base_text = format_duration(base_value) + base_number, base_unit = base_text.rsplit(" ", 1) + if pr_text.endswith(f" {base_unit}"): + base_text = base_number + cell = f"{base_text} → {pr_text}" + if pd.isna(ratio) or float(ratio) <= 0: + return cell + cell += f" ({float(ratio):.2f})" + marker = format_change_marker(float(ratio), improvement_threshold, regression_threshold) + return f"**{cell}** {marker}" if marker else cell + + +def is_sql_query(query: object) -> bool: + """Return whether a row's query is a SQL query number, not a random-access variant.""" + + if isinstance(query, bool): + return False + if isinstance(query, (int, np.integer)): + return True + # A column that also holds query-less rows stores the numbers as floats. + return isinstance(query, (float, np.floating)) and float(query).is_integer() + + +def query_column_label(engine: str, file_format: str) -> str: + """Name a query table column the way targets are named, e.g. `datafusion:vortex`.""" + + for full_name, short_name in FORMAT_COLUMN_NAMES.items(): + if file_format == full_name or file_format.startswith(f"{full_name} "): + file_format = short_name + file_format[len(full_name) :] + break + 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. + + A variant such as `vortex-file-compressed [scan-api]` sorts right after its base format. + """ + + engine, file_format = combo + base_format = file_format.split(" [", 1)[0] + return ( + ENGINE_ORDER.get(engine, len(ENGINE_ORDER)), + FILE_FORMAT_ORDER.get(base_format, len(FILE_FORMAT_ORDER)), + engine, + 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." + ), +} + + +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.""" + + 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] + return "
".join(lines) + + +def format_query_table_summary( + df: pd.DataFrame, run: str, title: str, improvement_threshold: float, regression_threshold: float +) -> str: + """Summarize a folded query table: the geomean ratio over every cell with a develop time, + marked 🟢 or 🔴 past the threshold, then the table's size and how many cells moved each way.""" + + ratios = df["ratio" if run == "hot" else "cold_ratio"] + geomean = geometric_mean_from_values(ratios) + badge = format_change_marker(geomean, improvement_threshold, regression_threshold) or "➖" + geomean_text = "no baseline" if pd.isna(geomean) else f"geomean {geomean:.3f}x {badge}" + queries = df["name"].map(lambda name: str(name).rsplit("/", 1)[0]).nunique() + targets = df[["engine", "file_format"]].drop_duplicates().shape[0] + faster = int((ratios <= improvement_threshold).sum()) + slower = int((ratios >= regression_threshold).sum()) + query_noun = "query" if queries == 1 else "queries" + target_noun = "target" if targets == 1 else "targets" + return f"{title}: {geomean_text} · {queries} {query_noun} × {targets} {target_noun} ({faster}↑ {slower}↓)" + + +def format_query_table( + df: pd.DataFrame, + run: str, + improvement_threshold: float, + regression_threshold: float, +) -> str | None: + """Render one row per query and one column per target, with a geomean row first. + + Each cell compares the develop baseline's `run` ("hot" or "cold") time with the PR's and + gives their ratio. The geomean row does the same with each target's geomeans over its + queries; it does not compare targets with each other. + """ + + value_column = f"{run}_value_pr" + base_column = f"{run}_value_base" + ratio_column = "ratio" if run == "hot" else "cold_ratio" + rows = df[df[value_column].notna()].copy() + if rows.empty: + return None + + rows["row_label"] = rows["name"].map(lambda name: str(name).rsplit("/", 1)[0]) + row_keys = ["row_label"] + for extra in ("storage", "dataset_key"): + if rows[extra].astype(str).nunique() > 1: + row_keys.append(extra) + combos = sorted( + {(str(engine), str(file_format)) for engine, file_format in zip(rows["engine"], rows["file_format"])}, + key=query_column_sort_key, + ) + + def cell(base_value: object, value: object, ratio: object) -> str: + return format_query_cell(base_value, value, ratio, improvement_threshold, regression_threshold) + + geomean_cells = [] + for engine, file_format in combos: + target_rows = rows[(rows["engine"] == engine) & (rows["file_format"] == file_format)] + geomean_cells.append( + cell( + geometric_mean_from_values(target_rows[base_column]), + geometric_mean_from_values(target_rows[value_column]), + calculate_geometric_mean(target_rows, ratio_column), + ) + ) + + table_rows = [["**geomean**", *geomean_cells]] + for key, group in sorted(rows.groupby(row_keys, sort=False), key=lambda item: tuple(str(k) for k in item[0])): + key = key if isinstance(key, tuple) else (key,) + label = str(key[0]) + "".join(f" ({part})" for part in key[1:] if part is not None and str(part) != "nan") + cells = [] + for engine, file_format in combos: + match = group[(group["engine"] == engine) & (group["file_format"] == file_format)] + if match.empty: + cells.append("—") + else: + cells.append(cell(match[base_column].iloc[0], match[value_column].iloc[0], match[ratio_column].iloc[0])) + table_rows.append([label, *cells]) + + headers = ["query", *(query_column_label(engine, file_format) for engine, file_format in combos)] + return pd.DataFrame(table_rows, columns=headers).to_markdown( + index=False, + tablefmt="github", + disable_numparse=True, + colalign=("left", *("right" for _ in combos)), + ) + + def format_comparison_ratio(value: float) -> str: """Render a PR/base ratio or identify an unmatched PR measurement.""" @@ -1026,10 +1224,13 @@ def format_report_help() -> str: "first-run cost per row, and `hot/cold` is how much of " "each run the warm path saves. Rows whose results predate per-run reporting " "show only one value, taken from the value the runner reported.", - "- **Table cells**: Each cell reads `PR / base / %diff`. The hot and cold " - "columns mark a change as 🔴 slower or 🟢 faster once it clears this suite's " - "threshold; anything smaller is noise here and is left unmarked, as is " - "`hot/cold`, because a shift in the warm-up ratio is not a win or a loss by itself.", + "- **Query tables**: One row per query and one column per target. Each cell " + "reads `develop → PR (PR ÷ develop)`, so `(0.80)` is 20% faster than develop. A " + "change that clears this suite's threshold is bold and marked 🔴 slower or 🟢 " + "faster; anything smaller is noise here and is left plain. The `geomean` row " + "compares each target's geomean over its queries with develop's. Hot runs are " + "shown first and cold runs are folded below them.", + "- **Other tables**: Each cell reads `PR / base / %diff`, marked the same way.", "", "", ] @@ -1199,7 +1400,28 @@ def main() -> None: print("---") print("") - grouped_tables = df3.groupby(["engine", "file_format", "unit"], dropna=False, sort=False) + sql_mask = df3["query"].map(is_sql_query) & df3["unit"].eq("ns") + sql_df = df3[sql_mask] + caption = format_query_table_caption(sql_df, base_label, pr_commit_id[:8], threshold_pct) + for run, title in (("hot", "Hot runs"), ("cold", "Cold runs (first iteration)")): + table = format_query_table(sql_df, run, improvement_threshold, regression_threshold) + if table is None: + continue + summary = format_query_table_summary(sql_df, run, title, improvement_threshold, regression_threshold) + print("
") + print(f"{summary}") + print("") + print("
") + print("") + if run == "hot": + print(caption) + print("") + print(table) + print("") + print("
") + print("") + + grouped_tables = df3[~sql_mask].groupby(["engine", "file_format", "unit"], dropna=False, sort=False) for engine, file_format, unit in sorted(grouped_tables.groups.keys(), key=group_sort_key): group_df = grouped_tables.get_group((engine, file_format, unit)).sort_values("name") group_performance = format_performance( diff --git a/scripts/tests/test_benchmark_reporting.py b/scripts/tests/test_benchmark_reporting.py index 49712ef9991..0a44b46fa2c 100644 --- a/scripts/tests/test_benchmark_reporting.py +++ b/scripts/tests/test_benchmark_reporting.py @@ -195,9 +195,17 @@ def render_report( return result.stdout +def markdown_rows(report: str, name: str) -> list[list[str]]: + """Return every Markdown table row whose first cell is `name`, in report order.""" + return [ + [cell.strip() for cell in line.strip("|").split("|")] + for line in report.splitlines() + if line.startswith(f"| {name} ") + ] + + def markdown_row(report: str, name: str) -> list[str]: - line = next(line for line in report.splitlines() if line.startswith(f"| {name} ")) - return [cell.strip() for cell in line.strip("|").split("|")] + return markdown_rows(report, name)[0] def test_within_engine_analysis_uses_each_engines_own_parquet_control() -> None: @@ -348,9 +356,11 @@ def test_comparison_report_retains_sql_analysis(tmp_path: Path) -> None: assert "**Vortex (geomean)**: hot " in report assert "**Parquet (geomean)**: hot " in report assert "How to read Verdict and Engines" in report - assert "datafusion / vortex-file-compressed / ns " in report - assert "datafusion / parquet / ns " in report - assert "unknown / unknown" not in report + # SQL queries share one table, with a row per query and a column per target. + assert markdown_row(report, "query") == ["query", "datafusion:vortex", "datafusion:parquet"] + assert markdown_row(report, "tpch_q01") == ["tpch_q01", "**80.0 → 70.0 ns (0.88)** 🟢", "100 → 105 ns (1.05)"] + assert "datafusion / " not in report + assert "unknown" not in report def test_large_hot_medians_render_without_scientific_notation() -> None: @@ -397,9 +407,11 @@ def test_only_changes_past_the_suite_threshold_are_marked(tmp_path: Path) -> Non report = render_report(tmp_path, base_rows, pr_rows, "TPC-H") - assert markdown_row(report, "tpch_q01/datafusion:vortex-file-compressed")[1] == "109 / 100 / +9.0%" - assert markdown_row(report, "tpch_q02/datafusion:vortex-file-compressed")[1] == "111 / 100 / +11.0% 🔴" - assert markdown_row(report, "tpch_q03/datafusion:vortex-file-compressed")[1] == "89 / 100 / -11.0% 🟢" + assert markdown_row(report, "tpch_q01")[1] == "100 → 109 ns (1.09)" + assert markdown_row(report, "tpch_q02")[1] == "**100 → 111 ns (1.11)** 🔴" + assert markdown_row(report, "tpch_q03")[1] == "**100 → 89.0 ns (0.89)** 🟢" + # The geomean row leads the table: geomean time and geomean ratio. + assert markdown_row(report, "**geomean**")[1] == "100 → 102 ns (1.02)" def test_report_splits_cold_and_hot_runs(tmp_path: Path) -> None: @@ -426,13 +438,13 @@ def test_report_splits_cold_and_hot_runs(tmp_path: Path) -> None: report = render_report(tmp_path, base_rows, pr_rows, "TPC-H") - # The marks sit on the numbers that moved, not on the benchmark name. - assert markdown_row(report, "tpch_q01/datafusion:vortex-file-compressed") == [ - "tpch_q01/datafusion:vortex-file-compressed", - "50 / 100 / -50.0% 🟢", - "2000 / 1000 / +100.0% 🔴", - "0.03 / 0.10 / -75.0%", - ] + # Hot runs come first; cold runs follow in their own folded table. + hot, cold = markdown_rows(report, "tpch_q01") + assert hot == ["tpch_q01", "**100 → 50.0 ns (0.50)** 🟢", "100 → 100 ns (1.00)"] + assert cold == ["tpch_q01", "**1.00 → 2.00 µs (2.00)** 🔴", "1.00 → 1.00 µs (1.00)"] + # Both tables fold by default, under a summary of what moved. + assert "Hot runs: geomean 0.707x 🟢 · 1 query × 2 targets (1↑ 0↓)" in report + assert "Cold runs (first iteration): geomean 1.414x 🔴 · 1 query × 2 targets (0↑ 1↓)" in report assert "**Attributed Vortex impact**: -50.0%" in report assert "**Vortex (geomean)**: hot 0.500x ✅ · cold 2.000x ❌" in report assert "**Parquet (geomean)**: hot 1.000x ➖ · cold 1.000x ➖" in report @@ -465,12 +477,9 @@ def test_verdict_ignores_a_cold_start_only_regression(tmp_path: Path) -> None: assert "**Attributed Vortex impact**: +0.0%" in report assert "**Vortex (geomean)**: hot 1.000x ➖ · cold 4.000x ❌" in report - assert markdown_row(report, "tpch_q01/datafusion:vortex-file-compressed") == [ - "tpch_q01/datafusion:vortex-file-compressed", - "100 / 100 / +0.0%", - "400 / 100 / +300.0% 🔴", - "0.25 / 1.00 / -75.0%", - ] + hot, cold = markdown_rows(report, "tpch_q01") + assert hot[1] == "100 → 100 ns (1.00)" + assert cold[1] == "**100 → 400 ns (4.00)** 🔴" def file_size_record(commit: str, size: int) -> dict[str, object]: @@ -793,7 +802,7 @@ def test_report_compares_ingest_records(tmp_path: Path) -> None: assert "**Engines**: DataFusion " in report assert "random-access " in report assert "ignored when records exist" not in report - assert markdown_row(report, "tpch_q01/datafusion:vortex-file-compressed")[1] == "70 / 80 / -12.5% 🟢" + assert markdown_row(report, "tpch_q01")[1:] == ["**80.0 → 70.0 ns (0.88)** 🟢", "100 → 105 ns (1.05)"] assert markdown_row(report, "random-access/taxi/uniform/parquet-cached")[1] == "105 / 100 / +5.0%" assert markdown_row(report, "random-access/taxi/uniform/lance-cached")[1] == "300 / — / no baseline" assert "random-access / lance / ns " in report @@ -815,7 +824,7 @@ def test_report_compares_file_size_records_from_the_database(tmp_path: Path) -> report = render_report(tmp_path, base_records, pr_results, "TPC-H", pr_records) - assert markdown_row(report, "tpch_q01/datafusion:vortex-file-compressed")[1] == "80 / 80 / +0.0%" + assert markdown_row(report, "tpch_q01")[1] == "80.0 → 80.0 ns (1.00)" assert "File Size Changes (2 files changed, -16.7% overall, 1↑ 1↓)" in report assert "| part-1.vortex | 10 | vortex-file-compressed | 50 B | 0 B | -50 B | -100.0% |" in report @@ -830,7 +839,7 @@ def test_report_handles_a_baseline_of_only_file_sizes(tmp_path: Path) -> None: report = render_report(tmp_path, base_records, pr_results, "TPC-H", pr_records) - assert markdown_row(report, "tpch_q01/datafusion:vortex-file-compressed")[1] == "80 / — / no baseline" + assert markdown_row(report, "tpch_q01")[1] == "— → 80.0 ns" assert "File Size Changes (1 files changed, +25.0% overall, 1↑ 0↓)" in report @@ -954,3 +963,67 @@ def test_capture_file_sizes_reads_only_the_named_directory(tmp_path: Path) -> No records = [json.loads(line) for line in output_path.read_text(encoding="utf-8").splitlines()] assert [record["value"] for record in records] == [42] + + +def test_query_table_puts_a_format_variant_beside_its_base_format(tmp_path: Path) -> None: + 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), + ] + 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:parquet", + "duckdb:vortex", + ] + 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 + + +def test_format_duration_picks_a_readable_unit() -> None: + compare = load_compare_module() + + assert compare.format_duration(950) == "950 ns" + assert compare.format_duration(12_345) == "12.3 µs" + assert compare.format_duration(1_234_567) == "1.23 ms" + assert compare.format_duration(152_400_000) == "152 ms" + assert compare.format_duration(2_500_000_000) == "2.50 s" + assert compare.format_duration(float("nan")) == "—" + + +def test_query_cell_names_both_units_when_they_differ() -> None: + compare = load_compare_module() + + assert compare.format_query_cell(980_000, 1_020_000, 1.04, 0.9, 1.1) == "980 µs → 1.02 ms (1.04)" + + +def test_query_table_says_what_it_compares(tmp_path: Path) -> None: + base = [query_record("base-sha", 1, "datafusion", "vortex-file-compressed", 80)] + pr = [query_record("pr-sha", 1, "datafusion", "vortex-file-compressed", 80)] + pr_results = [stored_timing_row("pr-sha", "ignored when records exist", 1)] + + 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 + + +def test_float_query_numbers_still_count_as_sql_queries() -> None: + compare = load_compare_module() + + assert compare.is_sql_query(3) + assert compare.is_sql_query(3.0) + assert not compare.is_sql_query(3.5) + assert not compare.is_sql_query("random-access/taxi/cached") + assert not compare.is_sql_query(None) + assert not compare.is_sql_query(True)