Repository navigation
perf(server): replace HTTP middleware wrappers with ASGI middleware - #2890
Conversation
|
Auto-sync is disabled for draft pull requests in this repository. Workflows must be run manually. Contributors can view more details about this message here. |
1f24010 to
d378ace
Compare
yuhezhang-ai
left a comment
There was a problem hiding this comment.
LGTM. The focused middleware checks passed, and the existing CI run passed on this commit. The inline cleanup suggestion is optional and can be handled in a follow-up.
d378ace to
61a653e
Compare
6680bcd to
2590f39
Compare
yuhezhang-ai
left a comment
There was a problem hiding this comment.
Reviewed head 2590f39. Four issues and two nonblocking test improvements are detailed inline.
Validation: 1,667 focused tests passed, with separate base/head reproductions for the findings. The broader local core-suite run was not clean, but every original failing/error test ID also appeared in the base comparison. No real model rollout, production sandbox, or throughput benchmark was run. The inline comments state the limits of the stream and body-disconnect reproductions.
yuhezhang-ai
left a comment
There was a problem hiding this comment.
LGTM at a8f688f. The four substantive findings and the handled-error cookie coverage are fixed and verified. CI is green for this head.
The remaining timeout-test follow-up is nonblocking: put pytest.raises(asyncio.CancelledError) outside asyncio.timeout(10) so the deadline cannot satisfy the expected-cancellation assertion. This improves the test's ability to detect a regression; it is not a remaining cancellation defect in the current implementation.
Local verification: 1,683 focused tests passed, and the four original defect reproductions now pass. Four unrelated Linux port-sharing tests failed on macOS and also failed against the base revision.
Every Gym server registered session ID assignment and exception handling with
@app.middleware("http"), and vllm_model added a third such layer for engine refusals.
Starlette runs each of these through BaseHTTPMiddleware, which starts a task and a stream pair
per request and relays every reply message through the stream.
Replace all three with ASGI middleware that calls the app directly and settles the reply when it
starts.
A cancelled request still gets the failure reply before the cancellation propagates, because Gym
cancels the task serving a route when a checkpoint retires an activation or a model call.
A route that raises CancelledError itself now gets a 500 instead of no reply.
Because routes now run in the request's own task, a context variable a route sets and never
resets would reach the next pipelined request on the same connection.
RequestContextIsolationMiddleware now serves each request in a task with a copy of the context
captured at install.
A unit test fails if Gym's servers add another @app.middleware("http") or BaseHTTPMiddleware layer.
osworld's two bearer-token checks are left for a separate change.
Signed-off-by: Ananth Subramaniam <[email protected]>
…ested branches ExceptionHandlingMiddleware builds the failure reply after its except block has exited, so SimpleServer._failure_reply's format_exc() and print_exc() found no active exception and logged "NoneType: None". Format the exception passed in instead. Add tests for a route that replies with an error status under a new session, a named session the route never reads, and a context refusal raised after the reply started. Widen the guard test to catch BaseHTTPMiddleware imported by name, and count osworld's allowed sites. SESSION_ID_KEY from server_utils now warns, since base_server no longer imports it. Update comments that named the removed functions, and wrap long docstring lines. Signed-off-by: Ananth Subramaniam <[email protected]>
…lost claim replaced ClientDisconnectCancellationMiddleware queued http.disconnect for the app and then cancelled it. A handler waiting on its body got ClientDisconnect before the cancellation landed, and one that treats a failed read as an empty body acted on it. The decorated middleware layers used to hide this by delaying the read. Cancel without handing the app the disconnect. When a lost multi-worker claim replaces a reply with a 409, raise from the route's send so the route stops instead of streaming into a reply that has ended. Exclude installed environments from the guard test's scan, bound the cancellation test's waits, and cover error replies under a router-chosen or claimed session. Signed-off-by: Ananth Subramaniam <[email protected]>
…r for session routing The cancellation test awaited the request inside `asyncio.timeout(10)` with `pytest.raises(asyncio.CancelledError)` inside the deadline, so the deadline's own cancellation could satisfy the check: a request that sent its 500 and then hung instead of propagating the cancellation still passed after ten seconds. The check now wraps the deadline, so an expired deadline raises `TimeoutError` and fails the test. Session routing now says owner and acquire in place of claim (NVIDIA-NeMo#5083). The session ID middleware's tests and the stopped-route exception follow it. Signed-off-by: Ananth Subramaniam <[email protected]>
|
A/B RL training runs against this PR's merge base (
This PR cuts the model server's CPU per call by about 20% under real multi-turn traffic. A separate CPU-only microbenchmark showed up to 29% less CPU per call, and 28–42% more throughput when the server is saturated. No regressions were seen in routing, token-capture lineage, per-call latency or step time. In these RL setups the model server isn't the bottleneck, so the benefit is headroom: fewer workers or CPU nodes, or more concurrency, for the same load. Microbenchmark results:
|
yuhezhang-ai
left a comment
There was a problem hiding this comment.
LGTM at 73999c6. All six review findings are addressed, including the cancellation test’s timeout handling. I verified that the test passes normally and fails when cancellation propagation is broken, and that the earlier runtime fixes remain intact after the rebase. Main CI passed; the nonblocking Hermes failure is a dependency-download HTTP 429.
|
🔄 Merge queue validation started! You can track the progress here: https://github.com/NVIDIA-NeMo/Gym/actions/runs/42644435320 |
Summary
Every Gym server registers session ID assignment and exception handling with
@app.middleware("http"), andvllm_modeladds a third such layer for engine refusals such as a context overflow. Starlette implements each decorator withBaseHTTPMiddleware. For every request, each of those layers starts the rest of the app in a new task, waits for the reply to start through an in-memory stream pair, and then relays every reply message back through that stream. A request crosses two or three of these layers on every server hop.This change replaces the three layers with ASGI middleware that calls the app directly in the request's own task:
SessionIDMiddleware(nemo_gym/server_runtime/request_handling/session_id.py) assigns the session ID before the route runs and settles it when the reply starts, beforeSessionMiddlewarewrites the cookie. Multi-worker session ownership keeps its behavior: a worker takes ownership of a session only if the route used it, a session another worker owns gets a 409 in place of the reply, and a failed or unused new session hands out no cookie.ExceptionHandlingMiddleware(request_handling/exception_handling.py) opens the request'sRequestFailureLog, adds the failure report to every reply's start message, and merges it with a report an inner layer already sent. A route that raises before replying gets the same failure body as before, including the partial observations it left in the request state.vllm_model's_ContextErrorMiddlewarereturns an engine refusal in OpenAI's error envelope with the engine's status, and lets every other error reach the exception middleware.flowchart TB subgraph after["After: one task per request"] direction TB a_iso["Context isolation: new task, fresh context"] a_cancel["Client-disconnect cancellation"] a_exc["ExceptionHandlingMiddleware"] a_ses["SessionMiddleware + SessionIDMiddleware"] a_route["FastAPI route"] a_iso --> a_cancel --> a_exc --> a_ses --> a_route end subgraph before["Before: a vllm_model request"] direction TB b_iso["Context isolation"] b_cancel["Client-disconnect cancellation"] b_exc["Exception handling (BaseHTTPMiddleware)"] b_ctx["Context errors (BaseHTTPMiddleware)"] b_ses["SessionMiddleware + session ID (BaseHTTPMiddleware)"] b_route["FastAPI route"] b_iso --> b_cancel --> b_exc b_exc -->|"new task and stream pair"| b_ctx b_ctx -->|"new task and stream pair"| b_ses b_ses -->|"new task and stream pair"| b_route endContext isolation now runs each request in its own task
BaseHTTPMiddlewareran each route in a child task with a copy of the request's context, so a context variable a route set and never reset was discarded when the route returned. With direct calls, the route runs in uvicorn's request task. When a client reuses a kept-alive connection before the previous reply has finished, uvicorn starts the next request's task from inside the previous one, and that task inherits whatever the previous route left behind. Several resources servers set context variables without resetting them, for exampleofficeenvandverifif.RequestContextIsolationMiddlewarenow serves each request in a new task with a copy of the context captured when it was installed, before the server started. The new task still starts with no OTel context and no rollout ID, so the OTel instrumentation extracts the inboundtraceparent. This is one task per request, in place of the two or three task groups and stream pairs the removed layers started.Behavior changes
asyncio.CancelledErroritself still gets a 500, now with the body"Request was cancelled"instead of"RuntimeError('No response returned.')"."Request was cancelled". When the client disconnected, the disconnect middleware drops the reply.BaseHTTPMiddlewarethe client saw a truncated 200 that looked complete.SystemExitnow gets a 500 instead of stopping the worker's event loop.RuntimeError("No response returned."), with the failure header. Without the exception middleware, as in apps built bysetup_webserveralone, the client now gets uvicorn's 500 instead of Starlette raising that error.ClientDisconnectCancellationMiddlewarenow cancels the route without handing it thehttp.disconnectmessage. It used to queue the message and then cancel. A route waiting on its body could then getClientDisconnectbefore the cancellation landed, and a handler that treats a failed read as an empty body would act on it. The decorated layers hid this race by delaying the read; without them it shows.skipped_on_direct_mcp_dispatch; the special case for decorated functions is gone because none remain.Compatibility
RequestContextIsolationMiddlewarenow takes a keyword-onlybase_context. Code that adds it directly must pass one;install_request_context_isolationpasses the context captured when it is called.SESSION_ID_KEYimported fromnemo_gym.server_utilsnow raises a deprecation warning. Import it fromnemo_gym.clientinstead.Keeping the stack free of task-per-request middleware
A unit test fails when any Gym server package adds
@app.middleware("http")or usesBaseHTTPMiddleware.resources_servers/osworldregisters two bearer-token checks that way. They are environment-specific and optional, so the test allows those two and no more, and they are left for a separate change.This implements #3004, tracked by the performance roadmap in #2998.
The branch was rebuilt on current
main, because the earlier version predated thenemo_gympackage reorganization.Validation
pytest -n 16 tests/unit_testswith the CI extras.pytest responses_api_models/vllm_model/tests, which drives engine refusals through the realsetup_exception_middleware.nemo-lensinstalled at the pinned revision.pre-commit runon the changed files.tests/unit_tests/server_runtime/test_asgi_middleware.pycheck session ID persistence, cookie suppression for a new session whose request failed or whose route replied with an error status, the session router's chosen ID, multi-worker session ownership (a session another worker owns, a used session, an unused new session, and theVaryheader on a named session the route never reads), partial observations in failure bodies, that a failed route's log keeps its traceback, a route that never replies, a route that raisesCancelledError, a route whose task other code cancels, failures after the reply starts, the request's own cancellation (failing on its deadline rather than passing when the cancellation never propagates), pipelined requests on a real uvicorn server with and without isolation, and the guard against new task-per-request middleware.mainand failed on this branch before the fix.vllm_modeltest checks that a context refusal raised after the reply started propagates instead of sending a second reply.main. The guard skips installed environments such as a server's.venv.Rollout evidence
N/A for model rollouts: the change is limited to HTTP middleware and does not change agent, model, or verifier decisions.
A CPU-only capacity simulator compared this branch with
main.The simulator ran a mock engine with no inference delay, a burst of 2048 rollouts, three interleaved runs per variant, telemetry off, and pinned CPUs: two for the engine, eight for the Gym servers, two for the rollout driver.
Values are medians, with the range across runs in parentheses.
simple_agentloadvllm_modelloadsimulated_toolsloadmainLoad is CPU seconds per wall-clock second, so 1.00 is one core fully busy.
The run started once the machine was idle, and the 1-minute load average stayed between 1.3 and 5.4 on 24 CPUs throughout.
Server CPU per rollout fell by two fifths, and every rollout completed on both variants.
Throughput roughly doubled, and
simple_agent's event loop is now close to saturated, so it is the next limit in this workload.