Skip to content

perf(server): replace HTTP middleware wrappers with ASGI middleware - #2890

Merged
ananthsub merged 4 commits into
NVIDIA-NeMo:mainfrom
ananthsub:ananthsub/pure-asgi-middleware
Nov 9, 2026
Merged

ananthsub merged 4 commits into
NVIDIA-NeMo:mainfrom
ananthsub:ananthsub/pure-asgi-middleware

Conversation

@ananthsub

@ananthsub ananthsub commented Aug 31, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Every Gym server registers session ID assignment and exception handling with @app.middleware("http"), and vllm_model adds a third such layer for engine refusals such as a context overflow. Starlette implements each decorator with BaseHTTPMiddleware. 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, before SessionMiddleware writes 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's RequestFailureLog, 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 _ContextErrorMiddleware returns 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
    end
Loading

Context isolation now runs each request in its own task

BaseHTTPMiddleware ran 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 example officeenv and verifif.

RequestContextIsolationMiddleware now 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 inbound traceparent. This is one task per request, in place of the two or three task groups and stream pairs the removed layers started.

Behavior changes

  • A route that raises asyncio.CancelledError itself still gets a 500, now with the body "Request was cancelled" instead of "RuntimeError('No response returned.')".
  • A cancelled request still gets the 500 failure reply before the cancellation propagates. Gym cancels the task serving a route when a checkpoint retires an activation or a model call, and when uvicorn shuts down. For those, the status is the same as before and the body is now "Request was cancelled". When the client disconnected, the disconnect middleware drops the reply.
  • A failure after a streamed reply has started now ends the connection without the final chunk, so the client raises a payload error. Under BaseHTTPMiddleware the client saw a truncated 200 that looked complete.
  • A route that raises SystemExit now gets a 500 instead of stopping the worker's event loop.
  • A route that returns without replying still gets Gym's failure body for RuntimeError("No response returned."), with the failure header. Without the exception middleware, as in apps built by setup_webserver alone, the client now gets uvicorn's 500 instead of Starlette raising that error.
  • When a client disconnects before its reply finishes, ClientDisconnectCancellationMiddleware now cancels the route without handing it the http.disconnect message. It used to queue the message and then cancel. A route waiting on its body could then get ClientDisconnect before 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.
  • When another worker took ownership of a session first, the route whose reply the 409 replaced now stops at its first send, instead of running on into a reply that has ended.
  • Direct MCP dispatch recognizes Gym's middleware only by the class marker skipped_on_direct_mcp_dispatch; the special case for decorated functions is gone because none remain.

Compatibility

  • RequestContextIsolationMiddleware now takes a keyword-only base_context. Code that adds it directly must pass one; install_request_context_isolation passes the context captured when it is called.
  • SESSION_ID_KEY imported from nemo_gym.server_utils now raises a deprecation warning. Import it from nemo_gym.client instead.

Keeping the stack free of task-per-request middleware

A unit test fails when any Gym server package adds @app.middleware("http") or uses BaseHTTPMiddleware. resources_servers/osworld registers 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 the nemo_gym package reorganization.

Validation

  • pytest -n 16 tests/unit_tests with the CI extras.
  • pytest responses_api_models/vllm_model/tests, which drives engine refusals through the real setup_exception_middleware.
  • The OTel tests for request context isolation, trace context in the path, and propagation, run in an environment with nemo-lens installed at the pinned revision.
  • pre-commit run on the changed files.
  • New tests in tests/unit_tests/server_runtime/test_asgi_middleware.py check 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 the Vary header 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 raises CancelledError, 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.
  • Tests on a real uvicorn server check that a client disconnecting during a body upload cancels the route before it can act on a failed read, and that a route whose reply the ownership 409 replaced streams nothing. The disconnect test passes on main and failed on this branch before the fix.
  • A new vllm_model test checks that a context refusal raised after the reply started propagates instead of sending a second reply.
  • Each new test fails when the line it covers is removed or changed, and the tests for cancellation, pipelining, the stopped route and the guard fail on 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.

Variant Rollouts per second Server CPU per rollout simple_agent load vllm_model load simulated_tools load
main 92.3 (90.8–98.9) 20.2 ms (20.1–20.3) 0.70 0.53 0.57
This branch 198.4 (196.1–199.9) 12.2 ms (12.2–12.2) 0.93 0.61 0.75

Load 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.

@ananthsub
ananthsub marked this pull request as draft August 31, 2026 17:57
@copy-pr-bot

copy-pr-bot Bot commented Aug 31, 2026

Copy link
Copy Markdown

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.

@ananthsub

Copy link
Copy Markdown
Contributor Author

Tracked by the performance roadmap in #2998. This PR directly implements #3004.

yuhezhang-ai
yuhezhang-ai previously approved these changes Oct 13, 2026

@yuhezhang-ai yuhezhang-ai left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread responses_api_models/vllm_model/app.py Resolved
@github-actions github-actions Bot added the sla:review-overdue Review response is over the one-business-day SLA label Oct 13, 2026
@ananthsub
ananthsub force-pushed the ananthsub/pure-asgi-middleware branch from d378ace to 61a653e Compare October 13, 2026 19:38
@ananthsub
ananthsub requested a review from a team as a code owner October 13, 2026 19:38
@ananthsub
ananthsub changed the base branch from main to ananthsub/instrument-only-with-traces October 13, 2026 19:38
@svcnvidia-nemo-ci svcnvidia-nemo-ci added area:core Shared APIs, servers, telemetry, health, and registries feature New capabilities, enhancements, or enablement work needs-review PR is ready for code review and waiting on a reviewer labels Oct 20, 2026
@ananthsub
ananthsub force-pushed the ananthsub/pure-asgi-middleware branch from 6680bcd to 2590f39 Compare November 5, 2026 14:40
@ananthsub ananthsub changed the title perf(server): replace HTTP middleware wrappers with ASGI perf(server): replace HTTP middleware wrappers with ASGI middleware Nov 5, 2026
@nemo-automation-bot
nemo-automation-bot Bot requested a review from a team November 5, 2026 14:41

@yuhezhang-ai yuhezhang-ai left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread nemo_gym/server_runtime/base_server.py Resolved
@github-actions

github-actions Bot commented Nov 5, 2026

Copy link
Copy Markdown
Contributor

yuhezhang-ai
yuhezhang-ai previously approved these changes Nov 5, 2026

@yuhezhang-ai yuhezhang-ai left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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]>
@snivertynv

Copy link
Copy Markdown
Contributor

A/B RL training runs against this PR's merge base (dc4a279a3): multi-turn SWE with an OpenCode harness in remote sandboxes, token capture on, and vllm_model with 64 workers and least-loaded endpoint placement. The arms differ only in this PR.

Off-policy lag vllm_model CPU per model call, base → PR Busy CPU per worker (p50) Rollouts split across engines Step time
15 (~13k calls in flight) 29.2 → 23.7 ms (−19%) 0.169 → 0.134 cores 2/9183 → 9/9208 unchanged
3 27.1 → 24.1 ms (−11%) 0.032 → 0.028 cores 0/3612 → 0/3588 unchanged

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: vllm_model under multi-turn agent traffic

vllm_model with 8 uvicorn workers on 8 pinned CPUs, in front of 4 mock OpenAI engines. Closed-loop rollouts behave like a coding-agent harness: no cookies, every call under /ng-rollout/<id>/, and history growing by one tool result per turn (swe: 20 turns, bodies up to ~100 KB; small: 3 short turns). Medians of 3 interleaved repetitions.

Scenario In flight Engine delay Calls/s, base → PR Server CPU per call, base → PR p50 / p99 latency, base → PR
small 1024 0 2416 → 3173 (+31%) 3.31 → 2.52 ms (−24%) 358 / 680 → 282 / 576 ms
swe 1024 0 1837 → 2351 (+28%) 4.35 → 3.40 ms (−22%) 499 / 919 → 397 / 693 ms
swe 2048 200 ms 1463 → 2073 (+42%) 5.47 → 3.86 ms (−29%) 1388 / 1794 → 996 / 1351 ms
swe 2048 2000 ms 918 → 965 4.72 → 3.67 ms (−22%) 2104 / 2838 → 2027 / 2477 ms
  • First three rows: the server is saturated in both variants (8 of 8 cores busy), so they measure capacity.
  • Last row: below saturation. The server adds 104 ms to a call's median latency on the base and 27 ms with this PR (838 → 477 ms at p99).
  • Affinity: no rollout's calls were split across engines in any run, so routing by current_rollout_id() still works with the per-request task.

@yuhezhang-ai yuhezhang-ai left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@github-actions

github-actions Bot commented Nov 9, 2026

Copy link
Copy Markdown
Contributor

🔄 Merge queue validation started! You can track the progress here: https://github.com/NVIDIA-NeMo/Gym/actions/runs/42644435320

This branch was previously deployed

1 inactive deployment
public — 73999c62 Deployed Nov 9, 2026 by copy-pr-bot[bot] via release / finalize / notify #10944
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:core Shared APIs, servers, telemetry, health, and registries feature New capabilities, enhancements, or enablement work needs-review PR is ready for code review and waiting on a reviewer sla:review-overdue Review response is over the one-business-day SLA

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Replace BaseHTTPMiddleware on hot paths with pure ASGI middleware

4 participants