diff --git a/docs/benchx.md b/docs/benchx.md index 3d0e1b4e..4d91208f 100644 --- a/docs/benchx.md +++ b/docs/benchx.md @@ -40,7 +40,7 @@ bx bench TARGET --suite NAME [CASE …] # the single-target form of bx compar [--adapter …] [--filter REGEX] [--quantity …] [-e NAME=VALUE ...] [--processes N] [--values N] [--min-time S | --loops N] [--warmups N] [--repetitions N] [--project P] [--run-key KEY] [--out DIR] [--no-build] [--source-uri URI] - [--label NAME=VALUE ... --round N --slot K] # one side of a session other calls join + [--label NAME=VALUE ... --round R[/N] --slot K] # one side of a session other calls join [--case-timeout S] [--no-ingest] bx bench MODULE.py [FUNCTION …] [--tree DIR] [...] # shorthand: Python functions under pyperf → results → store → table @@ -78,6 +78,9 @@ bx target describe|prepare TARGET # a target's description (a provider's bx validate … [--kind KIND] # every problem in each document, by schema and rules bx config init [--dir DIR] [--adapter …] # write a benchx.conf.json stating a harness's defaults bx config show # what benchx.conf.json and the defaults give, and where each value comes from + +# every command also takes: -v/-q (what the terminal shows), --log-level LEVEL, +# and --no-log | --log | --log-file PATH (where the log goes; the default is bx.log in the run's folder) ``` # Technical details @@ -87,8 +90,8 @@ bx config show # what benchx.conf.json and the default working directory; its directory is the root) says how the project is measured: the `provider`, the `project` name and `source`, an `adapter` block (`name`, `suite`, `quantities`, `precision`), `environment_variables`, `timeouts`, `paths` for the store -and the results (by default `store.parquet` and `results/` in the root), and the -comparator's `compare` policy. Every value is the command line's, else the file's, else a +and the results (by default `store.parquet` and `results/` in the root), the +comparator's `compare` policy, and the log (`logging`, `log_level`: see "The log" below). Every value is the command line's, else the file's, else a built-in default; a required one (`adapter.name`, `adapter.suite`, the target, and for `bx compare` the profile and `--rounds`) that has none is a hard failure that names the flag and the key. `--no-project` makes one run ad hoc whatever the file's `project` says. @@ -97,6 +100,42 @@ pyperf and for Google Benchmark. The store and the results directory are left ou measured tree's identity when they sit inside it. `.benchx/setup.json` (declared environment facts) is a separate file, written by whoever prepares an environment. +**The log.** `bx bench` and `bx compare` write `bx.log` in the run's output folder +(`--out`, else `RESULTS/RUN_KEY`), and `bx run --out DIR` writes `DIR/bx.log`. Each +invocation appends a header (the benchx version, its pid, the working directory and the +command line as given), the config file it found, the settings it resolved with where each +came from (flag, environment variable, file or default), and then what it decided, and ends +with a footer: `end: ok (exit 0), 41 s`. The word is `ok`, `invalid` (exit 1), `refused` +(exit 2), `crashed` or `interrupted` (Ctrl-C); a log that ends without a footer is the +trace of a process that was killed (`SIGTERM`, `SIGHUP` or `SIGKILL`). A refusal for a bad +flag or value leaves no folder; a run refused later, by the session, leaves `RUN_KEY/` +holding only `bx.log`, which says why. At the default +verbosity the terminal shows what `bx` printed before there was a log: the log is the full record, and `-v` shows its +INFO records on the terminal (`-vv` DEBUG too), `-q` only warnings and errors, `-qq` only +errors (`$BENCHX_VERBOSE` sets it: -2 or more). A `bx bench` call starts with a line saying what +it measures and where it sits (`measuring np_mean.py on @numpy (round 1/5, slot 3)`), and `bx run` +with one naming the order; `-q` keeps it, `-qq` does not. What `bx bench` and `bx run` report on +stdout when they finish, the table of results, the cases that were not measured and the result +line, is in the log as well, a line a record, and `-q` and `-qq` hide it by tiers: `-q` leaves +the not-measured section and the result line (`N result(s) -> DIR`), `-qq` only the +not-measured section (a failed case does not change the exit status, so it must not vanish; a case that failed +without a message is counted on a line that both keep, and a case the harness skipped is expected, so what it +said goes with the table). A +run that measured everything is silent at `-qq`. The ingest counts that follow a run +(`STORE: ingested 12, duplicate 0`) are a progress message on stderr, like `precision:`: shown +by default and with `-v`, not with `-q`. `bx ingest`, `bx compare`, the queries and everything +`--json` prints are answers, shown at every level. A target provider's own stderr, such as a build's output, is the provider's: `-qq` +does not silence it. Each `-v` past `-vv` also asks the harness itself to say more, as `--harness-verbosity N` does: `-vvv` is `-vv` and 1, `-vvvv` is `-vv` and 2. pyperf and asv are then given `--verbose`, and Google Benchmark `--v=N`; the output is logged in full (up to 2000 lines a stream, 40 otherwise). The default, 0, asks for nothing more. The harness prints between values, outside the timed call, but it is output on the machine between samples, so the order records it (`harness_verbosity`, not part of the measurement's identity) and so does each result's `provenance.info`. `$BENCHX_HARNESS_VERBOSITY` and `adapter.verbosity` in the config file set it too, below the flag. The log's own level is `--log-level` +(`debug`, the default, `info`, `warning`, `error`; `$BENCHX_LOG_LEVEL`, or `log_level` in the +file). `--no-log` turns it off, `--log` sends it to stderr instead, `--log-file PATH` appends it +to a file (`{out}` is the run's output folder, `{root}` the project root); the file's key +`logging` takes `false`, `true` or such a path, and is honoured by the commands that have an +output folder, while a flag works for any command. A file named `*.json` is refused, since +`bx ingest` reads such files in a directory. **A `bx.log` records the command line as given, +`-e` values and credentials in a `--source-uri` included, and a command's output as it was +printed. It does not claim to hide secrets: like `workorder-….json` in the same folder, it can +contain them, and a results folder that is archived or shared carries it.** It never holds the environment `bx` inherited, only names of variables, with one exception: the variables benchx itself reads (`BENCHX_HOME`, `BENCHX_VERBOSE`, `BENCHX_LOG_LEVEL`, `BENCHX_HARNESS_VERBOSITY`, `BENCHX_SETUP_FILE`, `BENCHX_ENV_ALLOWLIST`, `BENCHX_SCHEMAS`) are logged with their values, since they are settings someone typed for benchx and decide what it does. + Each target is `BUILD_DIR[:SOURCE_DIR]` or `@CONFIG[=SOURCE_REF]`. Two targets (one for `--profile variants`) select measure mode and `--run` selects read mode; mixing them is an error. @@ -148,8 +187,8 @@ order, so `bx run results/KEY/orders/order.json` replays any bench run. is a runnable walk-through. Environments that cannot share a process, such as two venvs with different numpy versions, are -measured by separate `bx bench` calls that share a `--run-key`; `--label NAME=VALUE`, `--round N` -and `--slot K` place each call in the session, and `bx compare --run KEY --profile environments +measured by separate `bx bench` calls that share a `--run-key`; `--label NAME=VALUE`, `--round R[/N]` +and `--slot K` place each call in the session (`--round 2/5` also says the session has 5 rounds, numbered 0 to 4, which the start line shows), and `bx compare --run KEY --profile environments --label NAME --baseline VALUE` compares the sides ([UC-04](https://benchx-dev.github.io/benchx/use-cases/UC-04-cross-env/)). `examples/numpy-venvs` in [benchx_examples](https://github.com/benchx-dev/benchx_examples) is the worked example, with a shell script that drives it. diff --git a/docs/design/prototype-design.md b/docs/design/prototype-design.md index c2dbf2f2..9919a330 100644 --- a/docs/design/prototype-design.md +++ b/docs/design/prototype-design.md @@ -42,7 +42,7 @@ bx bench TARGET --suite NAME [CASE …] # the single-target form of bx compar [--adapter …] [--filter REGEX] [--quantity NAMES] [-e NAME=VALUE ...] [precision flags, as for bx compare] [--project P | --no-project] [--run-key KEY] [--out DIR] [--no-build] [--source-uri URI] - [--label NAME=VALUE ... --round N --slot K] # one side of a session other calls join + [--label NAME=VALUE ... --round R[/N] --slot K] # one side of a session other calls join [--case-timeout S] [--no-ingest] bx bench MODULE.py [FUNCTION …] [--tree DIR] [...] # shorthand: the module's checkout, pyperf → result files → store → table @@ -119,8 +119,7 @@ walking up from the working directory; its directory is the root, and with no fi root is the working directory (`schemas/config/0.1.0`). It holds `project`, `source.uri`, `provider.command`, an `adapter` block (`name`, `suite`, `quantities`, `precision`), `environment_variables`, `collectors`, `timeouts`, `paths.store` and `paths.results` (default -`store.parquet` and `results/` in the root, and relative to the root), and `compare` -(`profile`, `rounds`, `k`, `min_rounds`). A command-line argument wins; if it is missing the +`store.parquet` and `results/` in the root, and relative to the root), `compare` (`profile`, `rounds`, `k`, `min_rounds`), and the log (`logging`, `log_level`). A command-line argument wins; if it is missing the value is read from the file; if that is missing too, a built-in default applies, where one exists. A required value with none of the three (`adapter.name`, `adapter.suite`, the target, and for `bx compare` the profile and the rounds) is a hard failure that names the @@ -134,6 +133,27 @@ measured tree they sit in, so a run's own output does not mark it dirty. The ear `.benchx/setup.json` (declared environment facts, §3) is a separate file. `schemas/config/0.1.0/examples` has recommended settings for each harness. +**Output channels and the log.** Stdout carries a command's answer: a query's tables and `--json`, +`bx history`'s caveat and the ingest counts of `bx ingest` at every verbosity, and what a measuring command +reports when it ends (`bx bench`'s table, the cases that were not measured and the result line), which `-q` and +`-qq` hide by tiers. Stderr carries what the user needs to see: progress (a run's start line, the store path and +the ingest counts that follow it), refusals, rejections. At the default verbosity both are what they were before +the log. Beside them +`bx` keeps a log through the standard library's `logging` (`benchx/log.py`): every module logs to +`benchx.`, the package installs only a `NullHandler`, and `cli.main` installs the +handlers. What `bx` shows on stderr is emitted once, as a record marked `console=True`, and the +console handler writes the bare message, so the default terminal output is byte for byte what +`print` wrote; `-v` and `-vv` also show the records that are not marked. What a run reports on +stdout when it ends (`bx bench`'s table, not-measured section and result line) is such a record too, marked +`stdout=True`: the stdout handler writes it unless `-q` or `-qq` hides it, and the log keeps it. The file handler +appends +every record at `--log-level` (DEBUG by default) in one line, `UTC-timestamp pid logger LEVEL +message`, with a header and a footer for each invocation. The default +file is `bx.log` in the run's output folder, which the CLI now settles, with the run key, before +it resolves any target (`session.run_directory`); a command without an output folder logs only +when a flag asks. The log makes no claim to protect secrets, since it records the command as +given (see `docs/benchx.md`, "The log"). + `bx compare` has two modes, chosen by its arguments. Two positional targets (a path read by the harness, or `@CONFIG[=SOURCE_REF]`, a call to the project's target provider; one target for `variants`, whose sides are two values of one diff --git a/docs/design/runner-schema.md b/docs/design/runner-schema.md index 503f8b7e..84134b89 100644 --- a/docs/design/runner-schema.md +++ b/docs/design/runner-schema.md @@ -34,6 +34,7 @@ A work order (`benchx/work-order/0.1.0`) has four required groups matching `runn | `project` | token | no | what | Project in the store; omit for an ad hoc run (results are then thin) | `project` | | `suites[]` | array | yes | what | `{adapter, suite, filter, include[], exclude[], parameters}` per harness suite; `filter` is a harness-native string, an alternative to `include`/`exclude` for adapters with only single-pattern selection | `coordinates.workload` via the adapter | | `quantities[]` | array of names | yes | what | Quantities to collect, e.g. `wall-time`, `peak-rss` | `measurement.quantity` | +| `harness_verbosity` | integer | no | what | benchx extension: how much the harness itself is asked to say, 0 (absent) for nothing more; pyperf and asv `--verbose`, Google Benchmark `--v=N`; not part of the identity | `provenance.info.harness_verbosity` | | `environment_variables` | string map | no | what | `{NAME: value}` set on the measured process, on top of what the runner inherited; a workload coordinate, not a machine fact — `OMP_NUM_THREADS=1` and `=10` are different, non-pooling variants | `coordinates.workload.parameters` | | `workload_parameters` | map | no | what | Parameters passed to the runner or harness, never as environment variables; a name may not appear in both maps | `coordinates.workload.parameters` | | `target` | one of 3 kinds | yes | at what | What code to measure (§3.1) | `source`, `revision`, dirty flags, tree ids | diff --git a/src/benchx/__init__.py b/src/benchx/__init__.py index aca83e71..abfc5547 100644 --- a/src/benchx/__init__.py +++ b/src/benchx/__init__.py @@ -6,4 +6,10 @@ and comparator). """ +import logging + __version__ = "0.1.0" + +# A library caller sees no log output unless it configures logging itself; `bx` (cli.main) +# installs its own handlers (log.py). +logging.getLogger(__name__).addHandler(logging.NullHandler()) diff --git a/src/benchx/adapters/asv.py b/src/benchx/adapters/asv.py index 4353ce11..b7ce642f 100644 --- a/src/benchx/adapters/asv.py +++ b/src/benchx/adapters/asv.py @@ -44,18 +44,23 @@ """ import json +import logging import math import shutil import statistics import subprocess -import sys import tempfile from pathlib import Path -from .. import snapshot +from .. import log, snapshot from . import benchx_params, pyperf -from .base import (Unsupported, check_filter, last_json, name_only_note, no_cases, parametrized_workload, run_bounded, - kill_group, stop_group) +from .base import (Unsupported, check_filter, kill_group, last_json, name_only_note, no_cases, note_case, + note_case_ended, note_cases, note_parameters, parametrized_workload, run_bounded, stop_group) + +# asv's skip warnings are shown to the user, as `bx` shows its other messages: the one +# library module that makes console messages, until `list_cases` returns them as data. +say = log.console(__name__) +logger = logging.getLogger(__name__) NAME = "asv" CONTEXT_KEY = "asv" @@ -135,12 +140,15 @@ def _which_python(env: dict) -> str | None: return shutil.which("python", path=path) or shutil.which("python3", path=path) -def _read_conf(path: Path) -> dict: - """asv.conf.json allows // comments; drop whole-line ones, as asv does.""" +def _read_conf(path: Path, level=logging.WARNING) -> dict: + """asv.conf.json allows // comments; drop whole-line ones, as asv does. A file that is not JSON gives + `{}` and a record at `level`: WARNING from the shorthand, which reads it once per command, DEBUG from + `_project`, which reads it again for every order.""" lines = [l for l in path.read_text(encoding="utf-8").splitlines() if not l.lstrip().startswith("//")] try: return json.loads("\n".join(lines)) - except ValueError: + except ValueError as e: + logger.log(level, "%s is not valid JSON, so its settings are not applied: %s", path, e) return {} @@ -149,7 +157,7 @@ def _project(benchmark_dir: Path, root: Path) -> str | None: for directory in [benchmark_dir, *benchmark_dir.parents]: for name in CONF_NAMES: if (directory / name).is_file(): - return _read_conf(directory / name).get("project") + return _read_conf(directory / name, logging.DEBUG).get("project") if directory == root: break return None @@ -186,13 +194,19 @@ def list_cases(runnable, case_filter, env, timeout=None) -> list[str]: shutil.copy(PARAMS, scratch) out = run_bounded([runnable["python"], runtime, "list", str(runnable["benchmark_dir"])], timeout=timeout, what=f"listing the asv benchmarks in {runnable['benchmark_dir']}", - env=env, cwd=scratch) + env=env, cwd=scratch, temporary=[scratch]) if out.returncode != 0: raise Unsupported(f"cannot discover asv benchmarks in {runnable['benchmark_dir']}: " f"{(out.stderr.strip().splitlines() or ['no output'])[-1]}") listing = last_json(out, str(runnable["benchmark_dir"])) for failure in listing["failed"]: - print(f"asv: skipped module {failure['module']}: {failure['error']}", file=sys.stderr) + say.warning(f"asv: skipped module {failure['module']}: {failure['error']}") + # the traceback, beside the console warning; a failed package's submodules are not scanned + log.harness_output(logger, f"module {failure['module']}", "traceback", failure.get("traceback"), failed=False) + logger.debug("module %s failed to import, so its submodules were not scanned", failure["module"]) + if listing.get("left_out"): + logger.debug("%d benchmark(s) the suite switched off with skip_benchmark: %s%s", len(listing["left_out"]), + ", ".join(listing["left_out"][:40]), ", …" if len(listing["left_out"]) > 40 else "") cases, other, unmatched = [], {}, [] runnable["cases"] = {} # case id -> (benchmark name, combination index or None) for info in listing["benchmarks"]: @@ -207,8 +221,8 @@ def list_cases(runnable, case_filter, env, timeout=None) -> list[str]: continue scope = info["declared"].get("setup_scope", "call") if scope not in SETUP_SCOPES: - print(f"asv: skipped {info['name']}: setup_scope must be one of {', '.join(map(repr, SETUP_SCOPES))}, " - f"not {scope!r}", file=sys.stderr) + say.warning(f"asv: skipped {info['name']}: setup_scope must be one of " + f"{', '.join(map(repr, SETUP_SCOPES))}, not {scope!r}") continue runnable["benchmarks"][info["name"]] = info for case, target in selected: @@ -229,8 +243,9 @@ def list_cases(runnable, case_filter, env, timeout=None) -> list[str]: raise no_cases(runnable["benchmark_dir"], case_filter, {i["name"] for i in listing["benchmarks"] if i["type"] == "time"}, notes) if other: - print(f"asv: not run (only time benchmarks map to wall-time): {not_run}", file=sys.stderr) - return cases + say.warning(f"asv: not run (only time benchmarks map to wall-time): {not_run}") + note_parameters(logger, runnable) + return note_cases(logger, cases, case_filter) def _describe(target: tuple[str, int | None]) -> str: @@ -271,6 +286,31 @@ def _plan(info: dict, invocation: dict) -> dict: "loops_from": loops_from, "setup_scope": scope} +def _note_plan(info: dict, invocation: dict, plan: dict) -> None: + """The case's plan, each setting with where it came from, and what the order asked for that did not + apply. The sources are worked out here, for the log: the plan itself is written into the `asv-case` + artifact and gets no new keys.""" + if not logger.isEnabledFor(logging.DEBUG): + return + declared = info["declared"] + sources = {"min_time": "order" if invocation["min_time"] is not None + else "sample_time" if "sample_time" in declared else "default", + "warmups": "order" if invocation["warmups"] is not None + else "warmup_time" if "warmup_time" in declared else "default", + "timeout": "timeout" if "timeout" in declared else "default"} + logger.debug("plan: values %s (%s), loops %s (%s), min_time %s (%s), warmups %s (%s), timeout %s (%s)", + plan["values"], plan["values_from"], plan["loops"], plan["loops_from"] or "adaptive calibration", + plan["min_time"], sources["min_time"], plan["warmups"], sources["warmups"], plan["timeout"], + sources["timeout"]) + if invocation["min_time"] is not None and plan["loops"] is not None and plan["loops_from"] != "order": + logger.debug("the order's min_time %g s is lost: the loops are fixed at %s by %s", invocation["min_time"], + plan["loops"], "a declared number" if plan["loops_from"] == "number" + else "the default setup_scope of call (any benchmark with a setup hook has it)") + if invocation["values"] is None and plan["values_from"] == "default" and declared.get("repeat") is not None: + logger.debug("repeat %r is not a form asv_runner reads here, so the default %s values are used", + declared["repeat"], plan["values"]) + + def _flags(plan: dict) -> list[str]: flags = ["--processes", str(plan["processes"]), "--values", str(plan["values"]), "--warmups", str(plan["warmups"]), "--timeout", str(math.ceil(plan["timeout"])), "--copy-env"] @@ -345,17 +385,20 @@ def _flags(plan: dict) -> list[str]: def _read_json(path: Path): try: return json.loads(path.read_text()) - except (OSError, ValueError): + except (OSError, ValueError) as e: + if path.exists(): # an absent file is how a skipped case or a missing probe looks: not worth a line + logger.debug("%s exists but cannot be read: %s", path, e) return None -def run_case(runnable, case, invocation, env, timeout, native_path, env_names=None) -> dict: +def run_case(runnable, case, invocation, env, timeout, native_path, env_names=None, harness_verbosity=0) -> dict: """One pyperf run for the case; never raises for harness failures, which become results.""" if env_names is None: env_names = snapshot.env_allowlist(env, ENV_ALLOWLIST) name, index = runnable["cases"][case] info = runnable["benchmarks"][name] plan = _plan(info, invocation) + _note_plan(info, invocation, plan) 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") @@ -373,8 +416,10 @@ def run_case(runnable, case, invocation, env, timeout, native_path, env_names=No env_names=list(env_names), benchmark_dir=str(runnable["benchmark_dir"]), module=info["module"], attr=info["attr"], index=index, case=case, has_cache=bool(info["setup_cache_key"]), skipped=str(skipped), facts=str(facts), project=runnable["project"] or "")) - args = [runnable["python"], str(driver.resolve()), *_flags(plan), "-o", str(native_path.resolve())] + args = [runnable["python"], str(driver.resolve()), *_flags(plan), *(["--verbose"] if harness_verbosity else []), + "-o", str(native_path.resolve())] # the workers are pyperf's: its --verbose # Its own process group, so a timeout takes the workers down with the manager. + note_case(logger, args, cwd=scratch, timeout=timeout) proc = subprocess.Popen(args, env=env, cwd=scratch, text=True, start_new_session=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) try: @@ -389,6 +434,7 @@ def run_case(runnable, case, invocation, env, timeout, native_path, env_names=No skip = _read_json(skipped) observed = _read_json(facts) or {} native = _read_json(native_path) + note_case_ended(logger, status, timeout, native_path, parsed=native is not None, skipped=skip is not None) if native is not None: native_path.write_text(json.dumps(native, indent=1) + "\n") asv = {"benchmark": info, "case": case, "plan": plan, "skipped": skip, **observed} @@ -405,6 +451,9 @@ def run_case(runnable, case, invocation, env, timeout, native_path, env_names=No "worker_env": _read_json(worker_env), "passed_env_digest": pyperf.env_digest(env)} +explain_warnings = pyperf.explain_warnings # the workers are pyperf's + + def _case_applied(applied: dict, plan: dict, version: str | None = None) -> dict: """The protocol one case ran under, in benchx terms.""" if plan["loops"] is not None: diff --git a/src/benchx/adapters/asv_runtime.py b/src/benchx/adapters/asv_runtime.py index d759ab4c..c8683ad6 100644 --- a/src/benchx/adapters/asv_runtime.py +++ b/src/benchx/adapters/asv_runtime.py @@ -249,8 +249,10 @@ def run_isolated(loops): return run_isolated -def _benchmark(attr_name, module, klass, func): +def _benchmark(attr_name, module, klass, func, left_out=None): if getattr(func, "skip_benchmark", False): + if left_out is not None: # a benchmark the suite switched off: the parent can say so + left_out.append(f"{module.__name__}.{klass.__name__ + '.' if klass else ''}{attr_name}") return None name = getattr(func, "benchmark_name", None) search = name.split(".")[-1] if name else attr_name @@ -280,9 +282,9 @@ def _modules(name, failed): def discover(benchmark_dir: str): - """(benchmarks, failed imports), in asv's order.""" + """(benchmarks, failed imports, names left out by `skip_benchmark`), in asv's order.""" package = use_package(benchmark_dir) - failed, found = [], [] + failed, found, left_out = [], [], [] for module in _modules(package, failed): for attr_name, value in list(module.__dict__.items()): if attr_name.startswith("_"): @@ -290,14 +292,14 @@ def discover(benchmark_dir: str): if inspect.isclass(value) and not inspect.isabstract(value): for name, member in inspect.getmembers(value): if inspect.isfunction(member) or inspect.ismethod(member): - benchmark = _benchmark(name, module, value, member) + benchmark = _benchmark(name, module, value, member, left_out) if benchmark is not None: found.append(benchmark) elif inspect.isfunction(value): - benchmark = _benchmark(attr_name, module, None, value) + benchmark = _benchmark(attr_name, module, None, value, left_out) if benchmark is not None: found.append(benchmark) - return found, failed + return found, failed, left_out def load(benchmark_dir: str, module: str, attr: list, index=None) -> Benchmark: @@ -318,8 +320,8 @@ def main(argv): command, benchmark_dir = argv[:2] if command != "list": raise SystemExit(f"unknown command {command!r}") - found, failed = discover(benchmark_dir) - print(json.dumps({"benchmarks": [b.describe() for b in found], "failed": failed})) + found, failed, left_out = discover(benchmark_dir) + print(json.dumps({"benchmarks": [b.describe() for b in found], "failed": failed, "left_out": left_out})) if __name__ == "__main__": diff --git a/src/benchx/adapters/base.py b/src/benchx/adapters/base.py index 0b5bef6e..965e73b7 100644 --- a/src/benchx/adapters/base.py +++ b/src/benchx/adapters/base.py @@ -69,16 +69,24 @@ import difflib import json +import logging +import math import os import re import signal import subprocess import textwrap +import time +from pathlib import Path +from .. import log from ..core import Refusal, Rejected from .benchx_params import combination, search_name +logger = logging.getLogger(__name__) + + class Unsupported(Rejected): """An order this adapter cannot carry out as written; the runner refuses it.""" @@ -220,7 +228,49 @@ def stop_group(proc, grace=STOP_GRACE_S) -> None: kill_group(proc) -def run_bounded(args, *, timeout, what, **kwargs) -> subprocess.CompletedProcess: +def note_cases(adapter_logger, cases, case_filter, limit=40) -> list: + """What `list_cases` found, for the log: how many, under which filter, and the first `limit` names.""" + shown = cases[:limit] + more = f", and {len(cases) - len(shown)} more" if len(cases) > len(shown) else "" + adapter_logger.debug("%d case(s)%s: %s%s", len(cases), f" for the filter {case_filter!r}" if case_filter else "", + ", ".join(shown), more) + return cases + + +def note_parameters(adapter_logger, runnable, limit=40) -> None: + """The parametrized benchmarks `list_cases` found: each one's parameters with their values (asv's `repr()` + strings) and the number of combinations, one case each. At most `limit` benchmarks.""" + found = [(name, info) for name, info in runnable.get("benchmarks", {}).items() if info.get("param_names")] + for name, info in found[:limit]: + values = ", ".join(f"{parameter}: {', '.join(shown[:10])}{', …' if len(shown) > 10 else ''}" + for parameter, shown in zip(info["param_names"], info["params"])) + adapter_logger.debug("%s: %d combination(s) of %s", name, math.prod(len(shown) for shown in info["params"]), + values) + if len(found) > limit: + adapter_logger.debug("and %d more parametrized benchmark(s)", len(found) - limit) + + +def note_case(adapter_logger, args, *, cwd, timeout) -> None: + """The command a `run_case` is about to start, as the log shows it, with the directory it + runs in (a relative path in the arguments only means something from there) and its limit.""" + adapter_logger.debug("run_case: %s (in %s, limit %g s)", log.command(args), cwd or Path.cwd(), timeout) + + +def note_case_ended(adapter_logger, status, timeout, native_path, *, parsed, skipped=False) -> None: + """After `run_case`'s process: a timeout that killed the group, and the native output file, which a + case that exited 0 should have left (WARNING when it is missing or does not parse). A case that + failed or timed out has its case line as the warning, so a missing file is then DEBUG; so is the + file of a benchmark that skipped itself, which has none.""" + if status is None: + adapter_logger.debug("timed out after %g s: the process group was killed", timeout) + if not native_path.exists(): + if not skipped: + adapter_logger.log(logging.WARNING if status == 0 else logging.DEBUG, "native output missing: %s", native_path) + elif not parsed: + adapter_logger.warning("native output does not parse: %s", native_path) + + +def run_bounded(args, *, timeout, what, scripts=None, temporary=(), **kwargs) -> subprocess.CompletedProcess: """`subprocess.run(args, capture_output=True, text=True, **kwargs)` with a time limit. The child leads its own process group, and the whole group is killed when the limit @@ -229,13 +279,25 @@ def run_bounded(args, *, timeout, what, **kwargs) -> subprocess.CompletedProcess `what` was being done: an order whose discovery cannot finish cannot be planned. `timeout` None means no limit. """ + logger.debug("%s: %s (in %s, limit %s)", what, log.command(args, scripts=scripts, temporary=temporary), + kwargs.get("cwd") or Path.cwd(), f"{timeout:g} s" if timeout else "none") + started = time.monotonic() proc = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, start_new_session=True, **kwargs) try: stdout, stderr = proc.communicate(timeout=timeout) except BaseException as error: - kill_group(proc) + stdout, stderr = kill_group(proc) if isinstance(error, subprocess.TimeoutExpired): + logger.debug("%s: no exit after %.1f s; its process group was killed", what, time.monotonic() - started) + log.harness_output(logger, what, "stderr", stderr, failed=True) + log.harness_output(logger, what, "stdout", stdout, failed=True) raise Unsupported(f"{what} did not finish within {timeout:g} s (timeouts.order_s)") from None + logger.debug("%s: interrupted (%s); its process group was killed", what, type(error).__name__) raise + logger.debug("%s: exit %d in %.1f s", what, proc.returncode, time.monotonic() - started) + # stdout is the listing benchx parses, so it is logged only when the call failed + log.harness_output(logger, what, "stderr", stderr, failed=proc.returncode != 0) + if proc.returncode != 0: + log.harness_output(logger, what, "stdout", stdout, failed=True) return subprocess.CompletedProcess(args, proc.returncode, stdout, stderr) diff --git a/src/benchx/adapters/gbench.py b/src/benchx/adapters/gbench.py index f7602092..5869727a 100644 --- a/src/benchx/adapters/gbench.py +++ b/src/benchx/adapters/gbench.py @@ -7,12 +7,15 @@ """ import json +import logging import os import re import subprocess from pathlib import Path -from .base import Unsupported, run_bounded +from .base import Unsupported, note_case, note_case_ended, note_cases, run_bounded + +logger = logging.getLogger(__name__) NAME = "google-benchmark" # The suite is a binary built from the subject's source, so its benchmarks are the subject's own. @@ -121,13 +124,15 @@ def list_cases(binary, case_filter, env, timeout=None) -> list[str]: # Nothing can be planned from a binary that will not say what it has: refuse, with its own words. last = (out.stderr.strip().splitlines() or ["no message"])[-1] raise Unsupported(f"{name} failed to list its benchmarks: exit status {out.returncode}: {last}") - return [line.strip() for line in out.stdout.splitlines() if line.strip()] + return note_cases(logger, [line.strip() for line in out.stdout.splitlines() if line.strip()], case_filter) -def run_case(binary, case, flags, env, timeout, native_path, env_names=()) -> dict: +def run_case(binary, case, flags, env, timeout, native_path, env_names=(), harness_verbosity=0) -> dict: """Run one case; never raises for harness failures, which become results.""" args = [str(binary), f"--benchmark_filter=^{re.escape(case)}$", - f"--benchmark_out={native_path}", "--benchmark_out_format=json", *flags] + f"--benchmark_out={native_path}", "--benchmark_out_format=json", *flags, + *([f"--v={harness_verbosity}"] if harness_verbosity else [])] # the library's own logging, on stderr + note_case(logger, args, cwd=None, timeout=timeout) try: out = subprocess.run(args, env=env, capture_output=True, text=True, timeout=timeout) status, stdout, stderr = out.returncode, out.stdout, out.stderr @@ -141,6 +146,7 @@ def run_case(binary, case, flags, env, timeout, native_path, env_names=()) -> di native = json.loads(native_path.read_text()) except ValueError: native = None + note_case_ended(logger, status, timeout, native_path, parsed=native is not None) return {"exit_status": status, "timed_out": status is None, "stdout": stdout, "stderr": stderr, "native": native} @@ -155,6 +161,12 @@ def translate(case: str, quantities: list[str], run: dict, attempted: int) -> li good = [r for r in iterations if not r.get("error_occurred") and not r.get("skipped")] aggregates = {r.get("aggregate_name"): r for r in rows if r.get("run_type") == "aggregate"} + if good and len(good) < attempted and not run["timed_out"]: + first = (failed or skipped or [{}])[0] + logger.warning("%s: %d of %d repetition(s) were not measured (%d errored, %d skipped)%s", case, + attempted - len(good), attempted, len(failed), len(skipped), + f"; the first said: {first.get('error_message') or first.get('skip_message')}" + if first.get("error_message") or first.get("skip_message") else "") outputs = [] for name in quantities: field, quantity = QUANTITIES[name] diff --git a/src/benchx/adapters/pyperf.py b/src/benchx/adapters/pyperf.py index 22b4509f..94afb22b 100644 --- a/src/benchx/adapters/pyperf.py +++ b/src/benchx/adapters/pyperf.py @@ -31,6 +31,7 @@ import hashlib import json +import logging import re import shutil import subprocess @@ -39,8 +40,10 @@ from .. import snapshot from . import benchx_params -from .base import (Unsupported, check_filter, last_json, name_only_note, no_cases, parametrized_workload, run_bounded, - kill_group, stop_group) +from .base import (Unsupported, check_filter, kill_group, last_json, name_only_note, no_cases, note_case, + note_case_ended, note_cases, note_parameters, parametrized_workload, run_bounded, stop_group) + +logger = logging.getLogger(__name__) NAME = "pyperf" # The suite is a Python source file, which may live outside the subject's checkout. @@ -196,33 +199,48 @@ def list_cases(runnable, case_filter, env, timeout=None) -> list[str]: where = runnable["module"] out = run_bounded([runnable["python"], "-c", LISTER, str(runnable["module"]), str(PARAMS)], timeout=timeout, what=f"importing {runnable['module'].name} to list its benchmarks", - env=env, cwd=runnable["root"]) + env=env, cwd=runnable["root"], scripts={"LISTER": LISTER}) if out.returncode != 0: raise Unsupported(f"cannot import {runnable['module'].name}: " f"{(out.stderr.strip().splitlines() or ['no output'])[-1]}") listing = last_json(out, runnable["module"].name) runnable["benchmarks"], runnable["cases"] = {}, {} # see base.parametrized_workload - cases, unmatched = [], [] + cases, unmatched, left_out, unversioned = [], [], 0, [] for info in listing: name = info["name"] if not case_filter and not name.startswith(DEFAULT_CASE_PREFIXES): + left_out += 1 continue selected = benchx_params.expand(name, info["params"], case_filter) if not selected: + if "error" in info: # not selected, so not refused: the log is the only place that says so + logger.debug("%s: its params could not be read, and it was not selected: %s", name, info["error"]) if benchx_params.matches_name_only(name, info["params"], case_filter): unmatched.append(info) continue if "error" in info: raise Unsupported(f"cannot read the params of {name} in {where}: {info['error']}") + if info.get("version") is None: + unversioned.append(name) runnable["benchmarks"][name] = info for case, index in selected: runnable["cases"][case] = (name, index) cases.append(case) + if left_out: + logger.debug("with no filter only bench_* and benchmark_* functions are cases: %d other callable(s) of %s " + "were left out", left_out, where) + if unversioned: # no `version` attribute, and its source cannot be read: no benchmark_version in its results + logger.debug("no version for %s: an edit to it starts no new series and is not caught as a failed " + "`sides-agree`", ", ".join(unversioned[:40])) + if unmatched: + logger.debug("a filter that matches the name but not the arguments of %d parametrized benchmark(s): %s", + len(unmatched), ", ".join(info["name"] for info in unmatched[:3])) if not cases: defaults = [info["name"] for info in listing if info["name"].startswith(DEFAULT_CASE_PREFIXES)] raise no_cases(where, case_filter, defaults or [info["name"] for info in listing], [name_only_note(unmatched)] if unmatched else []) - return cases + note_parameters(logger, runnable) + return note_cases(logger, cases, case_filter) workload = parametrized_workload # the function, and its parameters as value strings @@ -272,8 +290,9 @@ def list_cases(runnable, case_filter, env, timeout=None) -> list[str]: ''' -def run_case(runnable, case, flags, env, timeout, native_path, env_names=None) -> dict: - """Run one case; never raises for harness failures, which become results.""" +def run_case(runnable, case, flags, env, timeout, native_path, env_names=None, harness_verbosity=0) -> dict: + """Run one case; never raises for harness failures, which become results. A `harness_verbosity` above 0 + asks pyperf for `--verbose`: its workers then print a line after every value they measure.""" if env_names is None: env_names = snapshot.env_allowlist(env, ENV_ALLOWLIST) stem = native_path.name.removesuffix(".native.json") @@ -289,8 +308,10 @@ def run_case(runnable, case, flags, env, timeout, native_path, env_names=None) - module_dir=str(runnable["module"].parent), root=str(runnable["root"]), case=case, function=function, index=index, params=str(params.resolve()))) # Absolute: the child runs in the tree, not where the output directory was named. - args = [runnable["python"], str(driver.resolve()), *flags, "-o", str(native_path.resolve())] + args = [runnable["python"], str(driver.resolve()), *flags, *(["--verbose"] if harness_verbosity else []), + "-o", str(native_path.resolve())] # Its own process group, so a timeout takes the workers down with the manager. + note_case(logger, args, cwd=runnable["root"], timeout=timeout) proc = subprocess.Popen(args, env=env, cwd=runnable["root"], text=True, start_new_session=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) try: @@ -309,6 +330,7 @@ def run_case(runnable, case, flags, env, timeout, native_path, env_names=None) - native_path.write_text(json.dumps(native, indent=1) + "\n") except ValueError: native = None + note_case_ended(logger, status, timeout, native_path, parsed=native is not None) captured = None if worker_env.exists(): try: @@ -500,6 +522,22 @@ def observed_environment(run: dict, case: str, env_names) -> tuple[dict, list[st return facts, warnings +def explain_warnings(run: dict, case: str, warnings: list[str]) -> dict[str, str]: + """The reason behind each of `observed_environment`'s warnings, for the case's line in the log.""" + details = {} + native = run["native"] + benchmark = _benchmark(native, case) + if "env-mismatch" in warnings and benchmark is not None: + digests = [md.get(ENV_DIGEST_KEY) for r, md in _runs(native, benchmark) if r.get("values")] + matched = sum(1 for digest in digests if digest == run["passed_env_digest"]) + details["env-mismatch"] = f"{matched} of {len(digests)} worker(s) had the environment the manager passed" + if "env-capture-missing" in warnings: + written = any(kind == "worker-environment" for kind, _, _ in run.get("artifacts", [])) + details["env-capture-missing"] = ("the worker-environment file did not parse" if written + else "no worker-environment file was written") + return details + + def default_precision() -> dict: """pyperf's own defaults, spelled as a work-order `precision`.""" return {"repetitions": {"mode": "fixed", "levels": [{"unit": "process", "n": DEFAULTS["processes"]}, diff --git a/src/benchx/bench.py b/src/benchx/bench.py index d4c1c795..4fa6efde 100644 --- a/src/benchx/bench.py +++ b/src/benchx/bench.py @@ -9,6 +9,7 @@ """ import json +import logging import statistics from pathlib import Path @@ -17,13 +18,20 @@ from .projection import declared_workload, said, workload_label from .store import warning_codes +logger = logging.getLogger(__name__) + def tree_of(module: Path, tree=None) -> Path: """The tree being measured: --tree, else the module's git checkout, else its directory.""" if tree: + logger.debug("the shorthand's tree is %s, from --tree", Path(tree).resolve()) return Path(tree).resolve() top = snapshot._run(["git", "rev-parse", "--show-toplevel"], cwd=module.parent) - return Path(top).resolve() if top else module.parent.resolve() + if top: + logger.debug("the shorthand's tree is %s, the git checkout of %s", Path(top).resolve(), module) + return Path(top).resolve() + logger.info("no git checkout: the directory %s is the tree", module.parent.resolve()) + return module.parent.resolve() def module_target(module, tree=None) -> tuple[str, str]: @@ -33,9 +41,11 @@ def module_target(module, tree=None) -> tuple[str, str]: raise SessionError(f"no such module: {module}") root = tree_of(module, tree) try: - return str(root), module.relative_to(root).as_posix() + suite = module.relative_to(root).as_posix() except ValueError: raise SessionError(f"{module} is not inside the tree {root}; give --tree") from None + logger.debug("the shorthand's suite is %s", suite) + return str(root), suite def asv_target(path, tree=None) -> tuple[str, str]: @@ -47,6 +57,7 @@ def asv_target(path, tree=None) -> tuple[str, str]: for name in asv.CONF_NAMES: if (benchmark_dir / name).is_file(): conf = asv._read_conf(benchmark_dir / name) + logger.debug("read %s: benchmark_dir %s", benchmark_dir / name, conf.get("benchmark_dir", "benchmarks")) benchmark_dir = (benchmark_dir / conf.get("benchmark_dir", "benchmarks")).resolve() break if not benchmark_dir.is_dir(): diff --git a/src/benchx/cli.py b/src/benchx/cli.py index 07e155e8..443b6e34 100644 --- a/src/benchx/cli.py +++ b/src/benchx/cli.py @@ -7,17 +7,20 @@ """ import argparse +import dataclasses import json +import logging import os import sys import tempfile +import traceback from pathlib import Path from typing import get_args from . import bench as bench_mod from . import compare as compare_mod from . import config as config_mod -from . import core, harnesses, orders, runner, session, snapshot +from . import core, harnesses, log, orders, runner, session, snapshot from . import tables as tables_mod from . import target as target_mod from .core.validation import Kind @@ -27,11 +30,23 @@ EXIT_INVALID = 1 # a document invalid, a result rejected, or a target without a description EXIT_REFUSED = 2 # the command was refused or could not be carried out ASV_CASE_TIMEOUT_S = 1800 +VERBOSE_ENV = "BENCHX_VERBOSE" +LOG_LEVEL_ENV = "BENCHX_LOG_LEVEL" +HARNESS_VERBOSITY_ENV = "BENCHX_HARNESS_VERBOSITY" +DEFAULT_LOG = "{out}/bx.log" +# benchx's own control variables: every one the code reads. They are settings someone typed for benchx, a fixed +# list, so the log gives their values; the rest of the inherited environment is never dumped. +CONTROL_ENV = ("BENCHX_HOME", "BENCHX_VERBOSE", "BENCHX_LOG_LEVEL", "BENCHX_HARNESS_VERBOSITY", "BENCHX_SETUP_FILE", + "BENCHX_ENV_ALLOWLIST", "BENCHX_SCHEMAS") +OUTCOMES = {EXIT_OK: "ok", EXIT_INVALID: "invalid", EXIT_REFUSED: "refused"} + +say = log.console(__name__) # what `bx` shows its user: console messages +logger = logging.getLogger(__name__) def _refused(error: runner.Refused) -> int: for problem in error.problems: - print(f"refused: {problem}", file=sys.stderr) + say.error(f"refused: {problem}") return EXIT_REFUSED @@ -41,12 +56,212 @@ def _load(command): try: cfg = config_mod.load() except config_mod.ConfigError as e: - print(f"bx {command}: error: {e}", file=sys.stderr) + say.error(f"bx {command}: error: {e}") return None - snapshot.ignore(cfg.store_path, cfg.results_dir) + snapshot.ignore(*cfg.own_paths) return cfg +def _source_text(source, env=None) -> str: + return f"environment {env}" if source == "env" else source + + +def _verbosity(args) -> tuple[int, str, int]: + """How much the terminal shows, -2 (`-qq`) to 2 (`-vv`), where that came from, and how many `v` there are + beyond two: the net count of `-v` and `-q`, else $BENCHX_VERBOSE, else 0. Each one past `-vv` asks the harness + to say more (`-vvv` is `-vv` and --harness-verbosity 1). UsageError for a bad variable.""" + if args.verbose is not None or args.quiet is not None: + net, source = (args.verbose or 0) - (args.quiet or 0), "flag" + else: + net, source = 0, "default" + if text := os.environ.get(VERBOSE_ENV): + try: + net = int(text) + except ValueError: + net = None + if net is None or net < -2: + raise UsageError(f"{VERBOSE_ENV}={text}: not a whole number, -2 or more") + source = _source_text("env", VERBOSE_ENV) + return max(-2, min(2, net)), source, max(0, net - 2) + + +def _non_negative(text) -> int: + try: + value = int(text) + except ValueError: + value = -1 + if value < 0: + raise argparse.ArgumentTypeError(f"{text!r} is not a whole number from 0") + return value + + +def _harness_verbosity(cfg, args) -> tuple[int, str]: + """How much the harness is asked to say, and where that came from: `--harness-verbosity`, else the `v`s past + `-vv` on the command line, else $BENCHX_HARNESS_VERBOSITY, else the `v`s past `-vv` that $BENCHX_VERBOSE + stands for, else `adapter.verbosity` in the file, else 0 (nothing more). Only the flags beat the + environment: $BENCHX_VERBOSE does not override an explicit $BENCHX_HARNESS_VERBOSITY.""" + given = getattr(args, "harness_verbosity", None) # `bx config show` has no such option + extra = getattr(args, "verbose_extra", 0) + from_flag = getattr(args, "verbosity_source", "flag") == "flag" + label = None + if given is None and extra and from_flag: + given, label = extra, "flag: -v past -vv" + value, source = cfg.pick_with_source(given, cfg.adapter.get("verbosity"), 0, flag="--harness-verbosity", + key="adapter.verbosity", env=HARNESS_VERBOSITY_ENV) + if source == "env": + try: + value = int(value) + except ValueError: + value = -1 + if value < 0: + raise UsageError(f"{HARNESS_VERBOSITY_ENV}={os.environ[HARNESS_VERBOSITY_ENV]}: not a whole number from 0") + elif extra and not from_flag and source in ("file", "default"): + return extra, _source_text("env", VERBOSE_ENV) # the environment's, which beats the file + return value, label if source == "flag" and label else _source_text(source, HARNESS_VERBOSITY_ENV) + + +def _log_level(cfg, args) -> tuple[int, str]: + """The level the log keeps, and where it came from: the flag, $BENCHX_LOG_LEVEL, the file's + `log_level`, else debug.""" + value, source = cfg.pick_with_source(args.log_level, cfg.data.get("log_level"), "debug", flag="--log-level", + key="log_level", env=LOG_LEVEL_ENV) + if value.lower() not in log.LEVELS: + origin = f"{LOG_LEVEL_ENV}={value}" if source == "env" else f"log_level in {cfg.path}" + raise UsageError(f"{origin}: not one of {', '.join(log.LEVELS)}") + return log.LEVELS[value.lower()], _source_text(source, LOG_LEVEL_ENV) + + +def _log_setting(cfg, args, out, command): + """What the switch says for this command, and where that came from: False (off), True + (stderr) or the resolved log file. A command with no output folder (`out` None) logs only + when a flag asks: the file, the environment and the default are ignored.""" + setting, source = cfg.pick_with_source(args.log, cfg.data.get("logging"), DEFAULT_LOG, flag="--log", + key="logging") + if out is None and source != "flag": + return False, source + if isinstance(setting, str): + setting = setting.replace("{root}", str(cfg.root)) + if "{out}" in setting: + if out is None: + raise UsageError(f"--log-file {setting}: bx {command} has no output folder") + setting = Path(setting.replace("{out}", str(out))).resolve() + elif source == "file": + setting = cfg._path(setting).resolve() # relative to the project root, as paths.store is + else: + setting = Path(setting).expanduser().resolve() # a flag: relative to the working directory + return setting, source + + +def _check_log_file(path, out, origin): + """UsageError unless `path` can be appended to. benchx creates only its own output folder.""" + if str(path).endswith(".json"): + raise UsageError(f"{origin}: a log file must not end in .json") + folder = Path(out).resolve() if out is not None else None + if path == folder or path.is_dir(): + raise UsageError(f"{origin}: {path} is a directory") + try: + # Only the output folder itself is created, and only for a file directly in it or in a folder that exists: + # a refused path leaves nothing behind. + if folder is not None and path.is_relative_to(folder) and (path.parent == folder or path.parent.is_dir()): + folder.mkdir(parents=True, exist_ok=True) + path.open("a").close() + except OSError as e: + raise UsageError(f"{origin}: cannot open {path}: {e}") from None + + +def _start_logging(cfg, args, out, command, *, read_config=True, lenient=False): + """Turn the log on for this command: the config with `log_file` set, or None (after saying + why) when the setting is unusable. Called once the command has validated its own flags and + values, so a refusal for those leaves no folder, and before it calls `session`. + `out` is the command's output folder, or None. `lenient`: a log that cannot be opened is + skipped without a word, unless a flag named it (a read must not need to write).""" + try: + if args.log is False and args.log_level is not None: + raise UsageError("--no-log with --log-level: there is nothing to set a level on") + level, level_source = _log_level(cfg, args) + setting, source = _log_setting(cfg, args, out, command) + if isinstance(setting, Path): + origin = {"flag": f"--log-file {args.log}", "file": f"logging in {cfg.path}"}.get(source, "the default log") + try: + _check_log_file(setting, out, origin) + except UsageError: + if not (lenient and source != "flag"): + raise + setting = False + except UsageError as e: + say.error(f"bx {command}: error: {e}") + return None + log.configure(setting, level=level, argv=args.argv) + cfg = dataclasses.replace(cfg, log_file=setting if isinstance(setting, Path) else None) + snapshot.ignore(*cfg.own_paths, *([args.out] if getattr(args, "out", None) else [])) # the log is not the tree + if read_config: + _log_config(cfg) + _log_arguments(args) + _log_environment() + shown = "off" if setting is False else "stderr" if setting is True else str(setting) + logger.debug("logging: %s (%s); log level: %s (%s); verbosity: %d (%s)", shown, _source_text(source), + logging.getLevelName(level).lower(), level_source, args.verbosity, args.verbosity_source) + return cfg + + +def _log_arguments(args): + """The arguments as argparse understood them (DEBUG), beside the command line as given in the header: a + prefix spelled out, a case name taken from after the options, an option's value. As given: the log makes no + claim to hide a value.""" + skip = {"fn", "argv", "verbosity", "verbosity_source", "verbose_extra"} + # `0 == False`, so a test with `in` would drop `--slot 0`: compare by identity + shown = {name: value for name, value in vars(args).items() + if name not in skip and value is not None and value is not False and value != [] and value != ()} + logger.debug("arguments as parsed: %s", ", ".join(f"{name}={value!r}" for name, value in sorted(shown.items()))) + + +def _log_environment(): + """The environment variables `bx` consults that decide what it does (DEBUG): benchx's own, with their values, + and whether PATH is set, which the benchmark's `python` is looked up on. The other variables that shape a + run are the allowlisted ones, which each order logs by name.""" + shown = [f"{name}={os.environ[name]}" if os.environ.get(name) else f"{name} not set" for name in CONTROL_ENV] + logger.debug("environment variables consulted: %s; PATH is %s", "; ".join(shown), + "set (the benchmark's python is looked up on it)" if os.environ.get("PATH") else "not set") + + +def _log_config(cfg): + """Which config file was used, and where the store and the results are (INFO, once).""" + found = cfg.path or f"none found from {Path.cwd()} upward" + home = "" + if os.environ.get(config_mod.HOME_ENV): + home = f" (set by ${config_mod.HOME_ENV}" + (", which hides paths.store in the file)" if "store" in cfg.section("paths") else ")") + logger.info("config file: %s; project root %s; store %s%s; results %s", found, cfg.root, cfg.store_path, home, + cfg.results_dir) + + +def _log_settings(sources): + """The settings a command resolved, each with its value and where it came from (DEBUG).""" + for name, value, source in sources: + # the project decides where the results are filed: worth a line at INFO + logger.log(logging.INFO if name == "project" else logging.DEBUG, "setting %s: %s (%s)", name, value, source) + + +def _report_unmeasured(rows) -> None: + """What a run says about the cases it did not measure, for `bx run` and `bx bench` (the table is the + caller's). The section under the table, `case: message`, is an answer when a case failed (WARNING, shown at + every verbosity). When only skipped cases said anything, which the run expects, it is INFO and goes with the + table. The exit status stays 0 either way: `degraded` puts a phrase in the log's footer for the cases that + failed, and on stdout too when what the reader would see leaves some out (a hidden table, or an error that + said nothing).""" + said = bench_mod.failures(rows) + errors = [row for row in rows if not row["status"].startswith(("success", "skipped"))] + named = {row["case"] for row in errors if row["message"]} + if said: + loud = bool(named) + say.out(said, log.ANSWER if loud else log.TABLE, level=logging.WARNING if loud else logging.INFO) + unmeasured = {row["case"] for row in errors} + if unmeasured: + cases = {row["case"] for row in rows} + silent = unmeasured - named # nothing on the screen names these, whatever else is shown + log.degraded(f"{len(unmeasured)} of {len(cases)} cases not measured", + shown=bool(log.quiet() and (not named or silent))) + + def cmd_run(args): """Run one order, write its result files, and deliver them to the local store. The runner itself stays store-unaware (runner.md §2 principle 6); @@ -54,18 +269,24 @@ def cmd_run(args): if (cfg := _load("run")) is None: return EXIT_REFUSED out = Path(args.out) if args.out else cfg.results_dir - snapshot.ignore(cfg.store_path, cfg.results_dir, out) + # `bx run` has no check phase; the log goes in --out, and nowhere without it (the results + # directory is shared by every run). + if (cfg := _start_logging(cfg, args, Path(args.out) if args.out else None, "run")) is None: + return EXIT_REFUSED + logger.info("order file %s; output %s", Path(args.order).resolve(), out) + say.progress(f"running the order {Path(args.order).name}") try: summary = runner.run(args.order, out, allow_collectors=args.allow_collectors) except runner.Refused as e: return _refused(e) - print(f"{summary['results']} result(s) for {summary['cases']} case(s) -> {summary['out']}" - f" (order {summary['order'][:19]})") + _report_unmeasured(bench_mod.summarize(summary["files"])) + say.out(f"{summary['results']} result(s) for {summary['cases']} case(s) -> {summary['out']}" + f" (order {summary['order'][:19]})", log.SUMMARY) if args.no_ingest: + logger.info("ingest skipped (--no-ingest): the results are files only") return EXIT_OK store = Store(cfg.store_path) - print(f"{store.path}: ", end="") - return _report(store.ingest_paths(summary["files"])) + return _report(store.ingest_paths(summary["files"]), store.path) def _environment(items) -> dict: @@ -81,10 +302,29 @@ def _environment(items) -> dict: return env -def _session_position(args) -> tuple[dict, int | None, int | None]: - """Where `bx bench` sits in a session that other calls join through the same - `--run-key`: its `--label NAME=VALUE`s, `--round` and `--slot`. UsageError when - they could not join one.""" +def _parse_round(text) -> tuple[int | None, int | None]: + """`--round R` or `--round R/N`: the round, numbered from 0, and how many rounds the session has when the + caller says (only the start line shows it: the work order records the round alone). UsageError.""" + if text is None: + return None, None + first, slash, last = text.partition("/") + try: + round_, rounds = int(first), int(last) if slash else None + except ValueError: + raise UsageError(f"--round wants R, or R/N for a session of N rounds, whole numbers, not {text!r}") from None + if round_ < 0: + raise UsageError(f"--round wants a number from 0, not {round_}") + if rounds is not None and rounds < 1: + raise UsageError(f"--round {text}: a session has at least 1 round, not {rounds}") + if rounds is not None and not round_ < rounds: + raise UsageError(f"--round {text}: with {rounds} round(s) they are numbered 0 to {rounds - 1}") + return round_, rounds + + +def _session_position(args) -> tuple[dict, int | None, int | None, int | None]: + """Where `bx bench` sits in a session that other calls join through the same `--run-key`: its + `--label NAME=VALUE`s, `--round` (and, with `--round R/N`, the session's number of rounds) and `--slot`. + UsageError when they could not join one.""" labels = {} for item in args.label or []: name, eq, value = item.partition("=") @@ -94,17 +334,17 @@ def _session_position(args) -> tuple[dict, int | None, int | None]: if name in labels: raise UsageError(f"--label {name} is given twice") labels[name] = value - for flag, number in (("--round", args.round), ("--slot", args.slot)): - if number is not None and number < 0: - raise UsageError(f"{flag} wants a number from 0, not {number}") - placed = labels or args.round is not None or args.slot is not None + round_, rounds = _parse_round(args.round) + if args.slot is not None and args.slot < 0: + raise UsageError(f"--slot wants a number from 0, not {args.slot}") + placed = labels or round_ is not None or args.slot is not None if placed and not args.run_key: raise UsageError("--label, --round and --slot need an explicit --run-key: the default is a timestamp " "per call, so two calls would never share a run") - if (labels or args.round is not None) and args.slot is None: + if (labels or round_ is not None) and args.slot is None: raise UsageError("--label and --round need --slot: without one, the sides of a run would share an " "ingest key and their results would conflict") - return labels, args.round, args.slot + return labels, round_, args.slot, rounds def _bench_target(args) -> tuple[str, str | None, str | None]: @@ -115,13 +355,16 @@ def _bench_target(args) -> tuple[str, str | None, str | None]: `--adapter asv` it is an asv suite instead (`bx bench PATH --adapter asv`): PATH holds asv.conf.json or is the benchmark directory.""" if not args.suite and args.adapter == "asv": + logger.debug("the asv shorthand: --adapter asv on the command line, and no --suite") return (*bench_mod.asv_target(args.target, args.tree), "asv") if args.suite or not args.target.endswith(".py"): if args.tree: raise UsageError("--tree belongs to the shorthands; give the tree as the TARGET with --suite") + logger.debug("a plain target: %s, with the suite from --suite or the file's adapter.suite", args.target) return args.target, None, None if args.adapter not in (None, "pyperf"): raise UsageError(f"a Python file is benchmarked with pyperf, not {args.adapter}") + logger.debug("the Python-module shorthand: %s is benchmarked with pyperf", args.target) target, suite = bench_mod.module_target(args.target, args.tree) return target, suite, "pyperf" @@ -131,41 +374,83 @@ def _common(cfg, args, *, forced_adapter=None, forced_suite=None) -> dict: else the file, else its default (config.Config.pick); ConfigError when a required one has none. The file's adapter block belongs to the adapter it names and to the others of its family (pyperf's serves asv), so naming an - adapter of another family is refused.""" + adapter of another family is refused. `sources` lists each setting with where it came + from, for the log (the caller pops it before the rest goes to `session`).""" block = cfg.adapter given = forced_adapter or args.adapter if given and block.get("name") and not harnesses.same_family(given, block["name"]): raise config_mod.ConfigError(f"adapter {given!r}, but {cfg.where} sets adapter.name to {block['name']!r}, " "and its precision belongs to that harness and the ones that share it " "(pyperf and asv)") + sources = [] quantities = config_mod.parse_quantities(args.quantity) if args.quantity else block.get("quantities", ["wall-time"]) + sources.append(("quantities", ", ".join(quantities), + "flag" if args.quantity else "file" if "quantities" in block else "default")) if args.project and args.no_project: raise UsageError("give --project or --no-project, not both") timeouts = cfg.section("timeouts") - adapter = cfg.pick(given, block.get("name"), flag="--adapter", key="adapter.name") + adapter, adapter_source = cfg.pick_with_source(given, block.get("name"), flag="--adapter", key="adapter.name") + named = block.get("name") + if given and named and given != named: # the file's block serves another adapter of its family + adapter_source += f"; the file says {named}, same family" + sources.append(("adapter", adapter, adapter_source)) + suite, suite_source = cfg.pick_with_source(forced_suite or args.suite, block.get("suite"), flag="--suite", + key="adapter.suite") + sources.append(("suite", suite, suite_source)) + from_flag, from_file = _environment(args.env), cfg.section("environment_variables") + environment_variables = {**from_file, **from_flag} + where = [f"-e: {', '.join(sorted(from_flag))}" if from_flag else "", f"file: {', '.join(sorted(from_file))}" if from_file else ""] + if overrode := sorted(set(from_flag) & set(from_file)): + where.append(f"-e overrode the file's {', '.join(overrode)}") + sources.append(("environment_variables", "names only", "; ".join(w for w in where if w) or "default: none")) + if args.no_project: + project = None + sources.append(("project", "none: results are filed as local/HOST", "flag --no-project")) + else: + project, project_source = cfg.pick_with_source(args.project, cfg.data.get("project"), None, flag="--project", + key="project") + sources.append(("project", project or "none: results are filed as local/HOST", project_source)) + source_uri, uri_source = cfg.pick_with_source(args.source_uri or None, cfg.section("source").get("uri"), None, + flag="--source-uri", key="source.uri") + sources.append(("source.uri", source_uri or "the checkout's origin remote", uri_source)) + case_s, case_source = cfg.pick_with_source(getattr(args, "case_timeout", None), timeouts.get("case_s"), + ASV_CASE_TIMEOUT_S if adapter == "asv" else orders.CASE_TIMEOUT_S, + flag="--case-timeout", key="timeouts.case_s") + if case_source == "default": + case_source = "default for asv, which times every round of a benchmark" if adapter == "asv" else "default" + sources.append(("timeouts.case_s", f"{case_s:g} s", case_source)) + order_s = timeouts.get("order_s", orders.ORDER_TIMEOUT_S) + sources.append(("timeouts.order_s", f"{order_s:g} s", "file" if "order_s" in timeouts else "default")) + flagged = [name for name in harnesses.FLAG_NAMES if getattr(args, name) is not None] + precision_file = sorted(block.get("precision") or {}) + sources.append(("precision", f"flags {', '.join(flagged) or 'none'}; file {', '.join(precision_file) or 'none'}", + "flag over file over the harness's defaults")) + if args.filter: + sources.append(("filter", args.filter, "flag")) + harness_verbosity, verbosity_source = _harness_verbosity(cfg, args) + sources.append(("harness verbosity", harness_verbosity, verbosity_source)) return { "adapter": adapter, - "suite": cfg.pick(forced_suite or args.suite, block.get("suite"), flag="--suite", key="adapter.suite"), + "suite": suite, "flags": {name: getattr(args, name) for name in harnesses.FLAG_NAMES}, "file_precision": block.get("precision"), "quantities": quantities, "filter": args.filter, - "environment_variables": {**cfg.section("environment_variables"), **_environment(args.env)}, - "project": None if args.no_project else cfg.pick(args.project, cfg.data.get("project"), None, - flag="--project", key="project"), + "environment_variables": environment_variables, + "project": project, "run_key": args.run_key, "out": args.out, - "source_uri": args.source_uri or cfg.section("source").get("uri"), + "source_uri": source_uri, "build": not args.no_build, "provider": cfg.provider, "collectors": cfg.collectors, "results_dir": cfg.results_dir, # An asv case is every round of its benchmark, each bounded by the benchmark's own timeout. - "case_s": cfg.pick(getattr(args, "case_timeout", None), timeouts.get("case_s"), - ASV_CASE_TIMEOUT_S if adapter == "asv" else orders.CASE_TIMEOUT_S, - flag="--case-timeout", key="timeouts.case_s"), - "order_s": timeouts.get("order_s", orders.ORDER_TIMEOUT_S), + "case_s": case_s, + "order_s": order_s, "config_path": cfg.path, + "harness_verbosity": harness_verbosity, + "sources": sources, } @@ -175,6 +460,15 @@ def _needs_provider(cfg, *targets): cfg.require_provider(spec) +def _placed(settings, rounds=None) -> str: + """` (round 1/5, slot 3)`: where a `bx bench` call sits in a session, as the start line says it, with the + session's number of rounds when the caller gave it (`--round 1/5`); empty when alone.""" + parts = [f"round {settings['round_']}{f'/{rounds}' if rounds else ''}" if settings["round_"] is not None else "", + f"slot {settings['slot']}" if settings["slot"] is not None else "", + ", ".join(f"{name}={value}" for name, value in (settings["labels"] or {}).items())] + return f" ({', '.join(part for part in parts if part)})" if any(parts) else "" + + def cmd_bench(args): """Run one target once, as one order of a comparison session: resolve the target, build the order from the harness defaults, config file, flags and environment @@ -186,52 +480,98 @@ def cmd_bench(args): raise UsageError("give case names or --filter, not both") target, forced_suite, forced_adapter = _bench_target(args) settings = _common(cfg, args, forced_adapter=forced_adapter, forced_suite=forced_suite) - settings["labels"], settings["round_"], settings["slot"] = _session_position(args) + settings["labels"], settings["round_"], settings["slot"], rounds = _session_position(args) + session.check_harness(settings["adapter"], settings["flags"], settings["file_precision"], + settings["quantities"]) _needs_provider(cfg, target) # A name may carry `(arguments)` where the harness has parametrized benchmarks. names = harnesses.exact_filter(args.functions, harnesses.get(settings["adapter"]).NAMES_TAKE_ARGUMENTS) except (UsageError, config_mod.ConfigError, bench_mod.SessionError) as e: - print(f"bx bench: error: {e}", file=sys.stderr) + say.error(f"bx bench: error: {e}") + return EXIT_REFUSED + # The run key and the output folder are settled before any target is resolved (a provider + # may build), so the log can live in the folder from the start. + run_key = args.run_key or orders.default_run_key("bench") + out = Path(args.out) if args.out else session.run_directory(cfg.results_dir, run_key) + if (cfg := _start_logging(cfg, args, out, "bench")) is None: return EXIT_REFUSED + logger.info("run key %s (%s); output folder %s (%s)", run_key, "given" if args.run_key else "generated", out, + "--out" if args.out else "the results directory") + _log_settings(settings.pop("sources")) + settings["run_key"], settings["out"] = run_key, out settings["filter"] = names or settings["filter"] - snapshot.ignore(cfg.store_path, cfg.results_dir, *([args.out] if args.out else [])) store = None if args.no_ingest else Store(cfg.store_path) + # Where a quiet run says it started, before a provider that builds takes its time. + say.progress(f"measuring {Path(settings['suite']).name if settings.get('suite') else 'the suite'} on {target}" + + _placed(settings, rounds)) try: - summary = session.bench_target(target, store=store, progress=lambda message: print(message, file=sys.stderr), - **settings) + summary = session.bench_target(target, store=store, progress=say.info, **settings) except (session.SessionError, config_mod.ConfigError) as e: - print(f"bx bench: error: {e}", file=sys.stderr) + say.error(f"bx bench: error: {e}") return EXIT_REFUSED except runner.Refused as e: return _refused(e) + # What the run reports goes through the marker: stdout, by the tiers `-q` and `-qq` leave, and the log. rows = bench_mod.summarize(summary["files"]) - print(bench_mod.render(rows)) - if failed := bench_mod.failures(rows): - print(failed) - print(f"\n{summary['results']} result(s) -> {summary['out']} (order {summary['order'][:19]})") + say.out(bench_mod.render(rows), log.TABLE) + _report_unmeasured(rows) + say.out(f"\n{summary['results']} result(s) -> {summary['out']} (order {summary['order'][:19]})", log.SUMMARY) if store is None: + logger.info("ingest skipped (--no-ingest): the results are files only") return EXIT_OK - print(f"{store.path}: ", end="") - return _report(summary["outcome"]) + return _report(summary["outcome"], store.path) def cmd_config(args): if args.action == "init": + # `init` does not read the file: it resolves the logging settings from the flags and the environment + if _start_logging(_no_config(), args, None, "config", read_config=False) is None: + return EXIT_REFUSED try: path = config_mod.write_template(args.dir, args.adapter) except config_mod.ConfigError as e: - print(f"bx config: error: {e}", file=sys.stderr) + say.error(f"bx config: error: {e}") return EXIT_REFUSED print(f"wrote {path}") return EXIT_OK if (cfg := _load("config")) is None: return EXIT_REFUSED + if (cfg := _start_logging(cfg, args, None, "config")) is None: + return EXIT_REFUSED + try: # all the rows first: a bad $BENCHX_HARNESS_VERBOSITY refuses the command, with nothing half printed + rows = [*_resolved(cfg), *_logging_rows(cfg, args)] + except UsageError as e: + say.error(f"bx config: error: {e}") + return EXIT_REFUSED print(f"file {cfg.where}\nroot {cfg.root}") - for key, value, source in _resolved(cfg): + for key, value, source in rows: print(f"{key:<26} {value} ({source})") return EXIT_OK +def _no_config() -> config_mod.Config: + """The configuration of a command that does not read the file: the working directory, no data.""" + return config_mod.Config(root=Path.cwd(), path=None, data={}) + + +def _logging_rows(cfg, args): + """What `bx config show` adds for the log: the switch, the level and the verbosity, each with + where it came from (a flag, an environment variable, the file or the default).""" + setting, source = cfg.pick_with_source(args.log, cfg.data.get("logging"), DEFAULT_LOG, flag="--log", key="logging") + if isinstance(setting, str): + setting = setting.replace("{root}", str(cfg.root)) + if isinstance(setting, str) and "{out}" not in setting: + setting = str(cfg._path(setting).resolve() if source == "file" else Path(setting).expanduser().resolve()) + else: + setting = json.dumps(setting) + yield "logging", setting, _source_text(source) + level, level_source = _log_level(cfg, args) + yield "log level", logging.getLevelName(level).lower(), level_source + yield "verbosity", str(args.verbosity), args.verbosity_source + harness, harness_source = _harness_verbosity(cfg, args) + yield "harness verbosity", str(harness), harness_source + + def _resolved(cfg): """What the file and the built-in defaults give, before any command-line argument: (key, value, 'file' | 'default' | 'unset').""" @@ -262,27 +602,41 @@ def row(key, value, default=None): yield row("compare.min_rounds", compare.get("min_rounds"), 3) -def _report(outcome): +def _report(outcome, store_path=None): + """The ingest counts. After a run (`store_path` names the store) they are a progress message, + `STORE: ingested 3, duplicate 0`, on stderr as every progress message is: `-q` does not show it. For the + command that ingests they are its answer, on stdout, whatever the verbosity.""" for r in outcome["rejected"]: - print(f" rejected {r['document']}: {r['code']} — {r['message']}", file=sys.stderr) + say.warning(f" rejected {r['document']}: {r['code']} — {r['message']}") counts = f"ingested {outcome['ingested']}, duplicate {outcome['duplicate']}" if outcome["rejected"]: codes = sorted({r["code"] for r in outcome["rejected"]}) counts += f", rejected {len(outcome['rejected'])} ({', '.join(codes)})" - print(counts) + if store_path: + say.info(f"{store_path}: {counts}") + else: + say.out(counts, log.ANSWER) return EXIT_INVALID if outcome["rejected"] else EXIT_OK def cmd_ingest(args): if (cfg := _load("ingest")) is None: return EXIT_REFUSED + if (cfg := _start_logging(cfg, args, None, "ingest")) is None: + return EXIT_REFUSED + logger.info("ingesting %d path(s): %s", len(args.paths), ", ".join(str(Path(p).resolve()) for p in args.paths)) return _report(Store(cfg.store_path).ingest_paths(args.paths)) def cmd_series(args): if (cfg := _load("series")) is None: return EXIT_REFUSED - for s in Store(cfg.store_path).series(args.workload, args.quantity): + if (cfg := _start_logging(cfg, args, None, "series")) is None: + return EXIT_REFUSED + listed = Store(cfg.store_path).series(args.workload, args.quantity) + if not listed: + logger.info("no series%s", " matches the filter" if args.workload or args.quantity else " in the store") + for s in listed: estimator = json.loads(s["estimator"])["method_version"] print(f"{s['fingerprint'][:12]} {s['project']} {s['workload']} {s['quantity']} [{s['unit']}]" f" est={estimator}") @@ -292,7 +646,14 @@ def cmd_series(args): def cmd_history(args): if (cfg := _load("history")) is None: return EXIT_REFUSED + if (cfg := _start_logging(cfg, args, None, "history")) is None: + return EXIT_REFUSED points = Store(cfg.store_path).history(args.series) + if not points: + logger.info("no series matches %s", args.series) + elif len(matched := {p["series_fingerprint"] for p in points}) > 1: + logger.warning("%s matches %d series, whose points are listed together; `changed` is worked out per series: %s", + args.series, len(matched), ", ".join(sorted(f[:12] for f in matched))) print("revision order unavailable without a revision graph; listed by measurement start") for p in points: changed = f" changed: {', '.join(p['changed'])}" if p["changed"] else "" @@ -305,12 +666,16 @@ def cmd_history(args): def cmd_head(args): if (cfg := _load("head")) is None: return EXIT_REFUSED + if (cfg := _start_logging(cfg, args, None, "head")) is None: + return EXIT_REFUSED store = Store(cfg.store_path) total, rows = store.head(args.n, args.project, args.workload, measurands=args.table) if args.json: for row in rows: print(row["document"]) return EXIT_OK + if not total: + logger.info("%s holds no result%s", store.path, "s that match the filter" if args.project or args.workload else "") print(f"{store.path}: {total} result(s); latest {len(rows)}, newest first") if args.table: # the columns of `bx bench`, led by where each result came from; measurands only print(bench_mod.render([{**bench_mod.row_of(json.loads(r["document"])), "revision": r["revision"][:10], @@ -337,14 +702,16 @@ def cmd_target(args): build (the provider's own tools do that, never benchx).""" if (cfg := _load("target")) is None: return EXIT_REFUSED + if (cfg := _start_logging(cfg, args, None, "target")) is None: + return EXIT_REFUSED try: _needs_provider(cfg, args.target) description = target_mod.resolve(args.target, operation=args.operation, provider=cfg.provider) except (target_mod.TargetError, config_mod.ConfigError) as e: - print(f"cannot {args.operation} {args.target}: {e}", file=sys.stderr) + say.error(f"cannot {args.operation} {args.target}: {e}") return EXIT_REFUSED if description is None: - print(f"{args.target} has no description: no {target_mod.SIDECAR} in it", file=sys.stderr) + say.warning(f"{args.target} has no description: no {target_mod.SIDECAR} in it") return EXIT_INVALID print(json.dumps(description, indent=1)) return EXIT_OK @@ -391,25 +758,29 @@ def cmd_compare(args): if (cfg := _load("compare")) is None: return EXIT_REFUSED try: - policy = _policy(cfg, args) + policy, sources = _policy(cfg, args) mode = _mode(args, policy["profile"]) _profile_flags(args, policy["profile"]) _view_flags(args) except (UsageError, config_mod.ConfigError) as e: - print(f"bx compare: error: {e}", file=sys.stderr) + say.error(f"bx compare: error: {e}") return EXIT_REFUSED - return _measure(cfg, args, policy) if mode == "measure" else _read(cfg, args, policy) + sources.append(("mode", mode, "inferred: " + ("targets were given" if mode == "measure" else "--run was given"))) + return _measure(cfg, args, policy, sources) if mode == "measure" else _read(cfg, args, policy, sources) -def _policy(cfg, args) -> dict: - """The comparison's own settings: the command line, else `compare` in the file, else the default.""" +def _policy(cfg, args) -> tuple[dict, list]: + """The comparison's own settings: the command line, else `compare` in the file, else the default; + and each with where it came from, for the log.""" compare = cfg.section("compare") - return { - "profile": cfg.pick(args.profile, compare.get("profile"), flag="--profile", key="compare.profile"), - "k": cfg.pick(args.k, compare.get("k"), 3.0, flag="--k", key="compare.k"), - "min_rounds": cfg.pick(args.min_rounds, compare.get("min_rounds"), 3, flag="--min-rounds", - key="compare.min_rounds"), - } + profile, profile_source = cfg.pick_with_source(args.profile, compare.get("profile"), flag="--profile", + key="compare.profile") + k, k_source = cfg.pick_with_source(args.k, compare.get("k"), 3.0, flag="--k", key="compare.k") + min_rounds, min_source = cfg.pick_with_source(args.min_rounds, compare.get("min_rounds"), 3, flag="--min-rounds", + key="compare.min_rounds") + return ({"profile": profile, "k": k, "min_rounds": min_rounds}, + [("compare.profile", profile, profile_source), ("compare.k", k, k_source), + ("compare.min_rounds", min_rounds, min_source)]) def _profile_flags(args, profile): @@ -430,55 +801,95 @@ def _view_flags(args): raise UsageError("--all goes with --tables") -def _read(cfg, args, policy): +def _read(cfg, args, policy, sources): + # A read stores nothing, so its records join the run's own log when the run folder exists; + # and a log that cannot be opened there is skipped, not refused, unless a flag named it. + run_dir = session.run_directory(cfg.results_dir, args.run) + if (cfg := _start_logging(cfg, args, run_dir if run_dir.is_dir() else None, "compare", lenient=True)) is None: + return EXIT_REFUSED + _log_settings(sources) if args.results: with tempfile.TemporaryDirectory() as tmp: # the ad hoc path: a throwaway store store = Store(Path(tmp) / "store.parquet") outcome = store.ingest_paths(args.results) + # The throwaway store is deleted on exit: its path would say nothing, so the count does. + logger.debug("read mode with --results: %d document(s) ingested into a throwaway store", + outcome["ingested"]) if outcome["rejected"]: + logger.warning("%d document(s) were rejected: the comparison was not run", len(outcome["rejected"])) return _report(outcome) return _compare(store, args, policy) return _compare(Store(cfg.store_path), args, policy) -def _measure(cfg, args, policy): +def _measure(cfg, args, policy, sources): """The workbench's session loop: run both sides, deliver, compare.""" store = Store(cfg.store_path) - print(f"{store.path}", file=sys.stderr) # stderr, so --json output stays clean - try: + try: # the check phase: nothing has run, and no folder exists yet settings = _common(cfg, args) + session.check_harness(settings["adapter"], settings["flags"], settings["file_precision"], + settings["quantities"]) _needs_provider(cfg, *args.targets) - snapshot.ignore(cfg.store_path, cfg.results_dir, *([args.out] if args.out else [])) - rounds = cfg.pick(args.rounds, cfg.section("compare").get("rounds"), flag="--rounds", key="compare.rounds") - progress = lambda message: print(message, file=sys.stderr) # noqa: E731 + rounds, rounds_source = cfg.pick_with_source(args.rounds, cfg.section("compare").get("rounds"), + flag="--rounds", key="compare.rounds") + label = session.parse_label(args.label) if args.label else None + except (UsageError, config_mod.ConfigError) as e: + say.error(f"bx compare: error: {e}") + return EXIT_REFUSED + except session.SessionError as e: + say.error(f"cannot compare: {e}") + return EXIT_REFUSED + run_key = args.run_key or orders.default_run_key("compare") + out = Path(args.out) if args.out else session.run_directory(cfg.results_dir, run_key) + if (cfg := _start_logging(cfg, args, out, "compare")) is None: + return EXIT_REFUSED + say.info(f"{store.path}") # stderr, so --json output stays clean; after the checks, so a refusal does not print it + _log_settings([*sources, *settings.pop("sources"), ("compare.rounds", rounds, rounds_source)]) + settings["run_key"], settings["out"] = run_key, out + try: if policy["profile"] == "variants": doc = session.compare_variants( *args.targets, rounds=rounds, store=store, parameter=args.vary, baseline=args.baseline, - progress=progress, k=policy["k"], min_rounds=policy["min_rounds"], **settings) + progress=say.info, k=policy["k"], min_rounds=policy["min_rounds"], **settings) else: - label = session.parse_label(args.label) if args.label else None - doc = session.compare_targets(*args.targets, rounds=rounds, store=store, label=label, progress=progress, + doc = session.compare_targets(*args.targets, rounds=rounds, store=store, label=label, progress=say.info, **policy, **settings) except runner.Refused as e: return _refused(e) except (UsageError, config_mod.ConfigError) as e: - print(f"bx compare: error: {e}", file=sys.stderr) + say.error(f"bx compare: error: {e}") return EXIT_REFUSED except (session.SessionError, compare_mod.CompareError) as e: - print(f"cannot compare: {e}", file=sys.stderr) + say.error(f"cannot compare: {e}") return EXIT_REFUSED _show(doc, args, store.documents(doc["run_key"]) if args.tables else None) return EXIT_OK +def _degraded(doc): + """What a comparison that exited 0 left undone, for the footer: nothing is added for a clean one.""" + units, failed = doc["units"], doc.get("failed_invariants", []) + if failed and not units: + log.degraded(f"0 units compared, {len(failed)} invariant(s) failed") + elif failed: + log.degraded(f"{len(failed)} invariant(s) failed") + if indeterminate := [u for u in units if u["verdict"] == "indeterminate"]: + log.degraded(f"{len(indeterminate)} of {len(units)} units indeterminate") + + def _show(doc, args, documents): """The comparison as JSON, or as text; with --tables, the asv-style tables follow the summary.""" + _degraded(doc) if args.json: print(json.dumps(doc, indent=1)) return print(compare_mod.render(doc)) if args.tables: - print(tables_mod.render(doc, documents, all_rows=args.all)) + shown = tables_mod.render(doc, documents, all_rows=args.all) + if not shown: + logger.warning("tables skipped: no units, or no contender (%d failed invariant(s))", + len(doc.get("failed_invariants", []))) + print(shown) def _compare(store, args, policy): @@ -488,25 +899,32 @@ def _compare(store, args, policy): if policy["profile"] == "variants": parameter = args.vary or compare_mod.infer_parameter(documents, args.run) if not args.vary: # the choice is recorded in the document's `varying`, and said here too - print(f"varying: {parameter} (the only parameter)", file=sys.stderr) + say.info(f"varying: {parameter} (the only parameter)") + logger.info("%s was inferred from %d result document(s) of run %s", parameter, len(documents), args.run) doc = compare_mod.compare(documents, run_key=args.run, profile=policy["profile"], baseline=args.baseline, label=args.label, parameter=parameter, k=policy["k"], min_rounds=policy["min_rounds"]) except compare_mod.CompareError as e: - print(f"cannot compare: {e}", file=sys.stderr) + say.error(f"cannot compare: {e}") return EXIT_REFUSED _show(doc, args, documents) return EXIT_OK def cmd_validate(args): + # `validate` does not read the config file: the logging settings come from the flags and the environment. + if _start_logging(_no_config(), args, None, "validate", read_config=False) is None: + return EXIT_REFUSED valid = 0 + logger.info("validating %d file(s) as %s", len(args.files), args.kind) for path in args.files: inspection = core.inspect(path, args.kind) for error in inspection.errors: - print(f"{path}: {error}", file=sys.stderr) + say.warning(f"{path}: {error}") + if inspection.valid: + logger.debug("%s is a valid %s", path, args.kind) valid += inspection.valid - print(f"{valid}/{len(args.files)} valid", file=sys.stderr) + say.info(f"{valid}/{len(args.files)} valid") return EXIT_OK if valid == len(args.files) else EXIT_INVALID @@ -540,16 +958,46 @@ def _add_target_options(parser, command): parser.add_argument("--run-key", help=f"default: {command}-") parser.add_argument("--out", help="directory for orders and result files (default: RESULTS/RUN_KEY, " "RESULTS being paths.results, else ./results in the project root)") + parser.add_argument("--harness-verbosity", type=_non_negative, metavar="N", + help="ask the harness to say more (default 0: nothing more). pyperf and asv: 1 or more passes " + "--verbose; Google Benchmark: N is passed as --v=N. Its output is logged in full. " + f"Each -v past -vv does the same (-vvv is 1). ${HARNESS_VERBOSITY_ENV}, adapter.verbosity") parser.add_argument("--no-build", action="store_true", help="ask a provider to describe each @CONFIG target instead of preparing (building) it") parser.add_argument("--source-uri", help="the source's URI (default: source.uri, else the checkout's origin remote)") +def _logging_options() -> argparse.ArgumentParser: + """The options every subcommand takes: where the log goes, how much it keeps, and how much + the terminal shows. The three switch flags share one destination, so + `--no-log`, `--log` and `--log-file PATH` exclude each other. None means not given, so + any flag beats the environment and the file.""" + parent = argparse.ArgumentParser(add_help=False) + group = parent.add_mutually_exclusive_group() + group.add_argument("--no-log", dest="log", action="store_const", const=False, default=None, + help="write no log (the default is bx.log in the run's output folder)") + group.add_argument("--log", dest="log", action="store_const", const=True, default=None, + help="send the whole log to stderr instead of a file") + group.add_argument("--log-file", dest="log", metavar="PATH", + help="append the log to PATH ({out} is the run's output folder, {root} the project root)") + parent.add_argument("--log-level", type=str.lower, choices=list(log.LEVELS), metavar="LEVEL", + help=f"what the log keeps: {', '.join(log.LEVELS)} (default debug; ${LOG_LEVEL_ENV})") + parent.add_argument("-v", "--verbose", action="count", default=None, + help=f"show more on the terminal: -v every INFO record, -vv DEBUG too; each -v past -vv also asks the " + f"harness to say more (--harness-verbosity) (${VERBOSE_ENV})") + parent.add_argument("-q", "--quiet", action="count", default=None, + help="show less on the terminal: -q hides the table and the other INFO messages (it keeps warnings, " + "errors, the start line, the not-measured section and the result line); -qq keeps " + "only errors and the not-measured section") + return parent + + def main(argv=None): + options = _logging_options() ap = argparse.ArgumentParser(prog="bx", description=__doc__) sub = ap.add_subparsers(dest="cmd", required=True) - p = sub.add_parser("run", help="execute one work order (schemas/work-order/0.1.0)") + p = sub.add_parser("run", parents=[options], help="execute one work order (schemas/work-order/0.1.0)") p.add_argument("order") p.add_argument("--out", help="directory for result files (default ./results)") p.add_argument("--no-ingest", action="store_true", @@ -558,7 +1006,7 @@ def main(argv=None): help="run the order's context collectors: commands the order names (otherwise refused)") p.set_defaults(fn=cmd_run) - p = sub.add_parser("bench", help="benchmark one target: the single-target form of bx compare", + p = sub.add_parser("bench", parents=[options], help="benchmark one target: the single-target form of bx compare", description="bx bench TARGET --suite S [FUNCTION ...]: run one target once and print a table " "per case. TARGET and the options are those of bx compare: @CONFIG[=SOURCE_REF] " "(the project's target provider) or a path, which the harness reads (pyperf: a " @@ -587,16 +1035,17 @@ def main(argv=None): help="name this call's side of a session, such as env=numpy-2.0 (repeatable); the calls of a " "session share --run-key, and bx compare --run reads the label with --label NAME. " "Needs --run-key and --slot") - p.add_argument("--round", type=int, - help="this call's round in a session: the sides' attempts are paired by it. " - "Needs --run-key and --slot") + p.add_argument("--round", metavar="R[/N]", + help="this call's round in a session, numbered from 0: the sides' attempts are paired by it. " + "R/N also says the session has N rounds, which the start line shows (nothing else uses " + "it). Needs --run-key and --slot") p.add_argument("--slot", type=int, help="this call's position in the session's alternation (0, 1, 2, ...), kept by the caller's loop. " "Needs --run-key") p.add_argument("--no-ingest", action="store_true", help="only write result files; skip the local store") p.set_defaults(fn=cmd_bench) - p = sub.add_parser("config", help="write or show benchx.conf.json") + p = sub.add_parser("config", parents=[options], help="write or show benchx.conf.json") p.add_argument("action", choices=["init", "show"], help="init: write a benchx.conf.json stating a harness's defaults; show: what the file and the defaults give") p.add_argument("--dir", default=".", help="init: where to write benchx.conf.json (default .)") @@ -604,20 +1053,20 @@ def main(argv=None): help="init: the harness (default %(default)s)") p.set_defaults(fn=cmd_config) - p = sub.add_parser("ingest", help="sweep result files and work orders into the local store") + p = sub.add_parser("ingest", parents=[options], help="sweep result files and work orders into the local store") p.add_argument("paths", nargs="+") p.set_defaults(fn=cmd_ingest) - p = sub.add_parser("series", help="list series") + p = sub.add_parser("series", parents=[options], help="list series") p.add_argument("--workload") p.add_argument("--quantity") p.set_defaults(fn=cmd_series) - p = sub.add_parser("history", help="one series' points (a query; history mode is deferred)") + p = sub.add_parser("history", parents=[options], help="one series' points (a query; history mode is deferred)") p.add_argument("series", help="series fingerprint or prefix") p.set_defaults(fn=cmd_history) - p = sub.add_parser("head", help="the latest results in the store, newest first") + p = sub.add_parser("head", parents=[options], help="the latest results in the store, newest first") p.add_argument("-n", type=int, default=10, help="how many (default 10)") p.add_argument("--project", help="only this store project's results (e.g. numpy, local/HOST)") p.add_argument("--workload", help="only results whose benchmark name contains this") @@ -627,7 +1076,7 @@ def main(argv=None): help="the `bx bench` table (median, mean ± sd, range, n, status) with revision, run and project") p.set_defaults(fn=cmd_head) - p = sub.add_parser("target", help="ask for a target's description (schemas/target-description/0.1.0)", + p = sub.add_parser("target", parents=[options], help="ask for a target's description (schemas/target-description/0.1.0)", description="TARGET is @CONFIG[=SOURCE_REF], asking the provider named in " "benchx.conf.json, or a build directory holding .benchx-target.json. " "describe only reports a target that exists; prepare may build it.") @@ -635,7 +1084,7 @@ def main(argv=None): p.add_argument("target") p.set_defaults(fn=cmd_target) - p = sub.add_parser("compare", help="compare two sides: read mode (--run) or measure mode (two targets)", + p = sub.add_parser("compare", parents=[options], help="compare two sides: read mode (--run) or measure mode (two targets)", description="Read mode compares results already measured: --run KEY --baseline VALUE. " "Measure mode runs two prepared targets, alternating them over " "--rounds rounds, delivers the results to the local store, then compares: " @@ -673,7 +1122,7 @@ def main(argv=None): _add_target_options(measure, "compare") p.set_defaults(fn=cmd_compare) - p = sub.add_parser("validate", help="check documents against their schema and rules", + p = sub.add_parser("validate", parents=[options], help="check documents against their schema and rules", description="Report every problem in each document, or nothing when all are valid.") p.add_argument("files", type=Path, nargs="+") p.add_argument("--kind", choices=get_args(Kind), default="measurement-result", @@ -687,7 +1136,35 @@ def main(argv=None): args.functions += extra elif extra: ap.error(f"unrecognized arguments: {' '.join(extra)}") - return args.fn(args) + args.argv = list(sys.argv[1:] if argv is None else argv) # the header records the command as given + try: + args.verbosity, args.verbosity_source, args.verbose_extra = _verbosity(args) + except UsageError as e: + log.start_console(0) + say.error(f"bx {args.cmd}: error: {e}") + log.stop() + return EXIT_REFUSED + log.start_console(args.verbosity) # first, so that a broken config file is still reported + outcome, code = "crashed", None + try: + code = args.fn(args) + outcome = OUTCOMES.get(code, "crashed") + return code + except SystemExit as e: # argparse, or a command that exits: let it through + code = e.code if isinstance(e.code, int) else 0 if e.code is None else 1 + outcome = OUTCOMES.get(code, "crashed") + raise + except KeyboardInterrupt: + logger.warning("interrupted") + outcome = "interrupted" + raise # Python prints its traceback and exits by the signal, as it does without a log + except Exception: # what Python's own handler would print, and its exit status + say.error(traceback.format_exc().rstrip("\n")) + code = 1 + return code + finally: + log.footer(outcome, code) + log.stop() if __name__ == "__main__": diff --git a/src/benchx/collectors.py b/src/benchx/collectors.py index 3b9f69d1..8018b6ea 100644 --- a/src/benchx/collectors.py +++ b/src/benchx/collectors.py @@ -18,15 +18,20 @@ """ import json +import logging import subprocess +import time from dataclasses import dataclass, field from pathlib import Path -from . import core +from . import core, log from .core import Refusal, loader DEFAULT_TIMEOUT_S = 60.0 MAX_DIFFS = 5 +MAX_LOGGED_DIFFS = 40 # the log's cap, like its other lists; a refusal keeps MAX_DIFFS + +logger = logging.getLogger(__name__) @dataclass @@ -61,17 +66,28 @@ def _short(value, limit=80) -> str: def _collect(spec, cwd, env) -> tuple[dict | None, str | None]: """The facts a collector prints, or (None, why not).""" + name, limit = spec.get("name", "?"), spec.get("timeout_s", DEFAULT_TIMEOUT_S) + logger.debug("collector %s: %s (in %s, limit %g s)", name, log.command(spec["command"]), cwd, limit) + started = time.monotonic() try: - done = subprocess.run(spec["command"], cwd=cwd, env=env, capture_output=True, text=True, - timeout=spec.get("timeout_s", DEFAULT_TIMEOUT_S)) + done = subprocess.run(spec["command"], cwd=cwd, env=env, capture_output=True, text=True, timeout=limit) + status, stdout, stderr = done.returncode, done.stdout, done.stderr except OSError as e: return None, f"cannot run {spec['command'][0]!r}: {e}" - except subprocess.TimeoutExpired: - return None, f"timed out after {spec.get('timeout_s', DEFAULT_TIMEOUT_S):g} s" - if done.returncode != 0: - last = (done.stderr.strip().splitlines() or ["no message"])[-1] - return None, f"exit {done.returncode}: {last}" - facts, errors = loader.parse(done.stdout) + except subprocess.TimeoutExpired as expired: # the partial output comes back as bytes + status, stdout, stderr = None, log.as_text(expired.stdout), log.as_text(expired.stderr) + logger.debug("collector %s: %s in %.1f s", name, "timed out" if status is None else f"exit {status}", + time.monotonic() - started) + failed = status is None or status != 0 + log.harness_output(logger, f"collector {name}", "stderr", stderr, failed=failed) + if failed: # on success stdout is the facts, which are kept as the collector-output artifact + log.harness_output(logger, f"collector {name}", "stdout", stdout, failed=True) + if status is None: + return None, f"timed out after {limit:g} s" + if status != 0: + last = (stderr.strip().splitlines() or ["no message"])[-1] + return None, f"exit {status}: {last}" + facts, errors = loader.parse(stdout) if facts is None: return None, "; ".join(str(error) for error in errors) return facts, None @@ -81,19 +97,24 @@ def run_all(specs, *, declared, cwd, env, artifacts_dir, taken=()) -> Collected: """Run each collector. `declared` is the target's how_built, `taken` the environment.system names already in use.""" out = Collected() - for spec in specs: + for number, spec in enumerate(specs, 1): name = spec["name"] if name in taken or name in out.system: out.refusals.append(Refusal(f"collector {name!r}: that name is already in environment.system")) continue checks = bool(spec.get("verify") or spec.get("expect")) refuse = spec.get("on_fail", "refuse") == "refuse" + started = time.monotonic() facts, why = _collect(spec, cwd, env) + took = time.monotonic() - started problems = [] if facts is None: out.warnings.append("collector-failed") problems.append(f"collector {name!r} failed: {why}") + logger.info("collector %d/%d %s: failed, %.1f s", number, len(specs), name, took) + logger.warning("collector %s failed: %s", name, why) # even when it only warns: the reason is lost otherwise else: + logger.info("collector %d/%d %s: ok, %.1f s", number, len(specs), name, took) digest = core.sha256_hex(core.canonical(facts)) path = Path(artifacts_dir) / f"collector-{name}.json" path.write_bytes(core.pretty(facts)) @@ -108,6 +129,11 @@ def run_all(specs, *, declared, cwd, env, artifacts_dir, taken=()) -> Collected: problems += [f"collector {name!r}: expect {d}" for d in _differences(spec.get("expect", {}), facts)] if problems: out.warnings.append("collector-mismatch") + logger.warning("collector %s: %d difference(s) from what was declared or expected", name, len(problems)) + for problem in problems[:MAX_LOGGED_DIFFS]: + logger.warning("%s", problem) + if len(problems) > MAX_LOGGED_DIFFS: + logger.warning("collector %s: and %d more", name, len(problems) - MAX_LOGGED_DIFFS) if problems and checks and refuse: # an unchecked collector that fails only warns out.refusals += [Refusal(problem) for problem in problems[:MAX_DIFFS]] return out diff --git a/src/benchx/compare.py b/src/benchx/compare.py index 4427bd4b..8b83930c 100644 --- a/src/benchx/compare.py +++ b/src/benchx/compare.py @@ -11,6 +11,7 @@ import collections import json +import logging import math import re import statistics @@ -21,6 +22,8 @@ from .snapshot import DIRTY_WARNINGS from .store import store_project +logger = logging.getLogger(__name__) + METHOD = {"name": "benchx/paired-relative", "version": "v1", "effect_measure": "relative"} PROFILES = { # UC-03: two subject trees from one run. @@ -141,7 +144,80 @@ def infer_parameter(documents, run_key) -> str: def compare(documents, *, run_key, profile, baseline, label=None, parameter=None, k=3.0, min_rounds=3) -> dict: """The run-mode comparison document. `label` names the sides of `environments`, and `parameter` - those of `variants`.""" + those of `variants`. The comparator's contract is about its result (the same inputs give the same + document), which logging does not touch: this logs the inputs, then the outcome from the document + `_compare` returns, so that every return path gets its records.""" + doc = _compare(documents, run_key=run_key, profile=profile, baseline=baseline, label=label, + parameter=parameter, k=k, min_rounds=min_rounds) + _log_outcome(doc, documents, run_key=run_key, profile=profile, baseline=baseline, k=k, min_rounds=min_rounds) + return doc + + +def _log_outcome(doc, documents, *, run_key, profile, baseline, k, min_rounds) -> None: + """What the comparison found, one record per fact that explains a verdict or the lack of one.""" + ours = [d for d in documents if d["provenance"].get("run_key") == run_key] + logger.debug("compare: run %s, profile %s, varying %s, identity schema %s, baseline as typed %r, k %g, " + "min_rounds %d; %d result document(s) used of %d offered (the others are conditions, such as the " + "load average)", run_key, profile, doc["varying"], doc["identity_schema"], baseline, k, min_rounds, + len(doc["inputs"]), len(ours)) + if doc["local_only"]: + dirty = sorted({f"the {what} tree {(d['provenance'].get(tree) or d['revision']['key'])[:12]} is " + f"{d['provenance'][flag]}" for d in ours + for flag, tree, what in (("subject_dirty", "subject_tree", "subject"), + ("benchmark_dirty", "benchmark_tree", "benchmark")) + if d["provenance"][flag] != "clean"}) + logger.info("local-only: %s", "; ".join(dirty)) + for failed in doc["failed_invariants"]: + if "workload" in failed: + where = f"{workload_label(failed['workload'])} [{failed['quantity']}]" + logger.warning("invariant %s failed for %s: %s", failed["invariant"], where, failed["detail"]) + else: + logger.error("invariant %s failed: %s; no unit was compared", failed["invariant"], failed["detail"]) + groups = collections.defaultdict(list) + for exclusion in doc["exclusions"]: + groups[exclusion["reason"]].append(exclusion["result"]) + for reason, results in groups.items(): + logger.warning("excluded %d result(s): %s", len(results), reason) + for result in results: + logger.debug("excluded: %s %s", result["producer"], result["ingest_key"]) + if doc["missing"]: + first = ", ".join(f"{workload_label(m['workload'])} [{m['quantity']}] on {m['side']}" for m in doc["missing"][:3]) + logger.warning("%d unit(s) have no result on a side: %s%s", len(doc["missing"]), first, + ", …" if len(doc["missing"]) > 3 else "") + for m in doc["missing"]: + logger.debug("missing: %s [%s] on %s", workload_label(m["workload"]), m["quantity"], m["side"]) + for unit in doc["units"]: + facts = [unit["verdict"]] + ([f"reason {unit['reason']}"] if "reason" in unit else []) + facts.append(f"rounds {unit['rounds']}") + if "reference_estimate" in unit: + facts.append(f"reference {unit['reference_estimate']:.6g}") + if "effect" in unit: + facts += [f"effect {unit['effect']:+.2%}", f"noise {unit['noise']:.2%}", f"k x noise {k * unit['noise']:.2%}"] + if "reason" in unit and unit["reason"] == "insufficient-rounds": + facts.append(f"{max(min_rounds, MIN_PAIRS)} paired rounds required") + attempts = "; ".join(f"{role} " + ", ".join(f"{status} {n}" for status, n in counts.items()) + for role, counts in unit.get("attempts", {}).items()) + logger.info("unit %s [%s]: %s; attempts %s", workload_label(unit["workload"]), unit["quantity"], + ", ".join(facts), attempts) + by_verdict = collections.Counter(u["verdict"] for u in doc["units"]) + indeterminate = collections.Counter(u.get("reason", "-") for u in doc["units"] if u["verdict"] == "indeterminate") + def side(name): # a revision is a commit id, cut to read; an environment or a variant is a name, kept whole + text = str(name) + return text[:12] if profile == "revisions" else text + logger.log(logging.WARNING if indeterminate or doc["exclusions"] or doc["failed_invariants"] or doc["missing"] + else logging.INFO, + "compared run %s, profile %s, baseline %s, contender %s: %d unit(s)%s%s; %d missing, %d invariant(s) " + "failed, %d excluded", run_key, profile, side(doc["baseline"]), side(doc.get("contender")), + len(doc["units"]), "".join(f", {n} {verdict}" for verdict, n in sorted(by_verdict.items())), + f" (indeterminate: {', '.join(f'{r} {n}' for r, n in sorted(indeterminate.items()))})" if indeterminate else "", + len(doc["missing"]), len(doc["failed_invariants"]), len(doc["exclusions"])) + + +def _compare(documents, *, run_key, profile, baseline, label=None, parameter=None, k=3.0, min_rounds=3) -> dict: + """The body of `compare`: the document, and the decisions that only it makes (logged where they happen).""" + if min_rounds < MIN_PAIRS: + logger.warning("min_rounds %d is below %d, the fewest rounds a verdict needs: %d is used", + min_rounds, MIN_PAIRS, MIN_PAIRS) projection = profile_projection(profile, label, parameter) documents = _run_documents(documents, run_key) naming = projection.axis[0] @@ -188,8 +264,15 @@ def compare(documents, *, run_key, profile, baseline, label=None, parameter=None return doc contender = next(side for side in names if side != base) doc["contender"] = names[contender] + if profile == "revisions": + how = ("a prefix of the side's tree id" if any(str(names[s]).startswith(baseline) for s in matches) + else "a prefix of a result's revision.key") + else: + how = "equality with the recorded value" + logger.info("baseline %s (asked: %s, matched by %s), contender %s", names[base], baseline, how, names[contender]) doc["sides"] = {role: _declared(next(d for d, x in zip(documents, sides) if x == side)) for role, side in (("baseline", base), ("contender", contender))} + _log_declarations(documents, sides, base, contender) # Run-level invariants (schema §5.5, comparator.md §3), as the profile names them. check = set(projection.invariants) @@ -271,7 +354,7 @@ def compare(documents, *, run_key, profile, baseline, label=None, parameter=None "detail": f"{len(by_side[base])} against {len(by_side[contender])}: run the same " "number of rounds on both sides"}) continue - rounds, side_failed = {}, False + rounds, side_failed, overwritten = {}, False, [] for s in (base, contender): for d in by_side[s]: if d["measurement"]["status"] != "success": @@ -281,15 +364,33 @@ def compare(documents, *, run_key, profile, baseline, label=None, parameter=None doc["exclusions"].append({"result": result, "reason": f"{why}: {said(d)}" if said(d) else why}) side_failed = side_failed or (profile in STRICT_STATUS and status in FAILED_STATUSES) continue - rounds.setdefault(d.get("procedure", {}).get("round"), {})[s] = d + in_round = rounds.setdefault(d.get("procedure", {}).get("round"), {}) + if s in in_round: # a dict assignment: the second success replaces the first + overwritten.append(in_round[s]["ingest_key"]) + in_round[s] = d + label_of = f"{workload_label(where['workload'])} [{quantity}]" + if overwritten: + logger.warning("%s: %d second success(es) of a side in one round overwrote the first: %s", label_of, + len(overwritten), ", ".join(overwritten[:3]) + (", …" if len(overwritten) > 3 else "")) + if None in rounds: + logger.warning("%s: results with no procedure.round all share one round: %d side(s) of it", label_of, + len(rounds[None])) pairs = [(r[base], r[contender]) for _, r in sorted(rounds.items(), key=lambda x: (x[0] is None, x[0])) if base in r and contender in r] + if len(pairs) < len(rounds): + logger.debug("%s: %d round(s) paired, %d dropped for a success on one side only (%s)", label_of, len(pairs), + len(rounds) - len(pairs), "; ".join(f"round {r} has {'baseline' if base in v else 'contender'} only" + for r, v in rounds.items() if not (base in v and contender in v))) unit_doc = _unit(where, pairs, by_side, base, contender, k, min_rounds, side_failed) succeeded = {s: [d for d in by_side[s] if d["measurement"]["status"] == "success"] for s in (base, contender)} unit_doc["unmatched_differences"] = _differences(projection, succeeded[base], succeeded[contender]) if caveats := _caveats(by_side, base, contender): unit_doc["caveats"] = caveats doc["units"].append(unit_doc) + ignored = collections.Counter(p for u in doc["units"] for p in u.get("unmatched_differences", [])) + if ignored: + logger.debug("facts that differ between the sides but that the identity policy ignores, so no invariant " + "fails: %s", ", ".join(f"{pointer} ({n} unit(s))" for pointer, n in sorted(ignored.items()))) return doc @@ -371,6 +472,22 @@ def _differing(facts: list[dict]) -> list[str]: return sorted(p for key in set().union(*facts) for p in _diff(key, [f.get(key, _ABSENT) for f in facts])) +def _log_declarations(documents, sides, base, contender) -> None: + """`sides` takes each side's declarations (how built, activation, shell, provider) from its first result in + sort order and never looks at the others: say which result that was, and warn when the others disagree + (the fields' names: never their values, which are the user's text and the inherited environment).""" + for role, side in (("baseline", base), ("contender", contender)): + ours = [d for d, x in zip(documents, sides) if x == side] + first = _declared(ours[0]) + logger.debug("the %s side's declarations come from %s %s", role, ours[0]["producer"]["name"], + ours[0]["ingest_key"]) + differing = sorted({k for d in ours[1:] for k in set(first) | set(_declared(d)) + if first.get(k) != _declared(d).get(k)} - {"observed_env"}) + if differing: + logger.warning("the %s side's results disagree about %s: the comparison shows the first result's", + role, ", ".join(differing)) + + def _declared(document) -> dict: """What a side says about how it was built and entered, beside what the runner saw: the declarations are recorded as given and never judged.""" @@ -424,6 +541,12 @@ def _unit(where, pairs, by_side, base, contender, k, min_rounds, side_failed=Fal unit["reason"] = "not-measured" return unit estimates = [(_estimate(b), _estimate(c)) for b, c in pairs] + if empty := [d["ingest_key"] for pair in pairs for d in pair if _estimate(d) is None]: + logger.warning("%s [%s]: %d success(es) with no observations are dropped from the pairs; rounds counts %d " + "pair(s) before this and the threshold %d after it: %s", workload_label(where["workload"]), + where["quantity"], len(empty), len(pairs), len([1 for b, c in estimates if b is not None + and c is not None]), + ", ".join(empty[:3]) + (", …" if len(empty) > 3 else "")) estimates = [(b, c) for b, c in estimates if b is not None and c is not None] if estimates: unit["reference_estimate"] = statistics.median(b for b, _ in estimates) diff --git a/src/benchx/config.py b/src/benchx/config.py index 4d12347a..a52f7b3d 100644 --- a/src/benchx/config.py +++ b/src/benchx/config.py @@ -54,6 +54,7 @@ class Config: root: Path path: Path | None # None: no file was found, and root is the working directory data: dict + log_file: Path | None = None # the log's file, once cli._start_logging has resolved it @property def where(self) -> str: @@ -66,15 +67,24 @@ def section(self, name) -> dict: def adapter(self) -> dict: return self.section("adapter") - def pick(self, flag_value, file_value, default=REQUIRED, *, flag, key): - """The command-line value, else the file's, else `default`; ConfigError when - none is given and the value is required.""" - for value in (flag_value, file_value): - if value is not None: - return value + def pick_with_source(self, flag_value, file_value, default=REQUIRED, *, flag, key, env=None): + """The value and where it came from: the command line (`flag`), else the environment + variable named `env` (`env`; an empty one counts as unset), else the file's (`file`), + else `default` (`default`); ConfigError when none is given and the value is required.""" + if flag_value is not None: + return flag_value, "flag" + if env and (from_env := os.environ.get(env)): + return from_env, "env" + if file_value is not None: + return file_value, "file" if default is REQUIRED: raise ConfigError(f"{flag} is required: give it, or set {key} in {self.where}") - return default + return default, "default" + + def pick(self, flag_value, file_value, default=REQUIRED, *, flag, key, env=None): + """The command-line value, else the file's, else `default`; ConfigError when + none is given and the value is required.""" + return self.pick_with_source(flag_value, file_value, default, flag=flag, key=key, env=env)[0] def _path(self, value) -> Path: path = Path(value).expanduser() @@ -92,6 +102,12 @@ def store_path(self) -> Path: def results_dir(self) -> Path: return self._path(self.section("paths").get("results", DEFAULT_RESULTS)) + @property + def own_paths(self) -> tuple[Path, ...]: + """Everything benchx itself writes that may lie inside a measured tree: the store, the + results directory and the log file. The tree's identity leaves them out (snapshot.ignore).""" + return (self.store_path, self.results_dir, *([self.log_file] if self.log_file else [])) + @property def collectors(self) -> list[dict]: """The context collectors, as a work order lists them. `{root}` in a command diff --git a/src/benchx/core/validation.py b/src/benchx/core/validation.py index 0eab3d50..6bc1bbaa 100644 --- a/src/benchx/core/validation.py +++ b/src/benchx/core/validation.py @@ -1,3 +1,4 @@ +import logging from collections.abc import Iterator from typing import Any, Literal, assert_never @@ -6,6 +7,8 @@ from . import catalog from .errors import SchemaNotFound, StructureError +logger = logging.getLogger(__name__) + Kind = Literal[ "measurement-result", "work-order", @@ -52,6 +55,9 @@ def check( data: dict[str, Any], validator: Draft202012Validator ) -> Iterator[StructureError]: for error in validator.iter_errors(data): + # Its path, its keyword and jsonschema's message, which echoes the offending value: logged as it is. + logger.debug("schema error at /%s: %s: %s", "/".join(map(str, error.absolute_path)), error.validator, + error.message) yield StructureError( path=tuple(error.absolute_path), keyword=str(error.validator), diff --git a/src/benchx/log.py b/src/benchx/log.py new file mode 100644 index 00000000..e89dd07e --- /dev/null +++ b/src/benchx/log.py @@ -0,0 +1,382 @@ +"""benchx's diagnostics: what `bx` decided, warned about and failed at, kept in a log. + +Every module logs through the standard library: `log = logging.getLogger(__name__)`, so the +logger names are `benchx.runner`, `benchx.cli`, and so on. `benchx/__init__.py` gives the +`benchx` logger a `NullHandler`: a library caller sees nothing unless it configures logging +itself. The `bx` command installs two kinds of handler (cli.main): + +* the console handler (`start_console`), which writes to stderr exactly what `print` wrote + before logging existed: the bare message, for the records that carry `console=True` (the + messages `bx` shows its user, made with `console()`), or for every record under `-v`; +* the stdout handler, installed with it, for the records that carry `stdout=True` as well + (`console().out()`): what a command that did work reports on stdout, a run's table and its + result line. The log keeps them too. `-q` and `-qq` hide them by tier (`TABLE`, `SUMMARY`, + `ANSWER`). A progress message with a tier (`console().progress()`, the line a call starts + with) is shown on stderr at `-q` as well; +* a file, or with `--log` stderr, for the whole log (`configure`), in one line format. + +At the default verbosity the terminal shows what `bx` showed before there was a log, and the log changes neither +what a command stores nor its exit status. `-q` and `-qq` hide the stdout of a run that ended (the table, and by tier +the rest of its report); they are the only options that take anything off it. Query answers and machine-readable +output (`--json`, `bx head`, `bx target`) stay `print`: they are not records. +""" + +import datetime +import logging +import os +import shlex +import sys +import time +from pathlib import Path + +PACKAGE = "benchx" +LEVELS = {"debug": logging.DEBUG, "info": logging.INFO, "warning": logging.WARNING, "error": logging.ERROR} +# What the terminal shows at each verbosity (-qq to -vv): its level, and whether it shows only +# the messages meant for the user (console=True) or every record. +_CONSOLE = {-2: (logging.ERROR, True), -1: (logging.WARNING, True), 0: (logging.INFO, True), + 1: (logging.INFO, False), 2: (logging.DEBUG, False)} +# The log's own line: UTC to the millisecond, as provenance.started_at and ended_at are written, +# then the process id, so two `bx` processes given one file stay apart. +_FORMAT = "%(asctime)s %(process)d %(name)s %(levelname)s %(message)s" +_CONTINUATION = " " +# How many `-q` a piece of stdout survives: the table of a run goes at the first, its summary +# lines at the second, and an answer (what the user needs to see, even when failures are all) +# never goes. +TABLE, SUMMARY, ANSWER = 0, 1, 2 + + +class _Stderr(logging.StreamHandler): + """A stderr handler that finds `sys.stderr` each time it writes. The tests call `cli.main` + many times in one process under `capsys`; a stream taken once would be stale.""" + + def __init__(self): + logging.Handler.__init__(self) + + @property + def stream(self): + return sys.stderr + + +class _Full(logging.Formatter): + """`2026-11-02T22:36:12.345Z 48211 benchx.runner INFO message`. A message of several lines + keeps the prefix on the first and indents the others, so that a reader that goes by line + (`grep` for a pid, `sort`) loses none of it.""" + + def __init__(self): + super().__init__(_FORMAT) + + def formatTime(self, record, datefmt=None): + moment = datetime.datetime.fromtimestamp(record.created, datetime.timezone.utc) + return moment.strftime("%Y-%m-%dT%H:%M:%S.") + f"{int(record.msecs):03d}Z" + + def format(self, record): + first, *rest = super().format(record).split("\n") + return "\n".join([first, *(_CONTINUATION + line for line in rest)]) + + +class _Stdout(logging.StreamHandler): + """A stdout handler that finds `sys.stdout` each time it writes, as `_Stderr` does. A failed + write (a closed pipe) is the command's failure, as it is for `print`: logging would swallow it.""" + + def __init__(self): + logging.Handler.__init__(self) + + @property + def stream(self): + return sys.stdout + + def handleError(self, record): + raise # called from emit's `except`: re-raises what failed + + +class _Bare(logging.Formatter): + """The message as `print` wrote it. A record's leading blank lines (`lead`, set by `out`) are the + layout of the default output: a quiet terminal gets none of them.""" + + def format(self, record): + return ("\n" * getattr(record, "lead", 0) if _state.verbosity >= 0 else "") + record.getMessage() + + +class _Shown(logging.Filter): + """Only what `out` made, and only what the verbosity leaves: `-q` is 1, `-qq` is 2.""" + + def filter(self, record): + return bool(getattr(record, "stdout", False)) and getattr(record, "tier", ANSWER) >= quiet() + + +class _Visible(logging.Filter): + """What the verbosity shows on stderr: the records at its level, and the progress records (`progress`) + whose tier `-q` leaves. The handler itself takes everything from INFO, so that these get here.""" + + def filter(self, record): + if record.levelno >= _CONSOLE[_state.verbosity][0]: + return True + return getattr(record, "tier", None) is not None and record.tier >= quiet() + + +class _NotStdout(logging.Filter): + """stdout carries those records already: stderr does not repeat them, `-v` included.""" + + def filter(self, record): + return not getattr(record, "stdout", False) + + +class _OnlyConsole(logging.Filter): + def filter(self, record): + return bool(getattr(record, "console", False)) + + +class _Buffer(logging.Handler): + """Keeps the records made before the log is on (the config loaded, the shorthand's tree found, an + `asv.conf.json` read in the command's own checks) until `configure` knows where they go. Bounded.""" + + LIMIT = 1000 + + def __init__(self): + super().__init__(logging.DEBUG) + self.records = [] + + def emit(self, record): + if len(self.records) < self.LIMIT: + self.records.append(record) + + +class _State: + verbosity = 0 + buffer = None # records made before configure() + console = None # the console handler, or None + stdout = None # the stdout handler, or None + destination = None # the file handler, or the --log stderr handler, or None + level = logging.DEBUG # the level the destination keeps + configured = False # a destination is on, so a header was written and a footer is due + started = None # time.monotonic() at the header + degraded: list = [] + once: set = set() + + +_state = _State() + + +def _logger() -> logging.Logger: + return logging.getLogger(PACKAGE) + + +def _apply_level() -> None: + """The `benchx` logger passes the lowest level any handler wants, so a record nobody reads + costs nothing (and `isEnabledFor(DEBUG)` is false when nothing wants DEBUG).""" + wanted = [logging.DEBUG] if _state.buffer is not None else [] + if _state.console is not None: + wanted.append(_state.console.level) + if _state.stdout is not None: + wanted.append(logging.INFO) # what `out` says goes by its tier, not its level + if _state.destination is not None: + wanted.append(_state.level) + # With nothing to serve the logger defers to the root's, which is WARNING unless a library caller has set + # it: a fixed WARNING here would outlive `stop()` and hide the records from a caller that logs at INFO. + _logger().setLevel(min(wanted) if wanted else logging.NOTSET) + + +def _remove(handler) -> None: + if handler is not None: + _logger().removeHandler(handler) + handler.close() + + +class _Console(logging.LoggerAdapter): + def progress(self, text: str, tier: int = SUMMARY) -> None: + """A progress message on stderr that `-q` keeps (not `-qq`): where a quiet run says what it is + doing. An ordinary `info` is gone at `-q`. In the log it is an INFO record, as `info` makes.""" + self.logger.info(text, extra={"console": True, "tier": tier}) + + def out(self, text: str, tier: int = ANSWER, *, level: int = logging.INFO) -> None: + """`text` on stdout, and in the log. `tier` is how many `-q` it survives (`TABLE`, `SUMMARY`, + `ANSWER`). One record a line, as `harness_output` logs a process's lines: stdout gets the same + text, and the log keeps every line stamped, a table's columns lined up, and `grep` whole. + Leading blank lines are layout: kept on the default terminal, dropped when quiet and in the + log. The text is not a format string: a `%` in it is left as it is.""" + body = text.lstrip("\n") + for number, line in enumerate(body.split("\n")): + self.logger.log(level, line, extra={"console": True, "stdout": True, "tier": tier, + "lead": len(text) - len(body) if number == 0 else 0}) + + +def console(name: str) -> _Console: + """The logger of a module that shows the user something: its records carry `console=True`, + so the console handler writes them at the default verbosity. Used by `cli.py`, and by the + prints of `adapters/asv.py` that logging replaces. Its `out` is for what goes to stdout.""" + return _Console(logging.getLogger(name), {"console": True}) + + +def quiet() -> int: + """How many `-q` the terminal is asked for, 0 at the default and under `-v`.""" + return max(0, -_state.verbosity) + + +def start_console(verbosity: int = 0) -> None: + """Install the console handler: stderr, the bare message. `verbosity` is -2 to 2 (`-qq` to + `-vv`). Idempotent: it replaces its own handler and leaves any other alone.""" + _remove(_state.console) + _remove(_state.stdout) + _remove(_state.buffer) + _state.buffer = _Buffer() + _logger().addHandler(_state.buffer) + _state.verbosity = verbosity + level, only_console = _CONSOLE[verbosity] + handler = _Stderr() + handler.setLevel(min(level, logging.INFO)) # `_Visible` holds back what the level does not show + handler.setFormatter(logging.Formatter("%(message)s")) + handler.addFilter(_NotStdout()) + handler.addFilter(_Visible()) + if only_console: + handler.addFilter(_OnlyConsole()) + _logger().addHandler(handler) + _state.console = handler + out = _Stdout() + out.setLevel(logging.INFO) + out.setFormatter(_Bare()) + out.addFilter(_Shown()) + _logger().addHandler(out) + _state.stdout = out + _apply_level() + + +def configure(setting, *, level: int = logging.DEBUG, argv=None) -> None: + """Turn the log on or off: `setting` is False (the console handler only), True (stderr + carries the whole log, in the full format) or a resolved `Path` (appended to, never + truncated). Writes the header record. Idempotent: it replaces what an earlier call set up + and closes the file it had open. OSError when a file cannot be opened.""" + _remove(_state.destination) + _state.destination = None + _state.configured = False + _state.degraded = [] + _state.once = set() + earlier = _state.buffer.records if _state.buffer else [] + if _state.buffer is not None: # from here on the destination, if any, takes the records + _remove(_state.buffer) + _state.buffer = None + if setting is False or setting is None: + _apply_level() + return + if setting is True: + # One stderr handler: the log stream, which `-v` and `-q` do not touch. + _remove(_state.console) + _state.console = None + handler = _Stderr() + else: + handler = logging.FileHandler(Path(setting), mode="a", encoding="utf-8", errors="backslashreplace") + handler.setLevel(level) + handler.setFormatter(_Full()) + _logger().addHandler(handler) + _state.destination, _state.level, _state.configured = handler, level, True + _state.started = time.monotonic() + _apply_level() + _header(argv) + # What happened before the log was on, in order. The console handler has shown what it shows, so a + # console message is not repeated on a stderr that is now the log itself. + for record in earlier: + if record.levelno >= level and not (setting is True and getattr(record, "console", False)): + handler.handle(record) + + +def stop() -> None: + """Remove every handler this module installed, and close the file. `cli.main` calls it + on the way out, so a library call that follows in the same process is silent again.""" + _remove(_state.console) + _remove(_state.stdout) + _remove(_state.destination) + _remove(_state.buffer) + _state.console = _state.stdout = _state.destination = _state.buffer = None + # And what a command left in the state, so that a library call after `cli.main` starts from nothing (`once`, + # `degraded` and `quiet` are read without `configure`). + _state.configured, _state.verbosity, _state.started = False, 0, None + _state.degraded, _state.once = [], set() + _apply_level() + + +def configured() -> bool: + """A destination is on: a header was written, and a footer is due.""" + return _state.configured + + +def _header(argv) -> None: + from . import __version__ + + command = "bx " + shlex.join(argv) if argv is not None else "bx" + logging.getLogger(f"{PACKAGE}.cli").info("start: benchx %s, pid %d, in %s: %s", __version__, os.getpid(), + Path.cwd(), command) + + +def footer(outcome: str, code: int | None = None) -> None: + """The record that ends an invocation: its outcome word, exit code and elapsed time, then + what it left undone, if anything (`degraded`). A missing footer is itself the evidence of a + process that was killed.""" + if not _state.configured: + return + elapsed = time.monotonic() - _state.started + took = f"{elapsed:.1f} s" if elapsed < 10 else f"{elapsed:.0f} s" + where = f"{outcome} (exit {code})" if code is not None else outcome + phrases = "".join(f", {phrase}" for phrase in _state.degraded) + logging.getLogger(f"{PACKAGE}.cli").info("end: %s, %s%s", where, took, phrases) + + +def degraded(text: str, *, shown: bool = False) -> None: + """A command that exits 0 but did less than asked says so: the phrase ends the footer, and + is logged now at WARNING, so `--log-level warning` keeps it. `shown` also puts it on stdout + at every verbosity, for a command whose table, where the reader would see it, is not.""" + _state.degraded.append(text) + if shown: + console(f"{PACKAGE}.cli").out(text, ANSWER, level=logging.WARNING) + else: + logging.getLogger(f"{PACKAGE}.cli").warning("%s", text) + + +def once(key) -> bool: + """True the first time it is called with `key` since `configure()`, False after: for a + record that is the same in every order of a command (the first gets INFO, the rest DEBUG).""" + if key in _state.once: + return False + _state.once.add(key) + return True + + +def harness_output(logger, label, stream, text, *, failed, kept_at=None, limit=40) -> None: + """A process's output in the log, after it has exited: a header record that names the stream + and its size, then the last `limit` lines, one record each (`label| line`). DEBUG when the + process did well, WARNING when it `failed`. `kept_at` is where the full text is kept, if + anywhere. An empty stream is skipped. The text is the program's own, logged as written.""" + level = logging.WARNING if failed else logging.DEBUG + if not text or not text.strip() or not logger.isEnabledFor(level): + return + lines = text.splitlines() + kept = lines[-limit:] + where = f"all in {kept_at}" if kept_at else "the full text is not kept" + if len(kept) < len(lines): + header = f"{label}: {stream}, {len(lines)} lines (last {limit}; {where})" + else: + header = f"{label}: {stream}, {len(lines)} lines" + (f" (also in {kept_at})" if kept_at else "") + logger.log(level, "%s", header) + for line in kept: + logger.log(level, "%s: %s| %s", label, stream, line) + + +def as_text(data) -> str: + """What a timed-out process had printed, which `subprocess` hands back as bytes, as text: decoding for the log + never raises.""" + return data.decode(errors="backslashreplace") if isinstance(data, bytes) else data or "" + + +def command(args, *, scripts=None, temporary=()) -> str: + """A command line as the log shows it, pastable into a shell (`shlex.join`). Inline code + after `-c` that is one of `scripts` ({name: text}) is shortened to ``; paths + in `temporary` are marked as gone once the call returns. No environment is added: the inherited one is not logged.""" + shown = [str(a) for a in args] + for i in range(1, len(shown)): + if shown[i - 1] == "-c": + for name, script in (scripts or {}).items(): + if shown[i] == script: + shown[i] = f"<{name}: {len(script.strip().splitlines())} lines>" + text = shlex.join(shown) + gone = [str(p) for p in temporary if any(str(p) in a for a in shown)] + if gone: + text += f" (temporary, removed after the call: {', '.join(gone)})" + return text diff --git a/src/benchx/orders.py b/src/benchx/orders.py index 070c98cf..a246d6ad 100644 --- a/src/benchx/orders.py +++ b/src/benchx/orders.py @@ -28,7 +28,7 @@ def default_run_key(prefix: str) -> str: def make_order(*, suite: dict, target: dict, precision: dict, run_key: str, quantities=("wall-time",), case_s: float = CASE_TIMEOUT_S, order_s: float = ORDER_TIMEOUT_S, project=None, labels=None, environment_variables=None, round_=None, slot=None, benchmark=None, - collectors=None) -> dict: + collectors=None, harness_verbosity=0) -> dict: """One resolved work order. Optional fields that are None or empty are left out. Raises OrderError when the result is not a valid work order. @@ -62,6 +62,8 @@ def make_order(*, suite: dict, target: dict, precision: dict, run_key: str, quan order["benchmark"] = benchmark if collectors: order["collectors"] = list(collectors) + if harness_verbosity: # how much the harness is asked to say: left out at 0, so a default order is as before + order["harness_verbosity"] = harness_verbosity errors = core.check(order, "work-order") if errors: raise OrderError("; ".join(str(error) for error in errors)) diff --git a/src/benchx/runner.py b/src/benchx/runner.py index 0a0aaded..fd603417 100644 --- a/src/benchx/runner.py +++ b/src/benchx/runner.py @@ -5,17 +5,25 @@ of a case it did run is a result. """ +import collections +import contextlib +import json +import logging import os +import statistics import time import urllib.parse from collections.abc import Iterator from datetime import datetime, timezone from pathlib import Path -from . import __version__, adapters, collectors, core, snapshot +from . import __version__, adapters, collectors, core, log, snapshot from . import target as target_mod from .adapters.base import Unsupported, no_cases from .core import Refusal, Rejected +from .projection import said + +logger = logging.getLogger(__name__) RUNNER = {"name": "benchx", "version": __version__} # The runner's own probe: one condition measurement per attempt (schema §4.4). @@ -118,22 +126,166 @@ def _benchmark_mismatches(stated: dict | None, found: dict | None): f"but the suite is in {found['uri']}{'@' + found['revision'] if 'revision' in found else ''}") +def _refuse(problems): + """Log the whole refusal (the console shows it once the CLI catches it) and raise it: every + place `run` refuses comes through here.""" + problems = list(problems) + logger.debug("refused with %d problem(s): %s", len(problems), "; ".join(str(problem) for problem in problems)) + raise Refused(problems) from None + + +@contextlib.contextmanager +def _partial(state, total, out_dir): + """A case loop that raises or is interrupted after some result files were written: say what was + left, and how to store it. The exception goes on.""" + try: + yield + except BaseException as error: + if state["done"]: + logger.log(logging.ERROR if isinstance(error, Exception) else logging.WARNING, + "%d of %d cases written to %s, not ingested; bx ingest %s stores them", + state["done"], total, out_dir, out_dir) + raise + + +def _overlap(base: dict, facts: dict, path="") -> list[str]: + """The paths at which `facts` replaces a different value of `base`: names only, never values.""" + found = [] + for key, value in facts.items(): + if key in base: + if isinstance(value, dict) and isinstance(base[key], dict): + found += _overlap(base[key], value, f"{path}/{key}") + elif base[key] != value: + found.append(f"{path}/{key}") + return found + + +def _parameters_text(declared: dict, from_order: dict) -> str: + """A case's workload parameters for the log: the benchmark's own (asv's `repr()` strings), and the + order's `-e` variables, which the runner records as workload parameters too. Values as given.""" + parts = ["parameters " + ", ".join(f"{name}={value}" for name, value in declared.items()) + if declared else "no parameters of its own"] + if from_order: + parts.append("environment variables of the order " + ", ".join(f"{n}={v}" for n, v in from_order.items())) + return "; ".join(parts) + + +def _path_of(uri) -> str: + return urllib.parse.unquote(urllib.parse.urlparse(uri).path) + + +# The log's cap on a stream of harness output: 40 lines, or this many when the harness was asked to say more. +VERBOSE_OUTPUT_LINES = 2000 + +# Written once into the artifacts folder and overwritten by every case: named on the first case's line only. +SHARED_ARTIFACTS = ("params-helper", "asv-runtime") + + +def _case_line(results, warnings, run_, duration, load, details=None) -> tuple[int, str, bool]: + """The case's line: its statuses with their reasons (the message the producer gave, as `bx bench` + and `bx compare` show it), the warnings that differ from case to case, the exit status, the + duration and the load average. The level, and whether the case did badly: a status that is not + `success` or `skipped`, or a non-zero exit, or a warning that says the environment recorded may + not be the one the workers had.""" + statuses = [] + for status, reason, document in results: + text = status + (f" ({reason})" if reason else "") + counts = document.get("procedure", {}) + if status == "partial" and "completed_repetitions" in counts and "attempted_repetitions" in counts: + text += f" {counts['completed_repetitions']}/{counts['attempted_repetitions']}" + if text not in statuses: + statuses.append(text) + message = next((m for m in (said(document) for _, _, document in results) if m), None) + line = ", ".join(statuses) + (f": {message}" if message else "") + if warnings: + line += f" [{', '.join(f'{w}: {details[w]}' if w in (details or {}) else w for w in warnings)}]" + ended = "timeout" if run_["timed_out"] else f"exit {run_['exit_status']}" + bad = (any(status not in ("success", "skipped") for status, _, _ in results) + or run_["timed_out"] or run_["exit_status"] not in (0, None)) + raised = bad or bool({"env-mismatch", "env-capture-missing"} & set(warnings)) + load_text = f"load {load:.2f}" if load is not None else "load n/a" + return (logging.WARNING if raised else logging.INFO), f"{line}, {ended}, {duration:.1f} s, {load_text}", bad + + +def _log_identity(runnable, source, benchmark, source_dir): + """What each order found out about where it runs and what it measures. What is the same in every + order of a command (the interpreter, a dirty tree) is INFO the first time and DEBUG after; the sides of a + comparison may differ in those, so each distinct one is INFO once.""" + def level(key): + return logging.INFO if log.once(key) else logging.DEBUG + python = runnable.get("python") if isinstance(runnable, dict) else None + if python: + logger.log(level(("interpreter", str(python))), "the benchmarks run under %s", python) + snapshot.note_identity_fallback(source) + method = "directory-hash" if source["revision"].startswith("directory-") else "git" + logger.debug("subject: %s, found by %s: revision %s, tree %s, %s", source_dir, method, source["revision"][:12], + (source.get("tree") or "none")[:12], source["dirty"]) + if benchmark: + logger.debug("benchmark: %s, %s: tree %s, %s", benchmark["uri"], benchmark["type"], + (benchmark.get("tree") or "none")[:12], benchmark["dirty"]) + for what, state, changes, where, in_git in ( + ("subject", source["dirty"], source.get("changes"), source_dir, method == "git"), + ("benchmark", benchmark["dirty"] if benchmark else None, None, benchmark["uri"] if benchmark else None, + bool(benchmark) and benchmark["type"] == "git")): + if state == "dirty": + shown = (changes or [])[:10] + more = f", and {len(changes) - len(shown)} more" if changes and len(changes) > len(shown) else "" + if shown: + why = f": {'; '.join(shown)}{more}" + elif in_git: # a repository whose changes were not listed (the benchmark's are not) + why = "" + else: + why = " (not under git: a directory of files is always dirty)" + code = "dirty-subject-tree" if what == "subject" else "dirty-benchmark-tree" + logger.log(level(("dirty", what, str(where))), "the %s tree is dirty%s; every result carries %s", + what, why, code) + elif state == "unknown": # accepted here, so a result will say nothing about it: say it now + logger.warning("the %s tree's dirty state is unknown (%s): its results carry no tree id and no warning", + what, source.get("why_unknown", "git could not say")) + + +def _log_records(order, adapter, child_env, env_names, environment, system, configuration, setup, source, declared_text): + """What the order records, by name (DEBUG, once per order): never a value of the inherited environment.""" + if not logger.isEnabledFor(logging.DEBUG): + return + from_order = order.get("environment_variables", {}) + extra = {n.strip() for n in child_env.get("BENCHX_ENV_ALLOWLIST", "").split(",") if n.strip()} + + def origin(name): + return "core" if name in snapshot.ENV_ALLOWLIST else "$BENCHX_ENV_ALLOWLIST" if name in extra else "adapter" + allowed = [f"{n} ({origin(n)}; {'set by the order, enforced' if n in from_order else 'inherited, observed'})" + for n in env_names if n in child_env] + overriding = sorted(n for n in from_order if n in os.environ) + kept = set(declared_text) - {"target_provider"} | ({"provider"} if "target_provider" in declared_text else set()) + dropped = [f for f in target_mod.TEXT_FIELDS if f in order["target"] and f not in kept] + setup_file = Path(child_env.get("BENCHX_SETUP_FILE") or Path(source["path"]) / ".benchx" / "setup.json") + logger.debug("records: environment %s; system facts %s; allowlisted variables set: %s; the order's variables " + "that override an inherited one: %s", ", ".join(sorted(environment)) or "none", + ", ".join(sorted(system)) or "none", "; ".join(allowed) or "none", ", ".join(overriding) or "none") + logger.debug("records: CMake configuration %s; setup file %s; declared text fields kept %s, dropped as empty %s", + ", ".join(sorted(configuration)) or "none", setup_file if setup else "none read", + ", ".join(sorted(kept)) or "none", ", ".join(dropped) or "none") + + def run(order_path, out_dir, allow_collectors=False) -> dict: """Execute one order; write results and the order into out_dir. The order's context collectors are commands the runner would execute, so they run only if `allow_collectors`.""" inspection = core.inspect(Path(order_path), "work-order") if inspection.data is None: - raise Refused(inspection.errors) + _refuse(inspection.errors) order = inspection.data refusals = list(check(order)) if refusals: - raise Refused(refusals) + _refuse(refusals) if order.get("collectors") and not allow_collectors: - raise Refused([Refusal("the order names context collectors, which are commands to run; " - "pass --allow-collectors to run it")]) + _refuse([Refusal("the order names context collectors, which are commands to run; " + "pass --allow-collectors to run it")]) adapter = adapters.get(order["suites"][0]["adapter"]) applied_protocol, invocation = adapter.protocol(order["precision"]) + if logger.isEnabledFor(logging.DEBUG): + logger.debug("protocol: %s; invocation: %s", json.dumps(applied_protocol, sort_keys=True, default=str), + json.dumps(invocation, sort_keys=True, default=str)) target_path = Path(order["target"]["path"]).expanduser() child_env = {**os.environ, **order.get("environment_variables", {})} @@ -153,7 +305,8 @@ def run(order_path, out_dir, allow_collectors=False) -> dict: configuration = snapshot.cmake_configuration(target_path) if source is None: # runner.md §2: a result that cannot state its revision is a defect. - refusals.append(Refusal("cannot locate the checkout the target was built from; set target.source_dir")) + refusals.append(Refusal("cannot locate the checkout the target was built from " + f"({snapshot.why_no_checkout(target_path, source_dir)}); set target.source_dir")) benchmark = None if source is not None and getattr(adapter, "SUITE_IS_SOURCE", False): # The suite's own code, when it is not in the subject's checkout (runner-schema.md §3.3): @@ -163,7 +316,8 @@ def run(order_path, out_dir, allow_collectors=False) -> dict: elif "benchmark" in order: refusals.append(Refusal(f"{adapter.NAME} suites are the subject's own; the order names a benchmark source")) if refusals: - raise Refused(refusals) + _refuse(refusals) + _log_identity(runnable, source, benchmark, source_dir) parameters = dict(order.get("environment_variables", {})) environment = snapshot.environment() @@ -176,6 +330,7 @@ def run(order_path, out_dir, allow_collectors=False) -> dict: setup, setup_warning = snapshot.setup_facts(source["path"], child_env) if setup: system["setup"] = setup # declared; no placement rules in the implementation, so matched as a whole + _log_records(order, adapter, child_env, env_names, environment, system, configuration, setup, source, declared_text) out_dir = Path(out_dir) ref = core.order_ref(order) @@ -185,146 +340,220 @@ def run(order_path, out_dir, allow_collectors=False) -> dict: collected = collectors.run_all(order.get("collectors", []), declared=order["target"].get("how_built"), cwd=target_path, env=child_env, artifacts_dir=artifacts_dir, taken=system) if collected.refusals: - raise Refused(collected.refusals) + _refuse(collected.refusals) system.update(collected.system) order_file = out_dir / f"workorder-{ref[7:]}.json" order_file.write_bytes(core.pretty(order)) attempted = adapter.attempted(applied_protocol) + harness_verbosity = order.get("harness_verbosity", 0) + if harness_verbosity: + logger.info("the harness is asked to say more (harness_verbosity %d): its output is logged up to %d lines a " + "stream", harness_verbosity, VERBOSE_OUTPUT_LINES) + logger.info("listing the benchmarks of %s", order["suites"][0]["suite"]) # an asv listing imports a whole suite + listing_started = time.monotonic() try: cases = adapter.list_cases(runnable, order["suites"][0].get("filter"), child_env, timeout=order["timeouts"]["order_s"]) except Unsupported as e: - raise Refused(e.problems) from None + _refuse(e.problems) + logger.info("listed %d case(s) in %.1f s", len(cases), time.monotonic() - listing_started) if not cases: - raise Refused(no_cases(order["suites"][0]["suite"], order["suites"][0].get("filter")).problems) + _refuse(no_cases(order["suites"][0]["suite"], order["suites"][0].get("filter")).problems) workloads = [adapter.workload(case, runnable) if hasattr(adapter, "workload") else (case, {}) for case in cases] # Both share workload.parameters: a clash would overwrite the case's own value and merge distinct cases. clashes = sorted({name for _, case_parameters in workloads for name in case_parameters} & parameters.keys()) if clashes: - raise Refused([Refusal(f"environment variables named like workload parameters: {', '.join(clashes)}; " - "rename them")]) - written = [] - for index, case in enumerate(cases): - stem = f"{index:04d}" - native_path = artifacts_dir / f"{stem}.native.json" - load = snapshot.load_average() - # The wall clock can step backwards mid-case (NTP, WSL2 resyncs): the duration comes from a monotonic clock. - started, clock = time.time(), time.monotonic() - run_ = adapter.run_case(runnable, case, invocation, child_env, order["timeouts"]["case_s"], native_path, - env_names=env_names) - duration = time.monotonic() - clock - (artifacts_dir / f"{stem}.stdout").write_text(run_["stdout"]) - (artifacts_dir / f"{stem}.stderr").write_text(run_["stderr"]) - artifacts = [_artifact("stdout", "text/plain", artifacts_dir / f"{stem}.stdout"), - _artifact("stderr", "text/plain", artifacts_dir / f"{stem}.stderr")] - if native_path.exists(): - artifacts.insert(0, _artifact("native-output", "application/json", native_path)) - artifacts += [_artifact(kind, media_type, path) for kind, media_type, path in run_.get("artifacts", [])] - artifacts += [_artifact(kind, media_type, path) for kind, media_type, path in collected.artifacts] - native_system, native_info = adapter.context_facts(run_["native"]) - case_system, case_warnings = snapshot.merge(system, native_system), [] - if hasattr(adapter, "observed_environment"): - facts, case_warnings = adapter.observed_environment(run_, case, env_names) - case_system = snapshot.merge(case_system, facts) - attempt_key = f"urn:benchx:attempt:{ref[7:23]}:{index}" - workload_name, case_parameters = workloads[index] - case_parameters = {**case_parameters, **parameters} - # A harness whose benchmarks declare their own precision reports each case's own protocol. - case_protocol = (adapter.case_protocol(applied_protocol, run_, case) if hasattr(adapter, "case_protocol") - else applied_protocol) - protocol = {**case_protocol, "harness": adapter.harness(native_info)} - - for output in [*adapter.translate(case, order["quantities"], run_, attempted), _load_output(load)]: - condition = output["quantity"] is LOAD - procedure = dict(output["procedure"]) - if not condition: - procedure["duration_seconds"] = round(duration, 6) - if round_ is not None: - procedure["round"] = round_ - if slot is not None: - procedure["slot"] = slot - if not condition: - procedure["timeout_seconds"] = order["timeouts"]["case_s"] - if hasattr(adapter, "repetition_levels") and not condition: - procedure["repetition_levels"] = adapter.repetition_levels(applied_protocol, run_, case) - info = {"workorder_ref": ref, "requester": order["requester"], **output["info"]} - if native_info: - info[adapter.CONTEXT_KEY] = native_info - if "reason" in order: - info["reason"] = order["reason"] - info.update(declared_text) - provenance = { - "run_key": order["run_key"], - "started_at": _timestamp(started), - "ended_at": _timestamp(started + duration), - "subject_dirty": source["dirty"], - "benchmark_dirty": benchmark["dirty"] if benchmark else source["dirty"], - "runner": RUNNER, - **({} if condition else {"artifacts": artifacts}), - "info": info, - } - if "tree" in source: - provenance["subject_tree"] = provenance["benchmark_tree"] = source["tree"] - if benchmark: - provenance["benchmark_tree"] = benchmark["tree"] - if "labels" in order: - provenance["labels"] = order["labels"] - workload = {"name": workload_name} - if case_parameters: - workload["parameters"] = case_parameters - if len(case_parameters) > 1: # the store sorts keys: the order is data (projection.declared_workload) - info["parameter_names"] = list(case_parameters) - subject = {"name": _subject_name(order), "components": [{"role": "primary"}]} - if configuration: - subject["configuration"] = configuration - key = ingest_key(order["run_key"], workload_name, case_parameters, output["quantity"]["name"], slot) - document = { - "schema_version": core.catalog.MEASUREMENT_RESULT, - "producer": PROBE_PRODUCER if condition else adapter.PRODUCER, - "ingest_key": key, - "attempt_key": attempt_key, - **({"project": order["project"]} if "project" in order else {}), - "source": order["target"]["source"], - "revision": {"key": source["revision"]}, - "benchmark": ({"source": {"uri": benchmark["uri"], "type": benchmark["type"]}, - **({"revision": {"key": benchmark["revision"]}} if "revision" in benchmark else {})} - if benchmark else - {"source": order["target"]["source"], - # An unversioned tree is identified by its hash in provenance, not by a revision. - **({} if source["revision"].startswith("directory-") - else {"revision": {"key": source["revision"]}})}), - "coordinates": { - "workload": workload, - "subject": subject, - # A condition measurement's protocol is its probe alone (schema §4.4). - "protocol": {"probe": LOAD_PROBE} if condition else protocol, - "environment": {**environment, "system": case_system}, - }, - "measurement": {"quantity": output["quantity"], **output["measurement"]}, - "procedure": procedure, - "provenance": provenance, - } - # A result says so when its subject or benchmark tree is dirty (schema §4.1). - dirty = [code for flag, code in snapshot.DIRTY_WARNINGS if provenance[flag] == "dirty"] - warnings = [] if condition else (dirty + ([setup_warning] if setup_warning else []) - + collected.warnings + case_warnings) - if warnings: - document["quality"] = {"warnings": warnings} - errors = core.check(document, "measurement-result") - if errors: - # harness-adapter.md §4.1: never drop a case, never emit an invalid document. - document["measurement"] = {"quantity": output["quantity"], - **({"kind": "condition"} if condition else {}), - "status": "error", "reason": "adapter.mapping-failed"} - document["provenance"]["info"]["mapping_error"] = str(errors[0]) - document["procedure"] = {k: v for k, v in procedure.items() - if k not in ("inner_iterations", "completed_repetitions", "repetition_levels")} + _refuse([Refusal(f"environment variables named like workload parameters: {', '.join(clashes)}; " + "rename them")]) + logger.info("order %s: %s, %d case(s)", ref[:19], adapter.NAME, len(cases)) + written, overwritten, counts, named_once = [], [], collections.Counter(), set() + state, order_started, nonzero = {"done": 0}, time.monotonic(), False + with _partial(state, len(cases), out_dir): + for index, case in enumerate(cases): + stem = f"{index:04d}" + native_path = artifacts_dir / f"{stem}.native.json" + label = f"case {index + 1}/{len(cases)} {case}" + # before the clock starts: nothing is logged while a case runs + logger.info("%s: starting, limit %g s", label, order["timeouts"]["case_s"]) + if logger.isEnabledFor(logging.DEBUG): + logger.debug("%s: workload %s; %s", label, workloads[index][0], + _parameters_text(workloads[index][1], parameters)) + load = snapshot.load_average() + # The wall clock can step backwards mid-case (NTP, WSL2 resyncs): the duration comes from a monotonic clock. + started, clock = time.time(), time.monotonic() + run_ = adapter.run_case(runnable, case, invocation, child_env, order["timeouts"]["case_s"], native_path, + env_names=env_names, + **({"harness_verbosity": harness_verbosity} if harness_verbosity else {})) + duration = time.monotonic() - clock + (artifacts_dir / f"{stem}.stdout").write_text(run_["stdout"]) + (artifacts_dir / f"{stem}.stderr").write_text(run_["stderr"]) + artifacts = [_artifact("stdout", "text/plain", artifacts_dir / f"{stem}.stdout"), + _artifact("stderr", "text/plain", artifacts_dir / f"{stem}.stderr")] + if native_path.exists(): + artifacts.insert(0, _artifact("native-output", "application/json", native_path)) + artifacts += [_artifact(kind, media_type, path) for kind, media_type, path in run_.get("artifacts", [])] + artifacts += [_artifact(kind, media_type, path) for kind, media_type, path in collected.artifacts] + native_system, native_info = adapter.context_facts(run_["native"]) + scaling = native_system.get("cpu", {}).get("scaling_enabled") is True + debug_build = native_info.get("library_build_type") == "debug" + # recorded in the result, flagged nowhere else; each condition once, so that a side with one does not + # spend the warning of a side with the other + noisy = [text for flag, key, text in ((scaling, "scaling", "CPU frequency scaling is enabled"), + (debug_build, "debug", "the benchmark library is a debug build")) + if flag and log.once(("noisy-context", key))] + if noisy: + logger.warning("%s: the harness's own context says %s", label, " and ".join(noisy)) + case_system, case_warnings = snapshot.merge(system, native_system), [] + if hasattr(adapter, "observed_environment"): + facts, case_warnings = adapter.observed_environment(run_, case, env_names) + case_system = snapshot.merge(case_system, facts) + if log.once("overlap") and (clash := _overlap(system, case_system)): + # what the harness reported replaces what the runner read (snapshot.merge: the harness wins) + logger.debug("the harness's facts replace the context's at: %s", ", ".join(clash)) + attempt_key = f"urn:benchx:attempt:{ref[7:23]}:{index}" + workload_name, case_parameters = workloads[index] + case_parameters = {**case_parameters, **parameters} + # A harness whose benchmarks declare their own precision reports each case's own protocol. + case_protocol = (adapter.case_protocol(applied_protocol, run_, case) if hasattr(adapter, "case_protocol") + else applied_protocol) + protocol = {**case_protocol, "harness": adapter.harness(native_info)} + + results, case_paths = [], [] + for output in [*adapter.translate(case, order["quantities"], run_, attempted), _load_output(load)]: + condition = output["quantity"] is LOAD + procedure = dict(output["procedure"]) + if not condition: + procedure["duration_seconds"] = round(duration, 6) + if round_ is not None: + procedure["round"] = round_ + if slot is not None: + procedure["slot"] = slot + if not condition: + procedure["timeout_seconds"] = order["timeouts"]["case_s"] + if hasattr(adapter, "repetition_levels") and not condition: + procedure["repetition_levels"] = adapter.repetition_levels(applied_protocol, run_, case) + info = {"workorder_ref": ref, "requester": order["requester"], **output["info"]} + if harness_verbosity: # the output between samples is the harness's own: say that it was asked for + info["harness_verbosity"] = harness_verbosity + if native_info: + info[adapter.CONTEXT_KEY] = native_info + if "reason" in order: + info["reason"] = order["reason"] + info.update(declared_text) + provenance = { + "run_key": order["run_key"], + "started_at": _timestamp(started), + "ended_at": _timestamp(started + duration), + "subject_dirty": source["dirty"], + "benchmark_dirty": benchmark["dirty"] if benchmark else source["dirty"], + "runner": RUNNER, + **({} if condition else {"artifacts": artifacts}), + "info": info, + } + if "tree" in source: + provenance["subject_tree"] = provenance["benchmark_tree"] = source["tree"] + if benchmark: + provenance["benchmark_tree"] = benchmark["tree"] + if "labels" in order: + provenance["labels"] = order["labels"] + workload = {"name": workload_name} + if case_parameters: + workload["parameters"] = case_parameters + if len(case_parameters) > 1: # the store sorts keys: the order is data (projection.declared_workload) + info["parameter_names"] = list(case_parameters) + subject = {"name": _subject_name(order), "components": [{"role": "primary"}]} + if configuration: + subject["configuration"] = configuration + key = ingest_key(order["run_key"], workload_name, case_parameters, output["quantity"]["name"], slot) + document = { + "schema_version": core.catalog.MEASUREMENT_RESULT, + "producer": PROBE_PRODUCER if condition else adapter.PRODUCER, + "ingest_key": key, + "attempt_key": attempt_key, + **({"project": order["project"]} if "project" in order else {}), + "source": order["target"]["source"], + "revision": {"key": source["revision"]}, + "benchmark": ({"source": {"uri": benchmark["uri"], "type": benchmark["type"]}, + **({"revision": {"key": benchmark["revision"]}} if "revision" in benchmark else {})} + if benchmark else + {"source": order["target"]["source"], + # An unversioned tree is identified by its hash in provenance, not by a revision. + **({} if source["revision"].startswith("directory-") + else {"revision": {"key": source["revision"]}})}), + "coordinates": { + "workload": workload, + "subject": subject, + # A condition measurement's protocol is its probe alone (schema §4.4). + "protocol": {"probe": LOAD_PROBE} if condition else protocol, + "environment": {**environment, "system": case_system}, + }, + "measurement": {"quantity": output["quantity"], **output["measurement"]}, + "procedure": procedure, + "provenance": provenance, + } + # A result says so when its subject or benchmark tree is dirty (schema §4.1). + dirty = [code for flag, code in snapshot.DIRTY_WARNINGS if provenance[flag] == "dirty"] + warnings = [] if condition else (dirty + ([setup_warning] if setup_warning else []) + + collected.warnings + case_warnings) + if warnings: + document["quality"] = {"warnings": warnings} errors = core.check(document, "measurement-result") if errors: - raise RuntimeError(f"the error result is itself invalid: {errors[0]}") - path = out_dir / file_name(key) - path.write_bytes(core.pretty(document)) - written.append(path) + # harness-adapter.md §4.1: never drop a case, never emit an invalid document. + document["measurement"] = {"quantity": output["quantity"], + **({"kind": "condition"} if condition else {}), + "status": "error", "reason": "adapter.mapping-failed"} + document["provenance"]["info"]["mapping_error"] = str(errors[0]) + logger.warning("%s: result %s (%s) fell back to adapter.mapping-failed: %s", label, key, + output["quantity"]["name"], "; ".join(str(error) for error in errors[:5])) + document["procedure"] = {k: v for k, v in procedure.items() + if k not in ("inner_iterations", "completed_repetitions", "repetition_levels")} + errors = core.check(document, "measurement-result") + if errors: + raise RuntimeError(f"the error result is itself invalid: {errors[0]}") + path = out_dir / file_name(key) + if path.exists(): # a rerun of a run key: the store will refuse these results, and the folder says otherwise + overwritten.append(path) + if len(overwritten) == 1: + logger.warning("%s: result file %s exists and is overwritten, and so are the case's files under %s", + label, path, artifacts_dir) + path.write_bytes(core.pretty(document)) + written.append(path) + case_paths.append(path) + if not condition: + results.append((document["measurement"]["status"], document["measurement"].get("reason"), document)) + details = adapter.explain_warnings(run_, case, case_warnings) if hasattr(adapter, "explain_warnings") else {} + if "setup-per-call-unbatched" in case_warnings: + observations = next((d["measurement"]["observations"] for _, _, d in results + if d["measurement"].get("observations")), None) + values = [o["value"] if isinstance(o, dict) else o for o in observations or []] # as the comparator reads them + if values: + details["setup-per-call-unbatched"] = (f"median {statistics.median(values):.3g} s, " + f"minimum {min(values):.3g} s") + level, line, bad = _case_line(results, case_warnings, run_, duration, load, details) + logger.log(level, "%s: %s", label, line) + if logger.isEnabledFor(logging.DEBUG): + shown = [f"{a['kind']} {_path_of(a['uri'])}" for a in artifacts + if a["kind"] not in SHARED_ARTIFACTS or a["kind"] not in named_once] + named_once.update(a["kind"] for a in artifacts if a["kind"] in SHARED_ARTIFACTS) + logger.debug("%s files: %s, results %d %s", label, ", ".join(shown), len(case_paths), + case_paths[0] if case_paths else "") + cap = VERBOSE_OUTPUT_LINES if harness_verbosity else 40 + log.harness_output(logger, label, "stdout", run_["stdout"], failed=bad, kept_at=artifacts_dir / f"{stem}.stdout", + limit=cap) + log.harness_output(logger, label, "stderr", run_["stderr"], failed=bad, kept_at=artifacts_dir / f"{stem}.stderr", + limit=cap) + counts.update(status for status, _, _ in results) + nonzero = nonzero or run_["exit_status"] not in (0, None) + state["done"] += 1 + took = time.monotonic() - order_started + logger.log(logging.WARNING if {"error", "partial"} & set(counts) or nonzero else logging.INFO, + "order %s: %d case(s), results: %s, %.1f s", ref[:19], len(cases), + ", ".join(f"{status} {n}" for status, n in sorted(counts.items())) or "none", took) + if overwritten: + logger.warning("order %s: %d result file(s) in %s were overwritten by a rerun of run key %s; the store keeps " + "the first results of a key and slot and refuses these", ref[:19], len(overwritten), out_dir, + order["run_key"]) return {"order": ref, "cases": len(cases), "results": len(written), "out": str(out_dir), "files": [order_file, *written]} diff --git a/src/benchx/schemas/config/0.1.0/schema.json b/src/benchx/schemas/config/0.1.0/schema.json index 89181120..8ff4a952 100644 --- a/src/benchx/schemas/config/0.1.0/schema.json +++ b/src/benchx/schemas/config/0.1.0/schema.json @@ -42,6 +42,7 @@ "type": "string", "minLength": 1 }, + "verbosity": { "description": "How much the harness itself is asked to say: 0 (the default), or more (pyperf and asv: --verbose; Google Benchmark: --v=N). The same as --harness-verbosity.", "type": "integer", "minimum": 0 }, "quantities": { "description": "What one run collects, from those the harness reports.", "type": "array", @@ -98,6 +99,17 @@ "k": { "type": "number", "exclusiveMinimum": 0 }, "min_rounds": { "type": "integer", "minimum": 1 } } + }, + "logging": { + "description": "Diagnostics: false (off), true (to stderr), or a file to append to, relative to this file's directory. {out} in the path is the run's output folder and {root} the project root, as in collectors. Default: {out}/bx.log.", + "oneOf": [ + { "type": "boolean" }, + { "type": "string", "minLength": 1, "not": { "pattern": "\\.json$" } } + ] + }, + "log_level": { + "description": "Level of what the log keeps: debug (the default), info, warning or error.", + "enum": ["debug", "info", "warning", "error"] } } } diff --git a/src/benchx/schemas/work-order/0.1.0/schema.json b/src/benchx/schemas/work-order/0.1.0/schema.json index 46d17913..a00fa26b 100644 --- a/src/benchx/schemas/work-order/0.1.0/schema.json +++ b/src/benchx/schemas/work-order/0.1.0/schema.json @@ -205,6 +205,11 @@ "version": { "$ref": "#/$defs/nonEmptyString" } } }, + "harness_verbosity": { + "description": "How much the harness itself is asked to say (benchx extension): 0 or absent, nothing more than today. pyperf and asv: 1 or more passes --verbose; Google Benchmark: N is passed as --v=N. It is not part of the measurement's identity.", + "type": "integer", + "minimum": 0 + }, "environment_variables": { "description": "Environment variables set for the measured process, on top of the environment the runner inherited. Workload coordinates, not machine facts: each name and value is copied into coordinates.workload.parameters, so a run at OMP_NUM_THREADS=1 and one at 10 are different, non-pooling workload variants. Values are strings; one order carries one assignment.", "type": "object", diff --git a/src/benchx/session.py b/src/benchx/session.py index 0b554f4e..1399835d 100644 --- a/src/benchx/session.py +++ b/src/benchx/session.py @@ -16,8 +16,11 @@ of one value, then the other's. """ +import contextlib import json +import logging import os +import time from pathlib import Path from . import adapters, harnesses, orders, runner, snapshot, target as target_mod @@ -58,9 +61,12 @@ def parse_label(text: str) -> tuple[str, str, str]: KINDS = ("build", "working_tree") +logger = logging.getLogger(__name__) +MAX_LOGGED = 40 # the log's cap on a list, like its other lists + def _side(spec: str, suite: str, operation: str, harness, environment_variables=None, provider=None, - timeout=None) -> dict: + timeout=None, name=None) -> dict: """Locate and identify one side before anything runs. `spec` is `@CONFIG[=SOURCE_REF]` (ask the provider to `operation`) or a @@ -74,6 +80,7 @@ def _side(spec: str, suite: str, operation: str, harness, environment_variables= try: description = target_mod.resolve(spec, operation=operation, provider=provider) except target_mod.TargetError as e: + logger.debug("%s: the target could not be resolved: %s", name or "target", e) raise SessionError(str(e)) from None source = None if description: @@ -99,6 +106,8 @@ def _side(spec: str, suite: str, operation: str, harness, environment_variables= adapters.get(harness.name).locate(path, suite, {**os.environ, **(environment_variables or {})}, timeout=timeout) except Unsupported as e: + logger.debug("%s: the %s adapter refused %s: %s", name or "target", harness.name, spec, + " | ".join(str(problem) for problem in e.problems)) raise SessionError("; ".join(str(problem) for problem in e.problems)) from None if kind == "build" and ":" in spec and not spec.startswith("@"): source = parse_target(spec)[1] or source @@ -106,12 +115,19 @@ def _side(spec: str, suite: str, operation: str, harness, environment_variables= source = source or snapshot.cmake_source_dir(path) identity = source and snapshot.git_identity(source) if not identity: - raise SessionError(f"cannot locate the checkout {path} was built from; give BUILD_DIR:SOURCE_DIR") + raise SessionError(f"cannot locate the checkout {path} was built from " + f"({snapshot.why_no_checkout(path, source)}); give BUILD_DIR:SOURCE_DIR") else: identity = snapshot.git_identity(source) or snapshot.directory_identity(source) if not identity: raise SessionError(f"cannot identify the working tree {source}") + snapshot.note_identity_fallback(identity) found = _found_benchmark(harness, path, suite, identity["path"]) + how = ("a provider (the project's target provider) answered " + operation if spec.startswith("@") + else "a sidecar in the build directory" if description else "a bare path, read by the harness") + logger.debug("%s: %s, found by %s: a %s at %s, source %s, revision %s, tree %s, %s; benchmark %s", name or "target", + spec, how, kind, path, identity["path"], identity["revision"][:12], (identity.get("tree") or "none")[:12], + identity["dirty"], f"{found['type']} {found['uri']}, {found['dirty']}" if found else "in the subject's tree") return {"kind": kind, "path": path, "source": identity["path"], "identity": identity, "uri": uri, "benchmark": _benchmark(found), # As the runner records it: a benchmark in the subject's tree is dirty as the subject is. @@ -141,9 +157,16 @@ def _benchmark(found: dict | None) -> dict | None: **({"revision": found["revision"]} if "revision" in found else {})} +def run_directory(results_dir, run_key: str) -> Path: + """Where a run's orders, artifacts and result files go when `--out` names no folder: its + run key, `/` made `_`, under the results directory. The one place that builds it, so the CLI + can name the folder (and put the log in it) before the session starts.""" + return Path(results_dir or "results") / run_key.replace("/", "_") + + def _order(side: dict, *, harness, suite, filter, quantities, precision, environment_variables, project, run_key, source_uri, round_=None, slot=None, labels=None, case_s=orders.CASE_TIMEOUT_S, - order_s=orders.ORDER_TIMEOUT_S, collectors=None) -> dict: + order_s=orders.ORDER_TIMEOUT_S, collectors=None, harness_verbosity=0) -> dict: """One side's order; for one round and slot of a comparison, or neither (`bx bench`).""" target = {"kind": side["kind"], "path": str(side["path"]), "source_dir": side["source"], "source": {"uri": source_uri, "type": "git"}, **side["text"]} @@ -152,8 +175,10 @@ def _order(side: dict, *, harness, suite, filter, quantities, precision, environ quantities=quantities, run_key=run_key, project=project, labels={**side["labels"], **(labels or {})}, case_s=case_s, order_s=order_s, environment_variables=environment_variables, round_=round_, slot=slot, - benchmark=side.get("benchmark"), collectors=collectors) + benchmark=side.get("benchmark"), collectors=collectors, + harness_verbosity=harness_verbosity) except orders.OrderError as e: + logger.debug("the work order is not valid: %s", e) # the problems, before the SessionError replaces them raise SessionError(f"work order{'' if round_ is None else f' for round {round_}'}: {e}") from None @@ -169,6 +194,8 @@ def _harness(adapter, flags, file_precision=None, quantities=None) -> tuple: try: adapters.get(harness.name).protocol(precision) except Unsupported as e: + logger.debug("the %s adapter cannot apply the precision: %s", harness.name, + " | ".join(str(problem) for problem in e.problems)) raise SessionError("; ".join(str(problem) for problem in e.problems)) from None unknown = sorted(set(quantities or ()) - set(adapters.get(harness.name).QUANTITIES)) if unknown: @@ -176,34 +203,81 @@ def _harness(adapter, flags, file_precision=None, quantities=None) -> tuple: return harness, precision +def check_harness(adapter, flags, file_precision=None, quantities=None) -> None: + """SessionError for a flag the harness does not take, or a precision or quantity it cannot + apply. The CLI calls it in its check phase, so such a refusal comes before the log is + started and leaves no output folder (the session repeats it, at no cost).""" + _harness(adapter, flags, file_precision, quantities) + + def _source_uri(sides, source_uri) -> str: """The one URI the sides' source is known by; SessionError if they disagree.""" if source_uri: - uris = {normalize_remote(source_uri)} + uris, origin = {normalize_remote(source_uri)}, "--source-uri or source.uri" else: uris = {normalize_remote(side["uri"], base=side["source"]) if side["uri"] else snapshot.source_uri(side["source"]) for side in sides} + origin = ("a side's description, or the origin remote of its checkout (else the git directory's parent, " + "else a file:// URI of the directory)") if len(uris) != 1: raise SessionError(f"the sides report different source URIs {sorted(uris)}; pass --source-uri") + logger.debug("the source URI is %s, from %s", next(iter(uris)), origin) return uris.pop() -def _run_side(side: dict, path: Path, store=None, **order) -> tuple[dict, dict | None]: +def _run_side(side: dict, path: Path, store=None, *, title="the order", **order) -> tuple[dict, dict | None]: """Write one side's order to `path`, run it (results go beside `orders/`), and deliver them to `store` unless it is None. The runner's summary, and the - store's outcome (None without a store).""" + store's outcome (None without a store). `title` names the slot in the log.""" path.parent.mkdir(parents=True, exist_ok=True) path.write_text(json.dumps(_order(side, **order), indent=1) + "\n") + logger.info("%s: order %s", title, path) # before the wait it describes + started = time.monotonic() # The order is this session's own, built from the user's configuration: its collectors may run. summary = runner.run(path, path.parent.parent, allow_collectors=True) - return summary, store.ingest_paths(summary["files"]) if store else None + logger.debug("%s: work order %s; output %s; artifacts %s", title, summary["files"][0], summary["out"], + Path(summary["out"]) / "artifacts") # the work order holds the -e values: the path, never the content + try: + outcome = store.ingest_paths(summary["files"]) if store else None + except BaseException: + logger.error("%s: the results are in %s, not delivered to the store; bx ingest %s stores them", title, + summary["out"], summary["out"]) + raise + delivered = (f"; store: ingested {outcome['ingested']}, duplicate {outcome['duplicate']}, rejected " + f"{len(outcome['rejected'])}") if outcome else "" + logger.info("%s: %d case(s), %d result(s)%s, %.1f s", title, summary["cases"], summary["results"], delivered, + time.monotonic() - started) + return summary, outcome + + +def _rejected(outcome, where) -> None: + """The store refused results during a comparison: each rejection (at most MAX_LOGGED), where `bx bench` + prints them, with the round and side.""" + for r in outcome["rejected"][:MAX_LOGGED]: + logger.warning("%s: rejected %s: %s: %s", where, r["document"], r["code"], r["message"]) + if len(outcome["rejected"]) > MAX_LOGGED: + logger.warning("%s: and %d more rejected", where, len(outcome["rejected"]) - MAX_LOGGED) + + +@contextlib.contextmanager +def _stopped(slot, run_key, store, where): + """A round that is interrupted or fails after an earlier slot was ingested: say how much is in the + store and how to compare it. The exception goes on.""" + try: + yield + except BaseException as error: + if slot: + logger.log(logging.ERROR if isinstance(error, Exception) else logging.WARNING, + "stopped in %s after %d slot(s) were ingested into %s; bx compare --run %s compares what is there", + where, slot, store.path, run_key) + raise def bench_target(target: str, *, suite: str, adapter: str, store=None, flags=None, file_precision=None, environment_variables=None, filter=None, quantities=("wall-time",), project=None, run_key=None, out=None, source_uri=None, case_s=orders.CASE_TIMEOUT_S, order_s=orders.ORDER_TIMEOUT_S, progress=None, build=True, provider=None, config_path=None, results_dir=None, - collectors=None, round_=None, slot=None, labels=None) -> dict: + collectors=None, round_=None, slot=None, labels=None, harness_verbosity=0) -> dict: """Run one target once: a comparison session of one order, with no comparison. It has a round, a slot and labels when the caller places it in a session that other calls join through the same run key. Results are delivered to `store` @@ -220,14 +294,19 @@ def bench_target(target: str, *, suite: str, adapter: str, store=None, flags=Non timeout=order_s) source_uri = _source_uri([side], source_uri) run_key = run_key or orders.default_run_key("bench") - out = Path(out) if out else Path(results_dir or "results") / run_key.replace("/", "_") + out = Path(out) if out else run_directory(results_dir, run_key) + placed = "".join([f", round {round_}" if round_ is not None else "", f", slot {slot}" if slot is not None else "", + f", labels {labels}" if labels else ""]) + logger.info("run key %s, output %s%s", run_key, out, placed) if progress: progress(f"precision: {harness.describe_precision(precision, config_path)}") order_file = "order.json" if slot is None else f"order-{slot:04d}.json" # one per slot, as compare_targets - summary, outcome = _run_side(side, out / "orders" / order_file, store, harness=harness, suite=suite, + summary, outcome = _run_side(side, out / "orders" / order_file, store, title=f"slot {slot}" if slot is not None else "the order", + harness=harness, suite=suite, filter=filter, quantities=quantities, precision=precision, environment_variables=environment_variables, project=project, run_key=run_key, source_uri=source_uri, case_s=case_s, order_s=order_s, collectors=collectors, + harness_verbosity=harness_verbosity, round_=round_, slot=slot, labels=labels) return {**summary, "outcome": outcome, "precision": precision} @@ -238,15 +317,16 @@ def _refuse_unknown_tree(side: dict, name: str | None = None) -> None: after R rounds. `name` says which side of a comparison, when there are two.""" if side["identity"]["dirty"] == "unknown": # schema §4.1: no tree id exactly when unknown who = f"{name} tree" if name else "tree" + cause = side["identity"].get("why_unknown") raise SessionError(f"{who} {side['source']} has no working-tree id (its dirty state is " - f"{side['identity']['dirty']}): the sides cannot be told apart, or checked for " - "a change during the run. Make every file in the tree readable, or git-ignore " - "it (UC-03 §10)") + f"{side['identity']['dirty']}{f'; {cause}' if cause else ''}): the sides cannot be told " + "apart, or checked for a change during the run. Make every file in the tree readable, " + "or git-ignore it (UC-03 §10)") def _note_local_only(progress, sides) -> None: """Say before measuring which (name, side) pairs are not clean: the comparison will be local-only. - TODO: log these at logging.WARNING once benchx has logging (plan, Q13).""" + The messages are INFO, not WARNING: comparing uncommitted work is the expected case.""" for name, side in sides: for what, state in (("tree", side["identity"]["dirty"]), ("benchmark file", side["benchmark_dirty"] if side["benchmark"] else "clean")): @@ -260,7 +340,7 @@ def compare_targets(baseline: str, contender: str, *, profile: str, suite: str, quantities=("wall-time",), project=None, label=None, run_key=None, out=None, source_uri=None, k=3.0, min_rounds=3, progress=None, build=True, provider=None, results_dir=None, case_s=orders.CASE_TIMEOUT_S, order_s=orders.ORDER_TIMEOUT_S, config_path=None, - collectors=None) -> dict: + collectors=None, harness_verbosity=0) -> dict: """Alternate baseline and contender over `rounds` rounds, deliver every result to `store`, and return the run-mode comparison document. @@ -290,8 +370,8 @@ def compare_targets(baseline: str, contender: str, *, profile: str, suite: str, raise SessionError("--label names the sides of an environments comparison; revisions are named by their trees") harness, precision = _harness(adapter, flags, file_precision, quantities) operation = "prepare" if build else "describe" - sides = [_side(spec, suite, operation, harness, environment_variables, provider, - timeout=order_s) for spec in (baseline, contender)] + sides = [_side(spec, suite, operation, harness, environment_variables, provider, timeout=order_s, name=name) + for name, spec in (("baseline", baseline), ("contender", contender))] if profile == "revisions": for name, side in zip(("baseline", "contender"), sides): _refuse_unknown_tree(side, name) @@ -299,24 +379,35 @@ def compare_targets(baseline: str, contender: str, *, profile: str, suite: str, _note_local_only(progress, zip(("baseline", "contender"), sides)) source_uri = _source_uri(sides, source_uri) if len({json.dumps((side.get("benchmark") or {}).get("source")) for side in sides}) != 1: + logger.debug("the sides' benchmark sources: %s", "; ".join( + f"{name} {(side.get('benchmark') or {}).get('source') or 'the subject own tree'}" + for name, side in zip(("baseline", "contender"), sides))) raise SessionError("the sides' suites come from different sources; give --suite as one absolute path") run_key = run_key or orders.default_run_key("compare") - out = Path(out) if out else Path(results_dir or "results") / run_key.replace("/", "_") + out = Path(out) if out else run_directory(results_dir, run_key) labels = [{label[0]: label[1]}, {label[0]: label[2]}] if label else [None, None] + logger.info("run key %s, output %s, %d round(s)", run_key, out, rounds) + logger.debug("the baseline value for the comparison is %s: %s, and the baseline runs first in every round", + label[1] if profile == "environments" else sides[0]["identity"].get("tree"), + "the first label value" if profile == "environments" else "the first target's tree id") slot = 0 for round_ in range(rounds): for name, side, side_labels in zip(("baseline", "contender"), sides, labels): - summary, outcome = _run_side(side, out / "orders" / f"order-{slot:04d}.json", store, - harness=harness, suite=suite, filter=filter, quantities=quantities, - precision=precision, environment_variables=environment_variables, - project=project, run_key=run_key, source_uri=source_uri, - round_=round_, slot=slot, labels=side_labels, case_s=case_s, order_s=order_s, - collectors=collectors) - if outcome["rejected"]: - codes = sorted({r["code"] for r in outcome["rejected"]}) - raise SessionError(f"the store rejected results of round {round_} ({name}): {', '.join(codes)}") + title = f"slot {slot + 1}/{rounds * 2}, round {round_ + 1}/{rounds}, {name}" + with _stopped(slot, run_key, store, title): + summary, outcome = _run_side(side, out / "orders" / f"order-{slot:04d}.json", store, title=title, + harness=harness, suite=suite, filter=filter, quantities=quantities, + precision=precision, environment_variables=environment_variables, + project=project, run_key=run_key, source_uri=source_uri, + round_=round_, slot=slot, labels=side_labels, case_s=case_s, + order_s=order_s, collectors=collectors, + harness_verbosity=harness_verbosity) + if outcome["rejected"]: + _rejected(outcome, title) + codes = sorted({r["code"] for r in outcome["rejected"]}) + 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)") slot += 1 @@ -402,7 +493,7 @@ def compare_variants(target: str, *, suite: str, rounds: int, store, adapter, pa quantities=("wall-time",), project=None, run_key=None, out=None, source_uri=None, k=3.0, min_rounds=3, progress=None, build=True, provider=None, results_dir=None, case_s=orders.CASE_TIMEOUT_S, order_s=orders.ORDER_TIMEOUT_S, config_path=None, - collectors=None) -> dict: + collectors=None, harness_verbosity=0) -> dict: """Alternate the two values of one workload parameter of one target over `rounds` rounds, deliver every result to `store`, and return the run-mode comparison document (UC-02). @@ -434,6 +525,7 @@ def compare_variants(target: str, *, suite: str, rounds: int, store, adapter, pa runnable = module.locate(side["path"], suite, env, timeout=order_s) cases = module.list_cases(runnable, filter, env, timeout=order_s) except Unsupported as e: + logger.debug("listing the cases was refused: %s", " | ".join(str(problem) for problem in e.problems)) raise SessionError("; ".join(str(problem) for problem in e.problems)) from None if parameter is None: parameter = _infer_parameter(runnable, environment_variables) @@ -451,22 +543,36 @@ def compare_variants(target: str, *, suite: str, rounds: int, store, adapter, pa progress(f"not run on either side (no parameter {parameter}): {', '.join(without)}") run_key = run_key or orders.default_run_key("compare") - out = Path(out) if out else Path(results_dir or "results") / run_key.replace("/", "_") + out = Path(out) if out else run_directory(results_dir, run_key) filters = {value: harnesses.exact_filter(by_value[value], arguments=True) for value in values} + logger.info("run key %s, output %s, %d round(s)", run_key, out, rounds) + logger.info("varying %s: baseline %s, contender %s; %s", parameter, baseline, contender, + ", ".join(f"{len(by_value[value])} case(s) with {value}" for value in values)) + if logger.isEnabledFor(logging.DEBUG): + declared = _declared_by(runnable, environment_variables) + logger.debug("parameters declared: %s", "; ".join(f"{name}: {', '.join(who)}" for name, who in declared.items())) + for value in values: + shown = by_value[value][:MAX_LOGGED] + more = f", and {len(by_value[value]) - len(shown)} more" if len(by_value[value]) > len(shown) else "" + logger.debug("%s=%s runs filter %s: %s%s", parameter, value, filters[value], ", ".join(shown), more) slot = 0 for round_ in range(rounds): for value in (baseline, contender): - summary, outcome = _run_side(side, out / "orders" / f"order-{slot:04d}.json", store, - harness=harness, suite=suite, filter=filters[value], quantities=quantities, - precision=precision, environment_variables=environment_variables, - project=project, run_key=run_key, source_uri=source_uri, - round_=round_, slot=slot, case_s=case_s, order_s=order_s, - collectors=collectors) - if outcome["rejected"]: - codes = sorted({r["code"] for r in outcome["rejected"]}) - raise SessionError(f"the store rejected results of round {round_} ({parameter}={value}): " - f"{', '.join(codes)}") + title = f"slot {slot + 1}/{rounds * 2}, round {round_ + 1}/{rounds}, {parameter}={value}" + with _stopped(slot, run_key, store, title): + summary, outcome = _run_side(side, out / "orders" / f"order-{slot:04d}.json", store, title=title, + harness=harness, suite=suite, filter=filters[value], + quantities=quantities, precision=precision, + environment_variables=environment_variables, project=project, + run_key=run_key, source_uri=source_uri, round_=round_, slot=slot, + case_s=case_s, order_s=order_s, collectors=collectors, + harness_verbosity=harness_verbosity) + if outcome["rejected"]: + _rejected(outcome, title) + codes = sorted({r["code"] for r in outcome["rejected"]}) + raise SessionError(f"the store rejected results of round {round_} ({parameter}={value}): " + f"{', '.join(codes)}") if progress: progress(f"round {round_ + 1}/{rounds} {parameter}={value}: {summary['results']} result(s)") slot += 1 diff --git a/src/benchx/snapshot.py b/src/benchx/snapshot.py index e78f714a..9875ebea 100644 --- a/src/benchx/snapshot.py +++ b/src/benchx/snapshot.py @@ -6,16 +6,21 @@ import hashlib import json +import logging import os import platform import re import socket import subprocess import tempfile +import time from pathlib import Path +from . import log from .identity import normalize_remote +logger = logging.getLogger(__name__) + # §3.1: never the whole environment; only variables that shape execution: the # thread and device variables, and the dynamic loader's search variables. No # build or environment management tool is named; a project extends the list @@ -43,7 +48,12 @@ def env_allowlist(env: dict, adapter_names=()) -> tuple: def _run(args, cwd=None): try: out = subprocess.run(args, cwd=cwd, capture_output=True, text=True, check=True) - except (OSError, subprocess.CalledProcessError): + except OSError as e: + logger.debug("%s failed in %s: %s", log.command(args), cwd or Path.cwd(), e) + return None + except subprocess.CalledProcessError as e: + logger.debug("%s failed in %s: exit %d: %s", log.command(args), cwd or Path.cwd(), e.returncode, + " | ".join((e.stderr or "").strip().splitlines()[:3])) return None return out.stdout.strip() @@ -51,7 +61,9 @@ def _run(args, cwd=None): def _read(path): try: return Path(path).read_text().strip() - except OSError: + except OSError as e: + if log.once(("unreadable", str(path))): # read for every order: say it once per command + logger.debug("cannot read %s: %s", path, e.strerror or e) return None @@ -60,6 +72,9 @@ def _cpu_model(): return _run(["sysctl", "-n", "machdep.cpu.brand_string"]) text = _read("/proc/cpuinfo") or "" match = re.search(r"^model name\s*:\s*(.+)$", text, re.MULTILINE) + if not match and log.once("no-cpu-model"): + logger.debug("no CPU model found (no `model name` in /proc/cpuinfo, as on ARM Linux): left out of the " + "environment identity") return match.group(1).strip() if match else None @@ -85,6 +100,9 @@ def system_facts(child_env: dict, env_names=None) -> dict: facts["libc"] = {"name": libc, "version": version} if governor := _read("/sys/devices/system/cpu/cpu0/cpufreq/scaling_governor"): facts["cpu"] = {"governor": governor} + left_out = [name for name, found in (("libc", libc), ("cpu governor", "cpu" in facts)) if not found] + if left_out and log.once("facts-left-out"): + logger.debug("system facts left out, because they could not be read: %s", ", ".join(left_out)) env = {k: child_env[k] for k in (env_names or env_allowlist(child_env)) if k in child_env} if env: facts["process"] = {"environment": env} @@ -96,6 +114,8 @@ def load_average() -> float | None: try: return round(os.getloadavg()[0], 2) except (OSError, AttributeError): + if log.once("no-load-average"): # asked for every case: said once per command, the case line shows `load n/a` + logger.debug("the load average is unavailable on this system") return None @@ -133,6 +153,7 @@ def ignore(*paths) -> None: or changes its tree id. Replaces the previous set; no arguments clears it.""" global _IGNORED _IGNORED = tuple(Path(p).resolve() for p in paths) + logger.debug("left out of every tree identity from now on: %s", ", ".join(map(str, _IGNORED)) or "nothing") def _ignored_in(root: Path) -> list[str]: @@ -155,8 +176,14 @@ def git_identity(path) -> dict | None: head = top and _run(["git", "rev-parse", "HEAD"], cwd=top) if not head: return None - excludes = [_PYCACHE_EXCLUDE, *([_OUT_EXCLUDE] if _out_is_untracked(top) else []), - *(f":(top,exclude){rel}" for rel in _ignored_in(top) if not _git_ignores(top, rel))] + out_left_out = _out_is_untracked(top) + own = [(rel, _git_ignores(top, rel)) for rel in _ignored_in(top)] + excludes = [_PYCACHE_EXCLUDE, *([_OUT_EXCLUDE] if out_left_out else []), + *(f":(top,exclude){rel}" for rel, git_does in own if not git_does)] + logger.debug("tree id of %s leaves out __pycache__, %s, and benchx's own paths %s (git's own ignore rules already " + "cover %s)", top, "`**/out/**`" if out_left_out else "nothing under out/ (a tracked file is under an " + "out/, or `git ls-files` failed)", [r for r, g in own if not g] or "(none inside it)", + [r for r, g in own if g] or "none") status = _run(["git", "status", "--porcelain", "--untracked-files=all", "--", ".", *excludes], cwd=top) # A scratch index that does not exist yet, so the repository's own index # is untouched (schema §4.1). @@ -167,16 +194,46 @@ def git_identity(path) -> dict | None: subprocess.run(["git", "add", "-A", "--", ".", *excludes], cwd=top, env=env, check=True, capture_output=True) tree = subprocess.run(["git", "write-tree"], cwd=top, env=env, check=True, capture_output=True, text=True).stdout.strip() - except (OSError, subprocess.CalledProcessError): + except (OSError, subprocess.CalledProcessError) as e: + why_tree = " | ".join((getattr(e, "stderr", None) or b"").decode(errors="replace").strip().splitlines()[:2]) or str(e) + logger.debug("git add or write-tree failed in %s: %s", top, why_tree) tree = None identity = {"path": top, "revision": head} if tree is not None and status is not None: identity.update(dirty="dirty" if status else "clean", tree=tree) + if status: + identity["changes"] = status.splitlines() # why the tree is dirty, for the log else: identity["dirty"] = "unknown" + identity["why_unknown"] = "git status failed" if status is None else "git add or write-tree failed" return identity +def note_identity_fallback(identity: dict) -> None: + """A working tree identified by a content hash because git could not: INFO when the directory has no + `.git`, WARNING when it has one and git failed. Its revision is `directory-` and its state always + dirty, which the record says. Once per directory and command.""" + if not identity["revision"].startswith("directory-") or not log.once(("fallback", identity["path"])): + return + has_git = (Path(identity["path"]) / ".git").exists() + logger.log(logging.WARNING if has_git else logging.INFO, + "%s is identified by a hash of its files (method directory-hash), as %s: its revision is %s and its " + "state is always dirty", identity["path"], "git could not read it" if has_git else "it is not under git", + identity["revision"][:28]) + + +def why_no_checkout(build_dir, source_dir=None) -> str: + """Why the checkout a build was made from cannot be found, for the refusal that says so.""" + cache = Path(build_dir) / "CMakeCache.txt" + if not cache.exists(): + return f"there is no CMakeCache.txt in {build_dir}" + if not source_dir: + return "CMakeCache.txt has no CMAKE_HOME_DIRECTORY" + if not Path(source_dir).is_dir(): + return f"the recorded source directory {source_dir} is gone" + return f"git could not read {source_dir}" + + def source_uri(source_dir) -> str: """One canonical URI for every worktree of a repository, so both sides of a comparison report the same source: the origin remote, else the shared git @@ -210,14 +267,19 @@ def benchmark_identity(suite_file, subject_source) -> dict | None: """ suite = Path(suite_file).resolve() if suite.is_relative_to(Path(subject_source).resolve()): + logger.debug("the suite %s is in the subject's checkout: its identity is the subject's", suite) return None tree = blob_id(suite) + if tree is None: + logger.warning("the suite file %s cannot be read, so its identity has no blob id", suite) top = _run(["git", "rev-parse", "--show-toplevel"], cwd=suite.parent) head = top and _run(["git", "rev-parse", "HEAD"], cwd=top) if head: committed = _run(["git", "rev-parse", f"HEAD:{suite.relative_to(Path(top).resolve()).as_posix()}"], cwd=top) return {"uri": source_uri(top), "type": "git", "revision": head, "tree": tree, "dirty": "clean" if committed == tree else "dirty"} + logger.debug("the suite %s is under no version control: a file:// source, always dirty; its series does not " + "follow the suite to another machine", suite) return {"uri": suite.parent.as_uri(), "type": "directory", "tree": tree, "dirty": "dirty"} @@ -235,6 +297,7 @@ def directory_identity(path) -> dict | None: root = Path(path) if not root.is_dir(): return None + started, files, size = time.monotonic(), 0, 0 digest = hashlib.sha1() ignored = tuple(_IGNORED) for file in sorted(p for p in root.rglob("*") if p.is_file() @@ -242,10 +305,14 @@ def directory_identity(path) -> dict | None: and not any(p.resolve().is_relative_to(i) for i in ignored)): try: content = file.read_bytes() - except OSError: + except OSError as e: + logger.warning("cannot read %s, so the tree %s cannot be identified: %s", file, root, e.strerror or e) return None name = file.relative_to(root).as_posix().encode() digest.update(b"%d:%s:%d:" % (len(name), name, len(content)) + content) + files, size = files + 1, size + len(content) + logger.debug("hashed %d file(s), %d byte(s) of %s in %.2f s; left out: %s (always), and benchx's own paths", + files, size, root, time.monotonic() - started, ", ".join(sorted(_SKIPPED_DIRS))) tree = digest.hexdigest() return {"path": str(root.resolve()), "revision": f"directory-{tree}", "dirty": "dirty", "tree": tree} @@ -262,6 +329,8 @@ def _cmake_cache(build_dir) -> dict: def cmake_source_dir(build_dir) -> str | None: entry = _cmake_cache(build_dir).get("CMAKE_HOME_DIRECTORY") + if not entry and log.once(("no-source-dir", str(build_dir))): + logger.debug("%s has no CMakeCache.txt, or no CMAKE_HOME_DIRECTORY in it: no source directory", build_dir) return entry[1] if entry else None @@ -275,10 +344,16 @@ def cmake_configuration(build_dir) -> dict: """ cache = _cmake_cache(build_dir) config = {} + if not cache: + _once_warn(("no-cache", str(build_dir)), "no CMakeCache.txt in %s: no build configuration is recorded, so " + "`build-config-unverified` has nothing behind it", build_dir) for key, name in (("CMAKE_BUILD_TYPE", "build_type"), ("CMAKE_CXX_FLAGS", "cxx_flags")): if cache.get(key, (None, ""))[1]: config[name] = cache[key][1] compiler_file = next(Path(build_dir).glob("CMakeFiles/*/CMakeCXXCompiler.cmake"), None) + if cache and compiler_file is None: + _once_warn(("no-compiler-file", str(build_dir)), "no CMakeCXXCompiler.cmake under %s/CMakeFiles: the compiler " + "is not recorded", build_dir) text = _read(compiler_file) if compiler_file else None if text: found = dict(re.findall(r'set\(CMAKE_CXX_COMPILER_(ID|VERSION) "([^"]*)"\)', text)) @@ -291,20 +366,41 @@ def cmake_configuration(build_dir) -> dict: if k.startswith(prefix) and kind in ("BOOL", "STRING") and "/" not in v} if options: config["options"] = options + if log.once(("cmake", str(build_dir))): + logger.debug("CMake configuration of %s: recorded %s; from %d cache entries, %d option(s) with the prefix of " + "the project %r kept", build_dir, ", ".join(sorted(config)) or "nothing", len(cache), + len(config.get("options", {})), cache.get("CMAKE_PROJECT_NAME", (None, ""))[1]) return config +def _once_warn(key, message, *args) -> None: + """A WARNING the first time, DEBUG after: what is the same for every order of a command.""" + logger.log(logging.WARNING if log.once(key) else logging.DEBUG, message, *args) + + def setup_facts(suite_root, env) -> tuple[dict | None, str | None]: """Declared facts from the setup file (harness-adapter.md §5.1). Returns (facts, warning). An absent file is not an error; an unreadable one contributes nothing and yields the warning collector-failed. """ - path = Path(env.get("BENCHX_SETUP_FILE") or Path(suite_root) / ".benchx" / "setup.json") + named = env.get("BENCHX_SETUP_FILE") + path = Path(named or Path(suite_root) / ".benchx" / "setup.json") + # BENCHX_SETUP_FILE is one of benchx's own control variables, which the log gives with their values + # (cli.CONTROL_ENV): the path is named wherever the file is. + shown = str(path) if not path.exists(): + if named: + _once_warn("setup-missing", "BENCHX_SETUP_FILE names a file that does not exist (%s): no setup facts", path) return None, None try: facts = json.loads(path.read_text()) - except (OSError, ValueError): + except (OSError, ValueError) as e: + _once_warn(("setup-unreadable", shown), "the setup file (%s) could not be read, so it gives the results the " + "warning collector-failed: %s", shown, e) + return None, "collector-failed" + if not isinstance(facts, dict): + _once_warn(("setup-not-object", shown), "the setup file (%s) holds JSON that is not an object, so it gives the " + "results the warning collector-failed", shown) return None, "collector-failed" - return (facts, None) if isinstance(facts, dict) else (None, "collector-failed") + return facts, None diff --git a/src/benchx/store.py b/src/benchx/store.py index bb13b81f..35581ab9 100644 --- a/src/benchx/store.py +++ b/src/benchx/store.py @@ -14,8 +14,10 @@ """ import json +import logging import os import statistics +import time from pathlib import Path import pyarrow as pa @@ -26,6 +28,9 @@ from .core.errors import AttemptConflict, DocumentError, IdempotencyConflict, ReadError, UnitConflict from .projection import Projection +logger = logging.getLogger(__name__) +MAX_LOGGED = 40 # the log's cap on a list, like its other lists + # Schema §5.3 attempt integrity: what results sharing an attempt_key agree on. _ATTEMPT_FIELDS = ("project", "source", "revision", "benchmark") _ATTEMPT_COORDINATES = ("workload", "subject", "environment") @@ -58,7 +63,14 @@ def __init__(self, path): # -- reading ------------------------------------------------------------- def _table(self, columns=None) -> pa.Table | None: - return pq.read_table(self.path, columns=columns) if self.path.exists() else None + if not self.path.exists(): + logger.debug("%s: absent, read as an empty store", self.path) + return None + started = time.monotonic() + table = pq.read_table(self.path, columns=columns) + logger.debug("%s: read %d row(s), %s, in %.2f s", self.path, table.num_rows, + ", ".join(columns) if columns else "all columns", time.monotonic() - started) + return table def _index(self) -> list[dict]: table = self._table(["producer", "ingest_key", "attempt_key", "payload_sha256", "attempt_signature", @@ -77,8 +89,10 @@ def _documents(self, run_key=None) -> list[dict]: if table is None: return [] run_keys = table.column("provenance").combine_chunks().field("run_key").to_pylist() - return [json.loads(text) for r, text in zip(run_keys, table.column("document").to_pylist()) - if run_key is None or r == run_key] + found = [json.loads(text) for r, text in zip(run_keys, table.column("document").to_pylist()) + if run_key is None or r == run_key] + logger.debug("documents(%s): %d of %d stored document(s)", run_key, len(found), len(run_keys)) + return found def documents(self, run_key: str) -> list[dict]: """The stored documents of one run, exactly as ingested (canonical form).""" @@ -188,6 +202,8 @@ def ingest_paths(self, paths) -> dict: unreadable.append(_rejection(f.name, errors[0])) else: orders[core.order_ref(order)] = order + logger.debug("swept %d file(s): %d result document(s), %d work order(s), %d unreadable or malformed", len(files), + len(documents), len(orders), len(unreadable)) outcome = self.ingest(documents, orders) outcome["rejected"] = unreadable + outcome["rejected"] return outcome @@ -202,12 +218,19 @@ def ingest(self, documents: list[tuple[str, str]], orders: dict | None = None) - accepted, derived = [], [] outcome = {"ingested": 0, "duplicate": 0, "rejected": []} + used_orders, without_order = set(), 0 for name, text in documents: doc, errors = loader.parse(text) if doc is not None: errors = core.check(doc, "measurement-result") if errors: outcome["rejected"].append(_rejection(name, errors[0])) + logger.debug("%s: rejected with %d error(s)", name, len(errors)) # the rejection keeps the first + for error in errors[:MAX_LOGGED]: + logger.debug("%s: %s at %s: %s%s", name, error.code, error.location or "the document", error.message, + f" (rule {error.rule})" if getattr(error, "rule", None) else "") + if len(errors) > MAX_LOGGED: + logger.debug("%s: and %d more error(s)", name, len(errors) - MAX_LOGGED) continue project = store_project(doc) @@ -231,12 +254,24 @@ def ingest(self, documents: list[tuple[str, str]], orders: dict | None = None) - conflict = None if conflict is not None: outcome["rejected"].append(_rejection(name, conflict)) + if isinstance(conflict, IdempotencyConflict): # the error does not carry what makes it one + logger.warning("%s: idempotency-conflict: %s already holds payload %s for %s, and this one is %s", + name, self.path, existing[key][:16], doc["ingest_key"], payload[:16]) + else: + logger.warning("%s: %s: %s", name, conflict.code, conflict.message) continue existing[key] = payload + if not known: + logger.debug("%s: a new quantity %s [%s] in %s: the first result defines its unit", name, + quantity["name"], quantity["unit"], project) units[(project, quantity["name"])] = quantity["unit"] # first sight defines the unit ref = doc["provenance"].get("info", {}).get("workorder_ref") order = orders.get(ref) + if order is None: + without_order += 1 + else: + used_orders.add(ref) accepted.append(doc) derived.append({ "store_project": project, @@ -249,22 +284,62 @@ def ingest(self, documents: list[tuple[str, str]], orders: dict | None = None) - }) outcome["ingested"] += 1 + unused = [ref for ref in orders if ref not in used_orders] + logger.debug("ingest: %d ingested, %d duplicate, %d rejected; %d work order(s) attached, %d in the sweep " + "that no result references (neither stored nor reported), %d result(s) with no order in the sweep " + "(an order delivered by an earlier ingest is not attached)", outcome["ingested"], + outcome["duplicate"], len(outcome["rejected"]), len(used_orders), len(unused), without_order) if accepted: - self._write(parquet.results_table(accepted, derived)) + try: + table = parquet.results_table(accepted, derived) + except Exception: # one list comprehension over the batch: an error there writes nothing + logger.error("cannot convert %d result(s) to rows for %s: nothing is written", len(accepted), self.path) + raise + self._write(table) return outcome def _write(self, new: pa.Table) -> None: """Rewrite the file with the new rows appended, atomically.""" + started = time.monotonic() old = self._table() # Rows written under an older message schema are carried over, with # nulls in any column or nested field the schema has since gained. table = new if old is None else pa.concat_tables([old, new], promote_options="permissive") - self.path.parent.mkdir(parents=True, exist_ok=True) + if old is not None and logger.isEnabledFor(logging.DEBUG): + before, after = _fields(old.schema), _fields(table.schema) + added = sorted(set(after) - set(before)) + widened = sorted(f"{path}: {before[path]} to {after[path]}" for path in before if before[path] != after[path]) + if added or widened: # permissive promotion adds nested fields and widens types, not only columns + logger.debug("%s: the schema was promoted: added %s; widened %s", self.path, ", ".join(added) or "nothing", + ", ".join(widened) or "nothing") tmp = self.path.with_name(f".{self.path.name}.tmp") - pq.write_table(table.replace_schema_metadata(new.schema.metadata), tmp, compression="zstd") - with open(tmp, "rb") as f: - os.fsync(f.fileno()) - os.replace(tmp, self.path) + try: + self.path.parent.mkdir(parents=True, exist_ok=True) + pq.write_table(table.replace_schema_metadata(new.schema.metadata), tmp, compression="zstd") + with open(tmp, "rb") as f: + os.fsync(f.fileno()) + os.replace(tmp, self.path) + except OSError as e: # disk full, permissions: the results are still in their files + logger.error("cannot write %s (%d row(s) were to be added): %s; a partial %s may be left behind", + self.path, new.num_rows, e.strerror or e, tmp) + raise + logger.debug("wrote %s: %d row(s) added to %d, %.2f s", self.path, new.num_rows, old.num_rows if old else 0, + time.monotonic() - started) + + +def _fields(schema: pa.Schema) -> dict[str, str]: + """Every leaf of a schema by dotted path, with its type: what a schema promotion can change.""" + found = {} + + def walk(prefix, kind): + if pa.types.is_struct(kind): + for child in kind: + walk(f"{prefix}.{child.name}", child.type) + else: + found[prefix] = str(kind) + for field in schema: + walk(field.name, field.type) + return found def _rejection(name: str, error: DocumentError) -> dict: diff --git a/src/benchx/tables.py b/src/benchx/tables.py index 96e01782..4c3e235c 100644 --- a/src/benchx/tables.py +++ b/src/benchx/tables.py @@ -8,6 +8,8 @@ not asv's. """ +import collections +import logging import math import statistics @@ -15,6 +17,8 @@ from .snapshot import DIRTY_WARNINGS from .store import store_project +logger = logging.getLogger(__name__) + ROLES = ("baseline", "contender") CHANGED = {"regressed": "+", "improved": "-", "changed": "~"} # as asv continuous marks them MARKS = {**CHANGED, "no-change-detected": " ", "indeterminate": "?"} @@ -93,10 +97,12 @@ def summarize(doc, documents) -> tuple[list[dict], dict]: projection = _projection(doc) names = {_c(doc["baseline"]): "baseline", _c(doc["contender"]): "contender"} grouped, sides = {}, {role: [] for role in ROLES} + skipped = 0 for d in _run_documents(documents, doc["run_key"]): projected = projection.apply(d, store_project(d)) role = names.get(_c(projected.axis[0])) if role is None: + skipped += 1 continue variant = {ptr: v for ptr, v in projected.identity.items() if ptr == WORKLOAD or ptr.startswith(WORKLOAD + "/")} quantity = d["measurement"]["quantity"] @@ -104,6 +110,11 @@ def summarize(doc, documents) -> tuple[list[dict], dict]: {"quantity": quantity, "docs": {r: [] for r in ROLES}}) unit["docs"][role].append(d) sides[role].append(d) + if skipped: + logger.debug("--tables skipped %d document(s) that fit neither side", skipped) + if len(grouped) != len(doc["units"]): # side tables regroup every attempt: units the comparison dropped show up + logger.debug("the side tables hold %d unit(s), the comparison %d: units dropped for sides-agree, " + "equal-attempts or a missing side still appear in the side tables", len(grouped), len(doc["units"])) units = [] for unit in grouped.values(): units.append({"workload": _workload(unit["docs"], projection.axis), "quantity": unit["quantity"], @@ -194,10 +205,11 @@ def change_table(doc, units, info, *, all_rows=False) -> str: """asv's comparison table, and the verdict. As `asv continuous` does, only the rows that changed, unless `all_rows`.""" by_workload = {(_c(u["workload"]), u["quantity"]["name"]): u for u in units} - rows = [] + rows, hidden = [], collections.Counter() for verdict_unit in doc["units"]: 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 + hidden[verdict_unit["verdict"]] += 1 continue unit = by_workload[(_c(verdict_unit["workload"]), verdict_unit["quantity"])] before, after = unit["baseline"], unit["contender"] @@ -205,6 +217,8 @@ def change_table(doc, units, info, *, all_rows=False) -> str: noise = f"{verdict_unit['noise']:.2%}" if "noise" in verdict_unit else "n/a" rows.append([mark, *(_cell(unit, role) for role in ROLES), ratio, noise, _verdict(verdict_unit), _label(unit["workload"])]) + logger.info("--tables: %d row(s) shown; hidden by verdict: %s", len(rows), + ", ".join(f"{verdict} {n}" for verdict, n in sorted(hidden.items())) or "none") if not rows: return "No benchmark changed (the verdict is benchx's; --all lists every row)." headers = ["Change", f"Before [{info['baseline']['tag']}]", f"After [{info['contender']['tag']}]", diff --git a/src/benchx/target.py b/src/benchx/target.py index 375368e7..948b9953 100644 --- a/src/benchx/target.py +++ b/src/benchx/target.py @@ -17,12 +17,16 @@ """ import json +import logging import subprocess +import time from pathlib import Path -from . import core +from . import core, log from .core import loader +logger = logging.getLogger(__name__) + SIDECAR = ".benchx-target.json" TEXT_FIELDS = ("how_built", "activation", "shell", "provider") MAX_FACTS_CHARS = 65536 # how_built as an object, serialized; as text it is limited to 8192 @@ -62,14 +66,23 @@ def call_provider(command, cwd, operation, source_ref, configuration) -> dict: if errors: raise TargetError("; ".join(str(error) for error in errors)) label = f"@{configuration}" if configuration else source_ref + # A header for the build output that streams through the terminal next + logger.info("provider: %s %s (%s)", operation, label, source_ref) + logger.debug("provider command: %s (in %s); request: %s", log.command(command), cwd, json.dumps(request)) + started = time.monotonic() try: done = subprocess.run(command, input=json.dumps(request), text=True, cwd=cwd, stdout=subprocess.PIPE) except OSError as e: raise TargetError(f"cannot run the provider {command[0]!r}: {e}") from None - if done.returncode != 0: - raise TargetError(f"the provider failed to {operation} {label} (exit {done.returncode})") - return _validated(done.stdout, f"the provider's answer for {label}") + status, stdout = done.returncode, done.stdout + logger.info("provider: %s %s: exit %s, %.1f s", operation, label, status, time.monotonic() - started) + # The answer, before the exit status is judged: a failing provider's stdout is lost otherwise. The + # last 40 lines at DEBUG, WARNING when it failed; the refusal below carries the problems, once. + log.harness_output(logger, "provider", "stdout", stdout, failed=status != 0) + if status != 0: + raise TargetError(f"the provider failed to {operation} {label} (exit {status})") + return _validated(stdout, f"the provider's answer for {label}") def _validated(raw: str, where: str) -> dict: @@ -89,7 +102,9 @@ def sidecar(build_dir) -> dict | None: """The sidecar description in a build directory, if its builder wrote one.""" path = Path(build_dir) / SIDECAR if not path.is_file(): + logger.debug("no sidecar %s", path) return None + logger.debug("sidecar %s found", path) description = _validated(path.read_text(encoding="utf-8"), str(path)) target = description["target"] if target["kind"] != "build" or Path(target["path"]).resolve() != Path(build_dir).resolve(): @@ -112,6 +127,8 @@ def resolve(spec: str, *, operation="prepare", provider=None) -> dict | None: if provider is None: raise TargetError(f"{spec} needs a provider") command, directory = provider + if not source_ref: + logger.debug("%s has no SOURCE_REF: WORKSPACE is used", spec) return call_provider(command, directory, operation, source_ref or "WORKSPACE", configuration) build = spec.partition(":")[0] return sidecar(build) if build else None diff --git a/tests/conftest.py b/tests/conftest.py index a52dcdf8..814a1e57 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -125,6 +125,9 @@ def _isolated(monkeypatch, tmp_path): land in the test's directory.""" monkeypatch.delenv("BENCHX_SETUP_FILE", raising=False) monkeypatch.delenv("BENCHX_HOME", raising=False) + monkeypatch.delenv("BENCHX_VERBOSE", raising=False) + monkeypatch.delenv("BENCHX_HARNESS_VERBOSITY", raising=False) + monkeypatch.delenv("BENCHX_LOG_LEVEL", raising=False) monkeypatch.chdir(tmp_path) snapshot.ignore() yield diff --git a/tests/fake_gbench.py b/tests/fake_gbench.py index fadf3653..fe1e833c 100644 --- a/tests/fake_gbench.py +++ b/tests/fake_gbench.py @@ -5,7 +5,10 @@ {"seed": 1, "cases": {"BM_Quiet/1024": {"mean": 1e-3, "rel_sd": 0.002}}, "error": ["BM_Broken"], "skip": ["BM_Skipped"], "sleep": {"BM_Slow": 5}, - "ghost": ["BM_Ghost"]} + "ghost": ["BM_Ghost"], "scaling": true, "build_type": "debug"} + +A "scaling" build says in its context that CPU frequency scaling is on; a "build_type" other than the default +"release" is the benchmark library's. A ghost case is listed but never reported, as a binary that drops a case does. @@ -65,7 +68,8 @@ "real_time": value * 1e9, "cpu_time": value * 0.99e9, "time_unit": "ns"}) native = {"context": {"date": "2026-09-25T10:00:00+00:00", "host_name": "fake-host", "num_cpus": 8, - "mhz_per_cpu": 3000, "cpu_scaling_enabled": False, "library_build_type": "release", + "mhz_per_cpu": 3000, "cpu_scaling_enabled": bool(config.get("scaling", False)), + "library_build_type": config.get("build_type", "release"), "library_version": "v1.9.1-fake", "executable": sys.argv[0]}, "benchmarks": rows} if "--benchmark_out" in args: diff --git a/tests/test_bench.py b/tests/test_bench.py index 221fb2aa..ec01134d 100644 --- a/tests/test_bench.py +++ b/tests/test_bench.py @@ -213,6 +213,11 @@ def test_bench_places_calls_in_a_session(tree): (["--run-key", "S", "--slot", "0", "--label", "env"], "NAME=VALUE"), (["--run-key", "S", "--slot", "0", "--label", "env=a", "--label", "env=b"], "given twice"), (["--run-key", "S", "--slot", "-1"], "from 0"), + (["--run-key", "S", "--slot", "0", "--round", "-1"], "from 0"), + (["--run-key", "S", "--slot", "0", "--round", "5/5"], "numbered 0 to 4"), + (["--run-key", "S", "--slot", "0", "--round", "0/0"], "at least 1 round, not 0"), + (["--run-key", "S", "--slot", "0", "--round", "a"], "R/N"), + (["--run-key", "S", "--slot", "0", "--round", "1/x"], "R/N"), ]) def test_session_flags_are_refused_before_anything_runs(extra, message, tree, capsys): assert cli.main(["bench", "mod.py", "bench_a", "--no-ingest", *extra, *FAST]) == cli.EXIT_REFUSED diff --git a/tests/test_bench_harnesses.py b/tests/test_bench_harnesses.py index ad41f72f..28eca9f3 100644 --- a/tests/test_bench_harnesses.py +++ b/tests/test_bench_harnesses.py @@ -132,7 +132,8 @@ def test_what_does_not_fit_is_refused_before_anything_runs(argv, message, build, def test_a_suite_the_adapter_cannot_find_is_refused(build, tmp, capsys): assert cli.main(["bench", str(build), "--adapter", "google-benchmark", "--suite", "gone"]) == cli.EXIT_REFUSED assert "suite binary not found" in capsys.readouterr().err - assert not (tmp / "results").exists() + # refused inside the session, after the log was started: the run folder holds only the log, which says why + assert [p.name for p in (tmp / "results").glob("*/*")] == ["bx.log"] def test_a_provider_target_is_resolved_like_compare_does(repo, build, tmp, monkeypatch, capsys): diff --git a/tests/test_e2e_numpy_revisions.py b/tests/test_e2e_numpy_revisions.py index a74b441a..fdd7270f 100644 --- a/tests/test_e2e_numpy_revisions.py +++ b/tests/test_e2e_numpy_revisions.py @@ -236,7 +236,7 @@ def test_a_workspace_git_cannot_hash_is_refused_before_anything_runs(project, wo unreadable.unlink() assert done.returncode == 2, done.stderr[-3000:] assert "has no working-tree id" in done.stderr and "unknown" in done.stderr - assert not (project / "results" / "e2e-unknown").exists() # no order was written + assert [p.name for p in (project / "results" / "e2e-unknown").iterdir()] == ["bx.log"] # no order was written @pytest.mark.skipif(not SPIN_EXAMPLE, reason="set BENCHX_E2E_SPIN_EXAMPLE to the numpy-spin example directory") diff --git a/tests/test_harness_verbosity.py b/tests/test_harness_verbosity.py new file mode 100644 index 00000000..12d6ae1f --- /dev/null +++ b/tests/test_harness_verbosity.py @@ -0,0 +1,153 @@ +"""--harness-verbosity: how much the harness itself is asked to say. Off by default; one work-order field; the +`v`s past -vv ask for it too (-vvv is -vv and 1). Google Benchmark runs against the fake binary.""" + +import json +import subprocess + +import pytest + +from benchx import cli, core, runner +from conftest import cases, make_build +from test_config import write_config + +GBENCH = ["--adapter", "google-benchmark", "--suite", "demo-bench"] + + +@pytest.fixture +def build(repo, tmp): + return make_build(tmp / "build", repo["wt-head"], cases()) + + +def bench(build, *extra, key="h1"): + return cli.main(["bench", str(build), *GBENCH, "--run-key", key, "--no-ingest", *extra]) + + +def order_of(tmp, key="h1") -> dict: + return json.loads((tmp / "results" / key / "orders" / "order.json").read_text()) + + +def log_of(tmp, key="h1") -> str: + return (tmp / "results" / key / "bx.log").read_text() + + +def result_info(tmp, key="h1") -> dict: + path = next((tmp / "results" / key).glob(f"{key}_BM_Quiet*wall-time.json")) + return json.loads(path.read_text())["provenance"]["info"] + + +def test_by_default_the_harness_is_asked_for_nothing_more(build, tmp): + assert bench(build) == cli.EXIT_OK + assert "harness_verbosity" not in order_of(tmp) and "harness_verbosity" not in result_info(tmp) + assert " --v=" not in log_of(tmp) and "harness is asked to say more" not in log_of(tmp) + + +def test_the_option_goes_into_the_order_the_command_line_and_the_result(build, tmp): + assert bench(build, "--harness-verbosity", "2") == cli.EXIT_OK + order = order_of(tmp) + assert order["harness_verbosity"] == 2 and core.check(order, "work-order") == [] + text = log_of(tmp) + assert "--benchmark_min_time=0.5s --v=2 (in " in text # on the command line the log shows + assert " INFO the harness is asked to say more (harness_verbosity 2): its output is logged up to 2000 lines a stream" in text + assert result_info(tmp)["harness_verbosity"] == 2 + assert " DEBUG setting harness verbosity: 2 (flag)" in text + + +@pytest.mark.parametrize("flags, level", [(["-vv"], 0), (["-vvv"], 1), (["-vvvv"], 2), (["-v", "-v", "-v", "-v", "-v"], 3), + (["-vvvv", "-q"], 1)]) +def test_each_v_past_two_asks_the_harness_to_say_more(build, tmp, flags, level, capsys): + assert bench(build, *flags) == cli.EXIT_OK + assert order_of(tmp).get("harness_verbosity", 0) == level + assert (f"--v={level}" in log_of(tmp)) == bool(level) + assert capsys.readouterr().err.count("DEBUG") == 0 # the terminal got -vv's bare messages, never more than that + + +def test_the_explicit_option_beats_the_vs(build, tmp): + assert bench(build, "-vvvv", "--harness-verbosity", "5") == cli.EXIT_OK + assert order_of(tmp)["harness_verbosity"] == 5 + assert " DEBUG setting harness verbosity: 5 (flag)" in log_of(tmp) + + +def test_the_environment_and_the_file_ask_too_in_that_order(build, tmp, monkeypatch): + write_config(tmp, adapter={"name": "google-benchmark", "suite": "demo-bench", "verbosity": 1}) + assert cli.main(["bench", str(build), "--run-key", "h1", "--no-ingest"]) == cli.EXIT_OK + assert order_of(tmp)["harness_verbosity"] == 1 and "harness verbosity: 1 (file)" in log_of(tmp) + monkeypatch.setenv("BENCHX_HARNESS_VERBOSITY", "3") + assert cli.main(["bench", str(build), "--run-key", "h2", "--no-ingest"]) == cli.EXIT_OK + assert order_of(tmp, "h2")["harness_verbosity"] == 3 + assert "harness verbosity: 3 (environment BENCHX_HARNESS_VERBOSITY)" in log_of(tmp, "h2") + assert cli.main(["bench", str(build), "--run-key", "h3", "--no-ingest", "--harness-verbosity", "0"]) == cli.EXIT_OK + assert "harness_verbosity" not in order_of(tmp, "h3") # a flag of 0 beats both: nothing more + + +def test_a_bad_value_is_refused_naming_where_it_came_from(build, tmp, monkeypatch, capsys): + monkeypatch.setenv("BENCHX_HARNESS_VERBOSITY", "loud") + assert bench(build) == cli.EXIT_REFUSED + assert "bx bench: error: BENCHX_HARNESS_VERBOSITY=loud: not a whole number from 0" in capsys.readouterr().err + monkeypatch.delenv("BENCHX_HARNESS_VERBOSITY") + with pytest.raises(SystemExit): + bench(build, "--harness-verbosity", "-1") + assert "not a whole number from 0" in capsys.readouterr().err + + +def test_bx_verbose_from_the_environment_can_ask_too(build, tmp, monkeypatch): + monkeypatch.setenv("BENCHX_VERBOSE", "4") # the terminal's -vv, and two more + assert bench(build) == cli.EXIT_OK + assert order_of(tmp)["harness_verbosity"] == 2 and "verbosity: 2 (environment BENCHX_VERBOSE)" in log_of(tmp) + + +def test_config_show_has_the_row(monkeypatch, capsys): + assert cli.main(["config", "show", "-vvv"]) == cli.EXIT_OK + assert "harness verbosity 1 (flag: -v past -vv)" in capsys.readouterr().out + + +def test_the_log_keeps_more_of_the_output_when_the_harness_was_asked_for_more(build, tmp, monkeypatch): + assert bench(build, "--harness-verbosity", "1", key="h1") == cli.EXIT_OK + monkeypatch.setattr(runner, "VERBOSE_OUTPUT_LINES", 3) + assert bench(build, "--harness-verbosity", "1", key="h2") == cli.EXIT_OK + assert "BM_Quiet/1024: stdout, 7 lines (also in" in log_of(tmp, "h1") # all 7 kept: under the cap + assert "BM_Quiet/1024: stdout, 7 lines (last 3; all in " in log_of(tmp, "h2") + assert bench(build, key="h3") == cli.EXIT_OK # without it the cap is the usual 40: nothing is cut here either + assert "stdout, 7 lines (also in" in log_of(tmp, "h3") + + +def test_pyperf_is_given_verbose_and_says_more(tmp): + pytest.importorskip("pyperf") + (tmp / "m.py").write_text("def bench_x():\n sum(range(100))\n") + for command in (["init", "-q"], ["add", "-A"], ["-c", "user.name=t", "-c", "user.email=t@e", "commit", "-qm", "m"]): + subprocess.run(["git", *command], cwd=tmp, check=True) + common = ["bench", "m.py", "--no-ingest", "--processes", "2", "--values", "2", "--warmups", "0", "--loops", "1"] + assert cli.main([*common, "--run-key", "quiet"]) == cli.EXIT_OK + assert cli.main([*common, "--run-key", "loud", "--harness-verbosity", "1"]) == cli.EXIT_OK + quiet = next((tmp / "results" / "quiet").glob("artifacts/*/0000.stdout")).read_text() + loud = next((tmp / "results" / "loud").glob("artifacts/*/0000.stdout")).read_text() + assert len(loud.splitlines()) > len(quiet.splitlines()) and "- value 1:" in loud and "- value 1:" not in quiet + assert " --verbose " in (tmp / "results" / "loud" / "bx.log").read_text() + + +def test_verbose_in_the_environment_past_two_is_the_environments_and_does_not_pose_as_a_flag(build, tmp, monkeypatch): + monkeypatch.setenv("BENCHX_VERBOSE", "3") + assert bench(build) == cli.EXIT_OK + assert order_of(tmp)["harness_verbosity"] == 1 + assert " DEBUG setting harness verbosity: 1 (environment BENCHX_VERBOSE)" in log_of(tmp) + + +def test_an_explicit_harness_verbosity_in_the_environment_beats_verbose_in_the_environment(build, tmp, monkeypatch): + monkeypatch.setenv("BENCHX_VERBOSE", "4") + monkeypatch.setenv("BENCHX_HARNESS_VERBOSITY", "0") + assert bench(build) == cli.EXIT_OK + assert "harness_verbosity" not in order_of(tmp) # 0: nothing more, though BENCHX_VERBOSE=4 says 2 + assert " DEBUG setting harness verbosity: 0 (environment BENCHX_HARNESS_VERBOSITY)" in log_of(tmp) + + +def test_the_flags_still_beat_the_environment(build, tmp, monkeypatch): + monkeypatch.setenv("BENCHX_HARNESS_VERBOSITY", "0") + assert bench(build, "-vvv") == cli.EXIT_OK + assert order_of(tmp)["harness_verbosity"] == 1 + assert " DEBUG setting harness verbosity: 1 (flag: -v past -vv)" in log_of(tmp) + + +def test_config_show_refuses_a_bad_harness_verbosity_with_nothing_half_printed(tmp, monkeypatch, capsys): + monkeypatch.setenv("BENCHX_HARNESS_VERBOSITY", "loud") + assert cli.main(["config", "show"]) == cli.EXIT_REFUSED + seen = capsys.readouterr() + assert seen.out == "" and "BENCHX_HARNESS_VERBOSITY=loud: not a whole number from 0" in seen.err diff --git a/tests/test_logging.py b/tests/test_logging.py new file mode 100644 index 00000000..c57cc3c4 --- /dev/null +++ b/tests/test_logging.py @@ -0,0 +1,421 @@ +"""The log: its switch, levels and file, and what `bx` shows beside it. + +Google Benchmark runs against the fake binary, so these run anywhere. +""" + +import argparse +import logging +import re +from pathlib import Path + +import pytest + +from benchx import cli, log, snapshot +from conftest import QUIET, NOISY, cases, make_build +from test_config import write_config + +GBENCH = ["--adapter", "google-benchmark", "--suite", "demo-bench"] +STAMP = re.compile(r"^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d\.\d{3}Z \d+ benchx\.[\w.]+ [A-Z]+ ") + + +@pytest.fixture +def build(repo, tmp): + return make_build(tmp / "build", repo["wt-head"], cases()) + + +def log_of(tmp, run_key) -> str: + return (tmp / "results" / run_key / "bx.log").read_text() + + +def bench(build, *extra, key="g1"): + return cli.main(["bench", str(build), *GBENCH, "--run-key", key, *extra]) + + +# --- the default: stderr as before, and a log beside the results + +def test_the_default_leaves_stderr_as_it_was_and_writes_the_log_in_the_run_folder(build, tmp, capsys): + assert bench(build) == cli.EXIT_OK + out = capsys.readouterr() + assert not any(STAMP.match(line) for line in out.err.splitlines()) # no timestamped line on the terminal + assert "5 repetitions" in out.err and QUIET in out.out and NOISY in out.out + lines = log_of(tmp, "g1").splitlines() + assert all(STAMP.match(line) for line in lines) + assert " INFO start: benchx " in lines[0] and "bx bench" in lines[0] and str(tmp) in lines[0] + assert " INFO end: ok (exit 0), " in lines[-1] + assert len({line.split()[1] for line in lines}) == 1 # every line carries the one pid + + +def test_the_header_records_the_command_as_given_to_main(build, tmp): + assert bench(build, "-e", "SECRET=hunter2") == cli.EXIT_OK + assert "-e SECRET=hunter2" in log_of(tmp, "g1").splitlines()[0] # as given: the log makes no claim to hide it + + +def test_no_log_writes_no_file_and_stderr_is_the_same(build, tmp, capsys): + assert bench(build) == cli.EXIT_OK + with_log = capsys.readouterr().err + assert bench(build, "--no-log", key="g2") == cli.EXIT_OK + assert capsys.readouterr().err == with_log + assert not (tmp / "results" / "g2" / "bx.log").exists() + + +def test_a_run_key_with_a_slash_keeps_the_log_in_the_run_folder(build, tmp): + assert bench(build, key="a/b") == cli.EXIT_OK + assert (tmp / "results" / "a_b" / "bx.log").exists() and not (tmp / "results" / "a").exists() + + +def test_a_log_is_appended_to_under_a_new_header(build, tmp): + assert bench(build, "--no-ingest") == cli.EXIT_OK + assert bench(build, "--no-ingest") == cli.EXIT_OK + text = log_of(tmp, "g1") + assert text.count(" INFO start: ") == 2 and text.count(" INFO end: ") == 2 + + +def test_the_commands_without_an_output_folder_write_no_log(tmp): + for command in (["head"], ["series"], ["config", "show"]): + assert cli.main(command) == cli.EXIT_OK + assert not list(tmp.rglob("bx.log")) + + +def test_the_default_log_keeps_the_settings_with_their_sources(build, tmp): + assert bench(build, "--repetitions", "3", key="g3") == cli.EXIT_OK + text = log_of(tmp, "g3") + assert " DEBUG setting adapter: google-benchmark (flag)" in text + assert " DEBUG setting precision: flags repetitions; file none" in text + assert re.search(r" INFO config file: none found from \S+ upward; project root \S+; store \S+; results \S+", text) + + +def test_the_adapter_flag_over_a_same_family_file_names_both_in_the_log(build, tmp): + write_config(tmp, adapter={"name": "pyperf", "suite": "m.py"}) + cli.main(["bench", str(build), "--adapter", "asv", "--suite", "gone", "--run-key", "r19"]) # refused later + assert " DEBUG setting adapter: asv (flag; the file says pyperf, same family)" in log_of(tmp, "r19") + + +# --- refusals: the folder exists only once the command's own checks have passed + +@pytest.mark.parametrize("argv", [ + ["--processes", "2"], ["--adapter", "pyperf", "--suite", "m.py", "--repetitions", "3"], ["--tree", "t"]]) +def test_a_refusal_for_a_flag_leaves_no_folder(build, tmp, argv, capsys): + assert cli.main(["bench", str(build), *GBENCH, "--run-key", "r1", *argv]) == cli.EXIT_REFUSED + assert "bx bench: error:" in capsys.readouterr().err + assert not (tmp / "results").exists() + + +def test_a_refusal_inside_the_session_leaves_the_folder_holding_only_the_log(build, tmp, capsys): + assert cli.main(["bench", str(build), "--adapter", "google-benchmark", "--suite", "gone", "--run-key", "r2"]) \ + == cli.EXIT_REFUSED + assert "suite binary not found" in capsys.readouterr().err + assert [p.name for p in (tmp / "results" / "r2").iterdir()] == ["bx.log"] + text = log_of(tmp, "r2") + assert re.search(r" ERROR bx bench: error: suite binary not found", text) + assert " INFO end: refused (exit 2), " in text + + +# --- the switch: flags, and an unusable file + +@pytest.mark.parametrize("command", [["head"], ["bench", "x", "--adapter", "pyperf", "--suite", "s"], ["validate", "f.json"]]) +def test_a_log_file_ending_in_json_is_refused_by_every_command(command, tmp, capsys): + assert cli.main([*command, "--log-file", "out.json"]) == cli.EXIT_REFUSED + assert f"bx {command[0]}: error: --log-file out.json: a log file must not end in .json" in capsys.readouterr().err + assert not list(tmp.iterdir()) + + +def test_a_log_file_that_cannot_be_opened_is_refused_before_anything_runs(tmp, capsys): + assert cli.main(["head", "--log-file", str(tmp / "no" / "such" / "dir" / "bx.log")]) == cli.EXIT_REFUSED + assert "cannot open" in capsys.readouterr().err + + +def test_log_file_names_a_file_for_a_command_with_no_output_folder(tmp, capsys): + path = tmp / "mine.log" + assert cli.main(["head", "--log-file", str(path)]) == cli.EXIT_OK + text = path.read_text() + assert " INFO start: benchx " in text and "bx head --log-file" in text and " INFO end: ok (exit 0)" in text + assert "0 result(s)" in capsys.readouterr().out # stdout is the command's answer, not a log line + + +def test_the_out_placeholder_needs_an_output_folder_when_a_flag_uses_it(tmp, capsys): + assert cli.main(["head", "--log-file", "{out}/x.log"]) == cli.EXIT_REFUSED + assert "bx head has no output folder" in capsys.readouterr().err + + +def test_the_log_flag_sends_the_whole_log_to_stderr_and_stdout_stays_clean(build, tmp, capsys): + assert bench(build, "--log") == cli.EXIT_OK + out = capsys.readouterr() + assert STAMP.match(out.err.splitlines()[0]) and " INFO end: ok (exit 0)" in out.err + assert not any(STAMP.match(line) for line in out.out.splitlines()) + assert not (tmp / "results" / "g1" / "bx.log").exists() + + +def test_no_log_with_a_level_is_a_usage_error(tmp, capsys): + assert cli.main(["head", "--no-log", "--log-level", "info"]) == cli.EXIT_REFUSED + assert "--no-log with --log-level" in capsys.readouterr().err + + +def test_the_three_switch_flags_exclude_each_other(): + with pytest.raises(SystemExit): + cli.main(["head", "--log", "--no-log"]) + + +# --- levels + +def test_a_log_level_from_the_environment_drops_what_is_below_it(build, tmp, monkeypatch): + monkeypatch.setenv("BENCHX_LOG_LEVEL", "info") + assert bench(build) == cli.EXIT_OK + text = log_of(tmp, "g1") + assert " INFO start: " in text and " DEBUG " not in text + + +def test_the_flag_beats_the_environment_for_the_level(build, tmp, monkeypatch): + monkeypatch.setenv("BENCHX_LOG_LEVEL", "info") + assert bench(build, "--log-level", "DEBUG") == cli.EXIT_OK + assert " DEBUG " in log_of(tmp, "g1") + + +def test_a_bad_level_in_the_environment_is_refused_naming_the_variable(build, tmp, monkeypatch, capsys): + monkeypatch.setenv("BENCHX_LOG_LEVEL", "loud") + assert bench(build) == cli.EXIT_REFUSED + assert "bx bench: error: BENCHX_LOG_LEVEL=loud: not one of debug, info, warning, error" in capsys.readouterr().err + assert not (tmp / "results").exists() + + +def test_the_level_and_the_switch_come_from_the_file_too(build, tmp): + write_config(tmp, log_level="warning", logging="{root}/mine.log") + assert bench(build) == cli.EXIT_OK + assert not (tmp / "results" / "g1" / "bx.log").exists() + text = (tmp / "mine.log").read_text() + assert text.strip() == "" or " INFO " not in text and " DEBUG " not in text # only WARNING and above + + +def test_verbose_shows_every_info_record_on_the_terminal_and_quiet_hides_the_progress(build, tmp, capsys): + assert bench(build, "-v") == cli.EXIT_OK + err = capsys.readouterr().err + assert "start: benchx" in err and "config file:" in err and not any(STAMP.match(l) for l in err.splitlines()) + assert bench(build, "-q", key="g2") == cli.EXIT_OK + assert "5 repetitions" not in capsys.readouterr().err # the progress line is INFO + + +def test_verbosity_from_the_environment_and_its_refusal(build, monkeypatch, capsys): + monkeypatch.setenv("BENCHX_VERBOSE", "2") + assert bench(build, "--no-log") == cli.EXIT_OK + assert " DEBUG " not in capsys.readouterr().err # the bare message, not the log's line + monkeypatch.setenv("BENCHX_VERBOSE", "loud") + assert bench(build) == cli.EXIT_REFUSED + assert "bx bench: error: BENCHX_VERBOSE=loud: not a whole number, -2 or more" in capsys.readouterr().err + + +def test_config_show_has_the_three_rows_with_their_sources(monkeypatch, capsys): + monkeypatch.setenv("BENCHX_VERBOSE", "1") + assert cli.main(["config", "show"]) == cli.EXIT_OK + out = capsys.readouterr().out + assert '"{out}/bx.log" (default)' in out + assert "log level debug (default)" in out + assert "verbosity 1 (environment BENCHX_VERBOSE)" in out + + +# --- the wrapper: crashes, exits and interrupts reach the footer + +def test_a_crash_is_a_console_error_with_its_traceback_and_a_footer(tmp, monkeypatch, capsys): + def boom(*args): + raise RuntimeError("boom") + + monkeypatch.setattr(cli, "Store", boom) # inside the command, after it has started the log + path = tmp / "crash.log" + assert cli.main(["series", "--log-file", str(path)]) == 1 # the status an uncaught exception gives + err = capsys.readouterr().err + assert "Traceback (most recent call last)" in err and err.rstrip().endswith("RuntimeError: boom") + text = path.read_text() + assert " ERROR Traceback (most recent call last)" in text and " RuntimeError: boom" in text + assert " INFO end: crashed (exit 1), " in text + + +def test_system_exit_passes_through_with_a_footer(tmp, monkeypatch): + def leave(*args): + raise SystemExit(2) + + monkeypatch.setattr(cli, "Store", leave) + path = tmp / "exit.log" + with pytest.raises(SystemExit) as exited: + cli.main(["series", "--log-file", str(path)]) + assert exited.value.code == 2 + assert " INFO end: refused (exit 2), " in path.read_text() + + +def test_an_interrupt_is_logged_and_re_raised(tmp, monkeypatch): + def stop(*args): + raise KeyboardInterrupt + + monkeypatch.setattr(cli, "Store", stop) + path = tmp / "int.log" + with pytest.raises(KeyboardInterrupt): + cli.main(["series", "--log-file", str(path)]) + text = path.read_text() + assert " WARNING interrupted" in text and re.search(r" INFO end: interrupted, ", text) + + +def test_a_usage_error_leaves_no_log_and_no_footer(tmp): + with pytest.raises(SystemExit): + cli.main(["bench"]) + assert not list(tmp.rglob("*.log")) + + +def test_main_leaves_no_handler_behind(build): + assert bench(build) == cli.EXIT_OK + handlers = logging.getLogger("benchx").handlers + assert all(isinstance(h, logging.NullHandler) for h in handlers) + + +# --- the file: one line format, several-line messages, and the tree it sits in + +def test_a_message_of_several_lines_is_one_prefixed_line_and_indented_continuations(tmp): + path = tmp / "multi.log" + log.start_console(0) + log.configure(path, argv=["x"]) + try: + log.console("benchx.cli").error("first line\nsecond line\nthird line") + finally: + log.stop() + lines = path.read_text().splitlines() + assert STAMP.match(lines[1]) and lines[1].endswith(" ERROR first line") + assert lines[2:4] == [" second line", " third line"] + + +def test_the_console_handler_writes_a_multi_line_message_verbatim(capsys): + log.start_console(0) + try: + log.console("benchx.cli").error("first line\nsecond line") + finally: + log.stop() + assert capsys.readouterr().err == "first line\nsecond line\n" + + +def test_the_log_file_is_left_out_of_every_tree_identity(build, tmp): + path = tmp / "wt.log" + args = argparse.Namespace(log=str(path), log_level=None, argv=[], verbosity=0, verbosity_source="default", + out=None) + cfg = cli._load("bench") + try: + started = cli._start_logging(cfg, args, None, "bench") + assert started.log_file == path.resolve() and path.resolve() in snapshot._IGNORED + assert path.resolve() in started.own_paths + finally: + log.stop() + + +def test_the_command_helper_gives_a_pastable_line_and_shortens_inline_code(): + script = "import sys\nprint(1)\n" + text = log.command(["python", "-c", script, "it's"], scripts={"LISTER": script}, temporary=["/tmp/x"]) + assert text == "python -c '' 'it'\"'\"'s'" + assert log.command(["a", "/tmp/x/f"], temporary=["/tmp/x"]).endswith("(temporary, removed after the call: /tmp/x)") + + +def test_once_is_true_the_first_time_after_configure(tmp): + log.configure(False) + assert log.once("k") and not log.once("k") + log.configure(False) + assert log.once("k") + + +def test_degraded_phrases_end_the_footer_and_are_warnings(tmp): + path = tmp / "d.log" + log.start_console(0) + log.configure(path, argv=[]) + try: + log.degraded("1 of 2 cases not measured") + log.footer("ok", 0) + finally: + log.stop() + text = path.read_text() + assert " WARNING 1 of 2 cases not measured" in text + assert re.search(r" INFO end: ok \(exit 0\), [\d.]+ s, 1 of 2 cases not measured\n$", text) + + +def test_the_logger_passes_only_the_levels_somebody_wants(tmp): + """`isEnabledFor(DEBUG)` is false when nothing wants DEBUG, so a record costs nothing. Until the + log is on, DEBUG is kept: the command's own checks buffer their records for it.""" + benchx = logging.getLogger("benchx") + try: + log.start_console(0) + log.configure(False) # --no-log leaves the console's level + assert benchx.isEnabledFor(logging.INFO) and not benchx.isEnabledFor(logging.DEBUG) + log.start_console(2) # -vv + log.configure(False) + assert benchx.isEnabledFor(logging.DEBUG) + log.start_console(0) + log.configure(tmp / "x.log", level=logging.INFO) # --log-level info + assert benchx.isEnabledFor(logging.INFO) and not benchx.isEnabledFor(logging.DEBUG) + log.configure(tmp / "x.log") # the default: the log keeps DEBUG + assert benchx.isEnabledFor(logging.DEBUG) + finally: + log.stop() + assert not benchx.isEnabledFor(logging.INFO) # nothing installed: only the NullHandler + + +def test_the_log_records_the_arguments_as_parsed_and_the_environment_it_consults(build, tmp, monkeypatch): + monkeypatch.setenv("BENCHX_ENV_ALLOWLIST", "MY_VAR") + monkeypatch.setenv("BENCHX_HOME", str(tmp / "home")) + assert bench(build, "-e", "A=1", "--repetitions", "3") == cli.EXIT_OK + lines = log_of(tmp, "g1").splitlines() + parsed = next(l for l in lines if " DEBUG arguments as parsed: " in l) + assert "cmd='bench'" in parsed and "repetitions=3" in parsed and "run_key='g1'" in parsed and "env=['A=1']" in parsed + consulted = next(l for l in lines if " DEBUG environment variables consulted: " in l) + assert f"BENCHX_HOME={tmp / 'home'};" in consulted and "BENCHX_ENV_ALLOWLIST=MY_VAR;" in consulted + assert "BENCHX_VERBOSE not set;" in consulted and "BENCHX_SETUP_FILE not set;" in consulted + assert consulted.endswith("PATH is set (the benchmark's python is looked up on it)") + assert str(tmp / "home") in next(l for l in lines if " INFO config file: " in l) # the store the variable moved + + +def test_the_log_names_the_config_file_when_there_is_one(build, tmp): + path = write_config(tmp, adapter={"name": "google-benchmark", "suite": "demo-bench"}) + assert cli.main(["bench", str(build), "--run-key", "g1"]) == cli.EXIT_OK + assert f" INFO config file: {path}; project root {tmp}; " in log_of(tmp, "g1") + + +# --- review: a refused log path leaves nothing behind; zeros are arguments; stop() leaves no state + +@pytest.mark.parametrize("name, message", [("{out}", "is a directory"), ("{out}/sub/bx.log", "cannot open")]) +def test_a_refused_log_path_in_the_output_folder_does_not_create_the_folder(name, message, build, tmp, capsys): + assert cli.main(["bench", str(build), *GBENCH, "--out", str(tmp / "o"), "--log-file", name]) == cli.EXIT_REFUSED + assert message in capsys.readouterr().err + assert not (tmp / "o").exists() + + +def test_a_log_file_directly_in_the_output_folder_creates_it(build, tmp): + assert cli.main(["bench", str(build), *GBENCH, "--out", str(tmp / "o"), "--log-file", "{out}/mine.log", + "--no-ingest"]) == cli.EXIT_OK + assert " INFO start: benchx " in (tmp / "o" / "mine.log").read_text() + + +def test_arguments_given_as_zero_are_in_the_arguments_as_parsed(build, tmp): + assert bench(build, "--round", "0", "--slot", "0", "-vvv", "--no-ingest", key="z1") == cli.EXIT_OK + parsed = next(l for l in log_of(tmp, "z1").splitlines() if " DEBUG arguments as parsed: " in l) + assert "slot=0" in parsed and "round='0'" in parsed + assert "verbose_extra" not in parsed and "verbosity" not in parsed # computed, not given + + +def test_stop_leaves_no_state_for_a_library_call_that_follows(): + log.start_console(-2) + log.configure(False) + assert log.once("k") and not log.once("k") + log.degraded("something undone") + log.stop() + assert log.quiet() == 0 and log.once("k") # the key was forgotten, as it was for a fresh process + assert log._state.degraded == [] and log._state.started is None + + +def test_stop_hands_the_logger_back_to_the_root_not_to_a_fixed_level(): + benchx, root = logging.getLogger("benchx"), logging.getLogger() + log.start_console(0) + log.stop() + assert benchx.level == logging.NOTSET and not benchx.isEnabledFor(logging.INFO) # the root's WARNING + earlier = root.level + root.setLevel(logging.INFO) # a library caller that logs at INFO sees benchx's records + try: + assert benchx.isEnabledFor(logging.INFO) and not benchx.isEnabledFor(logging.DEBUG) + finally: + root.setLevel(earlier) + + +def test_a_refused_comparison_does_not_print_the_store_path(tmp, capsys): + assert cli.main(["compare", "A", "B", "--profile", "revisions", "--suite", "s", "--rounds", "3"]) \ + == cli.EXIT_REFUSED # no adapter + err = capsys.readouterr().err + assert "--adapter is required" in err and "store.parquet" not in err diff --git a/tests/test_logging_quiet.py b/tests/test_logging_quiet.py new file mode 100644 index 00000000..9d10ed47 --- /dev/null +++ b/tests/test_logging_quiet.py @@ -0,0 +1,249 @@ +"""`-q` and `-qq` on a run, and the run's report in the log (the console marker, +extended to stdout). Google Benchmark runs against the fake binary, so these run anywhere.""" + +import json +import re +import sys + +import pytest + +from benchx import bench as bench_mod +from benchx import cli, log +from conftest import cases, make_build + +GBENCH = ["--adapter", "google-benchmark", "--suite", "demo-bench"] +STAMP = re.compile(r"^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d\.\d{3}Z \d+ benchx(\.\w+)+ [A-Z]+ ") +HEADER = "mean ± sd" # the table's header line, which no other line has +START = r"measuring demo-bench on \S+ \(round 1/5, slot 3\)" # the line a call starts with, with the total +POSITION = ["--round", "1/5", "--slot", "3"] + + +@pytest.fixture +def build(repo, tmp): + """Four cases: one fails and one is skipped (both are listed under `not measured`, only the failure counts).""" + return make_build(tmp / "build", repo["wt-head"], cases(), error=["BM_Broken"], skip=["BM_Skipped"]) + + +@pytest.fixture +def clean(repo, tmp): + return make_build(tmp / "clean", repo["wt-head"], cases()) + + +def bench(build, capsys, *extra, key="r1"): + code = cli.main(["bench", str(build), *GBENCH, "--run-key", key, *extra]) + seen = capsys.readouterr() + return code, seen.out, seen.err + + +def log_of(tmp, key="r1") -> list[str]: + return (tmp / "results" / key / "bx.log").read_text().splitlines() + + +def test_the_default_stdout_is_the_table_the_failures_and_the_summary(build, capsys): + code, out, err = bench(build, capsys, *POSITION) + assert code == cli.EXIT_OK + assert out.splitlines()[0].startswith("case ") and HEADER in out + assert re.search(r"\n\nnot measured \(2\)\n BM_Broken: .+\n BM_Skipped: .+\n\n" + r"\d+ result\(s\) -> \S+ \(order sha256:\w+\)\n", out) + assert "ingested" not in out # a progress message now, and on stderr with the others + assert re.fullmatch(START + r"\nprecision: .*\n\S+store\.parquet: ingested \d+, duplicate 0\n", err) + + +def test_q_leaves_the_failures_and_the_result_line_and_no_table(build, capsys): + code, out, err = bench(build, capsys, "-q", *POSITION) + assert code == cli.EXIT_OK + lines = out.splitlines() + assert HEADER not in out and "" not in lines # no table, and no spacing between what is left + assert lines[0] == "not measured (2)" and lines[1].startswith(" BM_Broken: ") + assert lines[2].startswith(" BM_Skipped: ") + assert re.fullmatch(r"\d+ result\(s\) -> \S+ \(order sha256:\w+\)", lines[3]) and len(lines) == 4 + assert re.fullmatch(START + "\n", err) # on stderr, the start line: not the progress line or the ingest line + + +def test_qq_leaves_only_the_failures(build, capsys): + code, out, err = bench(build, capsys, "-qq", *POSITION) + assert code == cli.EXIT_OK # the exit status stays 0: a failed case is a result + assert out.splitlines()[0] == "not measured (2)" and len(out.splitlines()) == 3 + assert err == "" + + +def test_qq_on_a_run_that_succeeded_is_silent(clean, capsys): + code, out, err = bench(clean, capsys, "-qq") + assert (code, out, err) == (cli.EXIT_OK, "", "") + + +def test_q_on_a_run_that_succeeded_is_a_start_line_and_a_result_line(clean, capsys): + code, out, err = bench(clean, capsys, "-q", *POSITION) + lines = out.splitlines() + assert code == cli.EXIT_OK and re.fullmatch(START + "\n", err) and len(lines) == 1 + assert "result(s) ->" in lines[0] + + +def test_the_start_line_says_where_a_call_sits_and_what_it_measures(clean, capsys): + _, _, err = bench(clean, capsys, "-q", "--label", "side=base", "--round", "2", "--slot", "5") + assert re.fullmatch(r"measuring demo-bench on \S+ \(round 2, slot 5, side=base\)\n", err) # no total given + _, _, err = bench(clean, capsys, "-q", "--round", "4/5", "--slot", "9", key="r3") # the last of 5, numbered from 0 + assert re.fullmatch(r"measuring demo-bench on \S+ \(round 4/5, slot 9\)\n", err) + _, _, err = bench(clean, capsys, "-q", key="r2") # alone in its session: no position to give + assert re.fullmatch(r"measuring demo-bench on \S+\n", err) + + +def test_the_start_line_is_said_once_with_v_and_is_in_the_log_whatever_the_terminal_shows(build, tmp, capsys): + _, _, err = bench(build, capsys, "-v", *POSITION) + assert len(re.findall(START, err)) == 1 + for number, flags in enumerate([[], ["-q"], ["-qq"]]): + key = f"s{number}" + bench(build, capsys, *flags, *POSITION, key=key) + assert any(re.search(r" INFO " + START + "$", line) for line in log_of(tmp, key)) + + +def test_a_failure_with_no_message_is_one_line_when_the_table_is_hidden(build, capsys, monkeypatch): + monkeypatch.setattr(bench_mod, "said", lambda document: None) # the status column was all there was + one_line = r"\d+ of \d+ cases not measured" + _, out, _ = bench(build, capsys, "-qq") + assert re.fullmatch(one_line + "\n", out) + _, out, _ = bench(build, capsys, key="r2") # the table says it, so no line is added + assert not re.search(one_line, out) and "error (harness.error)" in out + + +@pytest.mark.parametrize("flags", [[], ["-q"], ["-qq"], ["-v"]]) +def test_the_log_holds_the_report_whatever_the_terminal_shows(build, tmp, capsys, flags): + bench(build, capsys, *flags) + lines = log_of(tmp) + assert all(STAMP.match(line) for line in lines) # a line a record, as the harness output is logged + table = [i for i, line in enumerate(lines) if HEADER in line] + assert len(table) == 1 and " INFO " in lines[table[0]] + rows = lines[table[0]:table[0] + 6] + assert any("BM_Quiet/1024" in row for row in rows) and any("BM_Broken" in row for row in rows) + assert any(" WARNING not measured (2)" in line for line in lines) # the errors, as a warning + assert any(re.search(r" INFO \d+ result\(s\) -> ", line) for line in lines) + assert any(re.search(r" INFO \S+store\.parquet: ingested \d+, duplicate 0$", line) for line in lines) # once + + +def test_the_log_level_decides_what_of_it_the_log_keeps(build, tmp, capsys): + bench(build, capsys, "--log-level", "warning") + text = "\n".join(log_of(tmp)) + assert HEADER not in text and " WARNING not measured (2)" in text + + +def test_v_does_not_say_the_report_twice(build, capsys): + _, out, err = bench(build, capsys, "-v") + assert HEADER in out and HEADER not in err # stdout carries it already + + +def test_with_the_log_on_stderr_the_report_is_on_stdout_and_once_in_the_log(build, capsys): + _, out, err = bench(build, capsys, "--log") + assert HEADER in out + assert sum(HEADER in line for line in err.splitlines()) == 1 and STAMP.match( + next(line for line in err.splitlines() if HEADER in line)) + + +def test_the_ingest_command_prints_its_counts_at_every_verbosity(clean, tmp, capsys): + assert bench(clean, capsys, "--no-ingest", "--out", str(tmp / "o"))[0] == cli.EXIT_OK + assert cli.main(["ingest", str(tmp / "o"), "-qq"]) == cli.EXIT_OK + assert re.fullmatch(r"ingested \d+, duplicate 0\n", capsys.readouterr().out) # its answer, not a summary + + +def test_bx_run_is_quiet_by_the_same_tiers(clean, tmp, capsys): + bench(clean, capsys, "--no-ingest", "--out", str(tmp / "o")) + order = next((tmp / "o").rglob("orders/order*.json")) + assert cli.main(["run", str(order), "--out", str(tmp / "o1"), "-q"]) == cli.EXIT_OK + seen = capsys.readouterr() + lines = seen.out.splitlines() + assert len(lines) == 1 and "result(s) for" in lines[0] + assert re.fullmatch(r"running the order order\S*\.json\n", seen.err) + # A second run of the order would meet its own results in the store: leave it out of this one. + assert cli.main(["run", str(order), "--out", str(tmp / "o2"), "-qq", "--no-ingest"]) == cli.EXIT_OK + assert capsys.readouterr() == ("", "") + + +def test_a_failed_write_to_stdout_is_the_commands_failure_as_with_print(monkeypatch): + class Closed: + def write(self, text): + raise BrokenPipeError + + def flush(self): + pass + + log.start_console(0) + try: + monkeypatch.setattr(sys, "stdout", Closed()) + with pytest.raises(BrokenPipeError): # logging would have swallowed it + log.console("benchx.cli").out("x") + finally: + log.stop() + + +def test_a_percent_sign_in_the_text_is_left_alone(capsys): + log.start_console(0) + try: + log.console("benchx.cli").out("50% of %s and %d") + finally: + log.stop() + assert capsys.readouterr().out == "50% of %s and %d\n" + + +def test_q_with_the_log_on_stderr_still_hides_the_report_on_stdout(build, capsys): + _, out, err = bench(build, capsys, "--log", "-qq") + assert HEADER not in out and out.splitlines()[0] == "not measured (2)" + assert HEADER in err # stderr is the log, which -q leaves alone + + +def test_the_total_of_rounds_is_for_the_start_line_only(clean, tmp, capsys): + """The work order records the round as it always did: 1, not 1/5.""" + bench(clean, capsys, "--round", "1/5", "--slot", "3", "--no-ingest") + order = json.loads(next((tmp / "results" / "r1" / "orders").glob("order-0003.json")).read_text()) + assert order["round"] == 1 and order["slot"] == 3 and "rounds" not in order + + +# --- the cases that were not measured, which `bx run` says as `bx bench` does + +def row(case, status, message=None): + return {"case": case, "status": status, "message": message} + + +def report(rows, verbosity): + log.start_console(verbosity) + try: + cli._report_unmeasured(rows) + finally: + log.stop() + + +def test_bx_run_reports_the_cases_that_were_not_measured_at_every_verbosity(build, tmp, capsys): + bench(build, capsys, "--no-ingest", "--out", str(tmp / "o")) + order = next((tmp / "o").rglob("orders/order*.json")) + assert cli.main(["run", str(order), "--out", str(tmp / "o1"), "--no-ingest", "-qq"]) == cli.EXIT_OK + out = capsys.readouterr().out + assert out.splitlines()[0] == "not measured (2)" and "BM_Broken: " in out # it was silent before + text = (tmp / "o1" / "bx.log").read_text() + assert re.search(r" WARNING not measured \(2\)", text) + assert re.search(r" INFO end: ok \(exit 0\), [\d.]+ s, 1 of \d+ cases not measured", text) # the footer says so + + +def test_a_run_whose_only_messages_are_skips_reports_them_as_expected_not_as_a_warning(repo, tmp, capsys): + skipping = make_build(tmp / "skipping", repo["wt-head"], cases(), skip=["BM_Skipped"]) + code, out, _ = bench(skipping, capsys) + assert code == cli.EXIT_OK and "not measured (1)\n BM_Skipped: " in out # the default terminal shows it + code, out, _ = bench(skipping, capsys, "-q", key="r2") + assert "not measured" not in out # nothing failed: it goes with the table, which -q hides + code, out, err = bench(skipping, capsys, "-qq", key="r3") + assert (out, err) == ("", "") + text = "\n".join(log_of(tmp, "r3")) + assert " INFO not measured (1)" in text and " WARNING not measured" not in text + assert "cases not measured" not in text # a skip is not an unmeasured case + + +def test_an_error_that_said_nothing_is_counted_when_a_skip_that_did_speak_is_what_the_table_has(capsys): + rows = [row("a", "success"), row("b", "skipped", "no GPU"), row("c", "error (harness.error)")] + report(rows, -1) # -q: the table and the skip's message are hidden, and nothing names `c` + assert capsys.readouterr().out == "1 of 3 cases not measured\n" + report(rows, 0) # the default terminal shows the skip, and the table (the caller's) shows `c` + out = capsys.readouterr().out + assert "b: no GPU" in out and "cases not measured" not in out + + +def test_an_error_that_said_nothing_is_counted_beside_one_that_did(capsys): + rows = [row("a", "success"), row("b", "error (harness.error)", "boom"), row("c", "error (harness.error)")] + report(rows, -2) + assert capsys.readouterr().out == "not measured (1)\n b: boom\n2 of 3 cases not measured\n" diff --git a/tests/test_logging_run.py b/tests/test_logging_run.py new file mode 100644 index 00000000..d686b868 --- /dev/null +++ b/tests/test_logging_run.py @@ -0,0 +1,233 @@ +"""What the log says about a run: the order, each case, the files, the harness output, the end. +Google Benchmark runs against the fake binary, so these run anywhere.""" + +import logging +import os +import re +import sys + +import pytest + +from benchx import cli, log, runner +from benchx.adapters import gbench +from conftest import cases, make_build + +GBENCH = ["--adapter", "google-benchmark", "--suite", "demo-bench"] + + +@pytest.fixture +def build(repo, tmp): + return make_build(tmp / "build", repo["wt-head"], cases(), error=["BM_Broken"], skip=["BM_Skipped"]) + + +def bench(build, *extra, key="r1"): + return cli.main(["bench", str(build), *GBENCH, "--run-key", key, *extra]) + + +def lines_of(tmp, key="r1") -> list[str]: + return (tmp / "results" / key / "bx.log").read_text().splitlines() + + +def record(lines, level, needle): + """The first line at `level` that contains `needle`.""" + return next(line for line in lines if f" {level} " in line and needle in line) + + +def test_the_log_names_the_order_and_each_case_before_and_after_it_runs(build, tmp): + assert bench(build) == cli.EXIT_OK + lines = lines_of(tmp) + assert re.search(r" INFO order sha256:\w+: google-benchmark, 4 case\(s\)$", record(lines, "INFO", "order sha256")) + assert " INFO listing the benchmarks of demo-bench" in "\n".join(lines) + for number in range(1, 5): + start = next(i for i, l in enumerate(lines) if f"case {number}/4 " in l and ": starting, limit 60 s" in l) + done = next(i for i, l in enumerate(lines) if f"case {number}/4 " in l and ", exit 0," in l) + assert start < done # the start is written before the case runs, the line after it + assert re.search(r" INFO case \d/4 BM_Quiet/1024: success, exit 0, [\d.]+ s, load [\d.n/a]+$", "\n".join(lines), + re.M) + + +def test_a_case_that_failed_is_a_warning_with_its_message_and_its_output(build, tmp): + assert bench(build) == cli.EXIT_OK # a failed case is a result, and the command's exit status stays 0 + lines = lines_of(tmp) + broken = record(lines, "WARNING", "BM_Broken: error (harness.error)") + assert re.search(r"error \(harness\.error\): fake failure, exit 0, [\d.]+ s", broken) + skipped = record(lines, "INFO", "BM_Skipped: skipped (harness.skipped)") # expected: not a warning + assert skipped.endswith(("fake skip, exit 0, " + skipped.rsplit("exit 0, ", 1)[1])) + assert any(" WARNING " in l and "BM_Broken: stdout| " in l or " WARNING " in l and "BM_Broken: stdout, " in l + for l in lines) # a failed case's output is a WARNING, a successful one's DEBUG + assert any(" DEBUG " in l and "BM_Quiet/1024: stdout, " in l for l in lines) + + +def test_the_end_of_the_order_and_the_footer_say_what_was_left_undone(build, tmp): + assert bench(build) == cli.EXIT_OK + lines = lines_of(tmp) + order = record(lines, "WARNING", "results: ") # an error result raises the line + assert "error" in order and "skipped" in order and "success" in order + assert re.search(r" INFO end: ok \(exit 0\), [\d.]+ s, 1 of 4 cases not measured$", lines[-1]) + assert " WARNING 1 of 4 cases not measured" in "\n".join(lines) # --log-level warning keeps the phrase + + +def test_the_files_line_names_what_the_case_left_with_absolute_paths(build, tmp): + assert bench(build) == cli.EXIT_OK + files = record(lines_of(tmp), "DEBUG", "case 1/4 BM_Quiet/1024 files: ") + for kind in ("native-output", "stdout", "stderr"): + assert f"{kind} {tmp}/results/r1/artifacts/" in files + assert re.search(r"results 2 " + re.escape(str(tmp)) + r"/results/r1/r1_BM_Quiet", files) + + +def test_a_discovery_call_is_logged_with_its_command_and_how_it_ended(build, tmp): + assert bench(build) == cli.EXIT_OK + text = "\n".join(lines_of(tmp)) + assert re.search(r"benchx\.adapters\.base DEBUG listing the benchmarks of demo-bench: \S+demo-bench " + r"--benchmark_list_tests=true \(in .+, limit 600 s\)", text) + assert "listing the benchmarks of demo-bench: exit 0 in " in text + + +def test_a_rerun_of_a_run_key_says_that_its_files_are_overwritten(build, tmp, capsys): + assert bench(build) == cli.EXIT_OK + capsys.readouterr() + assert bench(build) == cli.EXIT_INVALID # the store refuses the second draw of every result + lines = lines_of(tmp) + second = lines[next(i for i, l in enumerate(lines) if " INFO start: " in l and i > 0):] + assert any(" WARNING " in l and "exists and is overwritten" in l for l in second) + assert any(" WARNING " in l and "result file(s)" in l and "were overwritten by a rerun of run key r1" in l + for l in second) + assert " INFO end: invalid (exit 1)" in second[-1] + + +def test_an_interrupt_after_a_case_says_how_many_were_written_and_how_to_store_them(build, tmp, monkeypatch): + original, calls = gbench.run_case, [] + + def interrupted(*args, **kwargs): + calls.append(1) + if len(calls) == 2: + raise KeyboardInterrupt + return original(*args, **kwargs) + + monkeypatch.setattr(gbench, "run_case", interrupted) + with pytest.raises(KeyboardInterrupt): + bench(build) + text = "\n".join(lines_of(tmp)) + out = tmp / "results" / "r1" + assert f" WARNING 1 of 4 cases written to {out}, not ingested; bx ingest {out} stores them" in text + assert " INFO end: interrupted, " in text + + +def test_a_refusal_lists_its_problems_in_the_log_before_it_is_raised(build, tmp, capsys): + assert cli.main(["bench", str(build), *GBENCH, "--run-key", "r1", "--filter", "NoSuchCase"]) == cli.EXIT_REFUSED + err = capsys.readouterr().err + assert "refused: " in err and "selects no case" in err + lines = lines_of(tmp) + assert any(" ERROR refused: " in l for l in lines) and " INFO end: refused (exit 2)" in lines[-1] + assert any(" DEBUG refused with 1 problem(s): " in l for l in lines) + + +# --- the helpers + +def result(status, reason=None, message=None): + info = {"message": message} if message else {} + return status, reason, {"provenance": {"info": info}, "measurement": {"status": status}} + + +def case_line(results, warnings=(), exit_status=0, timed_out=False, load=0.42): + return runner._case_line(results, list(warnings), {"timed_out": timed_out, "exit_status": exit_status}, 41.2, load) + + +def test_a_case_line_is_info_unless_the_case_did_badly(): + level, text, bad = case_line([result("success")], ["setup-per-call-unbatched"]) + assert (level, bad) == (logging.INFO, False) + assert text == "success [setup-per-call-unbatched], exit 0, 41.2 s, load 0.42" + assert case_line([result("skipped", "harness.skipped", "no GPU")])[:2] == ( + logging.INFO, "skipped (harness.skipped): no GPU, exit 0, 41.2 s, load 0.42") + assert case_line([result("success")], load=None)[1].endswith("load n/a") + + +def test_a_non_zero_exit_raises_the_level_though_the_status_is_success(): + level, text, bad = case_line([result("success")], exit_status=1) + assert (level, bad) == (logging.WARNING, True) and text.startswith("success, exit 1, ") + + +def test_an_error_a_timeout_and_a_doubtful_environment_are_warnings(): + assert case_line([result("error", "harness.error", "ValueError: boom")])[:2] == ( + logging.WARNING, "error (harness.error): ValueError: boom, exit 0, 41.2 s, load 0.42") + level, text, bad = case_line([result("error", "harness.timeout")], exit_status=None, timed_out=True) + assert (level, bad) == (logging.WARNING, True) and ", timeout, " in text + assert case_line([result("success")], ["env-mismatch"])[0] == logging.WARNING # the line, not the output + assert case_line([result("success")], ["env-mismatch"])[2] is False + + +def test_what_is_the_same_in_every_order_is_info_once_and_debug_after(caplog): + log.configure(False) + source = {"path": "/p", "revision": "a" * 40, "dirty": "dirty", "tree": "b" * 40, "changes": [" M a.py", "?? b.py"]} + with caplog.at_level(logging.DEBUG, logger="benchx"): + runner._log_identity({"python": "/venv/bin/python"}, source, None, "/p") + runner._log_identity({"python": "/venv/bin/python"}, source, None, "/p") + by_level = [(r.levelname, r.getMessage()) for r in caplog.records if "run under" in r.getMessage() + or "tree is dirty" in r.getMessage()] + assert [level for level, _ in by_level] == ["INFO", "INFO", "DEBUG", "DEBUG"] + assert any("M a.py; ?? b.py" in m and "dirty-subject-tree" in m for _, m in by_level) + + +def test_a_dirty_state_that_is_unknown_is_a_warning_naming_the_cause(caplog): + log.configure(False) + source = {"path": "/p", "revision": "a" * 40, "dirty": "unknown", "why_unknown": "git status failed"} + with caplog.at_level(logging.DEBUG, logger="benchx"): + runner._log_identity({}, source, None, "/p") + warned = [r for r in caplog.records if r.levelname == "WARNING"] + assert len(warned) == 1 and "dirty state is unknown (git status failed)" in warned[0].getMessage() + + +def test_harness_output_keeps_the_last_forty_lines_and_says_where_the_rest_is(caplog, tmp): + text = "\n".join(f"line {n}" for n in range(1, 101)) + with caplog.at_level(logging.DEBUG, logger="benchx"): + log.harness_output(logging.getLogger("benchx.test"), "case 1/1 x", "stderr", text, failed=True, + kept_at=tmp / "0000.stderr") + log.harness_output(logging.getLogger("benchx.test"), "case 1/1 x", "stdout", " \n", failed=True) # empty + messages = [r.getMessage() for r in caplog.records] + assert messages[0] == f"case 1/1 x: stderr, 100 lines (last 40; all in {tmp}/0000.stderr)" + assert messages[1] == "case 1/1 x: stderr| line 61" and messages[-1] == "case 1/1 x: stderr| line 100" + assert len(messages) == 41 and all(r.levelno == logging.WARNING for r in caplog.records) + + +def test_a_failing_collector_is_a_warning_with_its_reason_and_the_progress_is_info(caplog, tmp): + from benchx import collectors + specs = [{"name": "good", "command": [sys.executable, "-c", "print('{\"x\": 1}')"]}, + {"name": "bad", "command": [sys.executable, "-c", "import sys; print('boom', file=sys.stderr); sys.exit(3)"], + "on_fail": "warn"}] + with caplog.at_level(logging.DEBUG, logger="benchx"): + collected = collectors.run_all(specs, declared=None, cwd=tmp, env=dict(os.environ), artifacts_dir=tmp) + assert collected.warnings == ["collector-failed"] + messages = {(r.levelname, r.getMessage()) for r in caplog.records} + assert any(level == "INFO" and m.startswith("collector 1/2 good: ok, ") for level, m in messages) + assert any(level == "INFO" and m.startswith("collector 2/2 bad: failed, ") for level, m in messages) + assert ("WARNING", "collector bad failed: exit 3: boom") in messages + assert any(level == "WARNING" and m == "collector bad: stderr| boom" for level, m in messages) + + +def test_a_bench_with_a_failed_case_keeps_the_not_measured_section_on_stdout_with_the_log_on(build, capsys): + assert bench(build, "--log") == cli.EXIT_OK + out = capsys.readouterr() + assert re.search(r"not measured \(\d+\)", out.out) and "BM_Broken" in out.out + assert not any(re.match(r"^\d{4}-\d\d-\d\dT", line) for line in out.out.splitlines()) # no log line on stdout + assert any(re.match(r"^\d{4}-\d\d-\d\dT", line) for line in out.err.splitlines()) # the log is on stderr + + +def test_a_parametrized_case_logs_its_workload_and_parameter_values_before_it_runs(tmp, monkeypatch): + pytest.importorskip("pyperf") + import subprocess + (tmp / "m.py").write_text( + "def bench_matmul(n, kind):\n sum(range(10))\n\n" + "bench_matmul.params = [[10, 100], ['a', 'b']]\n" + "bench_matmul.param_names = ['n', 'kind']\n") + for command in (["init", "-q"], ["add", "-A"], ["-c", "user.name=t", "-c", "user.email=t@e", "commit", "-qm", "m"]): + subprocess.run(["git", *command], cwd=tmp, check=True) + assert cli.main(["bench", "m.py", "--run-key", "p1", "--no-ingest", "--processes", "2", "--values", "1", + "--warmups", "0", "--loops", "1", "-e", "A=1", "bench_matmul"]) == cli.EXIT_OK + lines = lines_of(tmp, "p1") + listed = next(l for l in lines if " DEBUG " in l and "bench_matmul: 4 combination(s) of n: 10, 100, kind: 'a', 'b'" in l) + first = next(i for i, l in enumerate(lines) if " INFO case 1/4 bench_matmul-0: starting" in l) + shown = lines[first + 1] + assert " DEBUG case 1/4 bench_matmul-0: workload bench_matmul; parameters n=10, kind='a'; " \ + "environment variables of the order A=1" in shown + assert "n=100, kind='b'" in next(l for l in lines if "case 4/4 bench_matmul-3: workload" in l) + assert lines.index(listed) < first # listed once, before the first case diff --git a/tests/test_logging_silent.py b/tests/test_logging_silent.py new file mode 100644 index 00000000..944f8c2d --- /dev/null +++ b/tests/test_logging_silent.py @@ -0,0 +1,399 @@ +"""What the log says about the decisions that used to be silent: the +comparison's verdicts and what it dropped, a read-mode comparison in the run's log, the tree's identity, +the store.""" + +import logging +import os +import re +from pathlib import Path + +import pytest + +from benchx import cli, compare, runner, snapshot +from benchx import session as session_module # `session` is a fixture here +from benchx.store import Store +from conftest import cases, make_build +from test_comparator import BASE, HEAD +from test_parameter_order import NAME, case, evaluate, run_of + +GBENCH = ["--adapter", "google-benchmark", "--suite", "demo-bench"] + + +def records(caplog, level=logging.DEBUG): + return [(r.levelname, r.getMessage()) for r in caplog.records if r.levelno >= level] + + +# --- the comparison + +def test_a_comparison_logs_its_inputs_each_unit_and_a_summary(caplog): + with caplog.at_level(logging.DEBUG, logger="benchx"): + doc = evaluate(run_of()) + messages = records(caplog) + assert any(level == "DEBUG" and m.startswith("compare: run run, profile revisions") and + "40 result document(s) used of 40 offered" in m for level, m in messages) + units = [m for level, m in messages if level == "INFO" and m.startswith("unit ")] + assert len(units) == len(doc["units"]) == 4 + assert all(re.search(r"regressed, rounds 5, reference [\d.e-]+, effect \+50\.00%, noise [\d.]+%, k x noise", m) + and m.endswith("attempts baseline success 5; contender success 5") for m in units) + assert any(level == "INFO" and m.startswith("compared run run, profile revisions") and "4 unit(s), 4 regressed" in m + and "0 missing, 0 invariant(s) failed, 0 excluded" in m for level, m in messages) + assert any(level == "INFO" and m.startswith("baseline ") and "matched by" in m for level, m in messages) + + +def test_the_document_is_what_it_was_without_the_log(caplog): + quiet = evaluate(run_of()) + with caplog.at_level(logging.DEBUG, logger="benchx"): + loud = evaluate(run_of()) + assert quiet == loud # logging does not touch the comparator's result + + +def test_a_failed_invariant_and_an_indeterminate_unit_make_the_summary_a_warning(caplog): + docs = run_of(rounds=2) # two rounds are the fewest, and min_rounds is 3 + for d in docs: + if d["coordinates"]["workload"]["parameters"]["dtype"] == "'int16'": # the sides disagree about a fact + d["coordinates"]["environment"]["system"]["runtime"] = {"python": "3.13" if d["revision"]["key"] == HEAD + else "3.12"} + with caplog.at_level(logging.DEBUG, logger="benchx"): + evaluate(docs) + messages = records(caplog) + assert any(level == "WARNING" and m.startswith("invariant sides-agree failed for " + NAME) and "differ" in m + for level, m in messages) + assert any(level == "INFO" and "indeterminate, reason insufficient-rounds, rounds 2" in m and + "3 paired rounds required" in m for level, m in messages) + summary = [(level, m) for level, m in messages if m.startswith("compared run")] + assert summary[0][0] == "WARNING" and "indeterminate: insufficient-rounds 2" in summary[0][1] + + +def test_an_edited_benchmark_is_logged_as_not_comparable_and_makes_the_summary_a_warning(caplog): + """The benchmark's version differs between the sides: not a failed invariant, a unit with no pair.""" + docs = run_of(rounds=3) + 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"} + with caplog.at_level(logging.DEBUG, logger="benchx"): + evaluate(docs) + messages = records(caplog) + assert not any(m.startswith("invariant ") for level, m in messages) # no failed invariant, only a unit + assert any(level == "INFO" and "indeterminate, reason benchmark-changed, rounds 0" in m for level, m in messages) + summary = [(level, m) for level, m in messages if m.startswith("compared run")] + assert summary[0][0] == "WARNING" and "indeterminate: benchmark-changed" in summary[0][1] + + +def test_a_second_success_in_a_round_is_a_warning_naming_what_it_overwrote(caplog): + docs = run_of(rounds=3) + parameters = docs[0]["coordinates"]["workload"]["parameters"] + extras = [case(side, 1, slot, 9.0, parameters) for side, slot in ((BASE, 2), (HEAD, 3))] # one per side, in + # the slots the sides already have in round 1: the attempts stay equal and the slots still alternate + for extra in extras: + extra["ingest_key"] += ":again" + with caplog.at_level(logging.DEBUG, logger="benchx"): + evaluate([*docs, *extras]) + assert any(level == "WARNING" and "second success(es) of a side in one round overwrote the first" in m + for level, m in records(caplog)) + + +def test_a_min_rounds_below_two_is_said_once(caplog): + with caplog.at_level(logging.DEBUG, logger="benchx"): + compare.compare(run_of(), run_key="run", profile="revisions", baseline=BASE, min_rounds=1) + warned = [m for level, m in records(caplog) if level == "WARNING" and m.startswith("min_rounds 1 is below 2")] + assert len(warned) == 1 + + +# --- a read-mode comparison joins the run's log + +@pytest.fixture +def session(repo, tmp, monkeypatch): + """Three rounds of two builds in one run key, as a loop of `bx bench` calls leaves them.""" + builds = [make_build(tmp / name, repo[tree], cases(), **extra) + for name, tree, extra in (("b-base", "wt-base", {}), ("b-head", "wt-head", {}))] + slot = 0 + for round_ in range(3): + for build in builds: + assert cli.main(["bench", str(build), *GBENCH, "--run-key", "S", "--round", str(round_), + "--slot", str(slot)]) == cli.EXIT_OK + slot += 1 + return repo["base"][:10] + + +def test_compare_run_appends_the_comparison_to_the_run_folders_log(session, tmp, capsys): + capsys.readouterr() + assert cli.main(["compare", "--run", "S", "--profile", "revisions", "--baseline", session]) == cli.EXIT_OK + out = capsys.readouterr() + text = (tmp / "results" / "S" / "bx.log").read_text() + reading = text[text.rindex(" INFO start: "):] + assert "bx compare --run S" in reading.splitlines()[0] + assert " INFO compared run S, profile revisions" in reading and " INFO unit " in reading + assert reading.splitlines()[-1].endswith(" s") and " INFO end: ok (exit 0), " in reading.splitlines()[-1] + assert not any(re.match(r"^\d{4}-\d\d-", line) for line in out.err.splitlines()) # stderr stays as it was + + +def test_compare_run_without_a_run_folder_leaves_no_log(session, tmp): + assert cli.main(["compare", "--run", "nosuch", "--profile", "revisions", "--baseline", session]) == cli.EXIT_REFUSED + assert not (tmp / "results" / "nosuch").exists() + + +def test_compare_run_with_no_log_appends_nothing(session, tmp): + before = (tmp / "results" / "S" / "bx.log").read_text() + assert cli.main(["compare", "--run", "S", "--profile", "revisions", "--baseline", session, "--no-log"]) == cli.EXIT_OK + assert (tmp / "results" / "S" / "bx.log").read_text() == before + + +def test_the_read_does_not_need_to_write_beside_it(session, tmp): + log = tmp / "results" / "S" / "bx.log" + log.chmod(0o444) + try: + assert cli.main(["compare", "--run", "S", "--profile", "revisions", "--baseline", session]) == cli.EXIT_OK # skipped, silently + finally: + log.chmod(0o644) + + +# --- the tree, the setup file, the store + +def test_a_file_that_cannot_be_read_is_a_warning_naming_it(tmp, caplog): + tree = tmp / "tree" + tree.mkdir() + (tree / "a.py").write_text("x\n") + hidden = tree / "hidden.txt" + hidden.write_text("y\n") + hidden.chmod(0) + try: + with caplog.at_level(logging.DEBUG, logger="benchx"): + assert snapshot.directory_identity(tree) is None + finally: + hidden.chmod(0o644) + assert any(level == "WARNING" and str(hidden) in m and "cannot be identified" in m for level, m in records(caplog)) + + +def test_a_setup_file_that_is_missing_or_unreadable_is_a_warning_that_names_the_variable_and_the_path(tmp, caplog): + snapshot.log.configure(False) + with caplog.at_level(logging.DEBUG, logger="benchx"): + assert snapshot.setup_facts(tmp, {"BENCHX_SETUP_FILE": str(tmp / "secret-place.json")}) == (None, None) + broken = tmp / "setup.json" + broken.write_text("[1, 2]") + assert snapshot.setup_facts(tmp, {"BENCHX_SETUP_FILE": str(broken)}) == (None, "collector-failed") + messages = [m for level, m in records(caplog) if level == "WARNING"] + # BENCHX_SETUP_FILE is a benchx control variable: its value is logged here as cli._log_environment logs it + assert any(m.startswith("BENCHX_SETUP_FILE names a file that does not exist") and "secret-place" in m + for m in messages) + assert any(str(broken) in m and "not an object" in m for m in messages) + + +def test_the_store_says_what_it_swept_what_it_refused_and_what_it_read(session, tmp, caplog, capsys): + with caplog.at_level(logging.DEBUG, logger="benchx"): + # the same keys again: the fake binary draws fresh noise, so every payload differs + assert cli.main(["bench", str(tmp / "b-base"), *GBENCH, "--run-key", "S", "--round", "0", "--slot", "0"]) \ + == cli.EXIT_INVALID + messages = records(caplog) + assert any(level == "WARNING" and "idempotency-conflict: " in m and "already holds payload" in m + for level, m in messages) + assert any(level == "DEBUG" and m.startswith("swept 5 file(s): 4 result document(s), 1 work order(s)") + for level, m in messages) + assert any(level == "DEBUG" and "ingest: 0 ingested, 0 duplicate, 4 rejected" in m for level, m in messages) + caplog.clear() + with caplog.at_level(logging.DEBUG, logger="benchx"): + Store(tmp / "store.parquet").documents("S") + assert any("read " in m and " row(s), provenance, document" in m for _, m in records(caplog)) + assert any(m.startswith("documents(S): ") for _, m in records(caplog)) + with caplog.at_level(logging.DEBUG, logger="benchx"): + assert not Store(tmp / "absent.parquet").documents("S") + assert any("absent, read as an empty store" in m for _, m in records(caplog)) + + +@pytest.mark.parametrize("extra", [["--tables"], ["--tables", "--all"]]) +def test_compare_tables_keeps_stdout_clean_with_the_log_on(session, capsys, extra): + capsys.readouterr() + assert cli.main(["compare", "--run", "S", "--profile", "revisions", "--baseline", session, *extra, "--log"]) \ + == cli.EXIT_OK + out = capsys.readouterr() + assert "Before" in out.out or "Change" in out.out or out.out.strip() # the tables, whatever they hold + assert not any(re.match(r"^\d{4}-\d\d-\d\dT", line) for line in out.out.splitlines()) + assert " INFO compared run S" in out.err + + +def test_a_store_that_cannot_be_written_says_where_the_results_are(session, tmp, monkeypatch, capsys): + from benchx import store as store_mod + monkeypatch.setattr(store_mod.pq, "write_table", lambda *a, **k: (_ for _ in ()).throw(OSError(28, "No space left"))) + assert cli.main(["bench", str(tmp / "b-base"), *GBENCH, "--run-key", "fresh"]) == 1 # a crash: the status Python gives + text = (tmp / "results" / "fresh" / "bx.log").read_text() + assert " ERROR cannot write " in text and "No space left" in text + assert re.search(r" ERROR the order: the results are in \S+/results/fresh, not delivered to the store; " + r"bx ingest \S+/results/fresh stores them", text) + assert " INFO end: crashed (exit 1), " in text + + +def test_a_side_whose_results_disagree_about_their_declarations_is_a_warning_naming_the_field(caplog): + docs = run_of(rounds=3) + for d in docs[:4]: + d["provenance"]["info"] = {"how_built": "cmake -B build"} # the first results of the baseline say how + for d in docs[4:]: + d["provenance"]["info"] = {"how_built": "meson setup build"} + with caplog.at_level(logging.DEBUG, logger="benchx"): + evaluate(docs) + messages = records(caplog) + assert any(level == "DEBUG" and m.startswith("the baseline side's declarations come from ") for level, m in messages) + assert any(level == "WARNING" and "side's results disagree about how_built" in m for level, m in messages) + assert not any("cmake -B build" in m or "meson setup" in m for _, m in messages) # the field's name, not its text + + +def test_history_says_when_nothing_matches_and_when_several_series_do(session, caplog): + with caplog.at_level(logging.DEBUG, logger="benchx"): + assert cli.main(["history", "ffffffffffff"]) == cli.EXIT_OK + assert cli.main(["history", ""]) == cli.EXIT_OK # an empty prefix matches every series + messages = records(caplog) + assert any(level == "INFO" and m == "no series matches ffffffffffff" for level, m in messages) + assert any(level == "WARNING" and " matches " in m and "series, whose points are listed together" in m + for level, m in messages) + + +def test_validate_logs_its_kind_and_each_valid_file(tmp): + from conftest import EXAMPLES + example = next(EXAMPLES.glob("*.json")) + log_file = tmp / "v.log" + assert cli.main(["validate", str(example), "--log-file", str(log_file)]) == cli.EXIT_OK + text = log_file.read_text() + assert " INFO validating 1 file(s) as measurement-result" in text + assert f" DEBUG {example} is a valid measurement-result" in text + + +# --- the rest of §5's rows + +def test_series_and_head_say_when_the_store_has_nothing_to_list(tmp): + log_file = tmp / "empty.log" + assert cli.main(["series", "--log-file", str(log_file)]) == cli.EXIT_OK + assert cli.main(["head", "--log-file", str(log_file)]) == cli.EXIT_OK + text = log_file.read_text() + assert " INFO no series in the store" in text and " holds no result" in text + + +def test_the_tables_say_how_many_rows_they_showed_and_what_they_hid(session, tmp): + log_file = tmp / "t.log" + assert cli.main(["compare", "--run", "S", "--profile", "revisions", "--baseline", session, "--tables", + "--log-file", str(log_file)]) == cli.EXIT_OK + assert re.search(r" INFO --tables: \d+ row\(s\) shown; hidden by verdict: ", log_file.read_text()) + + +def test_a_schema_error_is_logged_with_its_path_and_keyword(tmp): + bad = tmp / "bad.json" + bad.write_text('{"schema_version": "benchx/measurement-result/0.1.0", "surprise": 1}') + log_file = tmp / "v.log" + assert cli.main(["validate", str(bad), "--log-file", str(log_file)]) == cli.EXIT_INVALID + assert re.search(r" DEBUG schema error at /[^:]*: \w+: ", log_file.read_text()) + + +def test_the_asv_runtime_returns_what_the_suite_switched_off(tmp): + from benchx.adapters import asv_runtime + suite = tmp / "benchmarks" + suite.mkdir() + (suite / "__init__.py").write_text("") + (suite / "bench.py").write_text( + "def time_on():\n pass\n\n" + "def time_off():\n pass\n\n" + "time_off.skip_benchmark = True\n\n" + "class Suite:\n def time_method(self):\n pass\n def time_hidden(self):\n pass\n" + " time_hidden.skip_benchmark = True\n") + found, failed, left_out = asv_runtime.discover(str(suite)) + assert failed == [] and sorted(b.name for b in found) == ["bench.Suite.time_method", "bench.time_on"] + assert sorted(left_out) == ["benchmarks.bench.Suite.time_hidden", "benchmarks.bench.time_off"] + + +def test_a_plan_says_where_each_setting_came_from_and_what_the_order_asked_for_in_vain(caplog): + from benchx.adapters import asv + info = {"declared": {"setup_scope": "call", "repeat": 0}, "has_setup": True} + invocation = {"processes": 20, "values": None, "loops": None, "min_time": 0.2, "warmups": None} + plan = asv._plan(info, invocation) + with caplog.at_level(logging.DEBUG, logger="benchx"): + asv._note_plan(info, invocation, plan) + messages = [m for _, m in records(caplog)] + assert any(m.startswith("plan: values 5 (default), loops 1 (setup_scope), min_time 0.2 (order)") for m in messages) + assert any("the order's min_time 0.2 s is lost: the loops are fixed at 1 by the default setup_scope" in m + for m in messages) + assert any("repeat 0 is not a form" in m and "the default 5 values are used" in m for m in messages) + + +def test_a_partial_case_line_gives_completed_over_attempted_and_a_warning_its_reason(): + from benchx import runner + document = {"provenance": {"info": {}}, "measurement": {"status": "partial"}, + "procedure": {"completed_repetitions": 3, "attempted_repetitions": 5}} + level, text, bad = runner._case_line([("partial", "harness.partial", document)], ["env-mismatch"], + {"timed_out": False, "exit_status": 0}, 1.0, 0.5, + {"env-mismatch": "2 of 3 worker(s) had the environment the manager passed"}) + assert text.startswith("partial (harness.partial) 3/5 [env-mismatch: 2 of 3 worker(s) had the environment the " + "manager passed], exit 0, 1.0 s, load 0.50") and (level, bad) == (logging.WARNING, True) + + +def test_the_overlap_of_two_sets_of_facts_names_paths_never_values(): + from benchx import runner + base = {"os": {"family": "Linux", "kernel": "6"}, "process": {"environment": {"A": "1"}}} + facts = {"os": {"family": "Linux"}, "process": {"environment": {"A": "2"}}, "cpu": {"x": 1}} + assert runner._overlap(base, facts) == ["/process/environment/A"] + + +# --- review: what is the same in every order is INFO once per distinct thing, not once per command + +def identity(path, dirty="dirty"): + return {"revision": "a" * 40, "tree": "t" * 40, "dirty": dirty, "changes": ["M a.py"], "path": path} + + +def test_each_distinct_interpreter_and_dirty_tree_is_info_once_and_the_repeats_are_debug(caplog): + snapshot.log.configure(False) # a command's state: nothing spent yet + sides = [("/py/base", "/src/base"), ("/py/head", "/src/head")] + with caplog.at_level(logging.DEBUG, logger="benchx"): + for python, path in sides * 3: # three rounds of a comparison whose sides differ in both + runner._log_identity({"python": python}, identity(path), None, Path(path)) + messages = records(caplog) + ran = [(level, m) for level, m in messages if m.startswith("the benchmarks run under")] + dirty = [(level, m) for level, m in messages if m.startswith("the subject tree is dirty")] + assert [level for level, _ in ran] == ["INFO", "INFO"] + ["DEBUG"] * 4 + assert [m.rsplit(" ", 1)[1] for _, m in ran[:2]] == ["/py/base", "/py/head"] + assert [level for level, _ in dirty] == ["INFO", "INFO"] + ["DEBUG"] * 4 + + +def test_a_dirty_benchmark_in_git_is_not_said_to_be_outside_git(caplog): + snapshot.log.configure(False) + suite = {"uri": "file:///suite", "type": "git", "revision": "b" * 40, "tree": "t" * 40, "dirty": "dirty"} + with caplog.at_level(logging.INFO, logger="benchx"): + runner._log_identity({}, identity("/s", "clean"), suite, "/s") + runner._log_identity({}, identity("/s", "clean"), {**suite, "type": "directory", "uri": "file:///other"}, "/s") + said = [m for level, m in records(caplog) if m.startswith("the benchmark tree is dirty")] + assert len(said) == 2 + assert "not under git" not in said[0] and said[0].startswith("the benchmark tree is dirty; every result carries") + assert "(not under git: a directory of files is always dirty)" in said[1] + + +def test_a_side_with_one_noisy_condition_does_not_spend_the_warning_of_a_side_with_the_other(repo, tmp, caplog): + scaling = make_build(tmp / "scaling", repo["wt-base"], cases(), scaling=True) + debug = make_build(tmp / "debug", repo["wt-head"], cases(), build_type="debug") + store = Store(tmp / "store.parquet") + with caplog.at_level(logging.WARNING, logger="benchx"): + session_module.compare_targets( + f"{scaling}:{repo['wt-base']}", f"{debug}:{repo['wt-head']}", profile="revisions", + adapter="google-benchmark", suite="demo-bench", rounds=2, store=store, run_key="n1", out=tmp / "out") + said = [m for level, m in records(caplog, logging.WARNING) if "the harness's own context says" in m] + assert len(said) == 2 # once for each condition, however many orders and cases + assert sum("CPU frequency scaling is enabled" in m for m in said) == 1 + assert sum("the benchmark library is a debug build" in m for m in said) == 1 + + +# --- review: the summary of a comparison + +def test_a_missing_unit_makes_the_summary_a_warning(caplog): + docs = [d for d in run_of(rounds=3) if not (d["revision"]["key"] == HEAD and + d["coordinates"]["workload"]["parameters"]["dtype"] == "'int16'")] + with caplog.at_level(logging.DEBUG, logger="benchx"): + doc = evaluate(docs) + assert doc["missing"] and not doc["failed_invariants"] and not doc["exclusions"] + summary = [(level, m) for level, m in records(caplog) if m.startswith("compared run")] + assert summary[0][0] == "WARNING" and re.search(r"; [1-9]\d* missing, 0 invariant", summary[0][1]) + + +def test_the_names_of_the_sides_are_cut_for_revisions_and_whole_for_anything_else(caplog): + docs = run_of() + doc = evaluate(docs) + doc["baseline"], doc["contender"] = "numpy-2.1.0-openblas", "numpy-2.1.0-mkl" + for profile, baseline, contender in (("revisions", "numpy-2.1.0-", "numpy-2.1.0-"), + ("environments", "numpy-2.1.0-openblas", "numpy-2.1.0-mkl")): + caplog.clear() + with caplog.at_level(logging.INFO, logger="benchx"): + compare._log_outcome(doc, docs, run_key="run", profile=profile, baseline=BASE, k=3.0, min_rounds=3) + summary = next(m for level, m in records(caplog) if m.startswith("compared run")) + assert f"baseline {baseline}, contender {contender}:" in summary diff --git a/tests/test_prototype.py b/tests/test_prototype.py index 204d77d6..8aa1c38e 100644 --- a/tests/test_prototype.py +++ b/tests/test_prototype.py @@ -419,7 +419,8 @@ def test_missing_build_is_refused_for_every_reason(tmp): assert all(type(problem) is core.Refusal for problem in problems) assert [str(problem).split(":")[0] for problem in problems] == [ "suite binary not found", - "cannot locate the checkout the target was built from; set target.source_dir", + f"cannot locate the checkout the target was built from (there is no CMakeCache.txt in {tmp / 'absent'}); " + "set target.source_dir", # the refusal says why ] @@ -590,7 +591,7 @@ def test_bx_run_delivers_to_the_local_store(repo, tmp, capsys): (tmp / f"{name}.json").write_text(json.dumps(order(build, repo["wt-head"], "cli", slot=slot))) store_path = tmp / "store.parquet" # no benchx.conf.json: the working directory is the root assert cli.main(["run", str(tmp / "o1.json"), "--out", str(tmp / "out")]) == cli.EXIT_OK - assert "ingested 4, duplicate 0" in capsys.readouterr().out # this run's files only, with load averages + assert "ingested 4, duplicate 0" in capsys.readouterr().err # this run's files only, with load averages assert cli.main(["run", str(tmp / "o2.json"), "--out", str(tmp / "out"), "--no-ingest"]) == cli.EXIT_OK assert len(results(tmp / "out")) == 4 # both runs' files are written total, rows = Store(store_path).head() diff --git a/tests/test_uc02.py b/tests/test_uc02.py index 7167d7c7..8782469e 100644 --- a/tests/test_uc02.py +++ b/tests/test_uc02.py @@ -244,7 +244,7 @@ def test_measure_mode_refuses_a_baseline_that_is_not_a_value_before_running(tree code, doc, err = measure(capsys, "--baseline", "variant") # the recorded value has its quotes assert code == cli.EXIT_REFUSED and doc is None assert "baseline 'variant' is not a value of role; use one of: 'baseline', 'variant'" in err - assert not (tree / "results").exists() # nothing ran + assert [p.name for p in (tree / "results").glob("*/*")] == ["bx.log"] # nothing ran: only the log, which says why def test_tables_name_the_sides_by_the_parameter_value(tree, capsys):