Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 4 additions & 3 deletions docs/benchx.md
Original file line number Diff line number Diff line change
Expand Up @@ -75,14 +75,15 @@ bx run <order.json> [--out DIR] [--no-ingest]
# runner + Google Benchmark adapter → result files → local store

bx ingest <dir|file> # result files and work orders → the local store
bx series [--workload … --quantity …] # list series
bx history <series> # one series' points (a query); dirty ones are marked
bx series [--workload … --quantity … --all] # list measurand series (--all adds conditions like load-average)
bx history <series> [--repo DIR] # one series' points (git ancestry order when --repo or checkout has them)
bx head [-n 10] [--project P] [--workload W] [--json|--table] # the latest results, newest first; dirty ones are marked
bx view [--out DIR] [--serve] [--host 127.0.0.1] [--port 8000] [--open]
[--store PATH | --results PATH… | --runs DIR]
[--project-file PATH] [--title TITLE] [--repo DIR]
[--views-format json|parquet] [--marts | --no-marts] [--stamp STR]
# build and serve the static benchmark dashboard (no --out: temp dir + serve)
[--cli [changes|movers|latest|commits] [--commit REF] [--workload REGEX] [-n N] [--json]]
# build/serve the static dashboard, or print derived views to stdout (--cli)

bx target describe|prepare TARGET # a target's description (a provider's answer, or a build directory's sidecar)
bx validate <file>… [--kind KIND] # every problem in each document, by schema and rules
Expand Down
119 changes: 108 additions & 11 deletions src/benchx/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
from . import bench as bench_mod
from . import compare as compare_mod
from . import config as config_mod
from . import core, harnesses, log, orders, runner, session, snapshot
from . import core, harnesses, log, orders, projection, runner, session, snapshot
from . import tables as tables_mod
from . import target as target_mod
from . import views as views_mod
Expand Down Expand Up @@ -665,30 +665,55 @@ def cmd_series(args):
return EXIT_REFUSED
if (store := _open_store(cfg.store_path, "series")) is None:
return EXIT_REFUSED
listed = store.series(args.workload, args.quantity)
listed = store.series(args.workload, args.quantity, include_conditions=args.all)
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']}]"
params = json.loads(s["parameters"]) if s.get("parameters") else {}
label = projection.workload_label({"name": s["workload"], "parameters": params})
print(f"{s['fingerprint'][:12]} {s['project']} {label} {s['quantity']} [{s['unit']}]"
f" est={estimator}")
return EXIT_OK


def _git_revision_order(shas: list[str], repo: Path) -> dict[str, int] | None:
"""Topological commit rank from git ancestry/committer_date for `shas`, or None."""
from .views import inputs as view_inputs, marts as view_marts

git_repo = view_inputs._find_git_repo(repo)
if git_repo is None or not shas:
return None
meta = view_inputs._git_commit_info(shas, git_repo)
if not meta:
return None
runs = [
{"sha": sha, "parents": info.get("parents") or [], "committer_date": info.get("committer_date")}
for sha, info in meta.items()
]
return view_marts._order_shas(runs)


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
if (store := _open_store(cfg.store_path, "history")) is None:
return EXIT_REFUSED
points = store.history(args.series)
raw_points = store.history(args.series)
repo = Path(args.repo) if args.repo is not None else cfg.root
rev_order = _git_revision_order(sorted({p["revision"] for p in raw_points}), repo) if raw_points else None
points = store.history(args.series, revision_order=rev_order) if rev_order else raw_points
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")
if rev_order:
print("ordered by git revision ancestry")
else:
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 ""
warned = f" [{', '.join(p['warnings'])}]" if p["warnings"] else "" # such as dirty-subject-tree
Expand Down Expand Up @@ -976,13 +1001,42 @@ def cmd_validate(args):


def cmd_view(args):
"""Build static dashboard views and optionally serve them over local HTTP."""
"""Build static dashboard views and optionally serve them over local HTTP, or render CLI views."""
if (cfg := _load("view")) is None:
return EXIT_REFUSED
serve = args.serve or args.out is None
if args.open and not serve:
say.error("bx view: error: --open goes with serving (omit --out, or pass --serve)")
return EXIT_REFUSED
if args.cli is not None:
site_flags = [
flag for flag, active in (
("--out", args.out is not None),
("--serve", args.serve),
("--open", args.open),
("--marts", args.marts),
("--no-marts", args.no_marts),
("--views-format parquet", args.views_format != "json"),
("--stamp", args.stamp is not None),
)
if active
]
if site_flags:
say.error(f"bx view: error: {', '.join(site_flags)} cannot be combined with --cli")
return EXIT_REFUSED
else:
cli_flags = [
flag for flag, active in (
("--commit", args.commit is not None),
("--workload", args.workload is not None),
("--limit", args.limit is not None),
("--json", args.json),
)
if active
]
if cli_flags:
say.error(f"bx view: error: {', '.join(cli_flags)} go with --cli")
return EXIT_REFUSED
serve = args.serve or args.out is None
if args.open and not serve:
say.error("bx view: error: --open goes with serving (omit --out, or pass --serve)")
return EXIT_REFUSED
if (cfg := _start_logging(cfg, args, None, "view")) is None:
return EXIT_REFUSED

Expand All @@ -994,6 +1048,37 @@ def cmd_view(args):
else:
source_kwargs["store_path"] = args.store if args.store is not None else cfg.store_path

repo = Path(args.repo) if args.repo is not None else cfg.root

if args.cli is not None:
try:
marts, _runs, _source, outcome = views_mod.load_marts(**source_kwargs, repo=repo)
rendered = views_mod.render_cli(
marts,
args.cli,
commit=args.commit,
workload=args.workload,
limit=args.limit,
as_json=args.json,
repo=repo,
)
except ModuleNotFoundError as exc:
if exc.name and exc.name.split(".")[0] == "pyarrow":
hint = ""
if "store_path" in source_kwargs:
hint = ", or pass --results DIR to build views from JSON results directly"
say.error(f"bx view: error: {exc}{hint}")
return EXIT_REFUSED
raise
except views_mod.ViewError as exc:
say.error(f"bx view: error: {exc}")
return EXIT_REFUSED
exit_code = EXIT_OK
if outcome and outcome["rejected"]:
exit_code = _report(outcome)
print(rendered)
return exit_code

if args.marts:
write_marts: bool | None = True
elif args.no_marts:
Expand All @@ -1003,7 +1088,6 @@ def cmd_view(args):
else:
write_marts = None

repo = Path(args.repo) if args.repo is not None else cfg.root
build_kwargs = {
**source_kwargs,
"project_file": Path(args.project_file) if args.project_file else None,
Expand Down Expand Up @@ -1209,10 +1293,13 @@ def main(argv=None):
p = sub.add_parser("series", parents=[options], help="list series")
p.add_argument("--workload")
p.add_argument("--quantity")
p.add_argument("--all", action="store_true",
help="include condition measurements such as load-average")
p.set_defaults(fn=cmd_series)

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.add_argument("--repo", help="git checkout used to order points by revision ancestry")
p.set_defaults(fn=cmd_history)

p = sub.add_parser("head", parents=[options], help="the latest results in the store, newest first")
Expand Down Expand Up @@ -1312,6 +1399,16 @@ def main(argv=None):
p.add_argument("--views-format", choices=("json", "parquet"), default="json",
help="format for frontend view payloads under data/views/ (default %(default)s; parquet requires benchx[parquet])")
p.add_argument("--stamp", help="cache-busting version stamped onto static asset URLs in index.html")
cli_group = p.add_argument_group("terminal output")
cli_group.add_argument(
"--cli", nargs="?", const="changes", choices=views_mod.CLI_VIEWS, metavar="VIEW",
help=f"print a derived view table to stdout instead of building/serving HTML "
f"({', '.join(views_mod.CLI_VIEWS)}; default changes)",
)
cli_group.add_argument("--commit", help="with --cli: filter to one commit (SHA prefix or git ref)")
cli_group.add_argument("--workload", help="with --cli: regex filter on suite or case name")
cli_group.add_argument("-n", "--limit", type=int, help="with --cli: maximum number of rows to print")
cli_group.add_argument("--json", action="store_true", help="with --cli: emit the selected view rows as JSON")
p.set_defaults(fn=cmd_view)

args, extra = ap.parse_known_args(argv)
Expand Down
47 changes: 38 additions & 9 deletions src/benchx/store.py
Original file line number Diff line number Diff line change
Expand Up @@ -225,19 +225,47 @@ def entities(self, projection: Projection = identity.POLICY) -> dict[str, list[d
_add_entities(found, doc, store_project(doc), projection)
return {name: list(rows.values()) for name, rows in found.items()}

def series(self, workload=None, quantity=None, projection: Projection = identity.POLICY) -> list[dict]:
def series(
self,
workload=None,
quantity=None,
projection: Projection = identity.POLICY,
*,
include_conditions: bool = False,
) -> list[dict]:
rows = self.entities(projection).get("series", [])
return [s for s in rows if (workload is None or workload in s["workload"])
and (quantity is None or s["quantity"] == quantity)]

def history(self, fingerprint_prefix: str, projection: Projection = identity.POLICY) -> list[dict]:
return [
s for s in rows
if (include_conditions or quantity is not None or s.get("kind", "measurand") != "condition")
and (workload is None or workload in s["workload"])
and (quantity is None or s["quantity"] == quantity)
]

def history(
self,
fingerprint_prefix: str,
projection: Projection = identity.POLICY,
*,
revision_order: dict[str, int] | None = None,
) -> list[dict]:
"""A series' points in axis order, each with the ignored facts that
changed since the point before it (§4.3). On the revision axis they
are listed by measurement start instead: the implementation has no revision
graph (schema §4.1)."""
are ordered by `revision_order` when a git graph supplies one, else by
measurement start (schema §4.1)."""
points = [p for p in self.entities(projection).get("series_point", [])
if p["series_fingerprint"].startswith(fingerprint_prefix)]
points.sort(key=lambda p: (projection.order_key(tuple(p["axis"])), p["started_at"], p["ingest_key"]))
if revision_order:
fallback = len(revision_order) + 1
points.sort(
key=lambda p: (
revision_order.get(p["revision"], fallback),
projection.order_key(tuple(p["axis"])),
p["started_at"],
p["ingest_key"],
)
)
else:
points.sort(key=lambda p: (projection.order_key(tuple(p["axis"])), p["started_at"], p["ingest_key"]))
previous = {}
for point in points:
ignored = point.pop("ignored")
Expand Down Expand Up @@ -379,11 +407,12 @@ def put(name, row):
"fingerprint": core.sha256_hex(core.canonical(env_identity)),
"identity": core.canonical(env["identity"]).decode()})
put("revision", {"source": doc["source"]["uri"], "key": doc["revision"]["key"]})
kind = doc["measurement"].get("kind", "measurand")
for point in identity.points(doc, project, projection):
put("series", {"fingerprint": point["series_fingerprint"],
"identity_schema": projection.identity_schema, "project": project,
"workload": coordinates["workload"]["name"], "parameters": parameters,
"quantity": quantity["name"], "unit": quantity["unit"],
"quantity": quantity["name"], "unit": quantity["unit"], "kind": kind,
"estimator": core.canonical(point["estimator"]).decode(),
"comparison_identity": core.canonical(point["identity"]).decode()})
put("series_point", {"series_fingerprint": point["series_fingerprint"],
Expand Down
6 changes: 5 additions & 1 deletion src/benchx/views/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,11 @@
from .inputs import ViewError, parse_time, read_results, read_runs_dir, read_runs_metadata, read_store, run_schema, write_run
from .marts import MOVERS_PER_COMMIT, RECENT, build_changes, build_commits, build_latest, build_marts, build_movers, build_points, write_parquet_marts
from .payloads import MOVERS, NOISIEST, NOTABLE, RECENT_COMMITS, SPARK_POINTS, build_views, last_executed, newest_commits, signed
from .site import STATIC_DIR, build_site, create_server, resolve_project, serve_site
from .site import STATIC_DIR, build_site, create_server, load_marts, resolve_project, serve_site
from .text import CLI_VIEWS, render_cli

__all__ = [
"CLI_VIEWS",
"MOVERS",
"MOVERS_PER_COMMIT",
"NOISIEST",
Expand All @@ -30,12 +32,14 @@
"build_views",
"create_server",
"last_executed",
"load_marts",
"newest_commits",
"parse_time",
"read_results",
"read_runs_dir",
"read_runs_metadata",
"read_store",
"render_cli",
"resolve_project",
"run_schema",
"serve_site",
Expand Down
60 changes: 41 additions & 19 deletions src/benchx/views/site.py
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,42 @@ def _write_logs(runs: list[dict], data_dir: Path) -> int:
return written


def load_marts(
*,
store_path: str | Path | None = None,
results_paths: list[str | Path] | None = None,
runs_dir: str | Path | None = None,
repo: Path | None = None,
has_parquet_marts: bool = False,
) -> tuple[dict, list[dict], str, dict | None]:
"""Load view inputs and compute derived marts in memory without writing a site."""
chosen = sum(x is not None for x in (store_path, results_paths, runs_dir))
if chosen != 1:
raise inputs.ViewError("give exactly one of store_path, results_paths, or runs_dir")

outcome = None
if runs_dir is not None:
source = "runs"
runs, raw_points, ingest_problems = inputs.read_runs_dir(runs_dir)
elif results_paths is not None:
source = "results"
runs, raw_points, ingest_problems, outcome = inputs.read_results(
list(results_paths), repo=repo
)
else:
source = "store"
runs, raw_points, ingest_problems = inputs.read_store(store_path, repo=repo)

marts = marts_mod.build_marts(
runs,
raw_points,
ingest_problems=ingest_problems,
source=source,
has_parquet_marts=has_parquet_marts,
)
return marts, runs, source, outcome


def build_site(
out: Path,
*,
Expand Down Expand Up @@ -155,27 +191,13 @@ def build_site(
if views_format == "parquet":
inputs._require_pyarrow("writing Parquet views")

outcome = None
if runs_dir is not None:
source = "runs"
runs, raw_points, ingest_problems = inputs.read_runs_dir(runs_dir)
elif results_paths is not None:
source = "results"
runs, raw_points, ingest_problems, outcome = inputs.read_results(
list(results_paths), repo=repo
)
else:
source = "store"
runs, raw_points, ingest_problems = inputs.read_store(store_path, repo=repo)

marts = marts_mod.build_marts(
runs,
raw_points,
ingest_problems=ingest_problems,
source=source,
marts, runs, source, outcome = load_marts(
store_path=store_path,
results_paths=results_paths,
runs_dir=runs_dir,
repo=repo,
has_parquet_marts=emit_marts,
)
del raw_points
marts["manifest"]["views_format"] = views_format

out = Path(out).resolve()
Expand Down
Loading
Loading