Skip to content

fix(telemetry): start every server request from a clean context - #4755

Merged
iguehring-nvidia merged 4 commits into
mainfrom
iguehring/request-context-isolation
Oct 20, 2026
Merged

iguehring-nvidia merged 4 commits into
mainfrom
iguehring/request-context-isolation

Conversation

@iguehring-nvidia

@iguehring-nvidia iguehring-nvidia commented Oct 19, 2026 •

Copy link
Copy Markdown
Contributor

What does this PR do?

Adds RequestContextIsolationMiddleware, installed by install_request_context_isolation(app) in run_webserver as 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 the BaseHTTPMiddleware layers run the rollout middleware, /run and 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 wrapping build_middleware_stack after instrumentation, the same way the FastAPI instrumentor installs itself, because a middleware added with add_middleware always 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:

  1. Gym servers answer through two Starlette BaseHTTPMiddleware layers (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.
  2. A client already holding the full Content-Length body releases the connection in that window; the next request arrives while the previous cycle is still open. In the traces the agent sent request N+1 between 0.4 and 17 ms before the server span for N ended, in every affected case.
  3. uvicorn (0.37, httptools_impl.py) queues that request as pipelined and, in on_response_complete, starts its task with loop.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.
  4. opentelemetry-instrumentation-asgi (_start_internal_or_server_span) extracts traceparent only 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 BaseHTTPMiddleware layers 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 extracting traceparent even 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

  • Install-order tests in tests/unit_tests/telemetry/test_request_context_isolation.py: after instrumenting, install_request_context_isolation leaves isolation outermost with the instrumentor's middleware inside it (the order run_webserver uses); 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.
  • Behavioural test in the same file: a real uvicorn app with a middleware that sends the terminating body 20 ms late, instrumented the way Gym instruments its servers, hit on one keep-alive connection by 8 coroutines with 12 sequential requests each, every request with its own traceparent. With the middleware: 96 of 96 server spans are SERVER spans parented to their own traceparent, 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_sites active-servers gauge), identical on main.
  • pre-commit run --files <changed files>: passed.

Rollout evidence

Same 16-rollout scicode workload on a Slurm cluster, before and after.

before (2026-10-17, plain main) after (2026-10-19, main + this PR and the three telemetry PRs it was found with)
policy server spans parented to the previous request on their connection 31 of 72 0 of 72
spans with a rollout attribute under a different rollout's tree 20 of 248 0 of 248
rollout 1-0: engine calls in its own trace / actually its own 5 / 12 12 / 12
rollout 2-0: engine calls in its own trace / actually its own 16 (5 foreign) / 14 14 / 14

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.

Engine calls under each rollout's trace, before and after the fix

In the after run every POST server span is SERVER kind and a child of the agent's client span, every gym.model.responses span is a child of its server span, and every engine llm_request span sits under the right rollout. The first revision of this PR (middleware added with add_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.

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]>
@nemo-automation-bot
nemo-automation-bot Bot requested review from a team October 19, 2026 20:10
@iguehring-nvidia iguehring-nvidia added bug Something isn't working area:core Shared APIs, servers, telemetry, health, and registries labels Oct 19, 2026
@iguehring-nvidia iguehring-nvidia self-assigned this Oct 19, 2026
@iguehring-nvidia iguehring-nvidia added the needs-review PR is ready for code review and waiting on a reviewer label Oct 19, 2026
@github-actions

github-actions Bot commented Oct 19, 2026 •

Copy link
Copy Markdown
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]>
@iguehring-nvidia

Copy link
Copy Markdown
Contributor Author

/review

@yaoyu-33 yaoyu-33 added the complexity:medium Single-domain change with interacting parts or a moderate review surface label Oct 19, 2026
@marcromeyn

Copy link
Copy Markdown
Contributor

LGTM. The fix is right, and outside the instrumentor is the only place it works. Two requests:

  1. Description and test docstring overstate the leak. They say _ROLLOUT_ID and handler contextvars leak. In Gym's current stacks, the BaseHTTPMiddleware layers run RolloutContextMiddleware, /run and the handlers in a child task, so only the inst
    rumentor's OTel context leaks. I forced the PR's 20 ms window and counted unprefixed requests that saw a rollout id: 0/100 with RolloutContextMiddleware inside those layers, 100/100 when it sits outside them. The rollout reset is still worth keeping as a
    guard for when those layers are replaced, so please describe it that way.
  2. Add a test that the real install order keeps RequestContextIsolationMiddleware outermost, wrapping the OTel middleware. run_webserver is uncovered, and revision 1 got this order wrong.

Nits:

  • Make setup_request_context_isolation a module-level function or a staticmethod; the test passes None as self.
  • Move the try import below the import block.

Verified locally:

  • The new test passes 6/6.
  • tests/unit_tests/telemetry, test_rollout_correlation.py and test_server_utils.py: 570 passed on Linux.
  • The PR merges cleanly into dc709bc.

…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]>
@iguehring-nvidia

Copy link
Copy Markdown
Contributor Author

LGTM. The fix is right, and outside the instrumentor is the only place it works. Two requests:

  1. Description and test docstring overstate the leak. They say _ROLLOUT_ID and handler contextvars leak. In Gym's current stacks, the BaseHTTPMiddleware layers run RolloutContextMiddleware, /run and the handlers in a child task, so only the inst
    rumentor's OTel context leaks. I forced the PR's 20 ms window and counted unprefixed requests that saw a rollout id: 0/100 with RolloutContextMiddleware inside those layers, 100/100 when it sits outside them. The rollout reset is still worth keeping as a
    guard for when those layers are replaced, so please describe it that way.
  2. Add a test that the real install order keeps RequestContextIsolationMiddleware outermost, wrapping the OTel middleware. run_webserver is uncovered, and revision 1 got this order wrong.

Nits:

  • Make setup_request_context_isolation a module-level function or a staticmethod; the test passes None as self.
  • Move the try import below the import block.

Verified locally:

  • The new test passes 6/6.
  • tests/unit_tests/telemetry, test_rollout_correlation.py and test_server_utils.py: 570 passed on Linux.
  • The PR merges cleanly into dc709bc.

Thanks for the great review @marcromeyn ! All addressed.

@iguehring-nvidia
iguehring-nvidia requested review from marcromeyn and removed request for ananthsub October 20, 2026 15:04
@oyilmaz-nvidia

Copy link
Copy Markdown
Contributor

/review

@oyilmaz-nvidia

Copy link
Copy Markdown
Contributor

/ok to test fda9fd2

@github-actions

Copy link
Copy Markdown
Contributor

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

Merged via the queue into main with commit ffe626a Oct 20, 2026
50 of 55 checks passed
@iguehring-nvidia
iguehring-nvidia deleted the iguehring/request-context-isolation branch October 20, 2026 19:37
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 branch was previously deployed

1 inactive deployment
public — fda9fd22 Deployed Oct 20, 2026 by copy-pr-bot[bot] via release / finalize / notify #6054
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 bug Something isn't working complexity:medium Single-domain change with interacting parts or a moderate review surface needs-review PR is ready for code review and waiting on a reviewer

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants