ENG-12608: reflex-bench harness core — CLI, benchmark model, statistics, result schema, reporting

Draft
FA
2mo ago
+10286-2

Linear: ENG-12608 (project P-ENG-487, Holistic Framework Benchmarks), PR-1.

All Submissions:

  • Have you followed the guidelines stated in CONTRIBUTING.md file?
  • Have you checked to ensure there aren't any other open Pull Requests for the desired changed?

Type of change

  • New feature (non-breaking change which adds functionality)

Description

Adds packages/reflex-bench, a never-published uv workspace member with the core of the macro benchmark harness: the reflex-bench CLI (list, run, show, compare, doctor, export), the benchmark model and scheduler, stdlib-only statistics, the reflex-bench/1 result schema, local storage and baselines, the machine profile and doctor, and terminal, markdown and Bencher Metric Format reports. It ships only self-test benchmarks (selftest.sleep, .noise, .exact, .fail, .timeout). The harness never imports reflex; it only reads its package metadata (a unit test checks that importing the CLI and discovering the suites loads no reflex, reflex_base or component module).

Repo wiring: reflex-bench in the dev group and [tool.uv.sources], in never-publish-packages, in pyright extraPaths and coverage source; .reflex-bench/ in .gitignore. reflex-release sync regenerates nothing (never-published packages are not in the workflows). The package README documents the CLI, the authoring API, the statistics and the storage layout.

Example (uv run reflex-bench run --suite selftest on this sandbox):

reflex-bench 0.0.0.post50.dev0+84bb6abb3 · reflex 0.9.12.post6.dev0+84bb6abb3 (workspace 84bb6ab, dirty) · py 3.14.7
machine: linux-x86_64 · Intel Xeon · 4 cores · vm ⚠ · load 0.26
policy: runs 10–30, min-time 30 s, warmup per benchmark, timeout per benchmark, α=0.01 (Holm), threshold 3 %, CI 95 %, bootstrap 10000, seed 1234, fail-on never
⚠ 1 doctor warning: expect ±3–5 % extra variance (run `reflex-bench doctor`)

selftest.exact          median ± 95 % CI   range                  n
  bytes                 238.4 kB (exact)                          1
selftest.fail
  ✗ failed: RuntimeError: selftest.fail always fails
selftest.noise[cv=5]
  value                 0.997 s ± 3.8 %    0.904 s … 1.160 s     30
selftest.noise[cv=20]
  value                 0.939 s ± 12 %     0.636 s … 1.397 s     30
  ⚠ high variance: CV 19 % (warns at 10 %)
selftest.sleep[ms=10]
  wall                  10.14 ms ± 0.1 %   10.10 ms … 15.11 ms   30
  ⚠ 3 severe outliers (samples 5: +49 %, 8: +1 %, 21: +3 %). Kept.
selftest.sleep[ms=50]
  wall                  50.17 ms ± 0.0 %   50.12 ms … 52.90 ms   30
  ⚠ 2 severe outliers (samples 2: +5 %, 30: +1 %). Kept.
selftest.timeout
  ✗ timeout: sample() exceeded the 0.5 s timeout

7 benchmarks: 5 ok · 1 failed · 1 timeout

saved .reflex-bench/results/linux-x86_64-xeon-py3.14/0001_84bb6ab_dirty_20260922T212107.json

and uv run reflex-bench run selftest.noise --param shift=1.2 --baseline 1 --fail-on regression (exit code 2):

reflex-bench compare 1 this run   α=0.01 (Holm, 2 metrics)  threshold=3 %

                                base              head
selftest.noise[cv=5]    value   0.997 s ± 3.8 %   1.187 s ± 1.8 %   +19 % [+15, +21]    p=0.000 n=30/30   regressed
selftest.noise[cv=20]   value   0.939 s ± 12 %    1.141 s ± 13 %    +21 % [+8.0, +42]   p=0.000 n=30/30   regressed
geomean (time) +20 %
2 regressed · 0 improved · 0 inconclusive · 0 unchanged
only in base: selftest.exact, selftest.fail, selftest.sleep[ms=10], selftest.sleep[ms=50], selftest.timeout

New Feature Submission:

  • Does your submission pass the tests?
  • Have you linted your code locally prior to submission?

Changes To Core Features:

  • Have you added an explanation of what your changes do and why you'd like us to include them?
  • Have you written new tests for your core changes, as applicable?
  • Have you successfully ran tests with your changes locally?

Check results

CheckResult
uv run ruff check .All checks passed!
uv run ruff format --check .1589 files already formatted
uv run pyright reflex tests packages/reflex-bench/src0 errors, 0 warnings, 0 informations
uv run pytest tests/units/reflex_bench236 passed in 3.5 s (also 236 passed on Python 3.10); package coverage 95.3 %
uv run pytest tests/units --cov --no-cov-on-fail --cov-report=9995 passed, 20 skipped in 153 s; "Required test coverage of 72.0% reached. Total coverage: 79.92%"
uv run python scripts/check_min_deps.py reflex-benchPASS (Python 3.14 and --python 3.10)
uv run --frozen --package reflex-release reflex-release sync --checkAll 5 scaffolded workflows are up to date.
reflex-release changelog-check / check-headings (BASE_REF=origin/main)No packaged source changes; no changelog fragments required. / No new changelog version headings.
uv run pre-commit run --files <changed files>ruff-format, ruff-check, codespell, update-pyi-files, pyright, ty: Passed
uv lock --check (uv 0.12.5 and 0.12.17)Passes

Acceptance criteria (section 12): list --suite selftest lists the 7 self-test instances; run --suite selftest prints the table, autosaves under .reflex-bench/results/… and exits 0 with selftest.fail/selftest.timeout reported as failed/timeout; run selftest.noise --param shift=1.2 --baseline <shift=1.0 run> --fail-on regression prints regressed and exits 2; compare A.json B.json --format md prints a GitHub table; doctor prints the checks; export FILE --to bmf prints valid BMF JSON.

Statistics golden values were computed once outside the repo with scipy 1.18.1, numpy 2.5.3 and statsmodels 0.15.0; each test notes the call that produced its value.

Interfaces for later PRs

@benchmark (reflex_bench.registry):

@benchmark(
    *, id: str, metrics: Mapping[str, Metric], suites: Sequence[str] = (),
    kind: Kind = "time",                # time | startup | rate | latency | peakmem | track
    params: Mapping[str, Sequence[Any]] | None = None,   # cartesian product -> instances
    hidden_params: Mapping[str, Any] | None = None,      # in ctx.params, not in name/series key
    warmup: int = 0, timeout: float = 60.0,              # per prepare/sample/conclude call
    setup_timeout: float = 600.0,                        # per setup_cache/setup/cleanup call
    estimate: float = 1.0, min_version: str | None = None,
)
class X:  # instantiated without arguments; every hook but sample is optional
    def setup_cache(self, ctx): ...  # once per subject + params per invocation
    def setup(self, ctx): ...
    def prepare(self, ctx): ...
    def sample(self, ctx) -> None | dict[str, float] | SampleResult: ...
    def conclude(self, ctx): ...     # always runs, also after a failure/timeout
    def cleanup(self, ctx): ...      # always runs

Metric(unit: str, direction: "lower" | "higher", assume: "nothing" | "exact" = "nothing", description: str = "")
SampleResult(values: Mapping[str, float], extra: dict[str, Any] | None = None)

sample() contract: return None, a dict of metric values or a SampleResult; extra must be JSON-serializable and is stored per sample. The scheduler always times the call with perf_counter_ns and fills a declared wall metric that is not returned. Undeclared keys, missing declared metrics and non-finite values fail the instance. Instance(benchmark, params, ctx) exposes setup_cache/setup/prepare/sample/conclude/cleanup as zero-argument methods, e.g. benchmark.pedantic(inst.sample, setup=inst.prepare, teardown=inst.conclude, rounds=n); hooks keep no state in the scheduler.

Threading/timeouts: all hooks of an instance run on one daemon worker thread; a hook that misses its deadline ends the instance with timeout, the stuck thread is abandoned (its stack becomes the traceback tail) and teardown runs on a fresh thread, so conclude should kill whatever sample started.

Context / Subject (reflex_bench.context):

@dataclass
class Subject:
    spec: str; source: str; python: Path; reflex_version: str | None
    commit: str | None; dirty: bool | None; python_version: str
    extra: dict[str, str] = field(default_factory=dict)
    def to_doc(self) -> SubjectDoc: ...

def workspace_subject(cwd: Path | None = None) -> Subject: ...  # sys.executable, importlib.metadata, git state
# Subject.identity: commit (+ "-dirty") when known, else spec

@dataclass
class Context:
    subject: Subject; params: dict[str, Any]
    workdir: Path      # fresh per instance, removed after cleanup unless --keep
    cache_dir: Path    # persistent per subject identity + benchmark id + params (setup_cache runs once per dir)
    env: dict[str, str]  # os.environ + telemetry/update checks off, NO_COLOR, PYTHONUNBUFFERED, PYTHONHASHSEED=0, granian
    rng: random.Random; log: logging.Logger; arm: str = "A"

For PR-2 (ABBA): Scheduler.open(planned, entry, arm=...) is a context manager yielding a Session that stays set up; session.sample_once(round=, order=, warmup=) runs prepare → sample → conclude and records the sample with the caller's round/order; closing runs cleanup and records failures. Several sessions (one per arm, possibly from two schedulers with different subjects) can fill one entry. run_one is a thin loop over one session. compare.compare(base, head, base_arm=..., head_arm=...) compares arms and applies Holm across the comparison.

For PR-11: make_context(subject, planned, *, home, seed, arm="A") -> Context builds the same context the scheduler uses (cache dir, env, seed), so a pytest-codspeed wrapper can call the hooks with benchmark.pedantic.

Schema reflex-bench/1 (reflex_bench.schema, TypedDicts; the validator is derived from them, unknown keys allowed):

{
  "schema": "reflex-bench/1",
  "tool": {"name", "version"},
  "invocation": {"id", "argv", "started_at", "duration_s", "mode": "local|ci",
                 "kind": "local|ci|pr|daily|backfill|aa", "ci": null | {"provider", "run_id", "url", "runner"}, "rng_seed"},
  "subjects": {"A": {"spec", "source", "python", "python_version", "reflex_version", "commit", "dirty", "extra"}},
  "machine": {"profile_id", "os", "kernel", "arch", "cpu_model", "cpu_count", "ram_bytes", "governor", "turbo",
              "load_avg_1m", "ac_power", "cgroup_v2", "container", "virtualized", "tools": {"bun", "node", "chromium"}},
  "fixture": null,                       // optional: {"name", "content_hash", "params"}
  "policy": {"runs", "min_runs", "max_runs", "min_time_s", "warmup", "timeout_s", "smoke", "alpha", "correction",
             "threshold_rel", "confidence", "bootstrap_resamples", "fail_on", "fail_on_inconclusive"},
  "benchmarks": [{
    "id", "params", "hidden_params"?, "kind", "version": "sha256:…", "status": "ok|failed|timeout|unsupported|skipped",
    "error", "traceback_tail", "dims": {},
    "metrics": {"<name>": {"unit", "direction", "assume", "samples": {"A": [...]}, "summary": {"A": {…}},
                           "comparison": null | {"base": {side}, "head": {side}, "ratio", "ci", "p", "p_adj", "test",
                                                 "threshold_rel", "verdict", "runs_needed", "mode": "ratio|absolute"},
                           "warnings": []}},
    "sample_meta": [{"arm", "round", "order", "started_at", "warmup", "duration_s"}],
    "sample_extra": [null, …]
  }],
  "compared_to": {…}                     // optional, written with the comparison blocks
}

Series key (store.series_key): id + canonical params + canonical dims + machine.profile_id + fixture.content_hash + benchmark version.

Deviations from the spec

  1. Branch: this session is pinned to farhan/fervent-cray-2fa3k9, so the PR comes from that branch instead of farhan/eng-12608-…; the title carries ENG-12608 for Linear.
  2. Two extra modules: compare.py (pairs entries by series key, runs the per-metric tests, Holm across the comparison, annotates the head document; shared by run --baseline, compare and later ab/history) and report/format.py (unit scaling and number formatting shared by the terminal and markdown reports). Tests follow CLAUDE.md's mirrored layout (tests/units/reflex_bench/report/test_{format,table,markdown,bmf}.py instead of one test_report.py, plus test_compare.py, test_context.py, suites/test_selftest.py).
  3. selftest.noise shift defaults to 1.0, not 0: it multiplies the values, so 0 would zero them. shift=1.2 is a 20 % regression.
  4. Hidden parameters are declared with a new hidden_params decorator argument, passed in ctx.params, stored as hidden_params on the entry and excluded from names and series keys (the acceptance flow compares shift=1.2 against a shift=1.0 baseline).
  5. Extra optional schema keys: benchmarks[].hidden_params; top-level compared_to (baseline label and invocation, alpha, threshold, Holm family size, only-in-base/head, not-comparable entries with reasons); base/head side summaries in each comparison, so show and export --to md can render an annotated document without the base file. policy also records runs, timeout_s, smoke, fail_on and fail_on_inconclusive. comparison.ratio/ci are relative changes median(B)/median(A) − 1 like bootstrap_ratio_ci; ratio is null when the base median is 0. Verdict tokens are regressed|improved|unchanged|inconclusive (displayed as "no change" / "~ below threshold").
  6. "Too few samples for a CI" is defined as either side having no median CI (n < 6 at 95 %): the change CI is then null and the verdict inconclusive. With min_achievable_p > alpha this keeps tiny samples from ever being "no change".
  7. runs_needed(n, effect, ci, threshold, *, alpha, confidence, cap) reuses the computed effect and CI (no second bootstrap) and uses |abs(effect) − threshold| as the margin, so it also estimates the runs needed to show "no change"; the spec's max(abs(effect) − threshold, small) returns the cap for every effect inside the threshold. It always returns more than the current n, and None (shown as "more than 200 runs/side needed") past the cap.
  8. stability_warnings(xs, first_sample, direction="lower"): the direction lets a slow first sample of a higher-is-better rate be caught; it also warns when the minimum is ≥ 50 % below the median (pyperf's symmetric check).
  9. Selection: without --suite, self-tests are hidden unless a filter starting with selftest names them (the spec's own run selftest.sleep … test needs that); all excludes them.
  10. Compare header shows the Holm family size (tested, non-exact metrics): "(Holm, 3 metrics)" where the mock counts all rows.
  11. Timeouts cover every hook: the per-sample timeout for prepare/sample/conclude and a new setup_timeout (600 s) for setup_cache/setup/cleanup, so a hung setup cannot hang the harness either.
  12. REFLEX_BENCH_HOME replaces the .reflex-bench directory itself (like CARGO_HOME), rather than the directory above it.
  13. CLI additions: usage errors exit with 1, since click's default 2 would read as "regression"; compare also takes --force, --fail-on and --fail-on-inconclusive; comparing with nothing comparable exits 1 with a message. --kind and --keep are on run as the spec asks.
  14. doctor: bun/node/chromium presence is informational and not counted as a warning (it adds no variance). Virtualization falls back to the cpuinfo hypervisor flag, and container detection also asks systemd-detect-virt --container.
  15. Machine profile: the CPU slug drops vendor names and marketing noise (AMD Ryzen 9 7950X 16-Core Processor → ryzen-9-7950x, as in the spec's example); arch is normalized (amd64→x86_64, aarch64→arm64); an unsafe REFLEX_BENCH_PROFILE is slugified because it names a directory.
  16. uv.lock: only the 21 lines for reflex-bench are added; a full re-lock with current uv re-simplifies unrelated markers (~180 lines of churn). uv lock --check passes.
  17. No news fragment: the package is never published and changelog-check requires none.

Self-review

Issues found in an adversarial pass over the diff, and what I did:

  1. The validator repeated every TypedDict field by hand (two sources of truth that later PRs would have to keep in sync). Fixed: it is now derived from the TypedDicts with get_type_hints; Annotated marks CI intervals.
  2. A failure while creating the context (e.g. an unwritable cache directory) escaped the failure capture and would have crashed the run. Fixed and tested.
  3. An invalid --save-as name was rejected only after the benchmarks ran. Fixed: validated up front, like --baseline.
  4. A comparison with nothing comparable printed an empty table and exited 1 without saying why. Fixed: "nothing compared: …" plus the reasons.
  5. The environment-dependent --fail-on default was not visible. Fixed: recorded in policy and printed in the header.
  6. cache_dir keying: see "Review fixes" below (now per subject identity + benchmark + params, matching when setup_cache runs).
  7. Efficiency: the median-CI rank recomputed large binomial coefficients on every step (now incremental) and summarize sorted twice for Tukey (now reuses its quartiles).
  8. Values just under 1 s rendered as 996.8 ms … 1,159.5 ms. Fixed: one scale per row from the row's largest value, as in the mock.
  9. On Python ≥ 3.11 concurrent.futures.TimeoutError is the builtin TimeoutError, so a hook raising TimeoutError could have been mistaken for a harness timeout. Timeouts are detected with concurrent.futures.wait; tested.
  10. sys.exit() inside a hook would have ended the harness; it now fails the instance. Tested.
  11. ThreadPoolExecutor threads are joined at interpreter exit, so a hung sample would block exit; the worker threads are daemons.

Known limitations, left as is: Python cannot kill a stuck thread, so it runs until its hook returns (later PRs kill process trees in conclude); Ctrl-C discards the partial result (exit 130); list estimates are rough (selftest.timeout shows ~15 s); round/order are 0 until ab exists. Windows and macOS were not run locally; the tests avoid Linux-only assumptions (fake sysroot, patched probes) and the CI matrix covers them.

Review fixes (commits b6a7b0444, c5dd7fac0)

Scheduler and interfaces:

  1. Ctrl-C during a hook runs conclude/cleanup on a fresh worker instead of queueing behind the running sample() (a SIGINT at 2 s with --timeout 8 now exits at 2.0 s instead of 8 s).
  2. An abandoned (timed-out or interrupted) hook gets ABANDON_GRACE_S (5 s) after teardown. If it is still running, the work directory is kept, the entry records why, and the benchmark's remaining parameter sets are skipped.
  3. cache_dir is keyed by subject identity (commit + dirty, else spec), benchmark id and params, so parameter sets no longer overwrite each other and a moving git: ref cannot reuse a stale cache.
  4. New Scheduler.open / Session lifecycle for interleaved arms, and a public make_context (see "Interfaces for later PRs").
  5. WorkspaceSubject is replaced by workspace_subject(), so dataclasses.replace works on subjects.
  6. REFLEX_BENCH_PROFILE is always slugified; an empty or dot-leading result falls back to the computed profile with a warning.
  7. Autosave numbers are claimed atomically (results/<profile>/.claims/NNNN), so concurrent runs cannot share a number.
  8. --max-runs defaults to max(30, --min-runs); the selftest.timeout estimate matches its real duration.

Statistics and gating:
9. A benchmark that fails or times out in head (and did not fail in base) is a regression for --fail-on regression (exit 2), in both compare and run --baseline; reports list it under "failed in head". Head becoming unsupported/skipped is not a regression.
10. A zero or negative value in the base no longer blocks a verdict: the ratio bootstrap only needs a positive base median per resample. When the base median is 0, the comparison is absolute (difference of medians with a bootstrap CI, in the metric's units), recorded as optional comparison.mode = "absolute".
11. runs_needed never returns a value at or below the current n; past the cap it returns None.
12. A slower first sample warns even when MAD is 0.
13. The summary line pluralizes correctly ("1 benchmark").

Simplification:
14. The schema validator is an explicit check (required keys from each TypedDict's __required_keys__, schema id, non-empty profile_id and subjects, valid statuses/directions/assume, finite non-boolean samples aligned with sample_meta and sample_extra) instead of a generic type checker built from the TypedDicts. Unknown and optional keys stay allowed.
15. Policy keeps only the cross-field max_runs >= min_runs check; click enforces the ranges. --fail-on is a click.Choice.
16. The macOS sysctl probes and the Windows browser path are removed; non-Linux systems fall back to platform/psutil.

Checks after the fixes: uv run pytest tests/units/reflex_bench 272 passed (package coverage 96.9 %); ruff check/format, pyright and the pre-commit hooks pass; manual smoke of run --suite selftest, run --baseline … --fail-on regression (exit 2) and doctor.