ENG-12605: reflex-bench app process driver (reflex run/compile/export as subprocesses) and collectors

Draft
FA
2mo ago
+5001-37

Linear: ENG-12605 (the driver part; upstreaming it into reflex.testing as public API is deferred), project P-ENG-487, PR-3 "App process driver and collectors". Stacked on #7274: base farhan/fervent-cray-2fa3k9.

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)

Stack update (rebased onto #7281)

This PR now stacks on #7281 (subjects/ab): main ← #7274 ← #7281 ← this PR. Nothing merges until the whole stack is complete.

  • Rebased with conflicts only in cli.py imports, README.md and test_cli.py imports; test_ab_self_tests_against_the_workspace gets the same selftest.[!a]* filter as run.
  • One PATH helper: context.subject_env(python) (os.environ + BASE_ENV, with the subject interpreter's directory first on PATH) replaces base_env(); make_context uses it, and the drivers no longer touch PATH (_reflex_env only forces its settings). Pass ctx.env, or subject_env(python) outside a benchmark. The 0.8.23 prod case (granian started by name) is covered through ctx.env.
  • Real cgroup run (Linux with a user systemd manager): doctor → cgroup scope ok (user systemd); REFLEX_BENCH_APP_TESTS=1 self-test passes (16 s); run selftest.app.compile selftest.app.dev_ready --runs 3 reports cpu_method/memory_method = cgroup for every compile sample; compile memory.peak 315.6 MB (cold first sample), then 75.4 / 75.6 MB; oom_kill 0; no reflex run/granian processes or reflex-bench-* units left afterwards.
  • 491 unit tests pass (2 opt-in skipped); ruff, pyright and the pre-commit hooks pass.

Description

Every real benchmark has to start Reflex exactly as a user does: <python> -m reflex run|compile|export|init in a subprocess, with the subject's interpreter. AppHarness cannot be used (it imports the app in-process, runs uvicorn in a thread, forces dev mode). This PR adds that driving primitive and the collectors later benchmarks need, plus two self-test benchmarks that exercise them against a real blank app. The harness still never imports the reflex under test: the caller passes subject.python and subject.reflex_version, which decide what to expect.

New modules in packages/reflex-bench/src/reflex_bench/:

  • drivers/app_process.py: run_cli() for one-shot commands, AppProcess for reflex run, cache_env(), free_ports(), strip_ansi().
  • collectors/cgroup.py: CgroupScope (transient systemd scope), CgroupReading, probe()/status().
  • collectors/pss.py: tree_pss(), PssSampler, available().
  • collectors/phases.py: parse_timing(), TreePhases, classify(), attribute().
  • suites/selftest.py: selftest.app.compile and selftest.app.dev_ready.
  • reflex-bench doctor gains a cgroup scope line.

Driver API

run_cli(python, args, *, cwd, env, timeout, scope=None, phases=False, sample_memory=False) -> CliResult
#   CliResult: args, returncode, wall_s, lines (ANSI-stripped, stdout+stderr), timeout_s, timed_out,
#              cpu_s + cpu_method ("cgroup" | "rusage"), peak_mem_bytes + memory_method ("cgroup" | "pss_sampling"),
#              cgroup: CgroupReading | None, pss: PssResult | None, timing (with phases), tree (with phases)
#              .check() raises with the output tail, .tail(n), .attribution() -> Attribution | None

AppProcess(python, app_dir, *, mode: "dev" | "prod" | "preview", reflex_version, env, extra_args=(),
           backend_only=False, frontend_port=None, backend_port=None, start_timeout=300.0,
           scope=None, phases=False)
    .start() -> Readiness            # tier 1; raises AppStartError with the log tail, after killing the tree
    .wait_http_ready(path=None, timeout=120.0) -> float   # tier 2: GET / (or /ping without a frontend) == 200
    .stop(timeout=10.0)              # idempotent, thread-safe, kills the whole tree
    .frontend_url, .backend_url, .pid, .logs(), .is_running(), .readiness; context manager

Readiness(spawned, ready_line, process_ready, http_ready=None, interactive_ready=None)  # s since just before Popen
cache_env(*, reflex_dir=None, web_dir=None, states_dir=None, bun_cache=None) -> dict[str, str]
  • Both start reflex with start_new_session=True, stdin from /dev/null, stdout+stderr merged into a pipe that a daemon thread drains line by line (bounded to 2000 lines for AppProcess, all lines for run_cli, which parses [timing] lines from them).
  • Environment: the caller's env (normally ctx.env) plus NO_COLOR=1, PYTHONUNBUFFERED=1, REFLEX_TELEMETRY_ENABLED=false, REFLEX_CHECK_LATEST_VERSION=false, REFLEX_USE_GRANIAN=true and COLUMNS=200 (rich wraps at 80 columns in a pipe). A venv interpreter's bin goes first on PATH, as activation would: 0.8.23 starts its prod backend as a granian command, and without it the backend crashes while both ready lines are still printed (captured as 0.8.23-run-prod-granian-not-on-path.log). phases=True adds --loglevel debug (the [timing] lines are debug level).
  • Ports are picked up front (bind to port 0, read, close) and passed as --frontend-port/--backend-port (both flags exist in 0.8.23 and HEAD); the ready lines only confirm them (0.0.0.0 becomes localhost).
  • Teardown (AppProcess.stop(), the end of run_cli, and an atexit hook for Ctrl-C): collect the tree before signalling (psutil descendants plus every process carrying the tree's REFLEX_BENCH_OWNER=<token> environment variable, which also finds children that called setsid or were re-parented after their parent died); SIGTERM the process group and each member outside it; after timeout, SIGKILL whatever is left or was spawned meanwhile; reap the root; raise if anything survived SIGKILL. killpg is only used while the root is unreaped (the zombie holds the group id, so it cannot have been reused); otherwise members get individual signals through psutil, which checks process identity. Every signal goes through two guards that never target a pid or group id <= 1, nor the harness's own pid or group.

Readiness per mode and version

reflex run0.8.23HEAD (0.9.x)
--env devApp running at: + Backend running at:, both printed when vite is up; two portssame
--env dev --backend-onlyBackend running at:, printed before granian bindssame
--env prodApp running at: (sirv) + Backend running at:, printed when sirv is up; two ports (no --single-port)App running at: only, printed before granian binds; one port (--frontend-port P --backend-port P)
--env prod --backend-onlyBackend running at:, before the bindApp running at: (sic), before the bind
--env previewnot available: ValueErrorlike prod, from 0.9.8

Process-ready = every line of the column seen and every announced port accepts a TCP connection. The version comes from reflex_version (packaging release tuple, so 0.9.0a1 counts as 0.9). Backend-only runs pass only --backend-port (HEAD refuses --frontend-port without a frontend); 0.8.23 two-port runs get distinct ports (equal ones switch 0.8.23 to single-port). Measured on this machine, the TCP probe matters: 0.8.23 prod printed its lines at 7.42 s and its backend accepted at 8.30 s; HEAD's head-run-prod-debug.log shows App running at: before granian's Listening at:. In HEAD dev, granian binds its socket in the supervisor before the worker is up, so TCP accepts before HTTP works, which is what tier 2 measures.

Collectors and their fallbacks

  • cgroup (CgroupScope(limit_bytes=None, swap_max=0)): wrap(argv) prefixes systemd-run --user --scope --quiet --collect --unit=reflex-bench-<hex> -p MemoryAccounting=yes -p CPUAccounting=yes [-p MemoryMax=… -p MemorySwapMax=0] --; without a user manager (GitHub runners) it uses sudo -n -E systemd-run --scope … --uid=<uid> --gid=<gid> --setenv=PATH=<path> (sudo resets the environment and PATH). attach(pid) polls /proc/<pid>/cgroup of the process and its descendants for the unit (sudo itself stays outside the scope). read() returns memory.peak, memory.current, anon/file from memory.stat, oom/oom_kill from memory.events, usage_usec/user_usec/system_usec from cpu.stat, and peak_reset. reset_peak() opens memory.peak read-write, writes reset and validates the re-read (Linux 6.12+ per-descriptor reset); on older kernels (read-only file) or root-owned files it keeps whole-run peaks with peak_reset: false. available() / probe() (cached) checks Linux, a cgroup v2 mount with the memory controller, kernel >= 5.19, systemd-run, then actually starts true in a user scope, then via sudo, and returns the reason when nothing works. One-shot commands: systemd removes a scope's cgroup when its last process exits, so run_cli runs the command under a tiny /bin/sh keeper that prints an end marker and holds the scope until its counters are read (about 1 MB in the peak).
  • PSS (fallback when scopes are unavailable): tree_pss(root_pid) sums Pss, Pss_Anon, Pss_File from smaps_rollup over the tree and reports USS (Private_Clean + Private_Dirty) per command name; processes that exit mid-read are skipped. PssSampler(root_pid, interval=0.05) keeps the peak reading and a timeline downsampled to at most 2000 points (maximum per bucket). Results carry method: "pss_sampling". run_cli(sample_memory=True) raises where PSS cannot be read (macOS) instead of reporting 0 bytes, and a sampler whose sampling fails raises from stop() instead of returning what it saw before (TreePhases too).
  • CPU without a scope: the RUSAGE_CHILDREN delta around the command (cpu_method: "rusage").
  • phases: parse_timing(lines) maps the labels of both versions to evaluate, compile, memoize, imports, assets, install, write (unknown labels keep their text; repeats are summed). TreePhases(root_pid, interval=0.02) records every descendant's command line, first/last sighting and CPU time, classifies bun/npm/pnpm/yarn install|add|i|ci as install and node/vite/react-router as frontend (a child inherits the class of its topmost classified ancestor, so a postinstall node under bun add is install time), and reports per-class wall time (union of lifetimes), CPU and intervals. attribute(total_s, timing, tree) returns python (the timing phases except install), install and frontend (from the tree), other = total - sum, and mismatch when the parts exceed the total by more than 5 %.

Verification

All on this sandbox: a 4-core Firecracker VM, no systemd (PID 1 is the VM agent) and a hybrid cgroup v1 layout, so cgroup scopes are unavailable and memory comes from PSS sampling. The sandbox also sets BUN_OPTIONS=--smol.

uv run reflex-bench run selftest.app.compile selftest.app.dev_ready --runs 3 on HEAD, first with a fresh bench home (so setup_cache inits the app, and the first compile installs the frontend packages), then again on the same cache:

$ uv run reflex-bench run selftest.app.compile selftest.app.dev_ready --runs 3   # fresh cache: cold setup_cache
reflex-bench 0.0.0.post54.dev0+c5dd7fac0 · reflex 0.9.12.post10.dev0+c5dd7fac0 (workspace c5dd7fa, dirty) · py 3.14.7
machine: linux-x86_64 · Intel Xeon · 4 cores · vm ⚠ · load 0.94
policy: runs 3 (fixed), warmup per benchmark, timeout per benchmark, α=0.01 (Holm), threshold 3 %, CI 95 %, bootstrap 10000, seed 11, fail-on never
⚠ 1 doctor warning: expect ±3–5 % extra variance (run `reflex-bench doctor`)

[1/2] selftest.app.compile ok · 3 samples · 10.8 s
[2/2] selftest.app.dev_ready ok · 3 samples · 13.3 s

selftest.app.compile     median ± 95 % CI             range                n
  wall                   0.998 s (need ≥ 6 samples)   0.944 s … 4.773 s    3
  ⚠ high variance: CV 98 % (warns at 10 %)
  ⚠ max is 378 % above the median
  ⚠ first sample much slower: raise --warmup (modified z-score 47.7)
  cpu                    0.989 s (need ≥ 6 samples)   0.946 s … 1.356 s    3
  ⚠ high variance: CV 21 % (warns at 10 %)
  peak_mem               83.0 MB (need ≥ 6 samples)   82.9 MB … 136.3 MB   3
  ⚠ high variance: CV 31 % (warns at 10 %)
  ⚠ max is 64 % above the median
  ⚠ first sample much slower: raise --warmup (modified z-score 439.3)
selftest.app.dev_ready
  process_ready          2.114 s (need ≥ 6 samples)   2.054 s … 2.482 s    3
  ⚠ high variance: CV 10 % (warns at 10 %)
  http_ready             2.886 s (need ≥ 6 samples)   2.878 s … 3.464 s    3
  ⚠ high variance: CV 11 % (warns at 10 %)
  ⚠ first sample much slower: raise --warmup (modified z-score 51.3)

$ uv run reflex-bench run selftest.app.compile selftest.app.dev_ready --runs 3   # same cache: warm
[1/2] selftest.app.compile ok · 3 samples · 3.1 s
[2/2] selftest.app.dev_ready ok · 3 samples · 9.2 s

selftest.app.compile     median ± 95 % CI              range                 n
  wall                   1.027 s (need ≥ 6 samples)    0.981 s … 1.050 s     3
  cpu                    1.018 s (need ≥ 6 samples)    0.974 s … 1.024 s     3
  peak_mem               82.97 MB (need ≥ 6 samples)   82.87 MB … 83.00 MB   3
selftest.app.dev_ready
  process_ready          2.081 s (need ≥ 6 samples)    1.997 s … 2.086 s     3
  http_ready             2.893 s (need ≥ 6 samples)    2.870 s … 2.981 s     3

Phase attribution stored in sample_extra of selftest.app.compile (parts/total = (python + install + frontend + max(other, 0)) / total):

runsampletotal spython sinstall sfrontend sother sparts/totalmismatchmemory
cold14.7730.0303.7350.0001.0081.000Falsepss_sampling, 88 samples
cold20.9440.0300.0000.0000.9141.000Falsepss_sampling, 18 samples
cold30.9980.0300.0000.0000.9681.000Falsepss_sampling, 19 samples
warm10.9810.0300.0000.0000.9511.000Falsepss_sampling, 19 samples
warm21.0500.0300.0000.0001.0201.000Falsepss_sampling, 20 samples
warm31.0270.0300.0000.0000.9971.000Falsepss_sampling, 20 samples

The cold sample's install (3.735 s) is the two bun add processes the tree sampler saw (0.79–4.16 s and 4.18–4.55 s after the spawn); the Install Frontend Packages timing phase that wraps them says 3.79 s. other is interpreter start-up and imports. No orphans after either run: a psutil scan for -m reflex, reflex run, react-router, granian, sirv, vite or the owner variable (excluding the scanning shell) printed leftovers: none. pgrep -f "reflex run" itself matches the shell running it here.

Reflex 0.8.23 (uv venv -p 3.12 /tmp/r0823 && uv pip install -p /tmp/r0823 reflex==0.8.23), driven by a small script that points the driver at /tmp/r0823/bin/python (no --reflex needed): init, three compiles with phases and PSS, then reflex run in each topology:

init: 1.91 s, exit 0
compile (cold): wall 1.576 s, cpu 1.400 s (rusage), peak 134.6 MB (pss_sampling)
  timing {'evaluate': 0.01, 'imports': 0.0, 'memoize': 0.0, 'assets': 0.0, 'compile': 0.01, 'install': 0.44, 'write': 0.0}
  attribution python 0.020 install 0.369 frontend 0.000 other 1.187 mismatch False
compile (warm): wall 1.075 s, cpu 1.058 s (rusage), peak 88.5 MB (pss_sampling)
  timing {'evaluate': 0.01, 'imports': 0.0, 'memoize': 0.0, 'assets': 0.0, 'compile': 0.0, 'install': 0.0, 'write': 0.0}
  attribution python 0.010 install 0.000 frontend 0.000 other 1.065 mismatch False
compile (warm): wall 1.092 s, cpu 1.077 s (rusage), peak 88.6 MB (pss_sampling)
  timing {'evaluate': 0.01, 'imports': 0.0, 'memoize': 0.0, 'assets': 0.0, 'compile': 0.0, 'install': 0.0, 'write': 0.0}
  attribution python 0.010 install 0.000 frontend 0.000 other 1.082 mismatch False
run --env dev: frontend http://localhost:50729 backend http://localhost:41339
  spawned 0.001 ready_line 1.874 process_ready 1.876 http_ready 2.988
  args: run --env dev --frontend-port 50729 --backend-port 41339
  stopped after 3.3 s, running: False
run --env prod: frontend http://localhost:46925 backend http://localhost:50805
  spawned 0.001 ready_line 7.418 process_ready 8.295 http_ready 8.306
  args: run --env prod --frontend-port 46925 --backend-port 50805
  stopped after 8.4 s, running: False
run --env dev --backend-only: frontend None backend http://localhost:39157
  spawned 0.001 ready_line 0.865 process_ready 1.090 http_ready 1.116
  args: run --env dev --backend-only --backend-port 39157
  stopped after 1.4 s, running: False
run --env prod --backend-only: frontend None backend http://localhost:39677
  spawned 0.001 ready_line 0.928 process_ready 1.888 http_ready 1.909
  args: run --env prod --backend-only --backend-port 39677
  stopped after 2.0 s, running: False
leftovers: none

Prod with two ports (sirv + granian) reaches process-ready; its lines came 0.9 s before the backend accepted connections.

uv run reflex-bench doctor (last line is new):

· cgroup v2     no: memory benchmarks need cgroup v2
✓ bun           found
✓ node          found
✓ chromium      found
· cgroup scope  unavailable: the cgroup v2 hierarchy at /sys/fs/cgroup/unified has no memory controller (hybrid cgroup v1 host): peak memory falls back to PSS sampling

On a host with scopes the line reads ✓ cgroup scope ok (user systemd) or ok (sudo) (unit-tested with a patched probe).

Ctrl-C during selftest.app.dev_ready: a script starts uv run reflex-bench run selftest.app.dev_ready --runs 5 --no-save in its own process group, waits until a reflex run carrying the owner variable exists, waits 0.3 s or 1.5 s, and sends SIGINT to the harness's group, as a terminal does:

=== Ctrl-C 0.3 s after the app started
app tree at Ctrl-C: 18347 python, 18349 python, 18350 python, 18351 python
harness exit code: 130
app tree processes still alive: []
interrupted
leftovers: none
=== Ctrl-C 1.5 s after the app started
app tree at Ctrl-C: 18381 python, 18383 python, 18384 python, 18390 bun, 18399 python, 18392 node
harness exit code: 130
app tree processes still alive: []
interrupted
leftovers: none

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?

Tests

Unit tests (all fast, no real Reflex app): tests/units/reflex_bench/drivers/test_app_process.py runs a fake reflex package written into the app directory, so python -m reflex resolves to it. It replays the captured ready lines, can print them 0.5 s before binding, serves GET / (503 until a delay passes, then 200), and can spawn a setsid child with a grandchild, leave a child behind in the app's process group, or ignore SIGTERM. Covered: topology and ready-line parsing for dev/prod/preview/backend-only × 0.8.23/HEAD against every captured log; "line printed before bind" waits for TCP; start timeout, early exit and never-opening ports raise with the log tail and leave nothing behind; stop() kills setsid children and grandchildren (checked with psutil.pid_exists, zombies counted as gone), escalates to SIGKILL, finds the children of a crashed app through the owner token, and is idempotent; a guard test patches os.killpg/os.kill with recorders that never forward a pid <= 1 and corrupts the group id to 0; run_cli output, phases, CPU, PSS memory, timeout, exit codes and the scope keeper (with a fake scope checking it is read while the keeper still holds it). Collectors: golden [timing] parsing of the captured HEAD and 0.8.23 debug logs, attribution arithmetic and the mismatch flag, classification, a real process tree for TreePhases, PSS over a fake /proc with real pids, the sampler peak and downsampling, sampler failures raising (also through run_cli, which still stops the other sampler), probe() reasons with patched probes, wrap() argv for both modes, attach() below a wrapper, reading fake memory.*/cpu.stat files and peak-reset detection.

Captured logs are in tests/units/reflex_bench/fixtures/logs/ (ANSI-stripped, trimmed, with the exact commands in its README): HEAD run dev, prod, prod debug, backend-only, prod backend-only, compile --loglevel debug; the same for 0.8.23 (prod without --single-port), plus the 0.8.23 prod crash without granian on PATH.

tests/units/reflex_bench/suites/test_selftest_app.py is opt-in (REFLEX_BENCH_APP_TESTS=1): it runs both app self-tests for real against the workspace reflex (passes in 23.4 s here) and checks statuses, peaks, attribution, readiness order and that no owned process is left.

Check results

CheckResult
uv run ruff check .All checks passed!
uv run ruff format --check .1603 files already formatted
uv run pyright reflex tests packages/reflex-bench/src0 errors, 0 warnings, 0 informations
uv run pytest tests/units/reflex_bench -q397 passed, 1 skipped (the opt-in module) in 21 s; also on Python 3.10.20. Package coverage 94.2 % (app_process 87.8 %, cgroup 88.6 %, phases 95.6 %, pss 96.4 %)
REFLEX_BENCH_APP_TESTS=1 uv run pytest tests/units/reflex_bench/suites/test_selftest_app.py1 passed in 23.4 s
uv run pytest tests/units -q10156 passed, 21 skipped in 166 s
uv run python scripts/check_min_deps.py reflex-benchPASS (no new dependencies: psutil, packaging)
uv run pre-commit run --files <changed files>ruff-format, ruff-check, codespell, update-pyi-files, pyright, ty: Passed

No news fragment: reflex-bench is in never-publish-packages, and nothing under reflex/ or a published package changed.

Deviations from the spec

  1. Branch: this session is pinned to farhan/quirky-wozniak-giqwdn, so the PR comes from that branch instead of farhan/reflex-bench-app-driver.
  2. AppProcess takes reflex_version (required: the version decides the ready lines and ports without importing reflex) and phases (adds --loglevel debug). None or an unparsable version raises ValueError.
  3. run_cli takes phases and sample_memory (the compile self-test needs [timing] lines, the process tree and the PSS fallback), and returns the collector results in CliResult.
  4. Scope keeper for one-shot commands: see "Collectors". Without it the cgroup of a finished command is gone before it can be read. With a scope, wall_s ends at the keeper's end marker and includes the scope's creation by systemd-run.
  5. wait_http_ready(path=None) instead of path="/": / with a frontend, /ping backend-only (the backend answers 404 on /).
  6. Ready lines: vite Local: and sirv Accepting connections at are not matched. reflex echoes them only at debug level and prints App running at: right after, and 0.8.23's sirv 3 prints - Local: http://0.0.0.0:<port> rather than Accepting connections at. HEAD prod --backend-only announces itself with App running at:, not Backend running at:.
  7. cache_env(..., bun_cache=None) (BUN_INSTALL_CACHE_DIR): bun's package cache lives outside REFLEX_DIR ($BUN_INSTALL/install/cache, else ~/.bun/install/cache). A fresh REFLEX_DIR re-downloads bun but not the packages, so keeping CI caches out of a measured cold install needs it too. The self-tests only set reflex_dir.
  8. attribute() returns a TypedDict Attribution (total, python, install, frontend, other, mismatch: bool) instead of dict[str, float]. install comes from the process tree, not from the install timing phase that wraps the bun calls, so nothing is counted twice. other absorbs the remainder, so the 5 % check is one-sided: it flags parts that overshoot the total.
  9. One label table instead of per-version maps: the 0.8.23 and 0.9 labels never collide, so parse_timing(lines) needs no version. Comments mark which version prints which label.
  10. CgroupScope extras: mode= (probed by default; tests pass it), proc_root=/cgroup_root= (fakes), wrap(argv, *, env=None) (sudo mode needs the command's PATH), close() for the reset descriptor, and status() for doctor. Sudo mode adds -E and --setenv=PATH to the spec's sudo -n systemd-run --scope --uid --gid, since sudo resets the environment and PATH.
  11. PR-1 files touched: cli.py (the doctor line), suites/selftest.py (as asked), README.md (a "Driving reflex" section) and test_cli.py. The self-test listing now has 9 entries, the suite-wide run test filters selftest.[!a]* (the app self-tests start real apps and have their own opt-in module), and a new test checks the doctor line.
  12. Windows: the modules still import (the harness test imports every suite; resource is imported conditionally), and the driver raises NotImplementedError. macOS: the driver's code paths are POSIX, but PSS needs /proc, so sample_memory raises there and selftest.app.compile fails for lack of a memory collector; not run on macOS.

Interfaces for later PRs

  • Starting reflex: run_cli(subject.python, ["compile"|"export"|"init", ...], cwd=app, env={**ctx.env, **cache_env(...)}, timeout=..., scope=..., phases=..., sample_memory=...); call .check() to fail the sample on errors. AppProcess(subject.python, app, mode=..., reflex_version=subject.reflex_version, env=...): start it in sample, stop it in conclude (keep a local reference in sample, since conclude may run on another thread after a timeout). This composes with PR-2's --reflex subjects unchanged.
  • Tier 3: Readiness.interactive_ready is reserved for the browser driver; its times share the same origin (just before Popen).
  • Memory of a running app: pass a CgroupScope to AppProcess and read() it before stop() (the cgroup disappears with the tree); reset_peak() between phases gives per-phase peaks on Linux 6.12+ (peak_reset tells). Without scopes, PssSampler(app.pid).start() after start() misses the start-up; a later PR may want a sampler hook at spawn time, like run_cli has.
  • 512 MB limit test: CgroupScope(limit_bytes=512 * 1024**2) sets MemoryMax and MemorySwapMax=0. systemd's default OOMPolicy for scopes may stop the scope on an OOM kill, which removes the cgroup before memory.events can be read; that PR should verify it on a systemd host and set -p OOMPolicy=continue if needed.
  • Results: record memory_method/cpu_method with every sample (as selftest.app.compile does in extra), so cgroup and PSS numbers are never compared.

Self-review

Findings of an adversarial pass over the diff (focused on teardown and signal safety), and what I did:

  1. EOF is no exit signal: a detached child holding the output pipe made start() wait the full start_timeout (300 s) after reflex had died. Fixed: the wait also checks the root process (without reaping it), and the scope keeper prints an end marker. Covered by test_stop_finds_children_of_a_crashed_app.
  2. Popen.wait(timeout) polls with sleeps of up to 50 ms, a 5 % error on a 1 s compile. Fixed: the root is reaped by a blocking waitpid on a thread.
  3. A malformed URL in a ready line raised inside the output thread, which stopped draining: the pipe would fill and reflex would block. Fixed (the line is skipped); the regression test fails without the fix.
  4. After the root was reaped (a finished run_cli), leftover processes in its group got no SIGTERM, only SIGKILL after the 5 s grace. Fixed: without a group signal every member gets SIGTERM; the regression test fails without the fix (5.1 s).
  5. run_cli started its samplers before the try, so a sampler error would have leaked the tree until exit. Fixed.
  6. Signal safety: all signals go through _signal_group/_signal, which refuse pids and groups <= 1 and the harness's own; killpg is only sent while the root is unreaped; single processes are signalled through psutil's identity check (pid + create time), so a reused pid is never hit. The guard test runs a real app with the group id corrupted to 0 and recorders that would not forward a bad call.
  7. Re-parented children become zombies until init reaps them, and pid_exists is true for zombies: liveness checks count zombies as gone, and a process whose state cannot be read counts as alive, so teardown fails loudly rather than silently.
  8. sample_memory=True where PSS cannot be read would have reported a peak of 0 bytes. Fixed: it raises.
  9. selftest.app.dev_ready read self.app after start(), while a conclude running on another thread after a timeout clears it. Fixed with a local reference.

Greptile's review, addressed in 14e47f003:

  1. Sampler failures became measurements (valid). An exception in the PSS sampling thread ended the thread silently, and stop() returned what it had seen, down to a 0-byte peak from no sample at all, which run_cli recorded. TreePhases had the same flaw. Fixed: both samplers run on a shared SamplingLoop whose stop() raises the thread's error, and run_cli stops the other sampler (the tree is already killed) before raising. One concrete trigger is fixed too: tree_pss decoded /proc/<pid>/comm strictly, but the kernel keeps 15 bytes of a name, which can end inside a UTF-8 character. The regression tests fail without the fixes.
  2. A concurrent stop() returned before the teardown (valid). stop() marked the app stopped before killing it, so conclude() after a timed-out start() could return while the tree still ran. Fixed: the whole teardown runs under the lock. The regression test stops an app that ignores SIGTERM from two threads, and fails without the fix.
  3. Hardcoded /proc and /sys/fs/cgroup (partly). reflex-bench has no constants module and must not import reflex's: the harness never imports the reflex under test, and reflex-bench does not depend on reflex. The collectors now define /proc once (reflex_bench.collectors.PROC) and the cgroup mount fallback is cgroup.CGROUP_ROOT. PR-1's machine.py reads its paths below a sysroot argument and is left as is.

Known limitations, left as they are:

  • The real cgroup path was first exercised after the rebase (see "Stack update"); the sudo mode is still unexercised on a real runner. Unit tests cover the probe, the argv of both modes, attach(), reading and peak-reset detection against fakes. The first run on a systemd host (e.g. a GitHub runner through sudo) should confirm systemd-run --scope --uid --gid --setenv, attach(), the keeper read and the memory.peak reset.
  • The owner-token scan reads the environment of every process of the user at teardown (tens of milliseconds). A process that execs with a cleaned environment and leaves both the tree and the group would be missed.
  • Without a scope, CPU misses processes whose parent never waited for them. PSS sampling every 50 ms misses short spikes: the ~10 ms bun install --frozen-lockfile of a warm compile is sometimes caught and sometimes not (warm peaks of 83 and 98 MB in one earlier run).
  • Ports picked with bind(0) can be taken before reflex binds them. That surfaces as a start failure, not a hang.
  • SIGTERM to the harness itself (e.g. CI cancelling a job) skips atexit, so app trees in their own sessions would survive; a signal handler in the CLI could cover this later.
  • TreePhases and PssSampler walk the process table with psutil at every sample (20 ms and 50 ms).