ENG-12605: reflex-bench app process driver (reflex run/compile/export as subprocesses) and collectors
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.pyimports,README.mdandtest_cli.pyimports;test_ab_self_tests_against_the_workspacegets the sameselftest.[!a]*filter asrun. - One PATH helper:
context.subject_env(python)(os.environ +BASE_ENV, with the subject interpreter's directory first onPATH) replacesbase_env();make_contextuses it, and the drivers no longer touchPATH(_reflex_envonly forces its settings). Passctx.env, orsubject_env(python)outside a benchmark. The 0.8.23 prod case (granianstarted by name) is covered throughctx.env. - Real cgroup run (Linux with a user systemd manager):
doctor→cgroup scope ok (user systemd);REFLEX_BENCH_APP_TESTS=1self-test passes (16 s);run selftest.app.compile selftest.app.dev_ready --runs 3reportscpu_method/memory_method=cgroupfor every compile sample; compilememory.peak315.6 MB (cold first sample), then 75.4 / 75.6 MB;oom_kill0; noreflex run/granianprocesses orreflex-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,AppProcessforreflex 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.compileandselftest.app.dev_ready.reflex-bench doctorgains acgroup scopeline.
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 forAppProcess, all lines forrun_cli, which parses[timing]lines from them). - Environment: the caller's
env(normallyctx.env) plusNO_COLOR=1,PYTHONUNBUFFERED=1,REFLEX_TELEMETRY_ENABLED=false,REFLEX_CHECK_LATEST_VERSION=false,REFLEX_USE_GRANIAN=trueandCOLUMNS=200(rich wraps at 80 columns in a pipe). A venv interpreter'sbingoes first onPATH, as activation would: 0.8.23 starts its prod backend as agraniancommand, and without it the backend crashes while both ready lines are still printed (captured as0.8.23-run-prod-granian-not-on-path.log).phases=Trueadds--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.0becomeslocalhost). - Teardown (
AppProcess.stop(), the end ofrun_cli, and anatexithook for Ctrl-C): collect the tree before signalling (psutil descendants plus every process carrying the tree'sREFLEX_BENCH_OWNER=<token>environment variable, which also finds children that calledsetsidor were re-parented after their parent died); SIGTERM the process group and each member outside it; aftertimeout, SIGKILL whatever is left or was spawned meanwhile; reap the root; raise if anything survived SIGKILL.killpgis 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 run | 0.8.23 | HEAD (0.9.x) |
|---|---|---|
--env dev | App running at: + Backend running at:, both printed when vite is up; two ports | same |
--env dev --backend-only | Backend running at:, printed before granian binds | same |
--env prod | App 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-only | Backend running at:, before the bind | App running at: (sic), before the bind |
--env preview | not available: ValueError | like 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)prefixessystemd-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 usessudo -n -E systemd-run --scope … --uid=<uid> --gid=<gid> --setenv=PATH=<path>(sudo resets the environment andPATH).attach(pid)polls/proc/<pid>/cgroupof the process and its descendants for the unit (sudo itself stays outside the scope).read()returnsmemory.peak,memory.current,anon/filefrommemory.stat,oom/oom_killfrommemory.events,usage_usec/user_usec/system_usecfromcpu.stat, andpeak_reset.reset_peak()opensmemory.peakread-write, writesresetand 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 withpeak_reset: false.available()/probe()(cached) checks Linux, a cgroup v2 mount with the memory controller, kernel >= 5.19,systemd-run, then actually startstruein 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, sorun_cliruns the command under a tiny/bin/shkeeper 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)sumsPss,Pss_Anon,Pss_Filefromsmaps_rollupover 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 carrymethod: "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 fromstop()instead of returning what it saw before (TreePhasestoo). - CPU without a scope: the
RUSAGE_CHILDRENdelta around the command (cpu_method: "rusage"). - phases:
parse_timing(lines)maps the labels of both versions toevaluate,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, classifiesbun/npm/pnpm/yarninstall|add|i|ciasinstallandnode/vite/react-routerasfrontend(a child inherits the class of its topmost classified ancestor, so a postinstallnodeunderbun addis install time), and reports per-class wall time (union of lifetimes), CPU and intervals.attribute(total_s, timing, tree)returnspython(the timing phases exceptinstall),installandfrontend(from the tree),other = total - sum, andmismatchwhen 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):
| run | sample | total s | python s | install s | frontend s | other s | parts/total | mismatch | memory |
|---|---|---|---|---|---|---|---|---|---|
| cold | 1 | 4.773 | 0.030 | 3.735 | 0.000 | 1.008 | 1.000 | False | pss_sampling, 88 samples |
| cold | 2 | 0.944 | 0.030 | 0.000 | 0.000 | 0.914 | 1.000 | False | pss_sampling, 18 samples |
| cold | 3 | 0.998 | 0.030 | 0.000 | 0.000 | 0.968 | 1.000 | False | pss_sampling, 19 samples |
| warm | 1 | 0.981 | 0.030 | 0.000 | 0.000 | 0.951 | 1.000 | False | pss_sampling, 19 samples |
| warm | 2 | 1.050 | 0.030 | 0.000 | 0.000 | 1.020 | 1.000 | False | pss_sampling, 20 samples |
| warm | 3 | 1.027 | 0.030 | 0.000 | 0.000 | 0.997 | 1.000 | False | pss_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
| Check | Result |
|---|---|
uv run ruff check . | All checks passed! |
uv run ruff format --check . | 1603 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 -q | 397 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.py | 1 passed in 23.4 s |
uv run pytest tests/units -q | 10156 passed, 21 skipped in 166 s |
uv run python scripts/check_min_deps.py reflex-bench | PASS (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
- Branch: this session is pinned to
farhan/quirky-wozniak-giqwdn, so the PR comes from that branch instead offarhan/reflex-bench-app-driver. AppProcesstakesreflex_version(required: the version decides the ready lines and ports without importing reflex) andphases(adds--loglevel debug).Noneor an unparsable version raisesValueError.run_clitakesphasesandsample_memory(the compile self-test needs[timing]lines, the process tree and the PSS fallback), and returns the collector results inCliResult.- 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_sends at the keeper's end marker and includes the scope's creation bysystemd-run. wait_http_ready(path=None)instead ofpath="/":/with a frontend,/pingbackend-only (the backend answers 404 on/).- Ready lines: vite
Local:and sirvAccepting connections atare not matched. reflex echoes them only at debug level and printsApp running at:right after, and 0.8.23's sirv 3 prints- Local: http://0.0.0.0:<port>rather thanAccepting connections at. HEAD prod--backend-onlyannounces itself withApp running at:, notBackend running at:. cache_env(..., bun_cache=None)(BUN_INSTALL_CACHE_DIR): bun's package cache lives outsideREFLEX_DIR($BUN_INSTALL/install/cache, else~/.bun/install/cache). A freshREFLEX_DIRre-downloads bun but not the packages, so keeping CI caches out of a measured cold install needs it too. The self-tests only setreflex_dir.attribute()returns a TypedDictAttribution(total,python,install,frontend,other,mismatch: bool) instead ofdict[str, float].installcomes from the process tree, not from theinstalltiming phase that wraps the bun calls, so nothing is counted twice.otherabsorbs the remainder, so the 5 % check is one-sided: it flags parts that overshoot the total.- 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. CgroupScopeextras:mode=(probed by default; tests pass it),proc_root=/cgroup_root=(fakes),wrap(argv, *, env=None)(sudo mode needs the command'sPATH),close()for the reset descriptor, andstatus()fordoctor. Sudo mode adds-Eand--setenv=PATHto the spec'ssudo -n systemd-run --scope --uid --gid, since sudo resets the environment andPATH.- PR-1 files touched:
cli.py(thedoctorline),suites/selftest.py(as asked),README.md(a "Driving reflex" section) andtest_cli.py. The self-test listing now has 9 entries, the suite-wideruntest filtersselftest.[!a]*(the app self-tests start real apps and have their own opt-in module), and a new test checks the doctor line. - Windows: the modules still import (the harness test imports every suite;
resourceis imported conditionally), and the driver raisesNotImplementedError. macOS: the driver's code paths are POSIX, but PSS needs/proc, sosample_memoryraises there andselftest.app.compilefails 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 insample, stop it inconclude(keep a local reference insample, sinceconcludemay run on another thread after a timeout). This composes with PR-2's--reflexsubjects unchanged. - Tier 3:
Readiness.interactive_readyis reserved for the browser driver; its times share the same origin (just beforePopen). - Memory of a running app: pass a
CgroupScopetoAppProcessandread()it beforestop()(the cgroup disappears with the tree);reset_peak()between phases gives per-phase peaks on Linux 6.12+ (peak_resettells). Without scopes,PssSampler(app.pid).start()afterstart()misses the start-up; a later PR may want a sampler hook at spawn time, likerun_clihas. - 512 MB limit test:
CgroupScope(limit_bytes=512 * 1024**2)setsMemoryMaxandMemorySwapMax=0. systemd's defaultOOMPolicyfor scopes may stop the scope on an OOM kill, which removes the cgroup beforememory.eventscan be read; that PR should verify it on a systemd host and set-p OOMPolicy=continueif needed. - Results: record
memory_method/cpu_methodwith every sample (asselftest.app.compiledoes inextra), 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:
- EOF is no exit signal: a detached child holding the output pipe made
start()wait the fullstart_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 bytest_stop_finds_children_of_a_crashed_app. 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 blockingwaitpidon a thread.- 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.
- 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). run_clistarted its samplers before thetry, so a sampler error would have leaked the tree until exit. Fixed.- Signal safety: all signals go through
_signal_group/_signal, which refuse pids and groups<= 1and the harness's own;killpgis 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. - Re-parented children become zombies until init reaps them, and
pid_existsis 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. sample_memory=Truewhere PSS cannot be read would have reported a peak of 0 bytes. Fixed: it raises.selftest.app.dev_readyreadself.appafterstart(), while aconcluderunning on another thread after a timeout clears it. Fixed with a local reference.
Greptile's review, addressed in 14e47f003:
- 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, whichrun_clirecorded.TreePhaseshad the same flaw. Fixed: both samplers run on a sharedSamplingLoopwhosestop()raises the thread's error, andrun_clistops the other sampler (the tree is already killed) before raising. One concrete trigger is fixed too:tree_pssdecoded/proc/<pid>/commstrictly, but the kernel keeps 15 bytes of a name, which can end inside a UTF-8 character. The regression tests fail without the fixes. - A concurrent
stop()returned before the teardown (valid).stop()marked the app stopped before killing it, soconclude()after a timed-outstart()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. - Hardcoded
/procand/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/proconce (reflex_bench.collectors.PROC) and the cgroup mount fallback iscgroup.CGROUP_ROOT. PR-1'smachine.pyreads its paths below asysrootargument 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 confirmsystemd-run --scope --uid --gid --setenv,attach(), the keeper read and thememory.peakreset. - 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-lockfileof 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. TreePhasesandPssSamplerwalk the process table with psutil at every sample (20 ms and 50 ms).