ENG-12614: reflex-bench memory suite (compile peak, idle, per session, leak slope, 512 MiB gate)
PR-8 of the Holistic Framework Benchmarks project: the memory half of ENG-12614 (plan item "PR-8 Memory suite"; the footprint half is #7284). It adds the memory benchmarks to reflex-bench: how much memory the playground takes to compile and to run, what each connected session costs, whether memory grows with events, and whether the app fits a 512 MiB box. The harness still never imports reflex.
Stack: main ← #7274 ← #7281 ← #7283 ← #7280 ← #7287 ← this PR (base farhan/admiring-albattani-pk9w94). Nothing merges until the whole project is done.
Host caveat, read first. This session's VM has no systemd (PID 1 is the VM agent) and binds the memory controller to cgroup v1, so CgroupScope.available() says the cgroup v2 hierarchy at /sys/fs/cgroup/unified has no memory controller (hybrid cgroup v1 host), and neither the user nor the sudo mode of systemd-run can run (System has not been booted with systemd as init system). So:
- every PSS path ran for real on HEAD and 0.8.23 (tables below);
- the cgroup paths are covered by unit tests with fake scopes, and I ran the suite's real 512 MiB code (
boot_and_serve, run_cli's keeper, the read-before-stop order, the failure messages) under kernel-enforced cgroup v1 limits through a scratch stand-in for CgroupScope (not committed; described in "512 MiB gate"). Those numbers come from a real memory cgroup, but a v1 one, not a systemd scope;
OOMPolicy was measured afterwards on a systemd 259 host and fixed; see "OOMPolicy".
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)
New Feature Submission:
- Does your submission pass the tests?
- Have you linted your code locally prior to submission?
Changes To Core Features:
Not applicable: nothing under reflex/ or in a published package changes. reflex-bench is in never-publish-packages, so there is no news fragment.
The benchmarks (reflex_bench/suites/memory.py)
Every sample is untimed and starts a fresh backend (reflex run --env prod --backend-only, GRANIAN_WORKERS=1, the manager in REFLEX_STATE_MANAGER_MODE, REFLEX_REDIS_URL for redis only), stopped in conclude. The playground is copied from git ls-files into the cache and compiled once in setup_cache; the disk manager's states directory is emptied in prepare. No metric is a time; every one is bytes, lower is better, except passed.
| id | suites | params | one sample | metrics | method |
|---|---|---|---|---|---|
memory.compile.peak | daily, all | command compile, export | run_cli(["compile"] or ["export", "--env", "prod", "--zip-dest-dir", <workdir>], scope=…, sample_memory=scope is None), warm app, warmup=1 | peak_mem | cgroup with a scope, else pss_sampling |
memory.idle | smoke (memory), daily, all | manager | /ping, sleep idle_s (hidden, 5), tree_pss 3× a second apart, median | pss, pss_anon, pss_file | pss_sampling (the scope's memory.current/anon/file in extra) |
memory.idle.allocator | all | allocator mimalloc, arena2 | the idle class, PYTHONMALLOC=mimalloc / MALLOC_ARENA_MAX=2 | same | pss_sampling |
memory.per_session | daily (K 0, 100, 500), all (0, 100, 500, 1000) | manager, max_sessions | hold K sessions (monotone), settle 5 s, 3 reads; fit; close all, settle, residual; the echo-server floor; wait for expiry; residual | bytes_per_session, bytes_per_session_ci_hi, residual_after_disconnect, residual_after_expiry | pss_sampling |
memory.leak | daily (50k events), all (100k) | manager, events | closed loop, 10 sessions, sized from a 5 s probe; tree sampled throughout; fit and gate | bytes_per_event, bytes_per_event_ci_hi, growth | pss_sampling |
memory.boot_512mb | daily (memory), all | manager | compile in one scope, boot + serve in another, each MemoryMax=512M + MemorySwapMax=0; no scope → fails | passed (1, exact, higher), peak_compile, peak_boot, peak_serve | cgroup |
memory.boot.min_limit | all | manager memory | bisection 64…1024 MiB in 32 MiB steps over boot + serve (≤ 6 steps) | min_limit | cgroup |
memory_methodgoes intoentry["dims"]through the newctx.dims(below), so cgroup and PSS numbers never pair up incompareor history. It names the collector of the values: the idle/per-session/leak values are the tree's PSS on every host (the scope adds its view to the extra data), so their dims saypss_samplingwith or without a scope; onlycompile.peakswitches. A non-default--param allocator=also lands in the dims.- Linux only: without
/proc/*/smaps_rollupa sample fails withpss.available()'s reason. - Hook timeouts cover the longest sample:
leak900 s,per_session600 s,min_limit600 s,boot_512mb600 s,compile.peak660 s (itsrun_clitimeout is 600 s),idle300 s;setup_timeout900 s. Server start and first/pingget 120 s each. Estimates are the measured sample durations below (compile 6 s, idle 9 s, per session 155 s, leak 45 s, gate 15 s, min limit 45 s). Nothing is in theprsuite (list --suite pris unchanged).
What the numbers say (this VM, linux-x86_64-xeon-py3.14, PSS)
- Idle: HEAD 151 MB (anon 128.8 MB), 0.8.23 229 MB: HEAD's backend is 34 % smaller at rest. Both trees are all
pythonbycomm(HEAD 4 processes: CLI, resource tracker, forkserver, worker; 0.8.23 6), souss_byteshas onepythonentry; the worker's own USS (the largest process) is 74 MB on HEAD, 96 MB on 0.8.23. - Per session: ~196 kB on HEAD (198 kB on 0.8.23), linear (r² 0.99999 up to K = 1000). Most of it is the transport, not reflex: a bare python-socketio echo in the subject's venv costs 170.5 kB/session under granian and 156.6 kB under uvicorn, a bare
websocketsecho (the in-harness floor) 17.5 kB. So python-socketio/engine.io holds ~140 kB per connection; reflex's own share (state, token maps) is ~25 kB. Probably worth its own issue. - Residuals: disconnecting frees nothing measurable (−8 MB of +98 MB for 500 sessions). After the expiry, HEAD's memory manager purges the states but the process keeps the pages (93 MB left for 500 sessions, unchanged), while the disk manager's residual drops by two thirds (92 → 31 MB). Details in "Per session".
- Leak: flat on both versions and managers: −3.3 to +1.4 B/event, every 95 % upper bound under 1.6 B/event against a 100 B tolerance. A deliberate 4 kB/event leak reads 4141.6 B/event and fails the gate.
- Compile / export peaks: compile 92 MB on HEAD (python 77 MB USS at the peak), 99 MB on 0.8.23; export 502 MB on HEAD, 737 MB on 0.8.23, node alone 410 MB / 629 MB USS at the peak (vite build and prerender).
exportdoes not fit 512 MiB on 0.8.23 and barely on HEAD; the boot gate only compiles. - 512 MiB (cgroup v1 cross-check): HEAD passes with compile 72.8 MiB, boot 124.7 MiB, serve 158.9 MiB; smallest passing limit 160 MiB (0.8.23: 83.7 / 189.9 / 191.8 MiB, 192 MiB).
- Allocators (HEAD idle): default 151.2 MB,
mimalloc158.6 MB (+7.4 MB),MALLOC_ARENA_MAX=2150.8 MB;arena2does not change the per-session residual either (90.6 MB after expiry), so the retention is not glibc arenas.
Per session: what disconnect and expiry free
Facts at HEAD and v0.8.23 (checked in the code, then measured):
- Disconnect only drops the sid ↔ token mapping:
LocalTokenManager.disconnect_tokenpopstoken_to_socketandsid_to_token(reflex/utils/token_manager.py:186-195; the same in 0.8.23). No state manager frees a state on disconnect. - HEAD
StateManagerMemorytracks every touched token (_track_token,reflex/istate/manager/memory.py:66-72) and a background task (_expire_states, lines 125-134) purges ittoken_expirationseconds later;token_expirationdefaults toconfig.redis_token_expiration(reflex/istate/manager/__init__.py:251-257, envREFLEX_REDIS_TOKEN_EXPIRATION, defaultExpiration.TOKEN= 3600 s). 0.8.23'sStateManagerMemoryhas no expiry (git show v0.8.23:reflex/istate/manager/memory.py). StateManagerDiskkeeps an in-memorystatesdict and purges it with the files after the same expiration, on both versions (HEADreflex/istate/manager/disk.py:303-309; 0.8.23disk.py:259-264).- Measured purge: a scratch script set
last_seq=7on a fixed token, disconnected, waitedexpiry + 10s (expiry 10 s) and re-hydrated the same token: HEAD memory and disk both answeredlast_seq = 0(purged); an immediate reconnect answered 7. - Measured reuse (HEAD, memory manager, 500 sessions): idle 151.0 → 500 held 249.5 → closed 241.2 → expired 241.2 → 500 new sessions 255.9 MB (+14.7 MB); the same with no expiry (3600 s): 151.0 → 248.7 → 245.3 → 245.3 → 257.4 (+12.1). The first 500 sessions cost 98 MB, the next 500 only 12–15 MB, with or without the purge: most of the per-session memory belongs to the connection, is freed at disconnect and reused by the next sessions, and is never returned to the kernel, so PSS cannot show the purge.
So the server runs with REFLEX_REDIS_TOKEN_EXPIRATION=<expiry_s> (hidden, 120 s, see deviation 1) and waits until the last session's priming plus expiry_s + 10 s; the residuals are PSS over the K = 0 level. A sweep that outlasts expiry_s fails the sample (states could expire mid-sweep; with the disk manager that would lower later levels). memory.leak keeps the default expiration (3600 s).
Levels (HEAD, memory manager, max_sessions=1000, one sample; PSS MB): 0 → 151.1, 100 → 170.2, 500 → 248.4, 1000 → 346.5; slope 195.5 kB (95 % CI 194.0–197.0), r² 0.999994; echo floor 17.4 kB (16.3–18.5); residual after disconnect 172.3 MB, after expiry 172.3 MB; sweep_s 32.4 s. An earlier sample: 195.2 kB (194.5–196.0), residuals 189.0 and 188.9 MB.
Manual python-socketio floor (scratch scripts, not committed): socketio.AsyncServer(async_mode="asgi", transports=["websocket"], allow_upgrades=False) with an /_event namespace that answers hydrate/on_load_internal and set_seq like the playground, mounted with socketio.ASGIApp(sio, socketio_path="_event"), started from the workspace venv (python-socketio 5.16.4, python-engineio 4.13.5, granian 2.8.1), swept with the suite's own sweep_sessions (0, 100, 500, 1000):
granian --interface asgi --workers 1: 0 → 95.7 MB, 100 → 112.5, 500 → 180.6, 1000 → 266.2
python-socketio + granian floor: 170534 B/session (95 % CI 169486 to 171582), r2 1.00000
uvicorn --ws websockets: 0 → 59.4 MB, 100 → 71.4, 500 → 134.7, 1000 → 214.7
python-socketio floor: 156584 B/session (95 % CI 145414 to 167753), r2 0.99945
Leak gate
A 5 s closed-loop probe gives the rate; the warmup covers warmup_events (hidden, 5000) and the window events × 1.1. A harness thread samples tree_pss(app.pid) every hundredth of the window (0.1 to 1 s apart), keeping the anonymous PSS and the largest process's USS (the worker). Each sample's time maps to answered events through the load's new answered_per_second; samples outside the measured window are dropped. fit_leak fits linear_slope_ci over the window and over each half; growth is the median of the last five samples minus the first five.
sample() raises LeakDetected when ci_hi > tolerance_bytes_per_event (hidden, 100) and second_half_slope > 0.5 × first_half_slope. An unanswered event or a failed session fails the sample (LoadError); generator saturation does not, since a busy generator still counts correctly.
- Deliberate leak (the opt-in test's
BenchState.leak_seq, appending"x" * 4096 + str(seq); a bare"x" * 4096is folded into one constant by the compiler and would leak 8 bytes):failed,LeakDetected: memory grows by 4141.6 B per event (95 % CI 4106.4 to 4176.8), over the tolerance of 100 B, and keeps growing: 4229.3 B per event in the second half after 4209.2 in the first; growth 13.15 MB over 18 samples. - The plain playground at the same 3000 events, three samples: −0.04 (CI −3.14…3.05), −22.86 (−30.98…−14.74), −4.62 (−8.31…−0.93) B/event, all
ok.
512 MiB gate
- Phases:
compilerunsreflex compilein its own scope (read byrun_cliwhile its keeper holds the scope);bootstarts the server in a second scope and reads it after/ping;serveruns 5 closed-loop sessions for 5 s against it and reads the same scope again before the server stops (memory.peakcannot be reset before Linux 6.12, so the serve peak includes the boot). Every limited scope isCgroupScope(limit_bytes=limit_mb·MiB, swap_max=0), sowrap()emits-p MemoryMax=… -p MemorySwapMax=0. - Pass = every phase ran (compile exit 0,
/pinganswered,app.is_running(), no failed session,unanswered == 0) andoom == 0 and oom_kill == 0in each reading. OtherwiseMemoryLimitExceeded("phase <p> under MemoryMax=<n>M: <what>; oom=…, oom_kill=…; peak … MiB; log tail: …"). A boot whosestart()failed has no reading (AppProcess stops the tree, and a systemd scope goes with it), so the message saysmemory.events unreadable: the scope ended with its treeand carries the exit code and the log tail. - No scope, no test:
CgroupScope(...)raisescgroup scopes are unavailable: <reason>and the entry fails with it. This host:RuntimeError: cgroup scopes are unavailable: the cgroup v2 hierarchy at /sys/fs/cgroup/unified has no memory controller (hybrid cgroup v1 host).
cgroup v1 cross-check. A scratch stand-in for CgroupScope (wrap joins a fresh v1 memory cgroup below the session's own, with memory.limit_in_bytes; read maps memory.max_usage_in_bytes/usage_in_bytes/stat rss and cache/oom_control oom_kill onto CgroupReading; v1 has no oom counter, reported 0; there is no swap on this VM) was patched into reflex_bench.suites.memory and the benchmarks ran through the scheduler:
| subject | limit | result |
|---|---|---|
| HEAD | 512 MiB | ok: peaks compile 72.8 MiB, boot 124.7 MiB, serve 158.9 MiB; oom_kill 0 in each |
| HEAD | 128 MiB | MemoryLimitExceeded: phase serve under MemoryMax=128M: 5 sessions failed: session 0: the websocket closed: no close frame received or sent; oom=0, oom_kill=1; peak 128.0 MiB; log tail: … App running at: http://0.0.0.0:52935/ / [ERROR] Unexpected exit from worker-1 / Info: Reflex app stopped. (dmesg: Memory cgroup out of memory: Killed process 6172 (python) total-vm:434156kB, anon-rss:70904kB) |
| HEAD | 96 MiB | phase boot under MemoryMax=96M: reflex run exited with code -9 before it was ready; memory.events unreadable: the scope ended with its tree; peak unknown; log tail: … |
| HEAD | 64 MiB | phase compile under MemoryMax=64M: reflex compile exited with code 137; oom=0, oom_kill=1; peak 64.0 MiB; log tail: Killed |
| HEAD | min_limit | 160 MiB in 6 steps, 40 s: 1024 ✓, 512 ✓, 256 ✓, 128 ✗ (serve), 192 ✓, 160 ✓ (peak 158.6 MiB) |
| 0.8.23 | 512 MiB | ok: 83.7 / 189.9 / 191.8 MiB |
| 0.8.23 | min_limit | 192 MiB: 1024 ✓, 512 ✓, 256 ✓, 128 ✗ (boot, -9), 192 ✓, 160 ✗ (boot, -9) |
The server just after /ping (no session) reads 130.7 MB memory.usage_in_bytes (anon 128.8 MB) in the v1 cgroup against 151.2 MB PSS (anon 128.8 MB): the anonymous parts agree; PSS adds its share of file pages that the cgroup did not fault in itself.
granian 2.8.1 on HEAD does not respawn an OOM-killed worker: Unexpected exit from worker-1, and reflex stops. So a failing serve phase ends the app (is_running() false) as well as counting oom_kill.
OOMPolicy (measured, fixed in 260a24a6a). On systemd 259 (Ubuntu 26, kernel 7.0), a limited scope's default OOMPolicy=stop makes systemd stop the whole scope after an OOM kill: the keeper that reads memory.events gets SIGTERM, and the gate reported exited with code -15; memory.events unreadable; peak unknown (journal: Failed with result 'oom-kill'). With -p OOMPolicy=continue only the killed process dies and the counters stay readable.
CgroupScope.wrap now adds -p OOMPolicy=continue to limited scopes when oom_policy_supported(mode) is true. That function tries the property once per process (systemd-run --scope -p OOMPolicy=continue true), so systemd 249 (the macro runner), which rejects it on scopes and does not stop scopes, keeps working unchanged.
Measured after the fix: memory.boot_512mb --param limit_mb=64 → phase compile under MemoryMax=64M: reflex compile exited with code 137; oom=1, oom_kill=1; peak 64.0 MiB; limit_mb=128 → phase serve … oom=1, oom_kill=1; peak 128.0 MiB; the default 512 MiB run passes; no processes left.
The published 512 MiB number must come from an amd64 reference profile (Fly shared-cpu is amd64); on the arm64 macro runner it is a trend. The README says so.
linear_slope_ci (stats.py)
linear_slope_ci(xs, ys, confidence=0.95) -> SlopeFit(slope, intercept, ci_lo, ci_hi, r2, n): ordinary least squares on centered values (math.fsum), the slope's standard error from the residuals, and t_quantile_975(n - 2). The t table holds scipy's 97.5 % quantiles for df 1–30, 40, 60, 120 and ∞, linear in 1/df between rows: the largest error over df 1–100 000 is 2.6e-5 relative (df 34), measured against scipy.stats.t.ppf, well inside the 0.5 % budget. Only 0.95 is tabulated (other levels raise). A constant series gives slope 0, a zero-width interval and r² 0; fewer than 3 points, unpaired values or equal x values raise ValueError.
Goldens from scipy 1.18.1 / numpy 2.5.3 in a scratch venv outside the repo, for n = 4, 5, 12, 32 and 100 (a memory-like step series, a negative slope, a 50 MB baseline with 4 kB noise), the script is in the test docstring:
fit = scipy.stats.linregress(xs, ys)
t = scipy.stats.t.ppf(0.975, len(xs) - 2)
print(fit.slope, fit.intercept, fit.slope - t * fit.stderr, fit.slope + t * fit.stderr, fit.rvalue**2)
# N4 1.94 0.15000000000000036 1.5503782241645947 2.329621775835405 0.9956613756613755
# N100 5.633855838415915 50000319.847557604 -14.319773555007707 25.587485231839537 0.0031933056425778304
(scipy returns NaN for r and the standard error of a constant series; the test pins our definition.)
Verification
uv run reflex-bench doctor (this VM): · 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. systemd-run --user --scope true → Failed to connect to bus: No medium found; sudo -n systemd-run --scope true → System has not been booted with systemd as init system (PID 1). Can't operate.
uv run reflex-bench run --suite daily 'memory.*' --runs 3, HEAD (0.9.12.post24.dev0+099e73f9e, 20 min 28 s):
[1/9] memory.boot_512mb[manager=memory] failed · 0 samples · 1.5 s
[2/9] memory.compile.peak[command=compile] ok · 3 samples · 6.6 s
[3/9] memory.compile.peak[command=export] ok · 3 samples · 23.0 s
[4/9] memory.idle[manager=memory] ok · 3 samples · 27.2 s
[5/9] memory.idle[manager=disk] ok · 3 samples · 27.2 s
[6/9] memory.leak[manager=memory,events=50000] ok · 3 samples · 114.7 s
[7/9] memory.leak[manager=disk,events=50000] ok · 3 samples · 118.3 s
[8/9] memory.per_session[manager=memory,max_sessions=500] ok · 3 samples · 454.3 s
[9/9] memory.per_session[manager=disk,max_sessions=500] ok · 3 samples · 454.8 s
memory.boot_512mb[manager=memory] median ± 95 % CI range n
✗ failed: RuntimeError: cgroup scopes are unavailable: the cgroup v2 hierarchy at /sys/fs/cgroup/unified has no memory controller (hybrid cgroup v1 host)
memory.compile.peak[command=compile]
peak_mem 92.28 MB (need ≥ 6 samples) 83.88 MB … 94.32 MB 3
memory.compile.peak[command=export]
peak_mem 501.8 MB (need ≥ 6 samples) 499.7 MB … 503.1 MB 3
memory.idle[manager=memory]
pss 151.2 MB (need ≥ 6 samples) 151.1 MB … 151.2 MB 3
pss_anon 128.8 MB (need ≥ 6 samples) 128.7 MB … 128.8 MB 3
pss_file 22.34 MB (need ≥ 6 samples) 22.33 MB … 22.35 MB 3
memory.idle[manager=disk]
pss 146.6 MB (need ≥ 6 samples) 146.5 MB … 151.2 MB 3
pss_anon 128.9 MB (need ≥ 6 samples) 128.8 MB … 128.9 MB 3
pss_file 17.74 MB (need ≥ 6 samples) 17.72 MB … 22.32 MB 3
⚠ high variance: CV 14 % (warns at 10 %)
memory.leak[manager=memory,events=50000]
bytes_per_event 0 B (need ≥ 6 samples) -1 B … 0 B 3
bytes_per_event_ci_hi 0 B (need ≥ 6 samples) -0 B … 0 B 3
growth -8.2 kB (need ≥ 6 samples) -114.7 kB … 12.3 kB 3
memory.leak[manager=disk,events=50000]
bytes_per_event 1 B (need ≥ 6 samples) 1 B … 1 B 3
bytes_per_event_ci_hi 1 B (need ≥ 6 samples) 1 B … 1 B 3
growth 49.15 kB (need ≥ 6 samples) 40.96 kB … 77.82 kB 3
memory.per_session[manager=memory,max_sessions=500]
bytes_per_session 195.8 kB (need ≥ 6 samples) 195.8 kB … 195.9 kB 3
bytes_per_session_ci_hi 218.8 kB (need ≥ 6 samples) 217.3 kB … 220.7 kB 3
residual_after_disconnect 93.15 MB (need ≥ 6 samples) 92.01 MB … 93.98 MB 3
residual_after_expiry 93.15 MB (need ≥ 6 samples) 92.01 MB … 93.87 MB 3
memory.per_session[manager=disk,max_sessions=500]
bytes_per_session 200.1 kB (need ≥ 6 samples) 200.0 kB … 200.4 kB 3
bytes_per_session_ci_hi 215.8 kB (need ≥ 6 samples) 213.6 kB … 226.4 kB 3
residual_after_disconnect 91.69 MB (need ≥ 6 samples) 89.06 MB … 98.23 MB 3
residual_after_expiry 30.93 MB (need ≥ 6 samples) 29.15 MB … 51.95 MB 3
⚠ high variance: CV 34 % (warns at 10 %)
9 benchmarks: 1 failed · 8 ok
(Warnings about the leak rows' variance are the CV of values near zero; trimmed here.)
| id | metric | HEAD median | min … max | n | 0.8.23 (n = 1) | method |
|---|---|---|---|---|---|---|
memory.compile.peak[command=compile] | peak_mem | 92.28 MB | 83.88 … 94.32 MB | 3 | 99.19 MB | pss_sampling |
memory.compile.peak[command=export] | peak_mem | 501.8 MB | 499.7 … 503.1 MB | 3 | 736.5 MB | pss_sampling |
memory.idle[manager=memory] | pss | 151.2 MB | 151.1 … 151.2 MB | 3 | 228.9 MB | pss_sampling |
| pss_anon | 128.8 MB | 128.7 … 128.8 MB | 3 | 205.7 MB | ||
| pss_file | 22.34 MB | 22.33 … 22.35 MB | 3 | 23.18 MB | ||
memory.idle[manager=disk] | pss | 146.6 MB | 146.5 … 151.2 MB | 3 | 219.7 MB | pss_sampling |
| pss_anon | 128.9 MB | 128.8 … 128.9 MB | 3 | 196.7 MB | ||
| pss_file | 17.74 MB | 17.72 … 22.32 MB | 3 | 23.01 MB | ||
memory.leak[manager=memory,events=50000] | bytes_per_event | 0.20 B | −0.85 … 0.21 B | 3 | −3.33 B | pss_sampling |
| bytes_per_event_ci_hi | 0.34 B | −0.48 … 0.35 B | 3 | −2.42 B | ||
| growth | −8.2 kB | −114.7 … 12.3 kB | 3 | −286.7 kB | ||
memory.leak[manager=disk,events=50000] | bytes_per_event | 0.67 B | 0.58 … 1.18 B | 3 | 1.43 B | pss_sampling |
| bytes_per_event_ci_hi | 0.86 B | 0.78 … 1.33 B | 3 | 1.59 B | ||
| growth | 49.15 kB | 40.96 … 77.82 kB | 3 | 90.11 kB | ||
memory.per_session[manager=memory,max_sessions=500] | bytes_per_session | 195.8 kB | 195.8 … 195.9 kB | 3 | 197.8 kB | pss_sampling |
| bytes_per_session_ci_hi | 218.8 kB | 217.3 … 220.7 kB | 3 | 233.0 kB | ||
| residual_after_disconnect | 93.15 MB | 92.01 … 93.98 MB | 3 | 97.56 MB | ||
| residual_after_expiry | 93.15 MB | 92.01 … 93.87 MB | 3 | 97.56 MB | ||
memory.per_session[manager=disk,max_sessions=500] | bytes_per_session | 200.1 kB | 200.0 … 200.4 kB | 3 | 201.9 kB | pss_sampling |
| bytes_per_session_ci_hi | 215.8 kB | 213.6 … 226.4 kB | 3 | 228.1 kB | ||
| residual_after_disconnect | 91.69 MB | 89.06 … 98.23 MB | 3 | 98.68 MB | ||
| residual_after_expiry | 30.93 MB | 29.15 … 51.95 MB | 3 | 66.87 MB | ||
memory.boot_512mb[manager=memory] | – | failed: no cgroup scopes | 0 | failed: same | cgroup |
The leak slopes are from the extra data (the terminal table rounds bytes to whole numbers). The daily fit has three counts (df = 1, t = 12.7), hence the wide bytes_per_session_ci_hi; the all sweep has four (df = 2): 197.0 kB for a 195.5 kB slope.
--reflex 0.8.23 (--suite daily 'memory.*' --runs 1, 7 min 48 s): every id ok except memory.boot_512mb (failed, no scopes, the same reason). No min_version is needed: every id runs on 0.8.23. As expected, 0.8.23's memory manager keeps its residual after expiry (97.56 → 97.56 MB: it has no expiry) and its disk manager drops (98.68 → 66.87 MB).
memory.idle details: HEAD uss_bytes {"python": 134.3 MB}, processes 4, worker USS 74.3 MB; 0.8.23 {"python": 208.7 MB}, 6 processes, worker 96.1 MB. pss_file moves by a few MB between identical samples (17.7 vs 22.3 MB for disk): PSS splits file pages with every other process mapping the same files, the harness's interpreter included; pss_anon stays within 0.1 MB. The README points trends at pss_anon. PSS vs the cgroup view: see the v1 cross-check above.
memory.idle.allocator (HEAD, --runs 3): mimalloc 158.6 MB (anon 136.5), arena2 150.8 MB (anon 128.8), against default 151.2 MB (128.8).
redis (REFLEX_REDIS_URL=redis://localhost:6399, redis 7.0.15): memory.idle[manager=redis] HEAD 151.3 MB, 0.8.23 219.6 MB; memory.per_session[manager=redis,max_sessions=500] HEAD 199.7 kB/session, 0.8.23 196.2 kB (the states live in redis, outside the measured tree; redis used_memory per session is a follow-up). GRANIAN_WORKERS=1 holds with redis on both versions: HEAD 4 processes with it, 12 without (2 × 4 + 1 workers); 0.8.23 6 with it, 14 without (0.8.23's exec.py:678 only sets GRANIAN_WORKERS when it is unset).
uv run reflex-bench ab --aa --head workspace memory.idle --param manager=memory --rounds 3: both arms ok; pss 151.0 vs 150.9 MB (−0.1 %, p = 0.60), pss_anon −0.0 %, pss_file −0.4 %, all inconclusive at 3 rounds (6 needed). No server alive between samples (each sample starts and stops its own).
Ctrl-C (a script starts the harness in its own process group, waits for a spawned child, then sends SIGINT to the group as a terminal does): during memory.leak's load (7 processes: harness, server tree, generator) and during memory.per_session's sweep (8 processes, holds included): exit code 130, interrupted, no leftovers (psutil scan for REFLEX_BENCH_OWNER, spawn_main, forkserver, reflex_bench, -m reflex). After every other run above: nothing left either. systemctl --user list-units 'reflex-bench-*' cannot run here (no systemd).
Opt-in app tests: REFLEX_BENCH_APP_TESTS=1 uv run pytest tests/units/reflex_bench/suites/test_memory_app.py: 2 passed, 1 skipped (test_the_512mb_gate: memory.boot_512mb needs cgroup scopes: …) in 159 s. test_each_memory_benchmark_once runs compile, idle, per session (K 0, 25, 50) and leak (3000 events), all ok with memory_method in dims and extra; test_a_deliberate_leak_fails_and_the_playground_passes gets LeakDetected from the leaky copy, then three ok samples of the plain playground; both check that no owned process, spawned child or scope unit is left.
Changes to lower PRs
context.py/scheduler.py(#7274):Context.dims: dict[str, str];Session._setupcopies it intoentry["dims"]aftersetup. Test:test_setup_fills_the_dims_of_the_entry. (PR-5 addsctx.fixture→ dims on a sibling branch; the two compose.)drivers/events.py(#7287):LoadResult.answered_per_second: list[int]: answers per second since the start of the load, warmup and drain included, merged over processes (deviation 4).GeneratorSaturatedleaves it out of its message like the histogram._Shard.addtakest0.SessionHold/hold_sessions(backend_url, count, *, reflex_version, pathname="/"): primescountsessions in one spawned process with the generator's own_Session.prime(connect, namespace,hydrate+on_load_internal), answers pings, and holds them;ready()raisesLoadError("N of M sessions could not start; …");close()sends41/_event,, closes each socket and returns the errors of sessions lost while held;kill()terminates from any thread; a hold whose parent exits closes itself._readable()and_session_errors()helpers shared with the load path (no behavior change).- Tests: per-second counts (single, closed loop, multi-second, two processes), holds (pings answered and 41 sent, sessions that cannot connect, a session lost while held, kill during priming).
drivers/echo_server.py(#7287):EchoProcess.pid.stats.py(#7274):linear_slope_ci,t_quantile_975,SlopeFit.tests/units/reflex_bench/factories.py:make_load_resulthasanswered_per_second.cgroup.py(#7283): limited scopes get-p OOMPolicy=continuewhere systemd accepts it (oom_policy_supported); see "OOMPolicy".
Deviations, with reasons
expiry_sdefaults to 120 s, not 30. A sweep must finish before the first held session's state expires. Measuredsweep_s: 23.2–23.7 s for K ≤ 500 and 32.4 s for K = 1000 on this 4-vCPU VM, so 30 s already failsallhere and leaves no margin fordailyon a slower runner (the sample raisesthe sweep and the disconnect took … s, not less than the token expiration). The cost is ~90 s more per sample (150 s instead of ~65 s).events(leak) andmax_sessions(per session) are visible parameters, withsuite_paramsfordaily(50 000; 500) and theallvalue as the default (100 000; 1000). A hidden parameter has one default for every suite, and a benchmark cannot see the suite; a visible one also keeps a 50k-eventgrowthfrom sharing a series with a 100k-event one. Instance ids are thereforememory.per_session[manager=disk,max_sessions=500],memory.leak[manager=memory,events=50000].--param max_sessions=50sweeps 0, 25, 50 (half of the largest is added when fewer than three counts remain).memory_methodfor idle/per-session/leak ispss_samplingeven with a scope (their values are PSS on every host; see "The benchmarks"). The unit test checkscgroupvspss_samplingonmemory.compile.peak, andcgroupon the limit ids.answered_per_secondstarts at the load's start, not the window's, so the leak's actual warmup count is known (warmup_eventsin the extra: 5776–6526 for 5000 asked) and the mapping needs onlyon_window("start")minus the warmup.hold_sessionshas noseed: tokens areuuid4, as in the generator (PR-7's deviation 5); nothing else is random.- Leak sampling is every hundredth of the window (0.1–1 s), not every second: the daily window is ~27 s at ~2000 ev/s, which 1 Hz would cover with 27 points (95 now). The rate probe runs at the start of
sample, right after the server start, not inprepare; its events are extra warmup. - The boot and serve phases share one scope, read twice: the load must reach the booted server, and a second server's scope would include its own boot anyway. Compile has its own scope.
- Hook timeouts of
compile.peak(660 s) andboot_512mb(600 s) exceed 300 s: each must outlast itsrun_clitimeout (600 s; 240 s for the gate's compile) plus the other phases, or a slow command would be abandoned with its tree running. memory.compile.peakruns at reflex's default log level (no--loglevel):phases=Falseis what drops the debug-level[timing]logging;infowould hide some default-level lines and change nothing measured.uss_byteshas a singlepythonentry, not supervisor and worker: every process of both versions' trees is namedpythonin/proc/<pid>/comm. The worker's own USS is recorded separately (worker_uss_bytesfor idle; the timeline's third column for the leak) as the largest process of the tree.- Estimates: set from the sample durations measured here. At the default policy (10 runs) the daily memory ids take ~74 min (
list --suite daily 'memory.*'); CI should pass--runs. - Verification ran without systemd (host caveat at the top): the cgroup numbers are from a cgroup v1 stand-in, 0.8.23 ran with
--runs 1, and theall-only ids (idle.allocator,min_limit) ran individually. - Branch: the session pins the branch, so this PR comes from
claude/memory-benchmarks-suite-l345kt, notfarhan/reflex-bench-memory.
Interfaces for later PRs
reflex_bench.stats.linear_slope_ci(xs, ys, confidence=0.95) -> SlopeFit(slope, intercept, ci_lo, ci_hi, r2, n)andt_quantile_975(df), for any trend (history drift, PR-10).reflex_bench.drivers.events.hold_sessions(url, count, *, reflex_version, pathname="/") -> SessionHold(ready(),close() -> list[str],kill()), for idle-session loads (e.g. SharedState fan-out observers, a connect/disconnect churn leak).LoadResult.answered_per_second, to index any timeline sampled during a load by events.ctx.dimsfor any benchmark whose method differs by host. Dims keys PR-10 will index:memory_method(cgroup|pss_sampling) on everymemory.*entry, andallocatorwhen a non-default allocator ran.memory.leak'stimeline([events, anonymous PSS, largest USS], ≤ 500 points) andmemory.per_session'slevelsare the series to plot.- ENG-12617 (reference profile): the published numbers need an amd64 machine with cgroup v2 scopes (user systemd or
sudo systemd-run):memory.boot_512mb[manager=memory]andmemory.boot.min_limit[manager=memory]there, plusmemory.idle,memory.per_session(all, K to 1000) andmemory.compile.peak[command=export]on the same profile. On systemd ≥ 253 run the OOMPolicy checklist first. - Future ids named in the README: a per-session leak (connect/disconnect churn), a per-page-load leak, redis
used_memoryper session, per-phase peaks (Linux 6.12).
Checks
uv run ruff check .: all checks passed.uv run ruff format --check .: 1633 files already formatted.uv run pyright reflex tests packages/reflex-bench/src: 0 errors.uv run pytest tests/units/reflex_bench -q: 618 passed, 7 skipped (the opt-in modules).test_memory.py(44 tests, ~10 s) patchesAppProcess,run_cli,tree_pss,LoadRunner,hold_sessions,EchoProcessand the scope class; it covers ids and suites, the env per id (manager,GRANIAN_WORKERS,REFLEX_REDIS_TOKEN_EXPIRATIONonly on per session, allocators, mimalloc on 3.12 failing), method labeling, a fake/proctree through the realtree_pss, synthetic timelines (plateau passes, 2 kB/event ramp fails naming the slope and both halves, a 1 MiB step in 50k events passes, unanswered fails), the three limit phases each failing onoom_kill=1, a pass with three peaks and every scope read before its tree stops, the 288 MiB bisection, and teardown after failures.REFLEX_BENCH_APP_TESTS=1app tests: above.uv run pre-commit run --files <changed files>: ruff-format, ruff-check, codespell, update-pyi-files, pyright, ty passed.test_the_harness_never_imports_reflexis green:suites/memory.pyimports nothing from reflex.
Adversarial self-review
- A cgroup read after its tree is gone. Every read happens before the tree stops:
run_clireads while its keeper holds the scope;boot_and_servereads after/pingand after the load, beforeapp.stop()infinally; idle/per-session/leak read beforeconclude. After a failedstart()the tree (and a systemd scope) is gone, so nothing is read and the message says so.read_or_noneturns a vanished cgroup into "unreadable", which always fails the phase. Unit test: the orderread compile, app start, read boot, load, read serve, app stop. - PSS and cgroup numbers in one series.
memory_methodis in the dims, set insetupfrom the cached probe thatsamplealso uses; the idle/per-session/leak values are PSS on every host, so they are labeledpss_samplingeven with a scope. A non-default allocator is in the dims too. - A leak verdict from a warm-up slope. The fit only uses samples inside the measured window, after
warmup_events; within it, the gate also needs the second half to keep at least half the first half's slope, and the plateau test (12 MiB in the first 20 %) passes withci_hi > 100. Known limit: in a short window one late arena step can land in the second half; a 1 MiB step puts the interval's upper end near 35 B/event over 50k events (under the tolerance on its own) but near 580 B/event over 3000. The opt-in test's three plain 3000-event samples passed, the daily window is 50k events. - Sessions or generator processes left after a hook timeout.
_Startedregisters each server, load runner, hold and echo server as it is created andconcludestops them newest first from any thread; whatever an abandonedsamplestarts after that is stopped at once.SessionHoldandLoadRunnerare safe to kill from another thread (their waits notice); hold and generator processes also end when their parent's pipe closes. Remaining gap (PR-7's):EchoProcess.start()is not locked, so a stop in the microseconds before it assigns its process would miss it; it then lives until the harness exits (its pipe closes). - A 512 MiB pass with swap enabled. Every limited scope is
CgroupScope(limit_bytes=…, swap_max=0), sowrap()emits-p MemorySwapMax=0next toMemoryMax(PR-3's argv test; the suite test asserts(512 MiB, 0)for both scopes). - Idle and residual numbers depend on other processes' mappings (
pss_file). Documented;pss_anonis the stable trend. - The per-session daily fit has three points (df = 1), so its CI is wide by construction; the
allsweep has four. - The echo floor is a Python
websocketsserver, not python-socketio (the harness must not depend on python-socketio); the python-socketio floor is the manual number above. raise_fd_limit(K)raises the harness's softRLIMIT_NOFILE(inherited by the server), as PR-7 does forat_1hz.- The byte formatter rounds to whole bytes, so the leak rows print
0 B/1 Bin the terminal; the data keeps full precision (the table above uses the extra data). Left as is (PR-1's formatter).
Rebase and review fixes (704ee1336, 927fe96bc)
Rebased onto #7287's current head (8f19bdffd). These supersede the matching parts above.
Rebase onto #7287's public session API:
hold_sessions(endpoint: Endpoint, count)andSessionHoldbuild onopen_sessions+wait_readable+event_loop. The fake_IDLE_SHAPEpriming and the private_Session/_readableimports are gone.- This PR no longer adds
answered_per_secondto the driver: #7287 now provides it, counting only answers received in the window. The leak timeline uses it;warmup_eventsis dropped from extra. - Small changes to #7287's files:
LoadResult.summary(),bench_shape/checked_loadmade public, and the events extra no longer stores the per-second array.test_daily_events_fit_the_ci_budgetnow sums onlyevents.*.
Fixes:
- OOM evidence kept (704ee1336, see "OOMPolicy"): at 64 MiB the gate reports
phase compile under MemoryMax=64M: reflex compile exited with code 137; oom=1, oom_kill=1; peak 64.0 MiB. - Leak gate: "leak" now needs the whole-window CI above the tolerance and growth in both halves (
ci_lo > 0in each). One 4 MiB allocator step at 50 % or 75 % of the window is no longer a leak; a steady ramp still is, and so is the deliberate-leak app. memory.leakmetrics:passed(exact) andbytes_per_event_ci_hi. The raw slope and growth move to extra, because near-zero values madecomparereport "+202 % regressed" on noise.- Per-session sweep: 0/50/100/250/500 (daily; 1000 in
all), about 7 s per step, so the CI has df ≥ 3. Measured: 198.0 kB/session, CI 192.0–204.0 kB, r² 0.9997; socket floor 17.6 kB. - Compile peak: records the whole-run
memory.peakonly. The anon/file/current fields were read after the command exited (a few kB next to a 75–494 MB peak) and are removed, together with the docstring claim. peak_reset:boot_and_serveresets the peak between boot and serve, sopeak_resetis true on kernels 6.12+.- Trims: the duplicated events helpers are gone (~120 lines);
largest_ussreuses the PSS reading;linear_slope_cihas no confidence parameter;session_errorsis removed; test helpers live infactories.py/conftest.py; the app test's leftover check filters on this run's own home.
Checks: 642 passed, 7 skipped; ruff, pyright and pre-commit pass. Real runs (HEAD, cgroup): memory.leak over 100k events passes, slope −0.48 B/event (CI −0.69…−0.27); memory.boot_512mb passes with peak_reset true, peaks compile 72 / boot 128 / serve 163 MiB; memory.compile.peak 76.0 MB. No processes or scopes left.
Not changed yet (maintainer decision pending): the daily time budget and expiry_s.
memory.per_session: 163 s → 39 s per sample (a641b9fc4)
Timing of one sample before the change (HEAD, memory manager, 500 sessions, 163 s total). About 160 s of it was idle waiting:
| Phase | Time |
|---|---|
| server start | 1.4 s |
| each level | 5 s settle + 2 s reads |
| echo floor sweep | 36 s |
| expiry wait | ~80 s (120 s expiry + 10 s margin) |
Sampling PSS every 0.25 s through every settle window shows the memory settles within 0.01 s of the hold being ready in 9 of 11 windows, and within 2.2 s in the rest (max drift 0.2 MiB against 8–47 MiB level steps). The three settled reads were identical at every level.
Changes:
- Expiry from the sweep:
expiry_sdefaults to 0, meaning it is sized from the sweep (sweep_seconds(levels)+ a 5 s margin; 23 s for 500 sessions, against a measured 11.6 s sweep). The guard that fails a sweep outlasting the expiration is unchanged. - Shorter waits:
SETTLE_S5 → 1 s andREAD_INTERVAL_S1 → 0.5 s. The latter also makesmemory.idle's reads 1 s shorter. - Echo floor once per instance: measured during the first sample's expiry wait and reused. Its slope was stable across runs: 17.0 / 16.9 / 16.6 kB.
Real runs (HEAD, --runs 2): 39.4 s per sample (was 162.8 s).
| Metric | Before | After |
|---|---|---|
bytes_per_session | 192.4 kB | 194.9 kB |
| its CI high end | 199.2 kB | 199.8 kB |
| r² | 0.9997–0.9999 | |
| residuals | ~97 MB | unchanged |
Finding, not fixed: on HEAD's memory manager, the tree's anonymous PSS doesn't move through the expiry deadline, so residual_after_expiry ≈ residual_after_disconnect (~97 MB). Either the freed states stay in the allocator, or the purge doesn't run. Worth a separate look.