ENG-12608: reflex-bench harness core — CLI, benchmark model, statistics, result schema, reporting
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
| Check | Result |
|---|---|
uv run ruff check . | All checks passed! |
uv run ruff format --check . | 1589 files already formatted |
uv run pyright reflex tests packages/reflex-bench/src | 0 errors, 0 warnings, 0 informations |
uv run pytest tests/units/reflex_bench | 236 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-bench | PASS (Python 3.14 and --python 3.10) |
uv run --frozen --package reflex-release reflex-release sync --check | All 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
- Branch: this session is pinned to
farhan/fervent-cray-2fa3k9, so the PR comes from that branch instead offarhan/eng-12608-…; the title carries ENG-12608 for Linear. - Two extra modules:
compare.py(pairs entries by series key, runs the per-metric tests, Holm across the comparison, annotates the head document; shared byrun --baseline,compareand laterab/history) andreport/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}.pyinstead of onetest_report.py, plustest_compare.py,test_context.py,suites/test_selftest.py). selftest.noiseshiftdefaults to 1.0, not 0: it multiplies the values, so 0 would zero them.shift=1.2is a 20 % regression.- Hidden parameters are declared with a new
hidden_paramsdecorator argument, passed inctx.params, stored ashidden_paramson the entry and excluded from names and series keys (the acceptance flow comparesshift=1.2against ashift=1.0baseline). - Extra optional schema keys:
benchmarks[].hidden_params; top-levelcompared_to(baseline label and invocation, alpha, threshold, Holm family size, only-in-base/head, not-comparable entries with reasons);base/headside summaries in eachcomparison, soshowandexport --to mdcan render an annotated document without the base file.policyalso recordsruns,timeout_s,smoke,fail_onandfail_on_inconclusive.comparison.ratio/ciare relative changesmedian(B)/median(A) − 1likebootstrap_ratio_ci;ratiois null when the base median is 0. Verdict tokens areregressed|improved|unchanged|inconclusive(displayed as "no change" / "~ below threshold"). - "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 > alphathis keeps tiny samples from ever being "no change". 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'smax(abs(effect) − threshold, small)returns the cap for every effect inside the threshold. It always returns more than the current n, andNone(shown as "more than 200 runs/side needed") past the cap.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).- Selection: without
--suite, self-tests are hidden unless a filter starting withselftestnames them (the spec's ownrun selftest.sleep …test needs that);allexcludes them. - Compare header shows the Holm family size (tested, non-exact metrics): "(Holm, 3 metrics)" where the mock counts all rows.
- Timeouts cover every hook: the per-sample
timeoutfor prepare/sample/conclude and a newsetup_timeout(600 s) for setup_cache/setup/cleanup, so a hung setup cannot hang the harness either. REFLEX_BENCH_HOMEreplaces the.reflex-benchdirectory itself (likeCARGO_HOME), rather than the directory above it.- CLI additions: usage errors exit with 1, since click's default 2 would read as "regression";
comparealso takes--force,--fail-onand--fail-on-inconclusive; comparing with nothing comparable exits 1 with a message.--kindand--keepare onrunas the spec asks. doctor: bun/node/chromium presence is informational and not counted as a warning (it adds no variance). Virtualization falls back to the cpuinfohypervisorflag, and container detection also askssystemd-detect-virt --container.- 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 unsafeREFLEX_BENCH_PROFILEis slugified because it names a directory. uv.lock: only the 21 lines forreflex-benchare added; a full re-lock with current uv re-simplifies unrelated markers (~180 lines of churn).uv lock --checkpasses.- No news fragment: the package is never published and
changelog-checkrequires none.
Self-review
Issues found in an adversarial pass over the diff, and what I did:
- 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;Annotatedmarks CI intervals. - 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.
- An invalid
--save-asname was rejected only after the benchmarks ran. Fixed: validated up front, like--baseline. - A comparison with nothing comparable printed an empty table and exited 1 without saying why. Fixed: "nothing compared: …" plus the reasons.
- The environment-dependent
--fail-ondefault was not visible. Fixed: recorded inpolicyand printed in the header. cache_dirkeying: see "Review fixes" below (now per subject identity + benchmark + params, matching whensetup_cacheruns).- Efficiency: the median-CI rank recomputed large binomial coefficients on every step (now incremental) and
summarizesorted twice for Tukey (now reuses its quartiles). - 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. - On Python ≥ 3.11
concurrent.futures.TimeoutErroris the builtinTimeoutError, so a hook raisingTimeoutErrorcould have been mistaken for a harness timeout. Timeouts are detected withconcurrent.futures.wait; tested. sys.exit()inside a hook would have ended the harness; it now fails the instance. Tested.ThreadPoolExecutorthreads 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:
- Ctrl-C during a hook runs
conclude/cleanupon a fresh worker instead of queueing behind the runningsample()(a SIGINT at 2 s with--timeout 8now exits at 2.0 s instead of 8 s). - 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 areskipped. cache_diris keyed by subject identity (commit + dirty, else spec), benchmark id and params, so parameter sets no longer overwrite each other and a movinggit:ref cannot reuse a stale cache.- New
Scheduler.open/Sessionlifecycle for interleaved arms, and a publicmake_context(see "Interfaces for later PRs"). WorkspaceSubjectis replaced byworkspace_subject(), sodataclasses.replaceworks on subjects.REFLEX_BENCH_PROFILEis always slugified; an empty or dot-leading result falls back to the computed profile with a warning.- Autosave numbers are claimed atomically (
results/<profile>/.claims/NNNN), so concurrent runs cannot share a number. --max-runsdefaults tomax(30, --min-runs); theselftest.timeoutestimate 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.