Repository navigation
fix(telemetry): start every server request from a clean context - #4755
Merged
Merged
Conversation
uvicorn starts a pipelined request's task from inside the previous request's task (on_response_complete -> loop.create_task), so the new task inherits that request's contextvars: the OpenTelemetry current span and Gym's rollout id. The OTel ASGI instrumentation then sees a current span, skips traceparent extraction, and files the request as an INTERNAL child of the previous request's SERVER span, inside the previous rollout's trace; the effect chains along the connection. Requests get pipelined because Gym's servers answer through Starlette's BaseHTTPMiddleware, which sends the terminating body message separately, 8-99 ms after the body in cluster traces. A client already holding the full Content-Length body reuses the connection in that window. RequestContextIsolationMiddleware, registered outermost in run_webserver, attaches an empty OpenTelemetry context and resets the rollout id for the request's duration, so the instrumentor extracts the inbound traceparent and the rollout middleware sets the id from the path. The test serves a real uvicorn app with a deliberate late terminating body, hammers one keep-alive connection from several coroutines with distinct traceparents, and checks every server span's parent; the control case shows the same server mis-parents requests without the middleware. Signed-off-by: Ingo Guehring <[email protected]>
Contributor
…tion The FastAPI instrumentor installs its middleware by overriding build_middleware_stack, so a middleware added with add_middleware always ends up inside it. Inside, the isolation emptied the context the handlers ran in: Gym's endpoint spans and outgoing client spans became trace roots and the cross-process chain broke, as a cluster run showed. The isolation now wraps the middleware-stack build the same way, after instrumentation, so it is the outermost layer: the instrumentor sees an empty context and extracts traceparent, and the handlers still see the server span it makes current. The test now also requires a span opened inside the handler to be a child of the request's server span. Signed-off-by: Ingo Guehring <[email protected]>
Contributor
Author
|
/review |
Contributor
|
LGTM. The fix is right, and outside the instrumentor is the only place it works. Two requests:
Nits:
Verified locally:
|
…lout reset described as a guard Review follow-up. install_request_context_isolation is a module-level function called from run_webserver; the optional OpenTelemetry import sits below the import block. Tests now pin the install order: after the instrumentor, isolation is outermost with the instrumentor inside; before it, the instrumentor finds a stack it does not recognise and skips the app, which is why run_webserver instruments first. The description of the rollout-id reset no longer claims a leak: Gym's BaseHTTPMiddleware layers run the rollout middleware and handlers in a child task, so only the instrumentor's OTel context leaks; the reset stays as a guard for stacks without such a layer, which the behavioural test exercises. Signed-off-by: Ingo Guehring <[email protected]>
Contributor
Author
Thanks for the great review @marcromeyn ! All addressed. |
iguehring-nvidia
requested review from
marcromeyn
and removed request for
ananthsub
October 20, 2026 15:04
Contributor
|
/review |
Contributor
|
/ok to test fda9fd2 |
oyilmaz-nvidia
approved these changes
Oct 20, 2026
Contributor
|
🔄 Merge queue validation started! You can track the progress here: https://github.com/NVIDIA-NeMo/Gym/actions/runs/39482903478 |
yaoyu-33
added a commit
that referenced
this pull request
Oct 20, 2026
Resolve the import conflict in nemo_gym/server_utils.py: keep main's rollout_context import (#4755) alongside this branch's session_routing import. Signed-off-by: yaoyu-33 <[email protected]> Co-Authored-By: Claude Opus 5.5 <[email protected]>
This was referenced Oct 20, 2026
7 tasks done
This branch was previously deployed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
What does this PR do?
Adds
RequestContextIsolationMiddleware, installed byinstall_request_context_isolation(app)inrun_webserveras the outermost layer of the middleware stack, which starts every HTTP request from an empty OpenTelemetry context. It also clears the rollout id, as a guard only: in Gym's current stack theBaseHTTPMiddlewarelayers run the rollout middleware,/runand the handlers in a child task, so a rollout id set there never reaches the task uvicorn copies (verified by @marcromeyn: 0 of 100 leaks with the current layering); the guard keeps that true if those layers are ever replaced by plain ASGI middleware. It is installed by wrappingbuild_middleware_stackafter instrumentation, the same way the FastAPI instrumentor installs itself, because a middleware added withadd_middlewarealways ends up inside the instrumentor's; inside, it would empty the context the handlers run in and detach Gym's own spans from the server span (observed on a cluster run of the first revision).Why: in cluster traces, 10 to 17 percent of the policy model's server spans were parented to the previous request on the same keep-alive connection, often another rollout's, with the caller's client span left without a child. Four pieces, each verified:
BaseHTTPMiddlewarelayers (the@app.middleware("http")session-id and exception handlers), which stream the response and send the terminating empty body message separately: 8 to 99 ms after the body in the traces, median 15 ms.httptools_impl.py) queues that request as pipelined and, inon_response_complete, starts its task withloop.create_task(...)from inside request N's task, so the new task inherits that task's contextvars. In Gym's stack that is the instrumentor's OTel context: the instrumentor runs outermost, so N's server span is current in the task that sends N's terminating message.opentelemetry-instrumentation-asgi(_start_internal_or_server_span) extractstraceparentonly when no span is current; otherwise it opens an INTERNAL span under the current one.Span attributes stayed correct throughout; only the parent edge was wrong.
The middleware closes the symptom regardless of what runs inside the window. Replacing the
BaseHTTPMiddlewarelayers would shrink the window but not close the race, and is left for a separate change. The two upstream angles (uvicorn starting pipelined tasks from a clean context; the instrumentation extractingtraceparenteven with a current span) will be reported separately.A note in the distributed-tracing docs describes the symptom and the middleware.
No issue in this repository; the investigation is recorded on the tracking item for the rollout-observability work.
Validation
tests/unit_tests/telemetry/test_request_context_isolation.py: after instrumenting,install_request_context_isolationleaves isolation outermost with the instrumentor's middleware inside it (the orderrun_webserveruses); installed before the instrumentor, the instrumentor finds a stack it does not recognise and skips instrumenting the app entirely, which is why the order matters; installing twice wraps once.traceparent. With the middleware: 96 of 96 server spans are SERVER spans parented to their owntraceparent, a span opened inside each handler is a child of that request's server span (so the instrumentor's span is still current in handlers), and no request sees a rollout id left behind by the previous handler (this app has no child-task layer, so it exercises the guard). The control case without the middleware mis-parents requests and leaks the rollout id, which is the failure the test exists to catch. Run three times; stable.pytest tests/unit_tests/telemetry: 367 passed; the 4 failures are the known macOS-only ones (test_memory×2,test_connection_pool,test_call_sitesactive-servers gauge), identical onmain.pre-commit run --files <changed files>: passed.Rollout evidence
Same 16-rollout scicode workload on a Slurm cluster, before and after.
main)main+ this PR and the three telemetry PRs it was found with)Engine calls under each rollout's trace, one row per call in time order, for three rollouts of the same workload before and after. Blue: the rollout's own call in its own trace. Red: another rollout's call mis-parented into this trace. Dashed: the rollout's own call missing from its trace because it was parented into another rollout's.
In the after run every
POSTserver span is SERVER kind and a child of the agent's client span, everygym.model.responsesspan is a child of its server span, and every enginellm_requestspan sits under the right rollout. The first revision of this PR (middleware added withadd_middleware) passed its unit test but, on the cluster, detached Gym's own spans from the server span because the instrumentor's middleware was outside it; that is the ordering fix in the second commit and the extra assertion in the test.