Repository navigation
feat(telemetry): carry trace context in the model URL for clients that send no traceparent - #4836
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. |
…t send no traceparent An agent harness running inside a sandbox, or a third-party client library in the agent's process, calls the model server without a traceparent header. The model server's SERVER span then starts a new trace, and the vLLM request spans under it never join the rollout's trace: on a tb4 run every model call was its own three-span trace next to the rollout's dispatch trace. The rollout id already travels in the URL for exactly these clients. Do the same for the trace context: base_url_for_run and resolve_model_base_url name the agent's current span as /ng-rollout/<id>/ng-trace/<traceparent>/, and a pure-ASGI layer installed outside the FastAPI instrumentor strips the segment and adds it as the inbound traceparent when the request has none. A header the client did send wins. The segment is stripped whether or not telemetry is on, so URLs built with it always route; it is only added while traces export. Gym's own clients send the header and do not use the segment. Signed-off-by: Ingo Guehring <[email protected]>
…refix itself and trim the comments Every caller of apply_rollout_prefix hands the URL to a client Gym does not instrument, so the segment no longer needs an opt-in flag; the gate stays in trace_context_path_segment (traces exporting, a span current). This also covers the agents that call apply_rollout_prefix directly (claude_code, anyswe, anyterminal, swe_agents). The middleware tests the path for the segment before running the regex, docstrings say why rather than what, and the harness docs tell URL-parsing harnesses to keep the segment. Signed-off-by: Ingo Guehring <[email protected]>
6f692d7 to
030b5d5
Compare
svcnvidia-nemo-ci
left a comment
There was a problem hiding this comment.
HOLD — two RISK findings leave gaps in URL-only trace propagation; one NOTE concerns documentation navigation.
The direct-request middleware ordering, header precedence, and tracing-disabled behavior look sound. The remaining propagation gaps affect diagnostic correlation, not demonstrated scoring correctness.
Completed the six-file review and directly affected caller/middleware checks. Validation was source-only; tests were not executed.
Note: formal approval is not available for this request, so this review is posted as a comment only.
Review generated by codex. This was a full review. Request a full review with /review reset=true.
| headers.append((b"traceparent", match.group("traceparent").encode("ascii"))) | ||
| scope = scope_with_routed_path(scope, match.group("head") + match.group("rest")) | ||
| scope["headers"] = headers | ||
| await self.app(scope, receive, send) |
There was a problem hiding this comment.
RISK — Preserve URL-carried context across same-origin redirects
Failure: With this middleware installed around a model app, send a headerless request to /ng-rollout/r/training-token-capture/ng-trace/<valid-traceparent>/v1/responses/. FastAPI redirects to the canonical path. This layer strips the trace segment and forwards send unchanged; the capture redirect helper restores only the rollout/training prefix. The client never possessed the internally injected header, so following the redirect starts a new trace. URL-only clients should retain their supplied parent after an internal redirect.
Correction: Wrap the response send in TraceContextPathMiddleware.__call__ and restore the trace segment in root-relative or same-origin 3xx Location targets. Insert it after an existing rollout/training prefix, or at the root when there is none; do not blindly prepend the complete original prefix, which would duplicate the prefix already restored by capture middleware. The exact rewrite needs integration with that helper rather than a standalone prepend.
Preserve: Keep routing and query strings unchanged, avoid duplicating an existing trace segment, retain client-header precedence, and leave cross-origin redirects and requests without a trace segment untouched. Retain capture's fail-closed behavior for unknown redirects.
Acceptance — proposed, not executed: Add an instrumented redirect-following test with no client traceparent: a trailing-slash model request must finish successfully, and both SERVER spans must have the URL's trace ID and parent span ID. Cover trace-only and rollout/training-prefixed URLs. Retain the existing redirect regression assertions: capture prefixes survive exactly once and unknown redirects still mark capture incomplete. Also assert an external Location remains byte-for-byte unchanged.
There was a problem hiding this comment.
Done in 04c26a5: the layer wraps send and restores the segment in root-relative and same-origin Location targets, after a prefix the capture middleware restored or at the root; cross-origin and already-tagged targets are left alone. Tests: placements as a unit, a followed trailing-slash redirect with both SERVER spans on the URL's parent, with and without the rollout prefix, and an unchanged external Location. The existing capture redirect assertions still pass.
| clients send the ``traceparent`` header instead and use ``url_path_for_run``. | ||
| """ | ||
| prefix = rollout_path_prefix(rollout_id, token_capture=token_capture) if rollout_id else "" | ||
| prefix += trace_context_path_segment() |
There was a problem hiding this comment.
RISK — Let the direct hand-off callers reach the trace-only branch
Failure: Enable trace export with a current span, disable evaluation/token capture and checkpointing, and run AnySwe or AnyTerminal against a Gym model server. rollout_id_from_run returns None. Although this helper now supports trace-only URLs, AnySwe and AnyTerminal both skip calling it without a rollout ID. Their headerless harness calls therefore still start separate traces. Trace propagation should not depend on capture being enabled.
Correction: Remove only those rollout-ID guards. Suggested replacements, which the author should verify:
In AnySwe's _model_url_for_rollout:
return apply_rollout_prefix(model_url, rollout_id) if model_url else model_urlIn AnyTerminal's _setup_params, replace the condition, retaining its existing body and token_capture argument:
if not self.config.sandbox_model_base_url and server_config["model_server_url"]:Preserve: Keep explicit sandbox_model_base_url overrides untouched, leave empty URLs empty, and retain existing rollout/training-prefix placement. When tracing is off and the rollout ID is absent, the URL must remain byte-for-byte unchanged; the helper already guarantees this.
Acceptance — proposed, not executed: Exercise both actual caller paths under the existing trace-export fixture with capture disabled and confirm the resulting model URL contains /ng-trace/<current-span-context> but no rollout prefix. With capture enabled, retain rollout-first ordering and AnyTerminal's training segment. Retain the existing AnySwe no-tracing assertions, and add checks that explicit sandbox overrides are never decorated.
There was a problem hiding this comment.
Done in 04c26a5, as suggested. Tests for both agents: segment present with capture off, rollout-first ordering with capture on, explicit sandbox_model_base_url never decorated, URL unchanged without traces. Marc's point about cached clients is handled in 2430858 so the two do not pull against each other: per-run URLs always get the segment, a URL a cached client keeps using opts out with trace_context=False.
| The built-in external agents, such as Claude Code, add this prefix when `token_id_capture` is enabled for them and they call a Gym model server. A custom harness must add it to every model call. Without the `training-token-capture` segment, the call is not recorded for training, and Gym masks the rollout because it finds no captured calls. | ||
|
|
||
| Agents based on `SimpleResponsesAPIAgent` can build the prefixed URL with `base_url_for_run(base_url, body)` or `url_path_for_run(url_path, body)`. Both helpers read the rollout id from the run request and add the training segment when the agent has opted into capture. [Model-Call Capture](/main/model-server/model-call-capture#if-you-build-a-custom-agent) describes the same URL prefix for evaluation capture, along with the other routing helpers. | ||
| Agents based on `SimpleResponsesAPIAgent` can build the prefixed URL with `base_url_for_run(base_url, body)` or `url_path_for_run(url_path, body)`. While the agent exports traces, `base_url_for_run` also appends `/ng-trace/<traceparent>` after the prefix so the model server can parent the harness's calls to the run's span; the model server strips it, and a harness that inspects the URL should keep it (see [Distributed Tracing](../observability/distributed-tracing)). Both helpers read the rollout id from the run request and add the training segment when the agent has opted into capture. [Model-Call Capture](/main/model-server/model-call-capture#if-you-build-a-custom-agent) describes the same URL prefix for evaluation capture, along with the other routing helpers. |
There was a problem hiding this comment.
NOTE — Use the published tracing-page URL
Failure: The new ../observability/distributed-tracing link is relative to a tutorial published beneath /main/tutorials/training-tutorials/. Browser resolution keeps it beneath the tutorials hierarchy, whereas observability is a top-level navigation folder. Readers therefore do not reach the tracing page. This also departs from the trusted version-prefixed link convention.
Correction: Replace just that link with:
[Distributed Tracing](/main/observability/distributed-tracing#trace-context-in-the-model-url)Preserve: Keep the helper/capture explanation and existing Model-Call Capture link unchanged.
Acceptance — static check: Verify the link uses the canonical /main/observability/ target and that its fragment names the new section. A published-site or preview click should open that section, not a /tutorials/observability/ URL. No preview was run.
…nd on capture-less hand-off URLs Review follow-ups on #4836. A client that only ever had the URL loses its parent when it follows a same-origin redirect, so the trace-path layer now puts the segment back into root-relative and same-origin Location targets, after a rollout or token-capture prefix the capture middleware has already restored, or at the root. anyswe and anyterminal no longer skip the prefix helper when there is no rollout id, so their harnesses carry the current span with capture off too; explicit sandbox URL overrides stay untouched. The harness tutorial links the tracing page by its published path. Signed-off-by: Ingo Guehring <[email protected]>
Signed-off-by: Ingo Guehring <[email protected]>
|
Nice fix, and the before/after span trees make it easy to follow. Putting the trace context next to the rollout id, stripping it outside the instrumentor and letting a real traceparent header win all look right to me. It merges cleanly into main, and the new tests plus test_rollout_correlation.py and test_base_responses_api_model.py pass locally. I agree with the bot's redirect and AnySwe/AnyTerminal findings. One more issue pulls against the second of them, so I'd fix the two together. A URL that is cached across rollouts keeps one span forever. apply_rollout_prefix appends the ng-trace segment whenever a span is current, also without a rollout id (asserted in the tests). That is right for a URL built per run, but not for one built once and reused. The verifiers agent does exactly this:
With traces on and capture off, every later rollout's model calls would be parented under the first rollout's span. Gating the segment on a rollout id would fix this but would undo the bot's AnySwe/AnyTerminal point, where trace propagation should work with capture off. The underlying distinction is per-run vs shared. Suggestion:
Minor
|
… rollout Review follow-up on #4836 (Marc). The segment names the span current when the URL is built, which is right for a URL built per run and wrong for one a cached client keeps using: every later rollout's calls would be parented to the first rollout's span. apply_rollout_prefix and resolve_model_base_url take trace_context (default on) and the verifiers agent's shared policy client passes False; its per-run copies keep the segment. Tests cover the helper, a reused URL whose requests each start their own trace, and the verifiers agent's cached versus per-run clients. The tracing page states the build-time semantics and the opt-out; the harness tutorial names the built-in agents that rewrite the model URL. Signed-off-by: Ingo Guehring <[email protected]>
|
Thanks, fixed in 2430858. |
|
/review |
svcnvidia-nemo-ci
left a comment
There was a problem hiding this comment.
SHIP — the prior two RISK findings and one NOTE are fixed; no escalation-eligible regressions found.
Verified against the current source:
- Redirect handling restores URL-carried context after an existing capture prefix while leaving external redirect targets untouched.
- AnySwe and AnyTerminal now reach trace-only URL generation with capture disabled; explicit sandbox URL overrides remain protected.
- The harness tutorial uses the canonical tracing-page link.
- The cached verifiers client opts out of build-time trace context, while per-run copies retain it.
Accounted for all 12 changed files and completed the directly affected caller/middleware checks. Discovery remained limited to prior findings and changes since the previously reviewed head, with new findings filtered above the historical moderate-impact ceiling. Validation was source-only: regression assertions were inspected, but tests were not executed.
Note: formal approval is not available for this request, so this review is posted as a comment only.
Review generated by codex. This was a findings-only review. Request a full review with /review reset=true.
marcromeyn
left a comment
There was a problem hiding this comment.
Thanks for the quick fix. The trace_context=False split for the cached client is exactly right, and the redirect and AnySwe/AnyTerminal fixes cover the bot's findings. LGTM.
|
🔄 Merge queue validation started! You can track the progress here: https://github.com/NVIDIA-NeMo/Gym/actions/runs/39955055386 |
|
🔄 Merge queue validation started! You can track the progress here: https://github.com/NVIDIA-NeMo/Gym/actions/runs/39958196007 |
…l URLs Follow-up to #4836. harness_agent, harness_exa_search and cvdp_agent built the model URL they give to a process outside Gym without the shared helpers, so their harnesses' model calls still arrived with no parent. harness_agent appends the current span's segment after the prefix it keeps in its run context; harness_exa_search builds the relay's upstream URL per run through a small method that adds it; cvdp_agent goes through base_url_for_run, which also gives it the rollout prefix it never had. A repo-wide test asserts that every agent exposing sandbox_model_base_url builds its URL with the helpers, so the list cannot grow silently again. Signed-off-by: Ingo Guehring <[email protected]>
…l URLs Follow-up to #4836. harness_agent, harness_exa_search and cvdp_agent built the model URL they give to a process outside Gym without the shared helpers, so their harnesses' model calls still arrived with no parent. harness_agent appends the current span's segment after the prefix it keeps in its run context; harness_exa_search builds the relay's upstream URL per run through a small method that adds it; cvdp_agent goes through base_url_for_run, which also gives it the rollout prefix it never had. A repo-wide test asserts that every agent exposing sandbox_model_base_url builds its URL with the helpers, so the list cannot grow silently again. Signed-off-by: Ingo Guehring <[email protected]>
…l URLs (NVIDIA-NeMo#4927) Follow-up to NVIDIA-NeMo#4836. harness_agent, harness_exa_search and cvdp_agent built the model URL they give to a process outside Gym without the shared helpers, so their harnesses' model calls still arrived with no parent. harness_agent appends the current span's segment after the prefix it keeps in its run context; harness_exa_search builds the relay's upstream URL per run through a small method that adds it; cvdp_agent goes through base_url_for_run, which also gives it the rollout prefix it never had. A repo-wide test asserts that every agent exposing sandbox_model_base_url builds its URL with the helpers, so the list cannot grow silently again. Signed-off-by: Ingo Guehring <[email protected]>
What changed and why
Some agents hand the model URL to a client they do not instrument: a harness running inside a sandbox (tb4 miniswe, terminus, opencode, hermes, codex, pi, …) or a third-party client library in the agent's own process (litellm in tau2). That client sends no
traceparentheader, so the model server's SERVER span starts a new trace and the vLLM request spans under it never join the rollout's trace. On a tb4 run with vLLM traces on, every one of the 339 model calls was its own three-span trace (POST /ng-rollout/<id>/v1/responses→HTTP POST→llm_request) next to the rollout's own trace. The rollout id still reached them through the URL prefix; the parent did not.The rollout id already travels in the URL for exactly these clients, so the trace context now does the same:
apply_rollout_prefixappends/ng-trace/<traceparent>naming the current span, right after the rollout prefix, while this process exports traces and a span is current. Every caller of that helper hands the URL to a client Gym does not instrument (base_url_for_run,resolve_model_base_url, and the direct calls in claude_code, anyswe, anyterminal and swe_agents), so it is on by default. The span named is the one current when the URL is built, so a URL that outlives one rollout opts out withtrace_context=False; the verifiers agent's cached policy client does, its per-run copies do not.url_path_for_run, used with Gym's own instrumented client, never adds it.TraceContextPathMiddleware, a pure-ASGI layer installed outside the FastAPI instrumentor (same mechanism asinstall_request_context_isolation, fix(telemetry): start every server request from a clean context #4755), strips the segment before routing and adds it as the inboundtraceparentwhen the request carries none. A header the client did send wins.Locationtargets, after a rollout or token-capture prefix the capture middleware has already restored, or at the root. Cross-origin targets are untouched.Result: a sandboxed agent's model calls become children of the agent's
/runspan, under the rollout's trace, with the engine spans beneath them. Gym's own clients, which send the header, are unaffected.No issue; follow-up to #4749/#4750/#4751/#4752 found on the first sandboxed run with engine spans.
Compatibility
/ng-rollout/<id>/v1to/ng-rollout/<id>/ng-trace/<traceparent>/v1while traces export. The rollout prefix stays first; consumers that parse it (_CaptureMiddleware, checkpointing, token capture) see the stripped path because the strip runs outermost.Validation
tests/unit_tests/telemetry/test_trace_context_path.py(new, 22 tests): redirect targets (segment after a restored prefix or at the root, cross-origin and already-tagged left alone, a followed trailing-slash redirect keeps both server spans on the URL's parent), producer gating and placement, the agent helpersbase_url_for_run/resolve_model_base_urlat the call site, path rewrite with and without the rollout and token-capture prefixes, header precedence, untouched paths, and with Gym's real stack order (instrumentor → trace-path → isolation) the SERVER span's trace id and parent span id equal the ones in the URL,http.targetis the stripped path, handler spans nest under the server span.test_trace_context_path.py: a reused URL without the segment gives each request its own root trace.sandbox_model_base_urlis never decorated, and without traces the URL is unchanged.pre-commit runon the changed files: clean.tests/unit_tests/telemetry,test_rollout_correlation.py,test_base_responses_api_model.py,test_server_utils.py,test_base_responses_api_agent.py,test_fern_docs_links.py: 713 passed; the 4 failures (test_call_sites::test_supervisor_is_the_only_writer_of_the_active_servers_gauge,test_connection_pool::test_multi_destination_waits…,test_memory×2) fail identically on cleanorigin/mainin this macOS environment.Local before/after, two harness agents, no GPU
Figure: the same rollout on main and with this PR
Span trees from the local runs below (pi harness; opencode is identical). Internal ASGI
http send/http receivespans omitted. Boxes are spans, arrows are parent to child, the dotted arrow is a span link.main
92407083b: three traces per rollout. The harness sends notraceparent, so each model call becomes the root of its own trace. Only the rollout id in the URL ties them together.flowchart TB classDef driver fill:#dbeafe,stroke:#2563eb,color:#111 classDef agent fill:#dcfce7,stroke:#16a34a,color:#111 classDef model fill:#ede9fe,stroke:#7c3aed,color:#111 classDef ext fill:#fef3c7,stroke:#d97706,color:#111 classDef orphan fill:#fee2e2,stroke:#dc2626,color:#111 subgraph T0["trace: job"] job["gym.job"]:::driver end subgraph T1["trace: rollout 0-0"] dispatch["gym.rollout.dispatch<br/>nemo.gym.rollout.id=0-0"]:::driver env["POST /run (environment server)"]:::driver run["POST /run (agent server)"]:::agent rollout["gym.rollout"]:::agent resp["POST /ng-rollout/0-0/v1/responses (agent server)"]:::agent agentspan["gym.agent.responses"]:::agent seed["HTTP POST …/seed_session"]:::agent verify["HTTP POST …/verify"]:::agent dispatch --> env --> run --> rollout rollout --> seed rollout --> resp --> agentspan rollout --> verify end cli["pi CLI (subprocess, no traceparent)"]:::ext agentspan -. "spawns" .-> cli subgraph T2["trace: model call 1 (orphan)"] m1["POST /ng-rollout/0-0/v1/chat/completions (model server)"]:::orphan c1["gym.model.chat_completions"]:::model b1["HTTP POST backend /v1/chat/completions<br/>nemo.gym.rollout.id=0-0"]:::model m1 --> c1 --> b1 end subgraph T3["trace: model call 2 (orphan)"] m2["POST /ng-rollout/0-0/v1/chat/completions (model server)"]:::orphan c2["gym.model.chat_completions"]:::model b2["HTTP POST backend /v1/chat/completions<br/>nemo.gym.rollout.id=0-0"]:::model m2 --> c2 --> b2 end cli -- "URL carries the rollout id only" --> m1 cli -- "URL carries the rollout id only" --> m2 dispatch -. "link" .-> jobthis PR
030b5d500: one trace per rollout. The agent's hand-off URL also carries/ng-trace/<traceparent>; the model server strips it and uses it as the parent, so both model calls and the backend calls beneath them nest undergym.agent.responses.flowchart TB classDef driver fill:#dbeafe,stroke:#2563eb,color:#111 classDef agent fill:#dcfce7,stroke:#16a34a,color:#111 classDef model fill:#ede9fe,stroke:#7c3aed,color:#111 classDef ext fill:#fef3c7,stroke:#d97706,color:#111 subgraph T0["trace: job"] job["gym.job"]:::driver end subgraph T1["trace: rollout 0-0"] dispatch["gym.rollout.dispatch<br/>nemo.gym.rollout.id=0-0"]:::driver env["POST /run (environment server)"]:::driver run["POST /run (agent server)"]:::agent rollout["gym.rollout"]:::agent resp["POST /ng-rollout/0-0/v1/responses (agent server)"]:::agent agentspan["gym.agent.responses"]:::agent seed["HTTP POST …/seed_session"]:::agent verify["HTTP POST …/verify"]:::agent m1["POST /ng-rollout/0-0/v1/chat/completions (model server)<br/>http.target without the ng-trace segment"]:::model c1["gym.model.chat_completions"]:::model b1["HTTP POST backend /v1/chat/completions<br/>nemo.gym.rollout.id=0-0"]:::model m2["POST /ng-rollout/0-0/v1/chat/completions (model server)"]:::model c2["gym.model.chat_completions"]:::model b2["HTTP POST backend /v1/chat/completions<br/>nemo.gym.rollout.id=0-0"]:::model dispatch --> env --> run --> rollout rollout --> seed rollout --> resp --> agentspan rollout --> verify agentspan --> m1 --> c1 --> b1 agentspan --> m2 --> c2 --> b2 end cli["pi CLI (subprocess, no traceparent)"]:::ext agentspan -. "spawns; URL = …/ng-rollout/0-0/ng-trace/<traceparent of gym.agent.responses>/v1" .-> cli cli -- "no header; parent comes from the URL" --> m1 cli -- "no header; parent comes from the URL" --> m2 dispatch -. "link" .-> jobOne rollout each of the
piandopencodeharness agents (external CLI processes, notraceparentof their own) against the realvllm_modelserver backed by a scripted OpenAI-compatible stub (one shell tool call, then a final answer), servers wired asrun_webserverdoes, spans to an in-memory exporter. Same scripted task on both revisions; agent behaviour identical (2 model calls, 1 turn, finished naturally).92407083b030b5d500gym.agent.responses92407083b030b5d500gym.agent.responseshttp.targeton the server span is/ng-rollout/0-0/v1/chat/completionson both revisions, so the segment never reaches routing or attributes.Rollout evidence
tb4 miniswe (sandboxed), 4 rollouts, Nano 3.5 on vLLM with
--otlp-traces-endpoint, job-side Gym = this branch merged with #4751 (a4f3e8aa9), HSG job 8118123, COMPLETED in 12 min, 4/4 rollouts scored. From the job's local OTLP dump:POST …/v1/responsesspans without a parentgym.rollout(the agent's span)llm_request(vLLM) spans inside a rollout's tracehttp.targeton the server span/ng-rollout/<id>/v1/responsesgym.rollout.dispatchroots, linked togym.job)Agent and verifier behavior unchanged: same benchmark, same config apart from the Gym ref.
Follow-ups (not in this PR)
The three agents that build the hand-off model URL without the helpers (harness_agent, harness_exa_search, cvdp_agent) are covered in #4927, stacked on this branch, together with a guard test that fails when a new agent hands a model URL to a sandbox by hand.