ENG-12612: add the open-loop event generator and the events suite to reflex-bench
PR-7 of the Holistic Framework Benchmarks project (ENG-12612, plan item "PR-7 Event generator and event suite"). This PR adds an open-loop event generator that talks socket.io to reflex's event websocket directly, without python-socketio. It shows the generator is not the bottleneck and adds the events suite on top of the app driver from reflex-dev/reflex#7283. The harness still never imports reflex: the reflex under test runs as <subject python> -m reflex run --env prod --backend-only in a subprocess.
Stack: main ← reflex-dev/reflex#7274 ← reflex-dev/reflex#7281 ← reflex-dev/reflex#7283 ← reflex-dev/reflex#7280 ← this PR. Nothing merges until the whole project is done.
CI cost: smoke and daily run two event benchmarks, estimated at 2 minutes per reflex version with the default policy (measured: 121 s on HEAD and 120 s on 0.8.23 on a 4-vCPU VM). The spec's windows and grid put daily at about 487 minutes and smoke at about 27 minutes per version, over the 500-minute monthly budget for all benchmarks. See deviation 1.
All Submissions:
- Have you followed the guidelines stated in CONTRIBUTING.md file?
- Have you checked to ensure there aren't any other open Pull Requests for the desired changed?
Type of change
- New feature (non-breaking change which adds functionality)
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 it needs no news fragment.
Wire protocol (verified at 0.8.23 and HEAD)
Both versions mount python-socketio at /_event with transports=["websocket"] and allow_upgrades=False: HEAD in reflex/app.py around lines 611–650, and 0.8.23 in git show v0.8.23:reflex/app.py around lines 531–566. On both, EventNamespace.on_connect reads the token from the query string and calls link_token_to_sid, which emits new_token when the token is already in use. It warns when HTTP_SEC_WEBSOCKET_PROTOCOL differs from the backend version, so the generator sends no subprotocol. On 0.8.23, the Event dataclass has token: str with no default.
Frames captured from the playground backend (reflex run --env prod --backend-only) with a raw websockets client. Long frames are shortened.
HEAD (0.9.12.post18.dev0+8e72b14be):
< 0{"sid":"X109Zrp-O2X9xiJaAAAA","upgrades":[],"pingTimeout":120000,"pingInterval":25000,"maxPayload":1000000}
> 40/_event,
< 40/_event,{"sid":"EsTJJYBYaW5vhnSjAAAB"}
> 42/_event,["event",{"name":"reflex___state____state.hydrate","payload":{},"router_data":{"pathname":"/","asPath":"/","query":{}},"token":"e2ea4e2c-…"}]
< 42/_event,["event",{"delta":{"reflex___state____state":{"is_hydrated_rx_state_":false,…},…,"reflex___state____state.playground___state____bench_state":{"handler_value_rx_state_":"","last_seq_rx_state_":0},…}}]
> 42/_event,["event",{"name":"reflex___state____state.reflex___state____on_load_internal_state.on_load_internal",…}]
< 42/_event,["event",{"delta":{"reflex___state____state":{"is_hydrated_rx_state_":true}}}]
> 42/_event,["event",{"name":"reflex___state____state.playground___state____bench_state.set_seq","payload":{"seq":7},…}]
< 42/_event,["event",{"delta":{"reflex___state____state.playground___state____bench_state":{"last_seq_rx_state_":7}}}]
0.8.23 (same requests):
< 0{"sid":"6Ae7yW1SajBl_4TLAAAA","upgrades":[],"pingTimeout":120000,"pingInterval":25000,"maxPayload":1000000}
< 40/_event,{"sid":"y9yPyOwAFyS54yWlAAAB"}
< 42/_event,["event",{"delta":{"reflex___state____state":{"is_hydrated_rx_state_":true}},"events":[],"final":true}]
< 42/_event,["event",{"delta":{"reflex___state____state.playground___state____bench_state":{"last_seq_rx_state_":7}},"events":[],"final":true}]
- Delta key:
reflex___state____state.playground___state____bench_state/last_seq_rx_state_, the same on both versions. HEAD leaves out emptyeventsandfinal; the generator ignoresfinal. - Every result stores a raw frame: each result's extra data keeps one frame that answered an event, as
reply_frame. From the smoke runs: HEAD42/_event,["event",{"delta":{"reflex___state____state.playground___state____bench_state":{"last_seq_rx_state_":1}}}], 0.8.2342/_event,["event",{"delta":{"reflex___state____state.playground___state____bench_state":{"last_seq_rx_state_":1}},"events":[],"final":true}]. - No compression: granian answers the upgrade without
sec-websocket-extensionson both versions, so permessage-deflate is never negotiated. The echo server doesn't negotiate it either. - Framing, from
python-engineio4.13.5 andpython-socketio5.16.4 in the workspace venv:- The OPEN packet carries
upgrades,pingTimeout,pingIntervalandmaxPayload(engineio/async_server.py:458-462). - The server sends a PING every
ping_interval. A PONG schedules the next one, and a client that never answers is closed afterping_timeout(engineio/async_socket.py:35-66,136-141). - Each engine.io packet is its own websocket message (the socket's writer loop).
- Socket.io packets are
type[attachments-][/namespace,][id]json(socketio/packet.py). Types 5 and 6 carry binary attachments; reflex serializes deltas as JSON and never sends them, so the generator rejects them. AsyncServer._handle_connect(socketio/async_server.py:537-584) runs the connect handler before it sends the namespace ack. Anew_tokenemitted inon_connecttherefore arrives before40/_event,{"sid":…}, and the generator handles frames in any order during the handshake.
- The OPEN packet carries
- New handlers, checked on both versions (each probe script run shows no errors or warnings in the server log):
set_seq_complex→{"parts_scaled_rx_state_":90,"part_b_rx_state_":3,"last_seq_rx_state_":2,"part_a_rx_state_":2,"parts_total_rx_state_":9,"part_c_rx_state_":4,"parts_label_rx_state_":"scaled total 90"}set_seq_cross→{"…playground_state":{"count_rx_state_":1},"…bench_state":{"last_seq_rx_state_":3}}set_seq_background: on 0.8.23 an empty{"delta":{},"events":[],"final":true}comes first, then the delta with"final":null; on HEAD only the delta arrives.
- Background ordering: a burst of 200 back-to-back
set_seq_backgroundevents (memory manager) came back as 200 deltas in order with 0 inversions, on both versions.set_seqbehaved the same. Sobackgroundkept per-session order here. Other managers may not (the tasks take the state lock in whatever order they get to it), so the background shape isordered=False: an answer that overtakes an earlier one counts asout_of_order, and the earlier event stays outstanding until its own answer comes. - HEAD finding: the first typed event handler call per worker takes about 360 ms on HEAD (2 ms on 0.8.23). With
PYTHONPROFILEIMPORTTIME=1, that call lazily importsreflex.model(sqlalchemy, alembic, sqlmodel: 471 ms cumulative), because the workspace has thedbextras installed. Warmup absorbs it, but a user's first click pays for it. It isn't in scope here and may deserve its own issue.
The generator (reflex_bench/drivers/events.py)
It uses plain asyncio on websockets.asyncio.client.connect(url, proxy=None, ping_interval=None, …). The websockets library's own pings are off; the generator answers engine.io 2 with 3 itself. One session is one browser tab. It connects with ?token=<uuid4>, joins the namespace (adopting a new_token), then primes with hydrate and on_load_internal until is_hydrated is true, within 30 s. That time is recorded as prime_s.
EventShape(name, payload: Callable[[int], dict], delta_key, seq_var, ordered=True) # payload: a module-level function, e.g. seq_payload
LoadPlan(*, backend_url, reflex_version, shape, sessions, mode: "open" | "closed", rate, warmup_s, duration_s,
pathname="/", drain_s=5.0, processes=1, cpus=None)
run_load(plan, on_window=None) -> LoadResult # sync; spawns the generator processes
LoadRunner(plan).run(on_window=None) / .stop() # stop() kills the processes from any thread
LoadResult.check() -> str | None; LoadResult.to_dict() # JSON-ready, no per-event arrays
GeneratorSaturated(reason, result) # what sample() raises when check() fails
- Open loop: session
splans eventiatt0 + (s + i·sessions)/rate, so all sessions together are evenly spaced. It sleeps until the planned time and sends late events at once; none is skipped.response = recv − planned(the latency metric, no coordinated omission),service = recv − sent,lag = sent − planned. All three areperf_counter_nsin the generator process. - Closed loop: each session sends the next event after the answer. It reports
service_sonly, neverresponse_*. - Correlation:
- A delta whose
delta_keycarriesseq_var == NanswersN. - A delta for
Nwhile a lower seq is outstanding counts once asout_of_order, and the lower seqs count as unanswered. Their late answers are ignored; nothing belowNis "resolved". A dropped answer shows up the same way when the next one overtakes it. - A shape with
ordered=False(background) keeps the lower seqs outstanding instead, and their answers still count; the overtaking answer still counts asout_of_order. - Events with no answer by
duration_s + drain_scount asunanswered = sent − answeredand are never dropped. - A
41/_event,, an engine.io close, a websocket close or areload(0.8.23) fails the session and records a reason.
- A delta whose
- Processes:
- Sessions are sharded round-robin over processes started with
multiprocessing.get_context("spawn"). - Each process pins itself with
os.sched_setaffinity(0, cpus), raisesRLIMIT_NOFILEfor its sockets, and primes its sessions (64 at a time). - Each process reports
ready, gets a commont0(perf_counter_nsis CLOCK_MONOTONIC, system-wide on Linux and macOS), and returns its per-event arrays over aPipe. on_window("start"/"end")runs in the parent at the edges of the measured window. The suite uses it to read the server's CPU counters.run()terminates the children on any exception and on KeyboardInterrupt (checked: a Ctrl-C during a run printedinterrupted, exited 130, and left no process).stop()terminates and kills them fromconcludeandcleanup.- A generator process also cancels its run when its pipe to the parent closes, so a harness that dies any other way leaves no generator behind. The echo server process does the same.
- Sessions are sharded round-robin over processes started with
- Timers: on Linux the loop uses an epoll selector that waits with
select()on the epoll fd.epoll_waitcounts whole milliseconds, which made asyncio timers fire 0–1 ms late: the default loop measured p50 671 µs and p99 1.23 ms of lag at 500 ev/s, against p50 165 µs and p99 325 µs with this selector. That is enough to fail the 1 ms lag check by itself. - Result:
response_s(p50/p90/p99/p999/max),service_sandlag_s(p50/p99/max), andprime_s.achieved_send_rate(events sent within the window),answered_rate, and the counts.generator_cpu_fraction: the maximum over processes ofprocess_timeCPU seconds per second of the window.- A fixed 120-bucket log histogram from 10 μs to 100 s, for pooled display.
- The
reply_frame. stats.percentilesis nearest-rank (with golden tests);stats.log_histogramis new.
Self-check (LoadResult.check(), run on every load). It fails with generator saturated: … when:
- a generator process used more than 75 % of a core;
- in the open loop, the send lag p99 exceeds the largest of 1 ms, 10 % of the median response and half the service time p99 (see deviation 2);
- in the open loop, fewer than 98 % of the offered events went out within the window.
The suite takes a load again, up to twice (RETAKES), when only the self-check rejects it. The sample fails only if every attempt does, and the reasons of the retaken loads go into the sample's extra data as rejected. With 5 s windows, one host stall of the generator's CPU (78 ms in the first run after the CI budget change, at 15 % generator CPU) delays more than 1 % of a window's events and fails the lag rule by itself. A saturated generator fails every attempt. Session errors are never retaken.
The suite (reflex_bench/suites/events.py)
Each benchmark instance starts the playground backend once: AppProcess(..., mode="prod", backend_only=True, scope=CgroupScope() when available) in setup, stopped in cleanup. Every sample reuses it; conclude only stops a load that a timed-out sample left running. setup also runs a closed-loop probe (2 s after 1 s of warmup) that measures the capacity, for rate=auto and the knee, and warms the backend, so no sample meets it cold: on HEAD, the first latency run's p99 was 28.7 ms without it and 4.5 ms with it. The environment is REFLEX_STATE_MANAGER_MODE=<manager> and GRANIAN_WORKERS=1. REFLEX_REDIS_URL is passed only for redis: both versions switch to redis whenever a URL is configured (0.8.23 StateManager.create; HEAD unless the mode is set explicitly), and the token manager follows. /ping must answer before any load. setup_cache copies the playground from git ls-files into cache_dir/app and compiles it once, with REFLEX_WEB_WORKDIR next to the copy and REFLEX_STATES_WORKDIR in the workdir, cleared per instance.
| id | suites | params | load | metrics |
|---|---|---|---|---|
events.<shape>.capacity | smoke, daily (simple, manager=memory, sessions=10) | manager, sessions 1, 10, 50, 200 | closed, 3 s after 1 s | throughput (ev/s ↑), service_p50 (s), cpu_us_per_event (s ↓) |
events.<shape>.latency | smoke, daily (simple, manager=memory, sessions=10, rate=500) | manager, sessions, rate (auto = 0.5 × the capacity the probe in setup measures) | open, 5 s after 1 s | response_p50/p90/p99/max, throughput, unanswered (count, exact ↓), cpu_us_per_event |
events.simple.knee | all | manager, sessions | 10, 50, 70, 80, 90, 95, 100, 110 % of the capacity probed in setup, 4 s after 1 s each | knee_rate (ev/s ↑), low_load_p99 (s) |
events.sessions.at_1hz | all | manager, sessions 50, 200, 1000 | open, 1 ev/s per session, 10 s after 3 s | response_p50, response_p99, unanswered, cpu_us_per_event |
selftest.events.calibrate | selftest | – | the generator against the echo server, 10 sessions: closed 3 s after 1 s, then open at 10–50 % of that, 2 s after 1 s each | closed_ceiling, open_max_rate (ev/s ↑) |
- CI budget:
reflex-bench listestimates, with the default policy (10 runs at least):--suite smoke2 benchmarks, about 2.0 min;--suite dailythe same 2, about 2.0 min;--suite all 'events.*'78 benchmarks, about 147 min, which is for manual runs only.test_daily_events_fit_the_ci_budgetfails ifdaily's events estimate goes over 3 minutes. - Shapes:
simple(set_seq),complex,crossandbackground; onlysimpleis insmokeanddaily.managerismemoryanddisk, plusrediswhenREFLEX_REDIS_URLis set when the suite is imported (built bymanagers(os.environ)). The SharedState fan-out and contention shapes are named in a comment in the shape table, and nothing is registered for them. - Percentiles are per run, from that run's events. A run with fewer than 10⁴ answered events keeps its
response_p99and addsextra["p99_underpowered"] = true. cpu_us_per_eventis(cpu.stat usage_usec at the end of the window − at the start) / answeredfrom the server's cgroup scope, or the delta of psutilcpu_times()summed over the server tree, withextra["cpu_method"]saying which. The value is stored in seconds.- Knee: the highest step with answered ≥ 99 % of offered,
unanswered == 0andp99 ≤ 3 × low_load_p99. When no step qualifies,knee_rate = 0andextra["knee"] = "none". The step table goes inextra["steps"]. - Pinning applies on Linux with at least 4 CPUs. The server tree gets the lower half of the allowed CPUs minus CPU 0, set with
psutil.Process.cpu_affinityon every tree member after/pinganswers; workers forked later inherit it. The generator gets the upper half, withmin(4, len(generator CPUs))processes, and always 1 whensessions ≤ 10.extra["pinning"]records the split. - Timeouts:
timeoutis 600 s per hook.estimateis per sample: capacity 5 s, latency 7 s, knee 50 s (8 steps, each with a fresh generator and freshly primed sessions), at_1hz 16 s, calibrate 25 s. The server start and the probe happen once per instance, insetup.
Playground changes
BenchState gains set_seq_complex (sets part_a/b/c, read by the computed var chain parts_total → parts_scaled → parts_label, rendered in the footer as #bench-parts), set_seq_cross (async, get_state(PlaygroundState).count += 1) and set_seq_background (@rx.event(background=True), asyncio.sleep(0), then async with self). All three set last_seq and use only APIs that exist at 0.8.23; they compile and answer on both versions (above). The README documents them in its benchmark contract. The markers and pragma lines of reflex-dev/reflex#7280 are unchanged.
New content hash: sha256:7b02de7795b154cdcc3c10536339a4ead198cf383f5f749d943143dbade78d26 (was sha256:5c66b0dc…).
Verification (section 6)
The machine is a 4-vCPU Firecracker VM (Intel Xeon 2.1 GHz, reflex-bench doctor: virtualized, container, no cgroup v2 memory controller, so cpu_method is psutil). vmstat shows 1–2 % steal time. The profile is linux-x86_64-xeon-py3.14. Pinning on every run: {"server": [1], "generator": [2, 3]}.
Pinning in effect (during a smoke sample, HEAD):
server root 8357: pid 8357's current affinity mask: 2
child 8359 …multiprocessing.resource_tracker…: pid 8359's current affinity mask: 2
child 8360 …multiprocessing.forkserver…: pid 8360's current affinity mask: 2
grandchild 8361 (granian worker, forked by the forkserver): pid 8361's current affinity mask: 2
generator 8419 (ppid = harness): pid 8419's current affinity mask: c
After the CI budget change: uv run reflex-bench run --suite daily 'events.*' (HEAD) and --reflex 0.8.23, default policy (10 runs per instance), one run each:
| reflex | benchmark | status | throughput (ev/s) | p50 (ms) | response p99 (ms) | CPU per event (µs) | wall time |
|---|---|---|---|---|---|---|---|
| HEAD | capacity | ok | 2633 (2345…2805) | service 3.26 (3.08…3.83) | – | 417 (398…469) | 51.7 s |
| HEAD | latency rate=500 | ok | 500 | 1.23 (1.18…1.26) | 4.15 (2.86…11.91) | 962 (924…988) | 68.6 s |
| 0.8.23 | capacity | ok | 2120 (1944…2225) | service 4.32 (4.21…4.67) | – | 525 (496…554) | 49.9 s |
| 0.8.23 | latency rate=500 | ok | 500 | 1.37 (1.30…1.51) | 3.53 (2.41…6.51) | 1082 (1016…1176) | 69.9 s |
Both are manager=memory, sessions=10, with the median and min…max over the 10 runs. The whole daily events run took 121 s on HEAD and 120 s on 0.8.23, including setup (the playground compile was cached from earlier runs; a fresh CI machine compiles once per version). Every run had unanswered == 0, no session errors and no retake, and nothing was left running afterwards. In the run before the warm-up probe, one HEAD latency load was retaken (send lag p99 12.55 ms exceeds 4.14 ms) and the sample passed on the second attempt. The capacity gap (HEAD about 24 % higher, 21 % less CPU per event) is in line with the long-window smoke runs below.
Before the CI budget change (--suite smoke, 10 runs per instance, the spec's windows: capacity 10 s after 3 s, latency 30 s after 10 s, a fresh server per sample). The median is shown with min…max over runs in brackets.
| reflex | manager | benchmark (sessions=10) | status | throughput (ev/s) | p50 (ms) | response p99 (ms) | CPU per event (µs) | runs |
|---|---|---|---|---|---|---|---|---|
| HEAD | memory | capacity | ok | 2668 (2503…2742) | service 3.39 (3.23…3.55) | – | 419 (402…442) | 10 |
| HEAD | disk | capacity | ok | 2570 (2243…2689) | service 3.47 (3.29…3.99) | – | 433 (405…492) | 10 |
| HEAD | memory | latency rate=50 | ok | 50 | 1.58 (1.48…1.88) | 3.78 (3.30…9.01) | 1240 (1140…1480) | 10 |
| HEAD | disk | latency rate=50 | failed in run 3 | 50 | 1.48 (1.45…1.52) | 3.03 (2.88…3.18) | 1263 (1240…1287) | 2 |
| 0.8.23 | memory | capacity | ok | 2123 (2103…2243) | service 4.34 (4.20…4.44) | – | 515 (491…521) | 10 |
| 0.8.23 | disk | capacity | ok | 2056 (1997…2169) | service 4.47 (4.29…4.61) | – | 534 (509…554) | 10 |
| 0.8.23 | memory | latency rate=50 | ok | 50 | 1.73 (1.61…1.90) | 4.00 (2.98…25.89) | 1317 (1207…1453) | 10 |
| 0.8.23 | disk | latency rate=50 | ok | 50 | 1.81 (1.61…2.03) | 4.81 (3.62…12.04) | 1460 (1300…1647) | 10 |
HEAD is 0.9.12.post18.dev0+8e72b14be. At 50 ev/s the server is mostly idle, so its per-event CPU includes the idle loop's work spread over few events; compare CPU per event within a benchmark, not across capacity and latency.
Every sample had unanswered == 0 and session_errors == []. On HEAD, latency[manager=disk,…] failed its 3rd sample: generator saturated: send lag p99 10.73 ms exceeds 2.78 ms. In that sample the generator's vCPU was stalled by the host (lag max 64 ms at 1.9 % generator CPU), and the server's own service p99 was only 5.56 ms, so the stall had inflated the response p99 to 26.6 ms. The check caught exactly the contamination it is meant to catch. On 0.8.23 the same instance passed all 10 runs.
After every run, the psutil scan (REFLEX_BENCH_OWNER in the environment, or spawn_main/reflex run/granian/reflex_bench in the command line) and pgrep -f reflex_bench found nothing.
Opt-in app tests: REFLEX_BENCH_APP_TESTS=1 [REFLEX_BENCH_NETWORK_TESTS=1] uv run pytest tests/units/reflex_bench/suites/test_events_app.py runs events.simple.capacity[manager=memory,sessions=1] and events.simple.latency[manager=memory,sessions=1,rate=20]. It passes on the workspace (61.8 s) and on --reflex 0.8.23 (64.8 s), asserting unanswered == 0, the echo key in reply_frame, and no leftover processes.
Deviations, with reasons
- CI budget: shorter windows, one backend per instance, two points in
smokeanddaily. The benchmark CI budget is 500 minutes a month for everything. With the spec's windows (capacity 10 s after 3 s, latency 30 s after 10 s, knee steps andat_1hz30 s after 10 s), a server started per sample, and every shape × manager × session count plusat_1hzindaily,listestimateddailyat about 487 minutes andsmokeat about 27 minutes per version. Now:- Windows: capacity 3 s after 1 s, latency 5 s after 1 s, knee steps 4 s after 1 s,
at_1hz10 s after 3 s. A capacity window still answers thousands of events, and so does a latency window at 500 ev/s. - The backend starts once per instance (
setup), not per sample. The probe runs once per instance (2 s after 1 s) and also warms the backend. smokeanddailyrunevents.simple.capacity[manager=memory,sessions=10]andevents.simple.latency[manager=memory,sessions=10,rate=500]only. The other shapes,disk/redis, the other session counts, the knee andat_1hzrun with--suite allor by name.- The latency point uses a fixed 500 ev/s instead of the spec's 50: 5 s at 50 ev/s is 250 events, too few for a p99. A fixed rate also loads both
abarms and every day the same. - The knee exists for the simple shape only, with 8 steps (10, 50, 70, 80, 90, 95, 100, 110 %) instead of 10; calibration has 5 open-loop steps instead of 10.
- A load the self-check rejects is taken again, up to twice, before the sample fails (see the self-check above). The spec fails the sample at once, which with short windows turns one host stall into a failed benchmark.
- Windows: capacity 3 s after 1 s, latency 5 s after 1 s, knee steps 4 s after 1 s,
- The lag rule has a third term, "half the service time p99". On this VM, with the spec's rule (
max(1 ms, 0.1 × response p50)), 2 of 7 smoke latency samples at 50 ev/s failed with "generator saturated" while the generator was at 2 % CPU (lag p50 about 0.2 ms, p99 1.2 and 6.5 ms). Host preemption (1–2 % steal) stalls the idle generator's vCPU and the server's vCPU alike. The rule now tolerates a lag tail up to half the server's own service tail. A generator that falls behind a quick server still fails; the unit tests cover the old cases and the observed noisy sample. With the new rule, 1 of 33 smoke latency samples failed, and that one was genuine contamination (above). rateis a visible parameter with the valueauto, not a hidden one. The spec's instance idevents.simple.latency[manager=memory,sessions=10,rate=…]names it, andsmokeanddailyuserate=500.rate=autoloads eachabarm to half of its own capacity;--param rate=Ncompares at the same absolute load. The README says so.- New
suite_paramsin the registry (a change to a lower PR). This is howsmokeanddailyrun one point of the grid. See "Changes to lower PRs". websockets >=15,<18, not>=14. websockets 15 connects through the environment's proxy by default, andproxy=Noneexists only from 15 (checked: 14.2 has noproxyparameter). Without it, local connections go to the proxy in environments withHTTP(S)_PROXYand nono_proxyfor localhost.LoadPlanhas noseed. Nothing in the generator is random: phases ares/rate, and tokens are freshuuid4as section 2 requires.out_of_orderalso counts an answer that overtakes a dropped one. It is indistinguishable from coalescing, and the dropped seq still counts as unanswered.- Values the spec doesn't give: the knee's
sessionsgrid is the capacity grid (1, 10, 50, 200). - The sample error reads
GeneratorSaturated: generator saturated: …. The harness prefixes every error with its exception type. The result, without the histogram, is attached as JSON. - The browser sanity check (3.4) is left out. It needs more than about 80 lines:
reflex run --env prodwith the frontend build, a thread-bound sync Playwright browser across hooks, and a playground button whose value changes on each click (#bench-set-seqalways sets 7, so "wait for#bench-seqto change" cannot work 200 times). - Section 6 was cut short. After the smoke runs above, the longer list (about 3 h on this VM with the spec's windows) was stopped for the CI budget. After the change, the check is one
dailyrun per version (above). - In
ab, both arms' backends run for the whole instance, one idle while the other is measured, both pinned to the server CPUs. An idle backend without sessions uses next to no CPU. - Branch: the session pins the branch, so this PR comes from
farhan/admiring-albattani-pk9w94, notfarhan/reflex-bench-events. check_min_deps.py: it coversreflex-bench(--listincludes it).uv run python scripts/check_min_deps.py reflex-benchpasses.EventShape.ordered(defaultTrue) is not in the spec. The spec's correlation counts the lower outstanding seqs as unanswered, which is right when the server answers a session in order and wrong for background tasks.
Changes to lower PRs
registry.py/scheduler.py/cli.py:@benchmark(suite_params={"smoke": {"sessions": [10]}})narrows a parameter's values when that suite is selected;plan(benchmarks, overrides, suite)applies it, and--paramstill wins. The CLI passes--suitetoplaninrun,abandlist. Tests are intest_registry.py.stats.py:percentiles(nearest rank) andlog_histogram, with golden tests, as the plan asks.tests/units/reflex_bench/test_cli.py:- The quick self-test runs name their five benchmarks instead of the glob
selftest.[!a]*, which would now includeselftest.events.calibrate(it starts processes, likeselftest.app.*). list --suite selftestexpects the calibration.listwithout a suite now lists the events benchmarks (the "no benchmarks selected" hint is checked with a filter that matches nothing).
- The quick self-test runs name their five benchmarks instead of the glob
tests/units/reflex_bench/factories.py:make_load_result.
Interfaces for later PRs
- PR-8 (memory per session, leak slope): call
run_load(LoadPlan(mode="closed", duration_s=<long>, …), on_window=…), orLoadRunner(plan).run(on_window)withLoadRunner.stop()inconclude.on_windowruns in the harness at the window edges, for cgroup or PSS reads; for a slope, run a sampler thread (collectors.pss.PssSampler) whilerun()blocks. The generator runs in its own process tree, never in the server's scope, andraise_fd_limit(n)is public for many sessions. The entry point is sync and importing it has no side effects. - SharedState shapes (ENG-12609): the playground needs an
rx.SharedStatewith aset_seq-style handler. Contention (many sessions writing one shared state) fits the current correlation if each writer's delta echoes its own seq. Fan-out (one event updating N sessions) needs observer correlation: session B recording the arrival of A's seq. That is a generator extension, for example anEventShapeoption to count deltas of other sessions' seqs, and it belongs with the fan-out shape. - The document-level
fixtureblock is stillNone. The events results don't carry the playground's content hash in their series key yet. Whichever PR first drives the playground from the CLI should set it.
Checks
uv run ruff check .: all checks passed.uv run ruff format --check .: 1630 files already formatted.uv run ruff check examples/anduv run python scripts/hash_examples.py --check: clean.uv run pyright reflex tests packages/reflex-bench/src: 0 errors.uv run pytest tests/units/reflex_bench tests/units/test_examples.py tests/units/test_hash_examples.py -q: 590 passed, 4 skipped (the opt-in app tests). The generator tests take about 11 s and passed 10 times in a row.uv run pre-commit run --files <changed files>: every hook passed.uv run python scripts/check_min_deps.py reflex-bench: PASS.test_the_harness_never_imports_reflexis green:suites/events.py,drivers/events.pyanddrivers/echo_server.pyimport nothing from reflex.- No unit test starts a reflex app or downloads packages.
Adversarial self-review
- Timing comes from planned send times.
response_ns = recv − plannedeverywhere. The closed loop recordsplanned = sentand never reportsresponse_*(response_s is None).test_late_sends_are_never_skipped_and_count_from_the_planblocks the generator's loop for 200 ms: all 50 events are sent, response max ≥ 0.19 s, service max < 0.1 s, and the check fails. - Unanswered events are never dropped.
unanswered = sent − answeredcounts events without an answer by the end of the drain, events skipped by an overtaking answer, and the outstanding events of a session that disconnects. A late answer to a skipped seq doesn't resolve it. A failed session's planned but unsent events aren't counted, but any session error fails the sample. - Generator processes are always terminated:
run()stops them infinally, which covers exceptions and KeyboardInterrupt.conclude→_Backend.stop_load()andcleanup→_Backend.stop()→LoadRunner.stop()→ terminate, then kill after 5 s, safe from any thread.cleanupalso stops the server, after a failedsetuptoo (test_a_failed_probe_stops_the_backend). A load that starts afterstop()raises.- A dead parent closes the pipe, and the child cancels its run.
- Tests cover
stop()from another thread, the closed pipe, and the echo process. - The remaining gap is outside this PR: a SIGKILLed harness still leaves the reflex server tree of reflex-dev/reflex#7283 behind, because atexit cannot run.
- No reflex import. The PR-1 test is green.
- Noise versus saturation. Deviation 2 widens the lag rule. A generator whose lag tail stays under half the server's service tail passes, so its lag inflates the reported response tail by at most that much. That is intended, and the unit tests pin down both sides. Retakes (deviation 1) discard a load that failed the check instead of keeping it, so a stall costs one more window, not a failed benchmark or a contaminated p99;
rejectedshows how often it happened. A machine that stalls in most windows still fails. - psutil CPU accounting adds the children each process reaped (
children_user/children_system), so a granian worker that exits in the window still counts. Only a process reaped outside the tree is lost, and a CPU time that goes back fails the sample (cpu_per_event). A cgroup scope is exact; this VM lacks one, andcpu_methodsays which was used. - Short windows mean small per-run samples. A latency run at 500 ev/s answers about 2500 events, so its p99 is the 25th slowest and is flagged
p99_underpowered; the harness compares the median over at least 10 runs. The server start (about 1 s on HEAD, 3 s on 0.8.23) and the probe are once per instance, so they are not inestimate. raise_fd_limitraises the harness's own softRLIMIT_NOFILE, which the server then inherits. That is intended forat_1hz[sessions=1000]and harmless otherwise.select()on the epoll descriptor relies on epoll fds being pollable (documented Linux behaviour) and on that fd being belowFD_SETSIZE(it is created first, so it is low).- The knee runs 8 fresh generator and session sets per sample, and each step waits for its drain. Overload at 110 % can leave events queued for disconnected sessions, which the next sample's first step (10 %, with one backend per instance) may still see. An inflated
low_load_p99loosens that sample's 3× rule; it is reported per run, so such a run stands out. The knee is for manual runs. - One backend per instance means samples are not independent of each other's leftovers: the states of earlier samples' sessions stay in the memory manager (10 per sample at
sessions=10) and on disk fordisk. That is small next to the per-sample warmup, and it is what a long-running server looks like.
reflex-dev/reflex#6751 can be closed once this project lands. Its production Socket.IO load suite is superseded here (open loop, correlation and a self-check instead of SimpleClient round trips), and its other wall-time suites map to other PRs of this project.
Review fixes (8f19bdffd)
These supersede the matching parts above.
- In-window rates: throughput and the answered rate count only answers received before the window ends. The drain only feeds
answered/unanswered. Before, drain answers inflatedachieved, so the knee's "achieved ≥ 99 % of offered" rule never failed. Now, on a real knee run (10 sessions, capacity 3426 ev/s), the 110 % step reached 1898.5 of 3769 offered (p99 2.95 s) and fails the rule; knee 3084 ev/s. - Pinning by physical core: CPUs are grouped by
topology/thread_siblings_list, and server and generator each get whole cores. Before, they could share SMT siblings. Example: server [1,2,6,7,8], generator [3,4,5,9,10,11]. It falls back to the plain split when the topology is unreadable. - No retakes: a window that fails the generator self-check fails the sample (
GeneratorSaturated), as the spec says. The lag check uses generator-side lag only (sent − planned); the service-time term is gone. This replaces deviation 2 and the retake part of deviation 1. - Calibration: one open-loop step at 3 × the highest suite rate (3000 ev/s) must pass the self-check with nothing unanswered. The metrics are
closed_ceiling(reported, not judged) andopen_lag_p99, replacingopen_max_rateand the step table. Measured: ceiling 24–25.5k ev/s; the 3000 ev/s step passes with lag p99 0.08–0.79 ms at about 30 % generator CPU. - Public session API (for #7292):
Endpoint(backend_url, pathname="/")LoadPlan(endpoint=…, shape, sessions, mode, rate, warmup_s, duration_s, drain_s, processes, cpus); thereflex_versionfield is removed fromLoadPlanandLoadResultLoadResult.answered_per_second(in-window only)SessionPool(endpoint, indices, shape=None)withprime()/close()/errors, andopen_sessions(endpoint, count)as an async context managerevent_loop()andwait_readable(conn)are public
- Metric renamed:
cpu_us_per_event→cpu_per_event(units). - Smaller frame handling:
decode/Packet/kind tables are removed. The handshake and reader match the known frames, and anything else fails the session ("unexpected frame").
Checks: 573 passed, 4 skipped; ruff, pyright and pre-commit pass. Real runs: capacity 3796–4029 ev/s, service p50 2.5 ms, cpu_per_event 304–321 µs.
Not changed yet (maintainer decision pending): the latency benchmark's throughput/response_max metrics and the suite/CI budget.