Skip to content

Commit 05a7af8

Browse files
committed
ENH: warn when both sides of bx compare import the same build (closes #185)
1 parent a69ee6e commit 05a7af8

2 files changed

Lines changed: 98 additions & 0 deletions

File tree

‎src/benchx/session.py‎

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -487,6 +487,30 @@ def _note_local_only(progress, sides) -> None:
487487
progress(f"{f'{name} ' if name else ''}{what}{where} is {state}: the comparison will be local-only")
488488

489489

490+
def _installed(files) -> dict | None:
491+
"""The project the asv workers imported, from the first of one order's results that records it."""
492+
for path in files:
493+
asv = json.loads(Path(path).read_text()).get("provenance", {}).get("info", {}).get("asv", {})
494+
if asv.get("installed", {}).get("path"):
495+
return asv["installed"]
496+
return None
497+
498+
499+
def _warn_same_build(sides, installed) -> None:
500+
"""#185: two trees that imported the project from one file measured one build twice. Only a
501+
warning: two revisions of a benchmark suite may rightly share one build."""
502+
aa = sides[0]["identity"].get("tree") == sides[1]["identity"].get("tree")
503+
if aa or None in installed or installed[0] != installed[1]:
504+
return
505+
logger.warning(
506+
"both sides imported %s from %s: unless only the benchmarks differ, this compares one build "
507+
"with itself. To compare builds, run bx bench in each build's environment with one --run-key, "
508+
"then bx compare --run-key",
509+
installed[0].get("name", "the project"),
510+
installed[0]["path"],
511+
)
512+
513+
490514
def counterbalanced(round_, sides):
491515
"""The two sides in the order they run in round `round_` (from 0): baseline first in even
492516
rounds, contender first in odd ones. A drift that slows whichever side runs second then
@@ -588,6 +612,7 @@ def compare_targets(
588612
)
589613

590614
slot = 0
615+
installed = {} # side name -> the project it imported in round 1
591616
for round_ in range(rounds):
592617
for name, side, side_labels in counterbalanced(round_, zip(("baseline", "contender"), sides, labels)):
593618
title = f"slot {slot + 1}/{rounds * 2}, round {round_ + 1}/{rounds}, {name}"
@@ -620,7 +645,11 @@ def compare_targets(
620645
raise SessionError(f"the store rejected results of round {round_} ({name}): {', '.join(codes)}")
621646
if progress:
622647
progress(f"round {round_ + 1}/{rounds} {name}: {summary['results']} result(s)")
648+
if round_ == 0:
649+
installed[name] = _installed(summary["files"][1:])
623650
slot += 1
651+
if round_ == 0 and profile == "revisions":
652+
_warn_same_build(sides, [installed["baseline"], installed["contender"]])
624653

625654
base_value = label[1] if profile == "environments" else sides[0]["identity"]["tree"]
626655
return compare_mod.compare(

‎tests/test_same_build_warning.py‎

Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
"""#185: `bx compare` warns when both revisions imported the project from the same file."""
2+
3+
import json
4+
import logging
5+
6+
import pytest
7+
8+
from benchx import session
9+
from benchx.results import MemoryStore
10+
11+
NUMPY = {"name": "numpy", "version": "2.3.0", "path": "/env/numpy/__init__.py"}
12+
13+
14+
def _side(tree):
15+
return {"identity": {"tree": tree, "dirty": "clean"}, "source": f"/src/{tree}", "benchmark": None}
16+
17+
18+
def _result(tmp_path, name, installed):
19+
path = tmp_path / f"{name}.json"
20+
path.write_text(json.dumps({"provenance": {"info": {"asv": {"installed": installed}}}}))
21+
return path
22+
23+
24+
def test_installed_comes_from_the_first_result_that_records_it(tmp_path):
25+
assert session._installed([_result(tmp_path, "a", {}), _result(tmp_path, "b", NUMPY)]) == NUMPY
26+
assert session._installed([_result(tmp_path, "c", {"name": "numpy"})]) is None
27+
28+
29+
@pytest.mark.parametrize(
30+
("trees", "other", "warned"),
31+
[
32+
(("t1", "t2"), NUMPY, True),
33+
(("t1", "t2"), {**NUMPY, "path": "/other/numpy/__init__.py"}, False),
34+
(("t1", "t2"), {**NUMPY, "version": "2.4.0"}, False),
35+
(("t1", "t2"), None, False), # not asv: nothing recorded
36+
(("t1", "t1"), NUMPY, False), # A/A: one build on purpose
37+
],
38+
)
39+
def test_same_build_warning(trees, other, warned, caplog):
40+
caplog.set_level(logging.WARNING, logger="benchx")
41+
session._warn_same_build([_side(t) for t in trees], [NUMPY, other])
42+
assert bool(caplog.records) is warned
43+
if warned:
44+
assert NUMPY["path"] in caplog.records[0].getMessage()
45+
46+
47+
@pytest.mark.parametrize("profile", ["revisions", "environments"])
48+
def test_compare_targets_checks_revisions_once(profile, tmp_path, monkeypatch, caplog):
49+
caplog.set_level(logging.WARNING, logger="benchx")
50+
sides = iter([_side("t1"), _side("t2")])
51+
result = _result(tmp_path, "r", NUMPY)
52+
monkeypatch.setattr(session, "_side", lambda *a, **k: next(sides))
53+
monkeypatch.setattr(session, "_source_uri", lambda *a: "uri")
54+
outcome = ({"files": ["order", result], "results": 1}, {"rejected": []})
55+
monkeypatch.setattr(session, "_run_side", lambda *a, **k: outcome)
56+
monkeypatch.setattr(session.compare_mod, "compare", lambda *a, **k: {})
57+
session.compare_targets(
58+
"A",
59+
"B",
60+
profile=profile,
61+
suite="s",
62+
rounds=3,
63+
adapter="asv",
64+
label=("env", "x", "y") if profile == "environments" else None,
65+
store=MemoryStore(),
66+
out=tmp_path / "out",
67+
)
68+
warned = [r for r in caplog.records if "both sides imported" in r.getMessage()]
69+
assert len(warned) == (profile == "revisions") # environments may share an install by design

0 commit comments

Comments
 (0)