Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
232 changes: 227 additions & 5 deletions scripts/compare-benchmark-jsons.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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 "<br>".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."""

Expand Down Expand Up @@ -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.",
"",
"</details>",
]
Expand Down Expand Up @@ -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("<details>")
print(f"<summary>{summary}</summary>")
print("")
print("<br>")
print("")
if run == "hot":
print(caption)
print("")
print(table)
print("")
print("</details>")
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(
Expand Down
Loading
Loading