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
4 changes: 4 additions & 0 deletions docs/benchx.md
Original file line number Diff line number Diff line change
Expand Up @@ -197,6 +197,10 @@ resolved values are written into the order. `--quantity` takes a comma-separated
and one run collects them all. The workers run the `python` first on `PATH`, which must have
pyperf (benchx brings it, so any environment benchx is installed in has it).

Each result records which copy of the target's `pyproject.toml` project the workers would
import (`provenance.info.pyperf.installed`), and `bx compare` warns if both sides import
the same one.

A function has a version, as an asv benchmark does: its `version` attribute, else a hash of
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
Expand Down
15 changes: 2 additions & 13 deletions src/benchx/adapters/asv.py
Original file line number Diff line number Diff line change
Expand Up @@ -427,7 +427,7 @@ def _flags(plan: dict) -> list[str]:
_DIGEST = hashlib.sha256(
json.dumps(_ENV, sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode()).hexdigest()

import importlib.metadata, importlib.util, pickle
import importlib.util, pickle
import pyperf

spec = importlib.util.spec_from_file_location("benchx_asv_runtime", {runtime!r})
Expand Down Expand Up @@ -461,18 +461,7 @@ def _flags(plan: dict) -> list[str]:

project = {project!r}
if project:
installed = {{"name": project}}
try:
installed["version"] = importlib.metadata.version(project)
except importlib.metadata.PackageNotFoundError:
pass
module = sys.modules.get(project)
if module is not None:
installed["path"] = getattr(module, "__file__", None)
for attr in ("__version__", "__git_version__"):
if isinstance(getattr(module, attr, None), str):
installed[attr.strip("_")] = getattr(module, attr)
Path({facts!r}).write_text(json.dumps({{"project": installed}}))
Path({facts!r}).write_text(json.dumps({{"project": rt.params_.installed(project)}}))
try:
runner.bench_time_func({case!r}, bench.time_func())
finally:
Expand Down
32 changes: 32 additions & 0 deletions src/benchx/adapters/benchx_params.py
Original file line number Diff line number Diff line change
Expand Up @@ -120,3 +120,35 @@ def matches_name_only(name, ids, case_filter) -> bool:
return bool(re.search(named, name))
except re.error:
return False


def installed(project) -> dict:
"""The project as the benchmark's interpreter would import it, for `bx compare` to tell
whether two sides measured one build (#185): `name`, and `version` and `path` when found.
The path is the imported module's file, else the one an import would load (a suite may
import the project only inside its benchmarks), found without importing it. `project` is a
distribution name, so `-` and `.` become `_` for the module name, as packaging normalizes them."""
import importlib.metadata
import importlib.util
import sys

found = {"name": project}
try:
found["version"] = importlib.metadata.version(project)
except importlib.metadata.PackageNotFoundError:
pass
name = re.sub(r"[-.]+", "_", project)
module = sys.modules.get(project) or sys.modules.get(name)
if module is not None:
found["path"] = getattr(module, "__file__", None)
for attr in ("__version__", "__git_version__"):
if isinstance(getattr(module, attr, None), str):
found[attr.strip("_")] = getattr(module, attr)
else:
try:
spec = importlib.util.find_spec(name)
except (ImportError, ValueError):
spec = None
if spec is not None and spec.origin:
found["path"] = spec.origin
return found
35 changes: 31 additions & 4 deletions src/benchx/adapters/pyperf.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@
import logging
import shutil
import subprocess
import tomllib
from pathlib import Path

from .. import snapshot
Expand Down Expand Up @@ -169,7 +170,18 @@ def locate(target_path, suite, env, timeout=None) -> dict:
raise Unsupported(
f"pyperf is not importable by {python}: {(probe.stderr.strip().splitlines() or ['no output'])[-1]}"
)
return {"python": python, "module": module.resolve(), "root": root.resolve()}
return {"python": python, "module": module.resolve(), "root": root.resolve(), "project": _project(root)}


def _project(root: Path) -> str | None:
"""The `[project] name` of the target's pyproject.toml: the package whose installed copy each
result records (`benchx_params.installed`), as asv's adapter records the `project` of its
asv.conf.json. None without one, and then nothing is recorded."""
try:
name = tomllib.loads((root / "pyproject.toml").read_text()).get("project", {}).get("name")
except (OSError, ValueError):
return None
return name if isinstance(name, str) and name else None


LISTER = r"""
Expand Down Expand Up @@ -315,6 +327,8 @@ def list_cases(runnable, case_filter, env, timeout=None) -> list[str]:
module = importlib.util.module_from_spec(spec)
sys.modules["benchx_suite"] = module
spec.loader.exec_module(module)
if runner.args.worker and {project!r}: # after the suite's own imports, before any timing
Path({facts!r}).write_text(json.dumps({{"project": params.installed({project!r})}}))
func = getattr(module, {function!r})
index = {index!r}
args = ()
Expand All @@ -333,8 +347,9 @@ def run_case(runnable, case, flags, env, timeout, native_path, env_names=None, h
stem = native_path.name.removesuffix(".native.json")
driver = native_path.with_name(f"{stem}.driver.py")
worker_env = native_path.with_name(f"{stem}.worker-env.json")
facts = native_path.with_name(f"{stem}.installed.json")
params = native_path.with_name(PARAMS.name)
for stale in (native_path, worker_env):
for stale in (native_path, worker_env, facts):
stale.unlink(missing_ok=True)
shutil.copyfile(PARAMS, params)
function, index = runnable.get("cases", {}).get(case, (case, None)) # a case run without listing is a function
Expand All @@ -350,6 +365,8 @@ def run_case(runnable, case, flags, env, timeout, native_path, env_names=None, h
function=function,
index=index,
params=str(params.resolve()),
project=runnable.get("project") or "",
facts=str(facts.resolve()),
)
)
# Absolute: the child runs in the tree, not where the output directory was named.
Expand Down Expand Up @@ -398,12 +415,19 @@ def run_case(runnable, case, flags, env, timeout, native_path, env_names=None, h
artifacts = [("driver", "text/x-python", driver), ("params-helper", "text/x-python", params)]
if worker_env.exists():
artifacts.append(("worker-environment", "application/json", worker_env))
observed = {}
if facts.exists():
artifacts.append(("installed-project", "application/json", facts))
try:
observed = json.loads(facts.read_text())
except ValueError:
observed = {}
return {
"exit_status": status,
"timed_out": status is None,
"stdout": stdout or "",
"stderr": stderr or "",
"native": native,
"native": {**native, "benchx_pyperf": observed} if native is not None and observed else native,
"artifacts": artifacts,
"worker_env": captured,
"passed_env_digest": env_digest(env),
Expand Down Expand Up @@ -555,7 +579,8 @@ def context_facts(native: dict | None) -> tuple[dict, dict]:
"""The native metadata split by meaning: (environment.system facts, provenance info).

The file-level metadata: what held for every run. Facts that differ per
run (load, frequency, temperature) stay in the native artifact.
run (load, frequency, temperature) stay in the native artifact. The installed project the
workers would import is provenance: it changes with the revision, so it is never a system fact.
"""
md = (native or {}).get("metadata", {})
system = {}
Expand All @@ -565,6 +590,8 @@ def context_facts(native: dict | None) -> tuple[dict, dict]:
info = {k: md[k] for k in ("hostname", "cpu_model_name", "cpu_count", "python_executable", "boot_time") if k in md}
if "perf_version" in md:
info["library_version"] = md["perf_version"]
if project := (native or {}).get("benchx_pyperf", {}).get("project"):
info["installed"] = project
return system, info


Expand Down
34 changes: 33 additions & 1 deletion src/benchx/session.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@
import time
from pathlib import Path

from . import adapters, config, harnesses, orders, runner, snapshot
from . import adapters, config, harnesses, log, orders, runner, snapshot
from . import compare as compare_mod
from . import target as target_mod
from .adapters import benchx_params
Expand Down Expand Up @@ -487,6 +487,33 @@ def _note_local_only(progress, sides) -> None:
progress(f"{f'{name} ' if name else ''}{what}{where} is {state}: the comparison will be local-only")


def _installed(files, key) -> dict | None:
"""The project the workers would import, from the first of one order's results that records it
in `info.<key>.installed`, `key` being the adapter's CONTEXT_KEY (asv's and pyperf's record it)."""
for path in files:
facts = json.loads(Path(path).read_text()).get("provenance", {}).get("info", {}).get(key, {})
if facts.get("installed", {}).get("path"):
return facts["installed"]
return None


def _warn_same_build(sides, installed) -> None:
"""#185: two trees that imported the project from one file measured one build twice. Only a
warning: two revisions of a benchmark suite may rightly share one build. The path alone says
which build: the version attributes are recorded only when the suite imported the project at
module level, which the two revisions of a suite need not both do."""
aa = sides[0]["identity"].get("tree") == sides[1]["identity"].get("tree")
if aa or None in installed or installed[0]["path"] != installed[1]["path"]:
return
log.console(__name__).warning( # on the terminal at the default verbosity, not only in the log
"both sides imported %s from %s: unless only the benchmarks differ, this compares one build "
"with itself. To compare builds, run bx bench in each build's environment with one --run-key, "
"then bx compare --run-key",
installed[0].get("name", "the project"),
installed[0]["path"],
)


def counterbalanced(round_, sides):
"""The two sides in the order they run in round `round_` (from 0): baseline first in even
rounds, contender first in odd ones. A drift that slows whichever side runs second then
Expand Down Expand Up @@ -588,6 +615,7 @@ def compare_targets(
)

slot = 0
installed = {} # side name -> the project it imported in round 1
for round_ in range(rounds):
for name, side, side_labels in counterbalanced(round_, zip(("baseline", "contender"), sides, labels)):
title = f"slot {slot + 1}/{rounds * 2}, round {round_ + 1}/{rounds}, {name}"
Expand Down Expand Up @@ -620,7 +648,11 @@ def compare_targets(
raise SessionError(f"the store rejected results of round {round_} ({name}): {', '.join(codes)}")
if progress:
progress(f"round {round_ + 1}/{rounds} {name}: {summary['results']} result(s)")
if round_ == 0:
installed[name] = _installed(summary["files"][1:], adapters.get(harness.name).CONTEXT_KEY)
slot += 1
if round_ == 0 and profile == "revisions":
_warn_same_build(sides, [installed["baseline"], installed["contender"]])

base_value = label[1] if profile == "environments" else sides[0]["identity"]["tree"]
return compare_mod.compare(
Expand Down
153 changes: 153 additions & 0 deletions tests/test_same_build_warning.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,153 @@
"""#185: `bx compare` warns when both revisions imported the project from the same file."""

import json
import logging
import sys
import textwrap

import pytest

from benchx import harnesses, session
from benchx.adapters import benchx_params
from benchx.results import MemoryStore
from conftest import SOURCE_URI, git

NUMPY = {"name": "numpy", "version": "2.3.0", "path": "/env/numpy/__init__.py"}


def _side(tree):
return {"identity": {"tree": tree, "dirty": "clean"}, "source": f"/src/{tree}", "benchmark": None}


def _result(tmp_path, name, installed, adapter="asv"):
path = tmp_path / f"{name}.json"
path.write_text(json.dumps({"provenance": {"info": {adapter: {"installed": installed}}}}))
return path


def test_installed_comes_from_the_first_result_that_records_it(tmp_path):
assert session._installed([_result(tmp_path, "a", {}), _result(tmp_path, "b", NUMPY)], "asv") == NUMPY
assert session._installed([_result(tmp_path, "c", {"name": "numpy"})], "asv") is None


def test_installed_is_read_under_the_adapters_own_key(tmp_path):
pyperf_result = _result(tmp_path, "d", NUMPY, adapter="pyperf")
assert session._installed([pyperf_result], "pyperf") == NUMPY
assert session._installed([pyperf_result], "asv") is None


def test_the_installed_project_is_found_without_importing_it(tmp_path, monkeypatch):
"""A suite may import the project only inside its benchmarks, so the path is the file an
import would load; a distribution name's `-` is the module name's `_`."""
(tmp_path / "my_lib").mkdir()
(tmp_path / "my_lib" / "__init__.py").write_text("raise RuntimeError('imported')\n")
monkeypatch.syspath_prepend(str(tmp_path))
found = benchx_params.installed("my-lib")
assert found == {"name": "my-lib", "path": str(tmp_path / "my_lib" / "__init__.py")}
assert "my_lib" not in sys.modules
assert benchx_params.installed("no-such-project-185") == {"name": "no-such-project-185"}


@pytest.mark.parametrize(
("trees", "other", "warned"),
[
(("t1", "t2"), NUMPY, True),
(("t1", "t2"), {**NUMPY, "path": "/other/numpy/__init__.py"}, False),
(("t1", "t2"), {"name": "numpy", "path": NUMPY["path"]}, True), # one side recorded no version: same file
(("t1", "t2"), None, False), # not asv: nothing recorded
(("t1", "t1"), NUMPY, False), # A/A: one build on purpose
],
)
def test_same_build_warning(trees, other, warned, caplog):
caplog.set_level(logging.WARNING, logger="benchx")
session._warn_same_build([_side(t) for t in trees], [NUMPY, other])
assert bool(caplog.records) is warned
if warned:
assert NUMPY["path"] in caplog.records[0].getMessage()


@pytest.mark.parametrize("profile", ["revisions", "environments"])
def test_compare_targets_checks_revisions_once(profile, tmp_path, monkeypatch, caplog):
caplog.set_level(logging.WARNING, logger="benchx")
sides = iter([_side("t1"), _side("t2")])
result = _result(tmp_path, "r", NUMPY)
monkeypatch.setattr(session, "_side", lambda *a, **k: next(sides))
monkeypatch.setattr(session, "_source_uri", lambda *a: "uri")
outcome = ({"files": ["order", result], "results": 1}, {"rejected": []})
monkeypatch.setattr(session, "_run_side", lambda *a, **k: outcome)
monkeypatch.setattr(session.compare_mod, "compare", lambda *a, **k: {})
session.compare_targets(
"A",
"B",
profile=profile,
suite="s",
rounds=3,
adapter="asv",
label=("env", "x", "y") if profile == "environments" else None,
store=MemoryStore(),
out=tmp_path / "out",
)
warned = [r for r in caplog.records if "both sides imported" in r.getMessage()]
assert len(warned) == (profile == "revisions") # environments may share an install by design


# --- end to end, with real pyperf (the reproducer in #189's review) ---------------------------

SUITE = textwrap.dedent("""
def bench_work():
import my_lib
my_lib.work()
""")


def _checkout(tmp_path, name, work, layout):
"""A tiny project `my-lib` with the suite at its root: `src` layout, where the tree's root does
not hold the package, so the workers import whatever copy the environment has; or `flat`, where
the root, first on the workers' `sys.path`, holds it."""
tree = tmp_path / name
package = tree / ("src" if layout == "src" else "") / "my_lib"
package.mkdir(parents=True)
(package / "__init__.py").write_text(f"def work():\n sum(range({work}))\n")
(tree / "pyproject.toml").write_text('[project]\nname = "my-lib"\nversion = "1.0"\n')
(tree / "bench_mylib.py").write_text(SUITE)
git(tree, "init", "-q")
git(tree, "add", "-A")
git(tree, "commit", "-qm", name)
return tree


@pytest.mark.parametrize(("layout", "warned"), [("src", True), ("flat", False)])
def test_a_pyperf_comparison_says_when_both_sides_imported_one_copy(tmp_path, monkeypatch, caplog, layout, warned):
pytest.importorskip("pyperf")
caplog.set_level(logging.WARNING, logger="benchx")
a = _checkout(tmp_path, "rev-a", 20000, layout)
b = _checkout(tmp_path, "rev-b", 200, layout)
monkeypatch.setenv("PYTHONPATH", str(a / "src")) # as if rev-a were installed: both src trees get it
session.compare_targets(
str(a),
str(b),
profile="revisions",
suite="bench_mylib.py",
rounds=1,
min_rounds=1,
store=MemoryStore(),
adapter="pyperf",
flags={"processes": 1, "values": 2, "loops": 10, "warmups": 1},
filter=harnesses.exact_filter(["bench_work"]),
source_uri=SOURCE_URI,
out=tmp_path / "out",
run_key="aa",
)
recorded = {
json.loads(path.read_text())["provenance"]["info"]["pyperf"]["installed"]["path"]
for path in (tmp_path / "out").rglob("*.json")
if "measurement" in json.loads(path.read_text())
}
package = "src/my_lib/__init__.py" if layout == "src" else "my_lib/__init__.py"
# each result records the copy its workers would import: rev-a's for both src trees, its own for a flat one
assert recorded == ({str(a / package)} if warned else {str(a / package), str(b / package)})
said = [r for r in caplog.records if "both sides imported" in r.getMessage()]
assert len(said) == warned
if warned:
assert str(a / "src" / "my_lib" / "__init__.py") in said[0].getMessage()
assert getattr(said[0], "console", False) # on the terminal, not only in the log
Loading