diff --git a/docs/benchx.md b/docs/benchx.md index d447fe20..55436065 100644 --- a/docs/benchx.md +++ b/docs/benchx.md @@ -134,9 +134,11 @@ A function has a version, as an asv benchmark does: its `version` attribute, els its source (as asv_runner hashes a plain function: comments and docstrings count; what it calls, its `params` and the library under test do not). Each result records it in `protocol.pyperf.benchmark_version`, and protocol is what the two sides of a comparison must -agree on, so two revisions whose function differs fail `sides-agree`. That suits a function -that exercises code elsewhere in the tree. When the function body is what changes, declare a -`version` (`bench_a.version = "1"`). A function without readable source has no version. +agree on. As `asv compare` does, a function whose version differs between the two revisions, +or during the run, is listed as not comparable (reason `benchmark-changed`) and the other +functions are compared. That suits a function that exercises code elsewhere in the tree. +When the function body is what changes, declare a `version` (`bench_a.version = "1"`). A +function without readable source has no version. `bx bench MODULE.py [FUNCTION …]` is the shorthand for the quickest case, timing a few functions: the module's git checkout is the target, its path the suite, and the diff --git a/docs/design/comparator.md b/docs/design/comparator.md index e36293c7..f6fffde4 100644 --- a/docs/design/comparator.md +++ b/docs/design/comparator.md @@ -121,7 +121,10 @@ profile. A unit in which a side has no successful attempt at all (every attempt skipped, or failed under a profile that drops failed pairs) leaves no pair, and more rounds would not help: it is indeterminate with reason `not-measured`, not `insufficient-rounds`, and the unit carries how each side's attempts ended -(`attempts`, counts by status). The schema's §5.5 table is not touched, since +(`attempts`, counts by status). A unit whose recorded benchmark version differs, between the sides or +between a side's rounds, and in nothing else, was edited: it is indeterminate with reason +`benchmark-changed`, uses no pair, and is listed as not comparable, as `asv compare` does, while the +other units are compared. The schema's §5.5 table is not touched, since this is a status rule, not an invariant. In history mode it additionally checks that: diff --git a/docs/design/prototype-design.md b/docs/design/prototype-design.md index a04eaccf..41e59f61 100644 --- a/docs/design/prototype-design.md +++ b/docs/design/prototype-design.md @@ -465,7 +465,8 @@ apart, so adding an estimator never renames the policy: point (schema §1). It does record a computed version of each benchmark function in `protocol` (asv, pyperf: a hash of the function's source, or its `version` attribute), which changes only when the function does and is matched like the rest of protocol: an - edited benchmark is not compared with its old self and starts a new series. + edited benchmark is not compared with its old self and starts a new series. The comparison lists + it as not comparable (`benchmark-changed`), as `asv compare` does, and compares the others. Being ignored, its change is flagged on each point where it happens. A thin result's identity carries its implicit project. - **Estimators** (`ESTIMATORS`): `median`, derived from observations, plus @@ -526,7 +527,10 @@ affect every unit; `sides-agree` looks at the attempts that succeeded); under `r `sides` invariant), to a tree edited during the run (a third side: `two-sides`), and to a benchmark recorded apart from the subject that is not one file on both sides and in every round (`one-benchmark-tree`, schema §5.5), as it does -under `variants`. A side that +under `variants`. A unit whose only differing matched fact is a benchmark's recorded +version (`protocol..benchmark_version`, between the sides or between a side's rounds) is not +a failed invariant: it is indeterminate with reason `benchmark-changed`, no pair is used, and it is +listed as not comparable, as `asv compare` lists a benchmark whose version changed. A side that is not clean does not fail the run: it makes the comparison local-only. A variant present on one side only is listed as missing (criterion 4). Results with a status other than `success` are excluded and listed. Under `variants` a failed attempt (`partial`, `censored` or `error`) on either side also makes diff --git a/src/benchx/compare.py b/src/benchx/compare.py index c90e4d38..4427bd4b 100644 --- a/src/benchx/compare.py +++ b/src/benchx/compare.py @@ -240,9 +240,12 @@ def compare(documents, *, run_key, profile, baseline, label=None, parameter=None units[key]["identities"].append(p.identity) run_failed = bool(failed) # the invariants above are about the run, and no unit is compared disagreeing = set() # `sides-agree` is about one unit: it gets no verdict, and the others are compared + changed = set() # the benchmark itself was edited: not comparable, which is not a failed invariant for key, unit in units.items(): differing = _differing(unit["identities"]) - if differing: + if differing and all(_BENCHMARK_VERSION.fullmatch(p) for p in differing): + changed.add(key) + elif differing: failed.append({"invariant": "sides-agree", "workload": _workload(unit["docs"], projection.axis), "quantity": key[1], "detail": f"{', '.join(differing)} differ"}) disagreeing.add(key) @@ -260,6 +263,9 @@ def compare(documents, *, run_key, profile, baseline, label=None, parameter=None if absent: doc["missing"].extend({**where, "side": role} for role in absent) continue + if (variant_key, quantity) in changed: + doc["units"].append(_unit(where, [], by_side, base, contender, k, min_rounds, benchmark_changed=True)) + continue if "equal-attempts" in check and len(by_side[base]) != len(by_side[contender]): failed.append({"invariant": "equal-attempts", **where, "detail": f"{len(by_side[base])} against {len(by_side[contender])}: run the same " @@ -355,6 +361,11 @@ def _diff(pointer: str, values: list) -> list[str]: return [pointer] if len(distinct) > 1 else [] +# The version a harness records for a benchmark (asv's hash, the pyperf function's): when it differs, the +# benchmark's own code changed, and the unit is "not comparable" as in `asv compare`, not an invariant failure. +_BENCHMARK_VERSION = re.compile(r"/coordinates/protocol/[^/]+/benchmark_version") + + def _differing(facts: list[dict]) -> list[str]: """Pointers whose value is not the same in every one of `facts` (pointer -> value).""" return sorted(p for key in set().union(*facts) for p in _diff(key, [f.get(key, _ABSENT) for f in facts])) @@ -387,7 +398,7 @@ def _caveats(by_side, base, contender) -> list[str]: return sorted(found) -def _unit(where, pairs, by_side, base, contender, k, min_rounds, side_failed=False): +def _unit(where, pairs, by_side, base, contender, k, min_rounds, side_failed=False, benchmark_changed=False): first = {s: by_side[s][0] for s in (base, contender)} quantity = first[base]["measurement"]["quantity"] # The evidence behind `rounds`: how each side's attempts ended, by status. @@ -397,6 +408,12 @@ def _unit(where, pairs, by_side, base, contender, k, min_rounds, side_failed=Fal for name, s in (("baseline", base), ("contender", contender))}, "rounds": len(pairs), "attempts": attempts, "noise_source": "paired-rounds", "verdict": "indeterminate"} + if benchmark_changed: + # As in `asv compare`: a benchmark whose version differs between the results (the sides, or the + # rounds of one side) was edited, so its results measure different things. No pair is used, + # and the other benchmarks are compared. + unit["reason"] = "benchmark-changed" + return unit if side_failed: # UC-02 §10: if either side fails to run, the benchmark has failed; no effect is reported. unit["reason"] = "side-failed" @@ -476,6 +493,8 @@ def _failed(items) -> list[str]: def _reason(unit) -> str: """The unit's reason; for `not-measured`, which side measured nothing, and how its attempts ended: `not-measured: contender skipped`, or `baseline error 2, skipped 1` when the statuses differ.""" + if unit["reason"] == "benchmark-changed": + return "benchmark-changed: its version differs between the results" if unit["reason"] != "not-measured": return unit["reason"] sides = [] @@ -523,12 +542,18 @@ def render(doc: dict) -> str: caveats = sorted({c for u in doc["units"] for c in u.get("caveats", [])}) if caveats: lines.append(f" caveats: {', '.join(caveats)}") - for section in ("regressed", "improved", "changed", "no-change-detected", "indeterminate"): - rows = [u for u in doc["units"] if u["verdict"] == section] + for section in ("regressed", "improved", "changed", "no-change-detected", "indeterminate", "not-comparable"): + # As asv sorts them: a benchmark that was edited is "not comparable", not indeterminate. + rows = [u for u in doc["units"] + if (u["verdict"] == section and u.get("reason") != "benchmark-changed") + or (section == "not-comparable" and u.get("reason") == "benchmark-changed")] if not rows: continue lines.append(f"\n{section.replace('-', ' ').upper()} ({len(rows)})") for u in rows: + if section == "not-comparable": # no effect, noise or rounds to show: say why, as asv does + lines.append(f" {workload_label(u['workload']):<32} {u['quantity']:<10} ({_reason(u)})") + continue effect = f"{u['effect']:+8.2%}" if "effect" in u else " ?" noise = f"{u['noise']:7.2%}" if "noise" in u else " ?" reason = f" ({_reason(u)})" if "reason" in u else "" diff --git a/src/benchx/tables.py b/src/benchx/tables.py index 707ae6d5..96e01782 100644 --- a/src/benchx/tables.py +++ b/src/benchx/tables.py @@ -185,6 +185,8 @@ def _pipe(headers, rows, right=()) -> str: def _verdict(unit) -> str: """The comparator's verdict in the words of its summary, with the reason when there is no verdict.""" + if unit.get("reason") == "benchmark-changed": # as asv words it + return "not comparable (benchmark-changed)" return unit["verdict"].replace("-", " ") + (f" ({unit['reason']})" if unit.get("reason") else "") @@ -194,8 +196,8 @@ def change_table(doc, units, info, *, all_rows=False) -> str: by_workload = {(_c(u["workload"]), u["quantity"]["name"]): u for u in units} rows = [] for verdict_unit in doc["units"]: - mark = MARKS[verdict_unit["verdict"]] - if mark not in CHANGED.values() and not all_rows: + mark = "x" if verdict_unit.get("reason") == "benchmark-changed" else MARKS[verdict_unit["verdict"]] + if mark not in (*CHANGED.values(), "x") and not all_rows: # asv lists "not comparable" by default continue unit = by_workload[(_c(verdict_unit["workload"]), verdict_unit["quantity"])] before, after = unit["baseline"], unit["contender"] diff --git a/tests/test_benchmark_version.py b/tests/test_benchmark_version.py index 66895979..c71ee9d0 100644 --- a/tests/test_benchmark_version.py +++ b/tests/test_benchmark_version.py @@ -158,7 +158,7 @@ def test_an_asv_result_has_its_own_version_and_no_pyperf_one(tmp_path): FLAGS = {"processes": 2, "values": 2, "loops": 50, "warmups": 0} -def compare(tmp_path, module, run_key): +def compare(tmp_path, module, run_key, names=("f",)): pytest.importorskip("pyperf") from benchx import harnesses, session from benchx.store import Store @@ -167,13 +167,23 @@ def compare(tmp_path, module, run_key): return session.compare_targets( str(trees["base"]), str(trees["head"]), profile="revisions", suite="mod.py", rounds=2, store=Store(tmp_path / "s.parquet"), adapter="pyperf", flags=FLAGS, - filter=harnesses.exact_filter(["f"]), out=tmp_path / "out", run_key=run_key) + filter=harnesses.exact_filter(list(names)), out=tmp_path / "out", run_key=run_key) -def test_two_revisions_whose_function_differs_do_not_agree(tmp_path): +def test_two_revisions_whose_function_differs_are_not_comparable(tmp_path): doc = compare(tmp_path, "def f():\n sum(range({work}))\n", "edited") - assert [f["invariant"] for f in doc["failed_invariants"]] == ["sides-agree"] - assert "/coordinates/protocol/pyperf/benchmark_version differ" in doc["failed_invariants"][0]["detail"] + assert doc["failed_invariants"] == [] + assert [(u["workload"]["name"], u["reason"]) for u in doc["units"]] == [("f", "benchmark-changed")] + + +def test_editing_one_function_leaves_the_others_compared(tmp_path): + """As in asv: only the edited function is not comparable, the comparison goes on for the rest.""" + module = "def f():\n sum(range({work}))\n\n\ndef g():\n sum(range(500))\n" + doc = compare(tmp_path, module, "two", names=("f", "g")) + assert doc["failed_invariants"] == [] + units = {u["workload"]["name"]: u for u in doc["units"]} + assert units["f"]["reason"] == "benchmark-changed" and units["f"]["rounds"] == 0 + assert units["g"]["rounds"] == 2 and units["g"].get("reason") != "benchmark-changed" # paired, not set aside def test_two_revisions_that_differ_outside_the_function_agree(tmp_path): diff --git a/tests/test_comparator.py b/tests/test_comparator.py index bc7f2efa..c1f4152b 100644 --- a/tests/test_comparator.py +++ b/tests/test_comparator.py @@ -641,19 +641,47 @@ def by_name(doc): return {u["workload"]["name"]: u for u in doc["units"]} -def test_an_edited_benchmark_fails_its_own_unit_only(): - """A benchmark whose code differs between the sides (asv's benchmark version) is a new series and is - not comparable; the other benchmark is compared.""" +def test_an_edited_benchmark_is_not_comparable_and_the_others_are_compared(): + """A benchmark whose code differs between the sides (asv's benchmark version) is a new series: as in + `asv compare` it is "not comparable", is no failed invariant, and the other benchmark is compared.""" docs = run_two() for d in docs: if d["coordinates"]["workload"]["name"] == "BM_B": version = "v2" if d["revision"]["key"] == HEAD else "v1" d["coordinates"]["protocol"]["asv"] = {"benchmark_version": version} doc = evaluate(docs) - assert invariants(doc) == ["sides-agree"] - failure = doc["failed_invariants"][0] - assert failure["workload"] == {"name": "BM_B"} and "benchmark_version differ" in failure["detail"] - assert list(by_name(doc)) == ["BM_A"] and by_name(doc)["BM_A"]["verdict"] == "regressed" + assert invariants(doc) == [] + edited = by_name(doc)["BM_B"] + assert (edited["verdict"], edited["reason"], edited["rounds"]) == ("indeterminate", "benchmark-changed", 0) + assert edited["attempts"] == {"baseline": {"success": 3}, "contender": {"success": 3}} + assert "effect" not in edited + assert by_name(doc)["BM_A"]["verdict"] == "regressed" + text = compare.render(doc) + assert "\nNOT COMPARABLE (1)\n BM_B" in text and "(benchmark-changed: its version differs" in text + assert "INDETERMINATE" not in text + + +def test_a_benchmark_edited_during_the_run_is_not_comparable_either(): + """The version differs between the rounds of one side, not only between the sides.""" + docs = run_two() + for d in docs: + if d["coordinates"]["workload"]["name"] == "BM_B": + d["coordinates"]["protocol"]["asv"] = {"benchmark_version": "v2" if d["procedure"]["round"] else "v1"} + doc = evaluate(docs) + assert invariants(doc) == [] and by_name(doc)["BM_B"]["reason"] == "benchmark-changed" + + +def test_a_version_and_another_fact_that_differ_together_are_still_a_failed_invariant(): + """Only the benchmark's own version is "not comparable": a runtime that differs as well is the sides + disagreeing about more than the benchmark.""" + docs = run_two() + for d in docs: + if d["coordinates"]["workload"]["name"] == "BM_B": + head = d["revision"]["key"] == HEAD + d["coordinates"]["protocol"]["asv"] = {"benchmark_version": "v2" if head else "v1"} + d["coordinates"]["environment"]["system"]["runtime"] = {"python": "3.13" if head else "3.12"} + doc = evaluate(docs) + assert invariants(doc) == ["sides-agree"] and list(by_name(doc)) == ["BM_A"] def test_a_failed_attempt_is_excluded_before_the_facts_are_matched(): @@ -733,19 +761,21 @@ def test_a_failed_invariant_of_one_unit_names_the_unit_in_words(): docs = run_two() for d in docs: if d["coordinates"]["workload"]["name"] == "BM_B": - d["coordinates"]["protocol"]["asv"] = {"benchmark_version": "v2" if d["revision"]["key"] == HEAD else "v1"} + d["coordinates"]["protocol"]["harness"] = {"name": "google-benchmark", + "version": "1.9" if d["revision"]["key"] == HEAD else "1.8"} text = compare.render(evaluate(docs)) - assert text.endswith("\nfailed invariants (1)\n BM_B: sides-agree: /coordinates/protocol/asv/benchmark_version differ") + assert text.endswith("\nfailed invariants (1)\n BM_B: sides-agree: /coordinates/protocol/harness/version differ") assert "'invariant'" not in text def test_units_that_failed_an_invariant_alike_are_one_line(): docs = run_two() for d in docs: - d["coordinates"]["protocol"]["asv"] = {"benchmark_version": "v2" if d["revision"]["key"] == HEAD else "v1"} + d["coordinates"]["protocol"]["harness"] = {"name": "google-benchmark", + "version": "1.9" if d["revision"]["key"] == HEAD else "1.8"} text = compare.render(evaluate(docs)) assert text.endswith("\nfailed invariants (2)\n" - " sides-agree: /coordinates/protocol/asv/benchmark_version differ (2 units: BM_A, BM_B)") + " sides-agree: /coordinates/protocol/harness/version differ (2 units: BM_A, BM_B)") def test_a_failed_invariant_of_the_run_is_in_words_too(): diff --git a/tests/test_parameter_order.py b/tests/test_parameter_order.py index 6a1fb91a..178ee0e7 100644 --- a/tests/test_parameter_order.py +++ b/tests/test_parameter_order.py @@ -98,11 +98,12 @@ def test_a_failed_invariant_names_the_parameters_in_the_declared_order_too(): docs = run_of() for d in docs: if d["coordinates"]["workload"]["parameters"]["dtype"] == "'int16'": - d["coordinates"]["protocol"]["asv"] = {"benchmark_version": "v2" if d["revision"]["key"] == HEAD else "v1"} + d["coordinates"]["environment"]["system"]["runtime"] = { + "python": "3.13" if d["revision"]["key"] == HEAD else "3.12"} doc = evaluate(docs) assert [list(f["workload"]["parameters"]) for f in doc["failed_invariants"]] == [DECLARED] * 2 assert compare.render(doc).splitlines()[-1] == ( - " sides-agree: /coordinates/protocol/asv/benchmark_version differ (2 units: " + " sides-agree: /coordinates/environment/system/runtime/python differ (2 units: " f"{NAME} [dtype='int16', array_type=('ordered',), k=10], {NAME} [dtype='int16', array_type=('random',), k=10])") diff --git a/tests/test_tables.py b/tests/test_tables.py index db8402d2..84c6bcfa 100644 --- a/tests/test_tables.py +++ b/tests/test_tables.py @@ -157,18 +157,20 @@ def test_a_benchmark_that_raises_on_one_side_leaves_the_others_compared(): and "indeterminate (not-measured)" in line for line in rows) -def test_an_edited_benchmark_has_no_row_but_the_others_do(): - """Its two sides ran different code, so it is not compared (`sides-agree`): no row in the change table, - while the table of each side still shows what it measured.""" +def test_an_edited_benchmark_is_marked_not_comparable_and_the_others_have_their_rows(): + """Its two sides ran different code, so it has no verdict: as `asv compare` does, the change table lists + it with `x` by default, and the table of each side still shows what it measured.""" docs = make() for d in docs: if d["coordinates"]["workload"]["name"] == MEAN: d["coordinates"]["protocol"]["asv"] = {"benchmark_version": "v2" if d["revision"]["key"] == HEAD else "v1"} doc = evaluate(docs) - assert [f["invariant"] for f in doc["failed_invariants"]] == ["sides-agree"] * 2 + assert doc["failed_invariants"] == [] shown = tables.render(doc, docs) rows = [line for line in shown.splitlines() if line.startswith("| ")] - assert len(rows) == 2 and PLAIN in rows[1] and not any(MEAN in line for line in rows) + edited = [line for line in rows if MEAN in line] + assert edited and all(line.startswith("| x ") and "not comparable (benchmark-changed)" in line for line in edited) + assert any(PLAIN in line for line in rows) assert shown.count(f"{MEAN} ok") == 2 # the grid of each side diff --git a/tests/test_uc02.py b/tests/test_uc02.py index f8fb9696..7167d7c7 100644 --- a/tests/test_uc02.py +++ b/tests/test_uc02.py @@ -250,8 +250,11 @@ def test_measure_mode_refuses_a_baseline_that_is_not_a_value_before_running(tree def test_tables_name_the_sides_by_the_parameter_value(tree, capsys): loop(["mod.py"], by_case([BASELINE, VARIANT]), PYPERF, rounds=3) capsys.readouterr() - code = cli.main(["compare", "--run", RUN, "--profile", "variants", "--baseline", BASELINE, "--tables"]) + # --all: every row, whatever its verdict. What the tables call the sides is the point here, not the sign of + # an effect, which rests on three timed rounds and fails to appear when a loaded machine spoils one of them. + code = cli.main(["compare", "--run", RUN, "--profile", "variants", "--baseline", BASELINE, "--tables", "--all"]) out = capsys.readouterr().out assert code == cli.EXIT_OK assert "role='baseline' (3 rounds):" in out and "role='variant' (3 rounds):" in out - assert f"Before [{BASELINE}]" in out and f"After [{VARIANT}]" in out and "| + " in out + assert f"Before [{BASELINE}]" in out and f"After [{VARIANT}]" in out + assert "bench_truncate" in out.split("Before", 1)[1] # the change table has the row