Skip to content

feat(telemetry): instrument the rollout path across Gym's server processes - #2647

Merged
oyilmaz-nvidia merged 10 commits into
mainfrom
ahmadki/lens-gym-callsites
Aug 28, 2026
Merged

oyilmaz-nvidia merged 10 commits into
mainfrom
ahmadki/lens-gym-callsites

Conversation

@ahmadki

@ahmadki ahmadki commented Aug 21, 2026

Copy link
Copy Markdown
Member

What does this PR do?

Stacked on #. Please review and merge that one first — this PR targets
ahmadki/lens-gym-base, so its diff is only the call sites.

Attaches the instrumentation call sites to the base layer, so a rollout produces a single
distributed trace spanning Gym's independent server processes. Everything here is a no-op
unless the telemetry extra is installed and telemetry is enabled, so the default path is
unchanged.

Cross-process propagation is the substance; the spans hang off it

A rollout crosses several Gym processes — the agent server calls the model server, both
call the resources server — and nothing in a plain HTTP request tells the receiving server
which rollout it belongs to. W3C Trace Context fixes that in two halves:

  • Egress. server_utils.request() is Gym's only outbound HTTP path — AGENTS.md bans
    httpx for async precisely to keep it that way — so it is the one place traceparent is
    injected. The retry loop moves into _request_with_retries so the gated wrapper can
    place one CLIENT span around the whole logical request rather than one per attempt.
  • Ingress. SimpleServer.run_webserver initialises telemetry once per process and
    applies OTel FastAPI auto-instrumentation, which extracts the inbound header and parents
    that server's SERVER span to the caller's. It also flushes on the way out, since a batch
    processor otherwise drops whatever is pending at exit.

The result is a continuous parent chain across process boundaries, with the CLIENT/SERVER
pairing a backend needs to draw the edge between two services.

Spans at the seams

Handlers are wrapped where routes are registered, which instruments every Gym server
without touching any of them individually: gym.rollout on the agent's /run,
gym.agent.responses, gym.model.*, gym.verify, gym.sandbox.*, and gym.job around
rollout collection.

Gym's existing current_rollout_id() is bridged, not replaced — it lands on spans as
nemo.gym.rollout.id, so a trace, Gym's own logs and a captured trajectory still line up.
The span starts inside rollout_context so the id is set by the time it is read.

Every site checks its span group before doing any work, including building attributes, so
a user who leaves telemetry off pays for one frozenset membership test per site.

Getting telemetry into the server processes

Server venvs install nemo-gym[dev], not nemo-gym[telemetry], so head_server_deps now
carries the telemetry packages when telemetry is enabled. The requirement is derived from
the nemo-lens distribution installed in the orchestrator rather than restated: the base
PR's [tool.uv.sources] entry governs only dependencies resolved through the local
project, so a bare nemo-lens[sdk] named on the uv command line would resolve from PyPI
and silently skew the servers against the orchestrator.

The container image gains the telemetry extra — a small set of pure-Python packages,
without which tracing cannot be switched on with an environment variable.

Deliberate omissions, in case they look like gaps

  • gym.server.request_duration_ms is unused. nemo-lens records it without attributes,
    so it would merge every endpoint of every server type into one histogram. The FastAPI
    instrumentor's http.server.request.duration, dimensioned by route/method/status, is
    used instead.
  • gym.servers.active is written only by the CLI orchestrator. It is a gauge, so a
    value written by every process would report whichever wrote last.
  • Sandbox commands and URL query strings are never recorded, since they carry model
    output, task content and credentials. Provider, exit code and duration are.
  • Reward and accuracy are not mirrored into OpenTelemetry. They are experiment
    telemetry and stay in AggregateMetricsMixin.

Docs

Adds an observability section under fern/versions/latest/pages/ covering
configuration, distributed tracing, span groups, metrics, and how to instrument your own
server. Frozen fern/versions/v0.* snapshots are untouched.

Checklist

  • I have read the contributing guidelines.
  • The change is focused; unrelated "drive-by" edits are tracked as separate issues/PRs.
  • Tests added or updated and pass locally, or N/A for docs-only / non-code changes (so CI unit/server checks pass when applicable).
  • Pre-commit checks pass locally (pre-commit run --all-files) (so CI lint/format/copyright pass).
  • All commits have DCO sign-off (git commit -s) (so the DCO check passes).

…lens

Adds `nemo_gym/telemetry/`, the base layer for optional OpenTelemetry instrumentation
built on nemo-lens. No call sites yet; those follow in a second PR so this one is
reviewable on its own.

Telemetry activates only when the `telemetry` extra is installed and it is switched on
via a `telemetry:` config block or `NEMO_GYM_OTEL_*` / `NEMO_LENS_*` environment
variables. With either missing, every instrumentation site is a no-op and Gym behaves
as it does today.

The module:

* `config.py` — `TelemetryConfig`, the `telemetry:` block. Imports pydantic only.
* `setup.py` — lifecycle. `configure_telemetry_env` translates the config block into
  `NEMO_GYM_OTEL_*` variables in the orchestrator before any server is spawned;
  `init_telemetry` reads that environment back in each server process. Gym runs N
  independent FastAPI processes that share no memory, so the environment is the only
  channel between them. `export_strategy` defaults to `all_ranks` rather than
  `single_rank` because each Gym server is rank 0 of its own world of one.
* `span_groups.py` — `GymSpanGroup` and the `default` / `per_rollout` / `all` presets.
  Groups live downstream in the consumer, as they do in NeMo-RL.
* `metrics.py` — a wrapper over nemo-lens's `gym.*` instruments that takes an explicit
  position on each, including which are unsuitable and why.
* `spans.py` — a CLIENT-kind span. `managed_span` cannot set `SpanKind`, and an INTERNAL
  span on a cross-service hop loses the client/server distinction a backend needs.
* `_fallbacks.py` — the single import point for the instrumentation primitives. It
  resolves to the real `nemo.lens` implementations when the extra is installed and to
  no-op shims when it is not, so a call site needs one import rather than its own
  `try/except ImportError`.

`telemetry` is registered as a reserved top-level config key so the config parser does
not read the block as a server instance definition.

The extra pins nemo-lens to the same commit Megatron-LM uses, via `[tool.uv.sources]`.
That table governs dependencies resolved through the local project, which includes the
per-server venvs that `gym env test` and `gym env start` build.

Signed-off-by: Ahmad Kiswani <[email protected]>
…esses

Attaches the instrumentation call sites, so a rollout produces a single distributed
trace spanning Gym's independent server processes. Builds on the base layer added in
the previous PR. Everything here is a no-op unless telemetry is installed and enabled.

Cross-process context propagation is the substance; the spans are supporting work.
Two halves:

* `server_utils.request()` is Gym's only outbound HTTP path — `AGENTS.md` bans httpx to
  keep it that way — so it is the one place W3C `traceparent` is injected. The retry
  loop moves into `_request_with_retries` so the gated wrapper can place one CLIENT span
  around the whole logical request rather than one per attempt.
* `SimpleServer.run_webserver` initialises telemetry once per process and applies OTel
  FastAPI auto-instrumentation, which extracts the inbound header and parents that
  server's SERVER span to the caller. It also flushes on the way out, since a batch
  processor otherwise drops whatever is pending at exit.

Semantic spans are added by wrapping handlers where routes are registered, which
instruments every Gym server without touching any of them individually: `gym.rollout`
on the agent's `/run`, `gym.agent.responses`, `gym.model.*`, `gym.verify`,
`gym.sandbox.*`, and `gym.job` around rollout collection. Gym's existing
`current_rollout_id()` is bridged onto spans as `nemo.gym.rollout.id` rather than
replaced; the span starts inside `rollout_context` so the id is set by the time it is
read.

Every site checks its span group before doing any work, including building attributes.

`nemo_gym.telemetry` is the only package that imports `nemo.lens`. Call sites reach the
instrumentation primitives through `telemetry._fallbacks` and the propagation and
framework helpers through `telemetry.contrib`, so no module outside that package has to
be audited for whether its imports are reachable with the extra absent. A test enforces
the boundary in both directions.

Server venvs install `nemo-gym[dev]`, not `nemo-gym[telemetry]`, so `head_server_deps`
now carries the telemetry packages when telemetry is enabled. The requirement is derived
from the nemo-lens distribution installed in the orchestrator, because `[tool.uv.sources]`
governs only dependencies resolved through the local project — a bare `nemo-lens[sdk]`
named on the uv command line would resolve from PyPI and skew the servers against the
orchestrator.

The orchestrator is the only writer of the `gym.servers.active` gauge; a gauge written
by every process reports whichever wrote last.

Sandbox commands and URL query strings are deliberately not recorded as span attributes,
since they carry model output, task content and credentials.

Adds an `observability` documentation section and the telemetry extra to the container
image, so tracing can be switched on with an environment variable.

Signed-off-by: Ahmad Kiswani <[email protected]>
@ahmadki
ahmadki requested a review from a team as a code owner August 21, 2026 13:26
@copy-pr-bot

copy-pr-bot Bot commented Aug 21, 2026

Copy link
Copy Markdown

This pull request requires additional validation before any workflows can run on NVIDIA's runners.

Pull request vetters can view their responsibilities here.

Contributors can view more details about this message here.

@github-actions github-actions Bot added the sla:review-overdue Review response is over the one-business-day SLA label Aug 24, 2026
Base automatically changed from ahmadki/lens-gym-base to main August 26, 2026 20:52
…sites

Signed-off-by: Onur Yilmaz <[email protected]>

# Conflicts:
#	nemo_gym/global_config.py
#	nemo_gym/telemetry/setup.py
#	pyproject.toml
#	tests/unit_tests/telemetry/test_setup.py
…elpers

The merge left request()'s _max_connection_retries param unused: it was
never passed to _traced_request/_request_with_retries, which is where
the retry loop actually reads it, so ruff flagged it as an undefined name.

Signed-off-by: Onur Yilmaz <[email protected]>
@oyilmaz-nvidia

Copy link
Copy Markdown
Contributor

/ok to test 9344e18

oyilmaz-nvidia
oyilmaz-nvidia previously approved these changes Aug 27, 2026

@oyilmaz-nvidia oyilmaz-nvidia 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. Tested with honeycomb and it's working.

@oyilmaz-nvidia

Copy link
Copy Markdown
Contributor

/ok to review 4836c92

@oyilmaz-nvidia
oyilmaz-nvidia enabled auto-merge (squash) August 27, 2026 23:42
@oyilmaz-nvidia

Copy link
Copy Markdown
Contributor

/ok to review b9aa9ff

@oyilmaz-nvidia

Copy link
Copy Markdown
Contributor

/ok to test c793f87

@oyilmaz-nvidia

Copy link
Copy Markdown
Contributor

/ok to test be0cafc

@oyilmaz-nvidia

Copy link
Copy Markdown
Contributor

/ok to test cb35125

@oyilmaz-nvidia
oyilmaz-nvidia merged commit c5cab82 into main Aug 28, 2026
40 checks passed
@oyilmaz-nvidia
oyilmaz-nvidia deleted the ahmadki/lens-gym-callsites branch August 28, 2026 17:48
ananthsub pushed a commit that referenced this pull request Aug 28, 2026
…esses (#2647)

## What does this PR do?

Stacked on #<base PR>. **Please review and merge that one first** — this
PR targets
`ahmadki/lens-gym-base`, so its diff is only the call sites.

Attaches the instrumentation call sites to the base layer, so a rollout
produces a single
distributed trace spanning Gym's independent server processes.
Everything here is a no-op
unless the `telemetry` extra is installed and telemetry is enabled, so
the default path is
unchanged.

### Cross-process propagation is the substance; the spans hang off it

A rollout crosses several Gym processes — the agent server calls the
model server, both
call the resources server — and nothing in a plain HTTP request tells
the receiving server
which rollout it belongs to. W3C Trace Context fixes that in two halves:

- **Egress.** `server_utils.request()` is Gym's only outbound HTTP path
— `AGENTS.md` bans
httpx for async precisely to keep it that way — so it is the one place
`traceparent` is
injected. The retry loop moves into `_request_with_retries` so the gated
wrapper can
place one CLIENT span around the whole logical request rather than one
per attempt.
- **Ingress.** `SimpleServer.run_webserver` initialises telemetry once
per process and
applies OTel FastAPI auto-instrumentation, which extracts the inbound
header and parents
that server's SERVER span to the caller's. It also flushes on the way
out, since a batch
  processor otherwise drops whatever is pending at exit.

The result is a continuous parent chain across process boundaries, with
the CLIENT/SERVER
pairing a backend needs to draw the edge between two services.

### Spans at the seams

Handlers are wrapped where routes are registered, which instruments
every Gym server
without touching any of them individually: `gym.rollout` on the agent's
`/run`,
`gym.agent.responses`, `gym.model.*`, `gym.verify`, `gym.sandbox.*`, and
`gym.job` around
rollout collection.

Gym's existing `current_rollout_id()` is **bridged**, not replaced — it
lands on spans as
`nemo.gym.rollout.id`, so a trace, Gym's own logs and a captured
trajectory still line up.
The span starts inside `rollout_context` so the id is set by the time it
is read.

Every site checks its span group before doing any work, including
building attributes, so
a user who leaves telemetry off pays for one frozenset membership test
per site.

### Getting telemetry into the server processes

Server venvs install `nemo-gym[dev]`, not `nemo-gym[telemetry]`, so
`head_server_deps` now
carries the telemetry packages when telemetry is enabled. The
requirement is derived from
the nemo-lens distribution installed in the orchestrator rather than
restated: the base
PR's `[tool.uv.sources]` entry governs only dependencies resolved
*through* the local
project, so a bare `nemo-lens[sdk]` named on the uv command line would
resolve from PyPI
and silently skew the servers against the orchestrator.

The container image gains the telemetry extra — a small set of
pure-Python packages,
without which tracing cannot be switched on with an environment
variable.

### Deliberate omissions, in case they look like gaps

- **`gym.server.request_duration_ms` is unused.** nemo-lens records it
without attributes,
so it would merge every endpoint of every server type into one
histogram. The FastAPI
instrumentor's `http.server.request.duration`, dimensioned by
route/method/status, is
  used instead.
- **`gym.servers.active` is written only by the CLI orchestrator.** It
is a gauge, so a
  value written by every process would report whichever wrote last.
- **Sandbox commands and URL query strings are never recorded**, since
they carry model
output, task content and credentials. Provider, exit code and duration
are.
- **Reward and accuracy are not mirrored into OpenTelemetry.** They are
experiment
  telemetry and stay in `AggregateMetricsMixin`.

### Docs

Adds an `observability` section under `fern/versions/latest/pages/`
covering
configuration, distributed tracing, span groups, metrics, and how to
instrument your own
server. Frozen `fern/versions/v0.*` snapshots are untouched.

## Checklist

- [x] I have read the [contributing
guidelines](https://docs.nvidia.com/nemo/gym/latest/contribute/development-setup).
- [x] The change is focused; unrelated "drive-by" edits are tracked as
separate issues/PRs.
- [x] Tests added or updated and pass locally, or N/A for docs-only /
non-code changes (so CI unit/server checks pass when applicable).
- [x] Pre-commit checks pass locally (`pre-commit run --all-files`) (so
CI lint/format/copyright pass).
- [x] All commits have DCO sign-off (`git commit -s`) (so the DCO check
passes).

---------

Signed-off-by: Ahmad Kiswani <[email protected]>
Signed-off-by: Onur Yilmaz <[email protected]>
Co-authored-by: Onur Yilmaz <[email protected]>
Co-authored-by: Onur Yilmaz <[email protected]>

This branch was previously deployed

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

Labels

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.

3 participants