diff --git a/.github/workflows/gpu.yml b/.github/workflows/gpu.yml index 6a95c9b..40a4adb 100644 --- a/.github/workflows/gpu.yml +++ b/.github/workflows/gpu.yml @@ -29,6 +29,8 @@ jobs: steps: - uses: actions/checkout@v4 + with: + fetch-depth: 2 - name: Install LLVM ${{ env.LLVM_VERSION }} and MLIR run: | @@ -68,6 +70,49 @@ jobs: fi uv run pytest -v -m gpu + - name: Compare against the base branch on Vast.ai + if: success() && github.event_name == 'pull_request' + timeout-minutes: 25 + env: + VASTAI_API_KEY: ${{ secrets.VASTAI_API_KEY }} + BASE_REF: ${{ github.base_ref }} + COMMENT_PATH: ${{ runner.temp }}/bench-comment.md + run: | + set -euo pipefail + # HEAD is GitHub's merge of this pull request. HEAD^1 is the base commit + # that merge used, which fetch-depth 2 makes available. A depth-1 checkout + # records the parent SHAs and still cannot resolve them. + git branch --force "$BASE_REF" HEAD^1 + uv run python -m bench compare "$BASE_REF" HEAD --comment "$COMMENT_PATH" + + - name: Post the bench comparison + if: always() && github.event_name == 'pull_request' + env: + GH_TOKEN: ${{ github.token }} + PR_NUMBER: ${{ github.event.pull_request.number }} + COMMENT_PATH: ${{ runner.temp }}/bench-comment.md + run: | + set -euo pipefail + if [ ! -s "$COMMENT_PATH" ]; then + echo "no bench comment to post" + exit 0 + fi + export MARKER + MARKER="$(head -n 1 "$COMMENT_PATH")" + id="$(gh api --paginate "repos/${GITHUB_REPOSITORY}/issues/${PR_NUMBER}/comments" \ + --jq '.[] | select(.user.login == "github-actions[bot]" and (.body | startswith(env.MARKER))) | .id' \ + | tail -n 1)" + # -F reads the file. -f posts the path string as the comment body. + if [ -n "$id" ]; then + gh api --method PATCH \ + "repos/${GITHUB_REPOSITORY}/issues/comments/${id}" \ + -F body=@"$COMMENT_PATH" + else + gh api --method POST \ + "repos/${GITHUB_REPOSITORY}/issues/${PR_NUMBER}/comments" \ + -F body=@"$COMMENT_PATH" + fi + - name: Remove GPU test trigger label if: always() && github.event_name == 'pull_request' env: diff --git a/bench/build.py b/bench/build.py index e3ef3d3..f0aee5b 100644 --- a/bench/build.py +++ b/bench/build.py @@ -68,6 +68,19 @@ def resolve(repo: Path, name: str) -> Ref: return Ref(name=name, sha=result.stdout.strip()) +def parents(repo: Path, ref: Ref) -> tuple[str, ...]: + """Parents of `ref` in order. A root commit is an empty tuple. + + `--verify` is not used. `rev-parse --verify ^@` exits 128 for a parent list. + """ + result = _git(repo, "rev-parse", f"{ref.sha}^@") + if result.returncode != 0: + detail = result.stderr.strip() or result.stdout.strip() + msg = f"cannot read parents of {ref.name} at {ref.short}: {detail}" + raise BuildError(msg) + return tuple(result.stdout.split()) + + def toolchain_of(build_dir: Path) -> Toolchain: """The MLIR and LLVM a fresh build needs, from the environment or a configured build. diff --git a/bench/cli.py b/bench/cli.py index d174a36..c34c743 100644 --- a/bench/cli.py +++ b/bench/cli.py @@ -7,15 +7,17 @@ import os import subprocess import sys +from dataclasses import dataclass +from pathlib import Path from typing import TYPE_CHECKING -from bench import acceptance, build, compare, gap +from bench import acceptance, build, comment, compare, gap from bench.report import Report from benchmarks import manifest from gpu_test import bench_stats, infrastructure if TYPE_CHECKING: - from collections.abc import Sequence + from collections.abc import Callable, Sequence logger = logging.getLogger("bench") REPO_ROOT = manifest.CASE_ROOT.parent @@ -107,15 +109,14 @@ def run(args: argparse.Namespace) -> int: def compile_both( - cases: Sequence[manifest.Case], args: argparse.Namespace -) -> tuple[build.Ref, build.Ref, dict[str, compare.BaseSide], list[gap.Item]]: - """Build both refs and compile every case with each binary inside that ref's worktree. - - A worktree is torn down as soon as it has produced its PTX, so the two compilers never share a - build directory and nothing depends on where the temporary checkouts live. + cases: Sequence[manifest.Case], + base: build.Ref, + head: build.Ref, + args: argparse.Namespace, +) -> tuple[dict[str, compare.BaseSide], list[gap.Item]]: + """A worktree is torn down as soon as it has produced its PTX, so the two compilers never + share a build directory and nothing depends on where the temporary checkouts live. """ - base = build.resolve(REPO_ROOT, args.base) - head = build.resolve(REPO_ROOT, args.head) logger.info("base %s at %s, head %s at %s", base.name, base.short, head.name, head.short) toolchain = build.toolchain_of(manifest.find_build(REPO_ROOT)) logger.info("compiling %d cases with both revisions at %s", len(cases), args.arch) @@ -129,16 +130,24 @@ def compile_both( error = item.error if isinstance(item, gap.Broken) else base_error if error: logger.error("%s: %s", item.case.id, error) - return base, head, bases, items + return bases, items -def run_compare(args: argparse.Namespace) -> int: - cases = select_cases(manifest.load(), args.case) - key = api_key() - base, head, bases, items = compile_both(cases, args) - if all(isinstance(item, gap.Broken) for item in items): - return EXIT_INCOMPLETE +@dataclass(frozen=True, slots=True) +class UnbuiltHead: + pass + +def compare_refs( + cases: Sequence[manifest.Case], + base: build.Ref, + head: build.Ref, + key: str, + args: argparse.Namespace, +) -> compare.Report | UnbuiltHead: + bases, items = compile_both(cases, base, head, args) + if all(isinstance(item, gap.Broken) for item in items): + return UnbuiltHead() commits = {"base_commit": base.sha, "head_commit": head.sha} logger.info("building the CUDA baselines and timing %d cases on one rental", len(items)) with infrastructure.VastSession(key, arch=args.arch) as session: @@ -148,8 +157,27 @@ def run_compare(args: argparse.Namespace) -> int: harness.request({"op": "ping"}), base.sha, head.sha ) rows = compare.rows_of(readied, bases, harness, commits) + return compare.Report(arch=args.arch, environment=environment, rows=tuple(rows)) + - report = compare.Report(arch=args.arch, environment=environment, rows=tuple(rows)) +def run_compare(args: argparse.Namespace) -> int: + cases = select_cases(manifest.load(), args.case) + key = api_key() + base = build.resolve(REPO_ROOT, args.base) + head = build.resolve(REPO_ROOT, args.head) + revisions = comment.Revisions.of(base, head, build.parents(REPO_ROOT, head)) + publish = comment_writer(args.comment) + publish(comment.Unfinished(revisions)) + try: + outcome = compare_refs(cases, base, head, key, args) + except BaseException as exc: + publish(comment.Failed.from_error(revisions, exc)) + raise + if isinstance(outcome, UnbuiltHead): + publish(comment.Failed(revisions, "no case compiled with the head revision")) + return EXIT_INCOMPLETE + report = outcome + publish(comment.Measured(revisions, report)) for line in report.lines(): print(line) # noqa: T201 - the command's own output if args.json: @@ -159,6 +187,18 @@ def run_compare(args: argparse.Namespace) -> int: return 0 if not report.failures else EXIT_INCOMPLETE +def comment_writer(path: Path | None) -> Callable[[comment.State], None]: + def write(state: comment.State) -> None: + if path is None: + return + path.parent.mkdir(parents=True, exist_ok=True) + temporary = path.with_name(f".{path.name}.tmp") + temporary.write_text(comment.render(state), encoding="utf-8", newline="\n") + temporary.replace(path) + + return write + + def run_acceptance(args: argparse.Namespace) -> int: cases = manifest.load() key = api_key() @@ -206,6 +246,11 @@ def build_parser() -> argparse.ArgumentParser: default=BUILD_JOBS, help="parallel compile jobs for each of the two fresh builds", ) + compare_command.add_argument( + "--comment", + type=Path, + help="write the review comment to this path as the run goes, without posting it", + ) acceptance_command = subcommands.add_parser( "acceptance", parents=[shared], diff --git a/bench/comment.py b/bench/comment.py new file mode 100644 index 0000000..0691f29 --- /dev/null +++ b/bench/comment.py @@ -0,0 +1,162 @@ +from __future__ import annotations + +from dataclasses import dataclass +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from collections.abc import Sequence + + from bench import build, compare + +MARKER = "" +_MERGE_PARENTS = 2 +_MIN_FENCE = 3 +_RATIO_DIGITS = 3 +_GAP_DIGITS = 2 +_TIME_DIGITS = 1 +_TEXT_COLUMNS = 2 +_NUMERIC_COLUMNS = 5 +_HEADERS = ("case", "verdict", "ratio", "mad", "base", "head", "gap") + + +@dataclass(frozen=True, slots=True) +class Revisions: + base: build.Ref + head: build.Ref + pull_head: str | None + + @classmethod + def of(cls, base: build.Ref, head: build.Ref, head_parents: Sequence[str]) -> Revisions: + pull_head = None + if len(head_parents) == _MERGE_PARENTS and head_parents[0] == base.sha: + pull_head = head_parents[1] + return cls(base, head, pull_head) + + +@dataclass(frozen=True, slots=True) +class Unfinished: + revisions: Revisions + + +@dataclass(frozen=True, slots=True) +class Failed: + revisions: Revisions + reason: str + + @classmethod + def from_error(cls, revisions: Revisions, error: BaseException) -> Failed: + if isinstance(error, KeyboardInterrupt): + return cls(revisions, "interrupted") + return cls(revisions, f"{type(error).__name__}: {error}") + + +@dataclass(frozen=True, slots=True) +class Measured: + revisions: Revisions + report: compare.Report + + +State = Unfinished | Failed | Measured + + +def render(state: State) -> str: + lines = [MARKER, _headline(state), ""] + result = _result(state) + if result is not None: + lines.extend([result, ""]) + lines.append(_details(state)) + return "\n".join(lines) + "\n" + + +def _headline(state: State) -> str: + return f"### Bench compare against `{state.revisions.base.name}`: {_status(state)}" + + +def _status(state: State) -> str: + if isinstance(state, Measured): + return state.report.summary + if isinstance(state, Failed): + return "no result" + return "did not finish" + + +def _result(state: State) -> str | None: + if isinstance(state, Measured): + return _table(state.report) + if isinstance(state, Failed): + return _fence(state.reason) + return None + + +def _table(report: compare.Report) -> str: + notes = any(row.outcome.note for row in report.rows) + headers = [*_HEADERS, "note"] if notes else list(_HEADERS) + rows = [_markdown_row(headers), _separator(len(headers))] + for row in report.rows: + cells = _cells(row) + if notes: + cells.append(_cell(row.outcome.note)) + rows.append(_markdown_row(cells)) + return "\n".join(rows) + + +def _cells(row: compare.Row) -> list[str]: + outcome = row.outcome + stats = outcome.stats + verdict = outcome.verdict.value if outcome.verdict else "-" + ratio = f"{stats.ratio_median:.{_RATIO_DIGITS}f}" if stats else "-" + mad = f"{stats.ratio_mad:.{_RATIO_DIGITS}f}" if stats else "-" + base = f"{stats.base_median_us:.{_TIME_DIGITS}f} us" if stats else "-" + head = f"{stats.head_median_us:.{_TIME_DIGITS}f} us" if stats else "-" + gap = f"{outcome.head_gap:.{_GAP_DIGITS}f}x" if outcome.head_gap is not None else "-" + return [_cell(value) for value in (row.case.id, verdict, ratio, mad, base, head, gap)] + + +def _markdown_row(cells: Sequence[str]) -> str: + return "| " + " | ".join(cells) + " |" + + +def _separator(columns: int) -> str: + cells = [] + for index in range(columns): + numeric = _TEXT_COLUMNS <= index < _TEXT_COLUMNS + _NUMERIC_COLUMNS + cells.append("---:" if numeric else "---") + return _markdown_row(cells) + + +def _cell(value: str) -> str: + return " ".join(value.replace("|", "\\|").split()) + + +def _details(state: State) -> str: + revisions = state.revisions + bullets = [f"Base: `{revisions.base.sha}`", f"Head: `{revisions.head.sha}`"] + if isinstance(state, Measured): + bullets.append(_rental(state.report)) + return "\n".join(f"- {bullet}" for bullet in bullets) + + +def _rental(report: compare.Report) -> str: + environment = report.environment + return ( + f"Rental: `{environment.gpu_uuid}`, driver {environment.driver_version}, " + f"SM clock {environment.sm_clock_mhz} MHz, " + f"memory clock {environment.memory_clock_mhz} MHz, `{report.arch}`" + ) + + +def _fence(text: str) -> str: + ticks = "`" * max(_backtick_run(text) + 1, _MIN_FENCE) + return f"{ticks}\n{text}\n{ticks}" + + +def _backtick_run(text: str) -> int: + longest = 0 + run = 0 + for char in text: + if char == "`": + run += 1 + longest = max(longest, run) + else: + run = 0 + return longest diff --git a/bench/compare.py b/bench/compare.py index 4df55d7..3bf134c 100644 --- a/bench/compare.py +++ b/bench/compare.py @@ -136,13 +136,14 @@ def lines(self) -> list[str]: header, *(_row_line(row) for row in self.rows), "", - self._sum_line(), + self.summary, ] def _environment_line(self) -> str: return " ".join(f"{name}={getattr(self.environment, name)}" for name in ENVIRONMENT_FIELDS) - def _sum_line(self) -> str: + @property + def summary(self) -> str: total = len(self.rows) if self.regressions: return f"{len(self.regressions)} of {total} cases slower: {', '.join(self.regressions)}" diff --git a/benchmarks/README.md b/benchmarks/README.md index 468c6b4..a702bad 100644 --- a/benchmarks/README.md +++ b/benchmarks/README.md @@ -179,6 +179,11 @@ the suite and `--json` prints the result document with both commits and each cas The command exits 2 when any case is slower, 1 when a case could not be compared, and 0 otherwise, so a hillclimb can gate a keep-or-revert on the exit code alone. +`--comment PATH` writes the review body and does not post it. The file is replaced as the run +goes, including before the process exits with code 2. A finished run is a markdown table of the +case rows, then bullets for the two commits and the rental. The `gpu-test` label runs this compare +for GitHub's merge onto the base branch and posts one comment, which a later run edits. + ## The acceptance fixture pair `benchmarks/acceptance/` holds `fast.forth` and `slow.forth`, one kernel and a deliberately slowed diff --git a/gpu_test/test_bench_comment.py b/gpu_test/test_bench_comment.py new file mode 100644 index 0000000..b7a45f4 --- /dev/null +++ b/gpu_test/test_bench_comment.py @@ -0,0 +1,302 @@ +from __future__ import annotations + +import subprocess +from pathlib import Path +from unittest import mock + +import pytest + +from bench import build, cli, comment, compare +from benchmarks import manifest +from gpu_test import bench_stats + +BASE_SHA = "a" * 40 +HEAD_SHA = "b" * 40 +PULL_SHA = "c" * 40 +OTHER_SHA = "d" * 40 +TABLE_HEADER = "| case | verdict | ratio | mad | base | head | gap |" +RENTAL = "- Rental: `gpu-0000`, driver 12.4, SM clock 1500 MHz, memory clock 7000 MHz, `sm_89`" +BY_ID = {case.id: case for case in manifest.load()} + + +def _ref(name: str, sha: str) -> build.Ref: + return build.Ref(name=name, sha=sha) + + +def _revisions(*, pull_head: str | None) -> comment.Revisions: + parents = (BASE_SHA, pull_head) if pull_head is not None else (OTHER_SHA, PULL_SHA) + return comment.Revisions.of(_ref("canon", BASE_SHA), _ref("HEAD", HEAD_SHA), parents) + + +def _samples(head_us: float) -> tuple[bench_stats.BenchSample, ...]: + return tuple( + bench_stats.BenchSample( + base_us=100.0, + head_us=head_us, + first=bench_stats.Side.BASE if index % 2 == 0 else bench_stats.Side.HEAD, + ) + for index in range(5) + ) + + +def _row(case_id: str, *, head_us: float) -> compare.Row: + samples = _samples(head_us) + return compare.Row( + BY_ID[case_id], + compare.Outcome( + verdict=bench_stats.verdict(samples), + stats=bench_stats.CaseStats.from_samples(samples), + head_gap=1.25, + ), + ) + + +def _report() -> compare.Report: + return compare.Report( + arch="sm_89", + environment=bench_stats.Environment( + gpu_uuid="gpu-0000", + driver_version="12.4", + sm_clock_mhz=1500, + memory_clock_mhz=7000, + base_commit=BASE_SHA, + head_commit=HEAD_SHA, + ), + rows=(_row("scale_i64", head_us=300.0), _row("axpy_f64", head_us=100.0)), + ) + + +def _fences(body: str) -> list[str]: + lines = body.split("\n") + if lines and lines[-1] == "": + lines = lines[:-1] + blocks: list[str] = [] + index = 0 + while index < len(lines): + line = lines[index] + if len(line) >= 3 and set(line) == {"`"}: + close = next( + (cursor for cursor in range(index + 1, len(lines)) if lines[cursor] == line), + None, + ) + assert close is not None, f"unclosed fence of {len(line)} backticks" + blocks.append("\n".join(lines[index + 1 : close])) + index = close + 1 + continue + index += 1 + return blocks + + +def _longest_backtick_run(text: str) -> int: + longest = 0 + run = 0 + for char in text: + if char == "`": + run += 1 + longest = max(longest, run) + else: + run = 0 + return longest + + +def test_each_state_opens_with_the_marker_and_headline() -> None: + report = _report() + revisions = _revisions(pull_head=PULL_SHA) + states = ( + (comment.Unfinished(revisions), "did not finish"), + (comment.Failed(revisions, "the rental died"), "no result"), + (comment.Measured(revisions, report), report.summary), + ) + for state, status in states: + lines = comment.render(state).splitlines() + assert lines[0] == comment.MARKER + assert lines[1] == f"### Bench compare against `canon`: {status}" + assert lines[2] == "" + rendered = comment.render(state) + assert f"- Base: `{BASE_SHA}`" in rendered + assert f"- Head: `{HEAD_SHA}`" in rendered + assert "Case sources" not in rendered + assert "head time over base time" not in rendered + if isinstance(state, comment.Measured): + assert RENTAL in rendered + else: + assert "Rental:" not in rendered + + +def test_a_measured_merge_uses_a_markdown_table_then_bullets() -> None: + report = _report() + revisions = _revisions(pull_head=PULL_SHA) + body = comment.render(comment.Measured(revisions, report)) + table, details = body.split("\n\n", maxsplit=2)[1:] + assert table.splitlines()[0] == TABLE_HEADER + assert "| scale_i64 | slower | 3.000 | 0.000 | 100.0 us | 300.0 us | 1.25x |" in table + assert "| axpy_f64 | no change | 1.000 | 0.000 | 100.0 us | 100.0 us | 1.25x |" in table + assert "compare base=" not in body + assert _fences(body) == [] + assert PULL_SHA not in body + assert details.splitlines() == [ + f"- Base: `{BASE_SHA}`", + f"- Head: `{HEAD_SHA}`", + RENTAL, + ] + + +def test_a_plain_compare_names_both_full_shas() -> None: + revisions = comment.Revisions.of(_ref("canon", BASE_SHA), _ref("topic", HEAD_SHA), (BASE_SHA,)) + body = comment.render(comment.Measured(revisions, _report())) + assert f"- Base: `{BASE_SHA}`" in body + assert f"- Head: `{HEAD_SHA}`" in body + assert "topic" not in body + assert "Pull request head" not in body + + +def test_a_failure_note_with_a_pipe_stays_inside_one_table_cell() -> None: + broken = compare.Row(BY_ID["scale_i64"], compare.Outcome(error="base: a|b\nsecond")) + report = compare.Report(arch="sm_89", environment=_report().environment, rows=(broken,)) + body = comment.render(comment.Measured(_revisions(pull_head=None), report)) + assert "| case | verdict | ratio | mad | base | head | gap | note |" in body + assert "| scale_i64 | - | - | - | - | - | - | base: a\\|b second |" in body + + +def test_revisions_of_sets_pull_head_only_when_the_first_parent_is_the_base() -> None: + base = _ref("canon", BASE_SHA) + head = _ref("HEAD", HEAD_SHA) + assert comment.Revisions.of(base, head, (BASE_SHA, PULL_SHA)).pull_head == PULL_SHA + assert comment.Revisions.of(base, head, (OTHER_SHA, PULL_SHA)).pull_head is None + assert comment.Revisions.of(base, head, (BASE_SHA,)).pull_head is None + assert comment.Revisions.of(base, head, ()).pull_head is None + assert comment.Revisions.of(base, head, (BASE_SHA, PULL_SHA, OTHER_SHA)).pull_head is None + + +def test_a_triple_backtick_in_the_reason_stays_inside_one_longer_fence() -> None: + reason = "nvcc said\n```\nstill the reason\n```\n" + body = comment.render(comment.Failed(_revisions(pull_head=PULL_SHA), reason)) + blocks = _fences(body) + assert blocks == [reason] + opening = next(line for line in body.splitlines() if set(line) == {"`"}) + assert len(opening) == max(3, _longest_backtick_run(reason) + 1) + assert len(opening) > 3 + + +def test_from_error_names_the_type_and_calls_an_interrupt_interrupted() -> None: + revisions = _revisions(pull_head=None) + failed = comment.Failed.from_error(revisions, build.BuildError("missing llvm")) + assert failed.reason == "BuildError: missing llvm" + assert comment.Failed.from_error(revisions, KeyboardInterrupt()).reason == "interrupted" + + +def test_a_slower_compare_exits_2_and_the_headline_says_slower( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + monkeypatch.setenv("VASTAI_API_KEY", "dummy") + path = tmp_path / "out" / "bench-comment.md" + report = _report() + with ( + mock.patch.object( + build, "resolve", side_effect=[_ref("canon", BASE_SHA), _ref("HEAD", HEAD_SHA)] + ), + mock.patch.object(build, "parents", return_value=(BASE_SHA, PULL_SHA)), + mock.patch.object(cli, "compare_refs", return_value=report), + ): + code = cli.main(["compare", "canon", "HEAD", "--comment", str(path)]) + assert code == 2 + assert "slower" in path.read_text(encoding="utf-8").splitlines()[1] + + +def test_a_build_error_propagates_and_the_comment_says_no_result( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + monkeypatch.setenv("VASTAI_API_KEY", "dummy") + path = tmp_path / "bench-comment.md" + + def explode(*_args: object, **_kwargs: object) -> None: + msg = "toolchain missing" + raise build.BuildError(msg) + + with ( + mock.patch.object( + build, "resolve", side_effect=[_ref("canon", BASE_SHA), _ref("HEAD", HEAD_SHA)] + ), + mock.patch.object(build, "parents", return_value=(BASE_SHA, PULL_SHA)), + mock.patch.object(cli, "compare_refs", side_effect=explode), + pytest.raises(build.BuildError, match="toolchain missing"), + ): + cli.main(["compare", "canon", "HEAD", "--comment", str(path)]) + text = path.read_text(encoding="utf-8") + headline = text.splitlines()[1] + assert "no result" in headline + assert "BuildError" in text + assert _fences(text) == ["BuildError: toolchain missing"] + + +def test_the_comment_says_did_not_finish_when_compare_starts( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + monkeypatch.setenv("VASTAI_API_KEY", "dummy") + path = tmp_path / "bench-comment.md" + seen: list[str] = [] + + def entered(*_args: object, **_kwargs: object) -> compare.Report: + seen.append(path.read_text(encoding="utf-8").splitlines()[1]) + return compare.Report( + arch="sm_89", + environment=_report().environment, + rows=(_row("axpy_f64", head_us=100.0),), + ) + + with ( + mock.patch.object( + build, "resolve", side_effect=[_ref("canon", BASE_SHA), _ref("HEAD", HEAD_SHA)] + ), + mock.patch.object(build, "parents", return_value=(BASE_SHA,)), + mock.patch.object(cli, "compare_refs", side_effect=entered), + ): + cli.main(["compare", "canon", "HEAD", "--comment", str(path)]) + assert seen == ["### Bench compare against `canon`: did not finish"] + + +def test_a_missing_ref_writes_no_comment(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setenv("VASTAI_API_KEY", "dummy") + path = tmp_path / "bench-comment.md" + with pytest.raises(build.BuildError, match="cannot resolve"): + cli.main(["compare", "no-such-bench-ref", "HEAD", "--comment", str(path)]) + assert not path.exists() + + +def test_parents_of_a_no_ff_merge_are_first_then_second(tmp_path: Path) -> None: + repo = tmp_path / "repo" + repo.mkdir() + + def git(*args: str) -> str: + result = subprocess.run( # noqa: S603 - a fixed argument list, never a shell string + ["git", "-C", str(repo), *args], # noqa: S607 - git from PATH + check=True, + capture_output=True, + text=True, + ) + return result.stdout.strip() + + git("init", "--template=", "-b", "master") + git("config", "user.email", "bench@example.invalid") + git("config", "user.name", "bench") + git("config", "commit.gpgsign", "false") + (repo / "file.txt").write_text("base\n") + git("add", ".") + git("commit", "-m", "base") + first = git("rev-parse", "HEAD") + git("checkout", "-b", "feature") + (repo / "file.txt").write_text("feature\n") + git("commit", "-am", "feature") + second = git("rev-parse", "HEAD") + git("checkout", "master") + git("merge", "--no-ff", "feature", "-m", "merge") + assert build.parents(repo, build.resolve(repo, "HEAD")) == (first, second) + + +def test_only_compare_takes_a_comment_path() -> None: + args = cli.build_parser().parse_args(["compare", "canon", "HEAD", "--comment", "out.md"]) + assert args.comment == Path("out.md") + with pytest.raises(SystemExit): + cli.build_parser().parse_args(["gap", "--comment", "out.md"]) + with pytest.raises(SystemExit): + cli.build_parser().parse_args(["acceptance", "--comment", "out.md"]) diff --git a/gpu_test/test_bench_compare.py b/gpu_test/test_bench_compare.py index 4761e64..549b136 100644 --- a/gpu_test/test_bench_compare.py +++ b/gpu_test/test_bench_compare.py @@ -417,15 +417,16 @@ def compile_base(case: manifest.Case, compiler: Path, _arch: str) -> compare.Bas return compare.BaseSide(ptx=f".visible .entry {case.kernel}( )\n") args = cli.build_parser().parse_args(["compare", "base", "head", "--jobs", "2"]) + base = build.Ref("base", "a" * 40) + head = build.Ref("head", "b" * 40) with ( - mock.patch.object(build, "resolve", return_value=build.Ref("ref", "a" * 40)), mock.patch.object(build, "worktree", side_effect=checkout), mock.patch.object(build, "toolchain_of", return_value=build.Toolchain((), "")), mock.patch.object(build, "compiler", side_effect=_fake_compiler), mock.patch.object(compare, "compile_base", side_effect=compile_base), mock.patch.object(gap, "plan", side_effect=plan), ): - cli.compile_both(CASES[:2], args) + cli.compile_both(CASES[:2], base, head, args) assert len(built_in) == 2 * len(CASES[:2]) assert len({path.parent.parent.parent for path in built_in}) == 2, "one build per ref"