Skip to content

feat(telemetry): add optional OpenTelemetry instrumentation via nemo-lens - #2646

Merged
oyilmaz-nvidia merged 12 commits into
mainfrom
ahmadki/lens-gym-base
Aug 26, 2026
Merged

oyilmaz-nvidia merged 12 commits into
mainfrom
ahmadki/lens-gym-base

Conversation

@ahmadki

@ahmadki ahmadki commented Aug 21, 2026

Copy link
Copy Markdown
Member

What does this PR do?

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 and changes no runtime
behaviour.

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

Why the design looks the way it does

Gym's process model drove most of it. Megatron-LM is one process tree and NeMo-RL is a Ray
driver plus actors, but a Gym run is N independent FastAPI processes spawned with Popen
that share no memory and inherit no handle. So the orchestrator translates the config block
into NEMO_GYM_OTEL_* variables before spawning anything, and each server reads that
environment back on startup — the environment is the only channel between them.

For the same reason export_strategy defaults to all_ranks rather than single_rank:
each Gym server is rank 0 of its own world of one, so a rank filter would either silence
all of them or none.

What's in it

Module Role
config.py TelemetryConfig, the telemetry: block. Imports pydantic only.
setup.py Lifecycle: configure_telemetry_env (orchestrator), init_telemetry (per server process), get_telemetry, shutdown_telemetry.
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 Wrapper over nemo-lens's gym.* instruments, taking 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 for service maps.
contrib.py Gym's boundary onto lens's propagation and FastAPI helpers.
_fallbacks.py The single import point for the instrumentation primitives.

_fallbacks.py 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 at every site. Together with contrib.py this makes
nemo_gym.telemetry the only package that imports nemo.lens, which is enforced by a
test rather than by convention.

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

Dependency pin

The extra pins nemo-lens to the same commit Megatron-LM uses, via [tool.uv.sources].
Two things that table does not do, worth knowing before review:

  • It is a uv-only mechanism and is not recorded in a built wheel, so
    pip install nemo-gym[telemetry] from PyPI resolves nemo-lens from PyPI instead. The pin
    governs source checkouts and the uv lock.
  • It governs only dependencies resolved through the local project. Getting the pin into
    the per-server venvs needs more than this, and is handled in the follow-up PR.

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]>
@ahmadki
ahmadki requested a review from a team as a code owner August 21, 2026 13:24
@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.

`nemo_gym.telemetry` is the only package that imports `nemo.lens`. Everything outside it
reaches telemetry through this package, so a reader never has to work out whether a given
`nemo.lens` import is reachable when the extra is not installed. The invariant is
enforced by `tests/unit_tests/telemetry/test_call_sites.py`.

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.

NOTE — this docstring states the "only nemo_gym.telemetry imports nemo.lens" invariant "is enforced by tests/unit_tests/telemetry/test_call_sites.py." That test file is not in this PR (the added tests are config/endpoints/fallbacks/metrics/overhead/setup/span_groups). What breaks: the invariant is documented as test-enforced but is actually unenforced — when call sites land in the follow-up PR, a stray from nemo.lens import ... outside this package will import fine with the extra installed and only blow up in the lens-absent config nobody runs by accident. Fix: add the test, or soften the claim to "by convention" until it exists.

pytest tests/unit_tests/telemetry/ -x
```

The load-bearing test is `test_propagation.py`: two Gym apps, an in-memory span exporter,

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.

NOTE — README calls test_propagation.py "the load-bearing test" and instructs future editors to "make sure that test still fails when propagation breaks." That file is not in this PR. Since cross-process context propagation (one rollout → one trace) is the entire stated purpose of the module, the one test that would guard it is absent. Fine for a no-call-site base layer, but the doc promises a regression guard that doesn't exist yet — either land it with the call sites in PR2 or mark it as TODO here so nobody trusts a green suite to mean propagation works.

@claude

claude Bot commented Aug 21, 2026

Copy link
Copy Markdown
Contributor

SHIP WITH CARE — clean opt-in base layer; the correctness-critical hazards this repo worries about don't apply here yet, but two claimed test guarantees are missing.

I reviewed this as the engineer who'd get paged. Up front: this PR adds no call sites (author's explicit design), so none of the usual page-triggers are in play — no verify()/scorer change, no async HTTP path, no ray.get() in async, no public-API break. The only runtime-reachable change is global_config.py importing nemo_gym.telemetry.setup and adding telemetry to NEMO_GYM_RESERVED_TOP_LEVEL_KEYS. I traced that chain: config.py (pydantic-only), _fallbacks.py, span_groups.py, and setup.py all guard every nemo.lens import behind try/except or make it function-local — core stays importable without the extra, and the telemetry: block is correctly shielded from being parsed as a server instance. Confirmed no live callers of init_telemetry/configure_telemetry_env/server_venv_requirements/traced_*/record_* outside the module and its tests. Env-only cross-process coordination and setdefault precedence (raw env wins over YAML) match Gym's Popen process model. shutdown_telemetry and the lens-setup failure paths swallow exceptions so telemetry can't take a server down.

What to carry forward, none blocking for a no-op base layer:

  • RISK — two documented test guarantees don't exist in this PR. contrib.py:20 says the "only telemetry imports nemo.lens" invariant is "enforced by test_call_sites.py"; README.md:98 calls test_propagation.py "the load-bearing test." Neither file is in the diff. The propagation guard matters most: cross-process trace-joining is the module's whole reason to exist, and it's the one behavior a green suite won't catch when call sites land. Land both with PR2, or downgrade the prose to TODO so nobody trusts enforcement that isn't there. (Inline.)

  • NOTE — [tool.uv.sources] git pin is uv-only and absent from built wheels. Called out honestly in the PR body and pyproject comment: pip install nemo-gym[telemetry] from PyPI silently resolves nemo-lens 0.1.0, which the module says lacks the required post-0.1.0 APIs. Acceptable while lens is pre-release and the extra is opt-in, but it's a latent "works in dev, broken from PyPI" trap — track the 0.2.0 cleanup so the pin table actually gets removed.

  • NOTE — _installed_requirement builds an unquoted pkg@git+URL@commit string that setup_env_command will interpolate into a shell line (per the inline comment at setup.py). The author chose the no-space PEP 508 form to survive unquoted splitting and flagged the real fix (quote at the call site) as tracked separately. Fine with no live caller yet; don't let PR2 wire this into a subprocess without the quoting fix.

  • NOTE — gym.verify.success_rate is a cumulative process-lifetime fraction, not a windowed rate, and flattens as a process ages. Documented plainly in metrics.py. It's application telemetry, deliberately kept away from reward/accuracy (which stay in AggregateMetricsMixin/W&B), so no risk of contaminating training signal — correct call.

Nothing here corrupts scores or hangs a run. Merge once the missing-test prose is reconciled with reality.

@github-actions github-actions Bot added the sla:review-overdue Review response is over the one-business-day SLA label Aug 24, 2026
except ImportError:
# TODO(ahmadki): SpanGroups are moving from nemo-lens to downstream consumers, at
# which point this stub and the try/except disappear and GymSpanGroup stands alone.
class SpanGroup: # type: ignore[no-redef]

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.

If this will be on the downstream consumers, let's remove the from the

nemo.lens.groups import SpanGroup

And add the SpanGroup class here.

Comment thread nemo_gym/telemetry/setup.py Outdated
Reads the optional top-level ``telemetry:`` block. A run that never mentions
telemetry gets the all-defaults config, which is disabled.
"""
from nemo_gym.telemetry.config import TelemetryConfig

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.

Can we move the imports to the top of the file if there is no specific reason to keep them here?

Comment thread nemo_gym/telemetry/setup.py Outdated

# OmegaConf nodes are Mapping-like but not dicts; resolve them before validating.
try:
from omegaconf import DictConfig, OmegaConf

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.

Same here.

#: ``TelemetryConfig`` field -> env var. ``service_name`` is handled separately because it
#: maps to the standard unprefixed ``OTEL_SERVICE_NAME``, and the Gym-owned flags
#: (``service_name_per_server``, ``instrument_aiohttp``) are not lens config fields.
_ENV_FIELD_MAP = {

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.

Does user have to set these env vars? Or, is there a function in the setup or anywhere else that sets these env vars for us? If not, having a function that connects the config or inputs to the env vars will be helpful.

return attrs


def init_telemetry(

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.

Currently, it doesn't seem that setting telemetry.enabled: true is calling these? Will you do it in the next PR?

Comment thread nemo_gym/telemetry/setup.py Outdated
disabled. Never raises: a telemetry failure must not take a server down.
"""
global _TELEMETRY_HANDLE, _INITIALISED
if _INITIALISED:

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.

Not sure if there will be a concurrent init calls but there is a an unguarded singleton race and concurrent init calls can both pass the guard and register duplicate OTel providers.

Comment thread uv.lock
{ url = "https://files.pythonhosted.org/packages/9d/1a/c8923d819b49872a612033b90d29299c0be73a7cbed1ddb3dc78dfe5e9f1/apache_tvm_ffi-0.1.9-cp314-cp314t-win_amd64.whl", hash = "sha256:a42d7ca27dce83efbdce7ec970fe3e773a69c31d928730ee5d9badb1229d106c", size = 2039007, upload-time = "2026-02-27T19:27:43.618Z" },
]

[[package]]

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.

uv.lock forces an opentelemetry-api version bump for all installs, not just ones opting into the telemetry extra

return f"{requirement_name}=={dist.version}"


def server_venv_requirements() -> list:

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.

This is not called anywhere and will this be called in the second PR?

@oyilmaz-nvidia

Copy link
Copy Markdown
Contributor

/ok to test 2c85ae2

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

- Move the TelemetryConfig and omegaconf imports in setup.py to module
  scope; neither requires nemo-lens, so the function-local-import
  convention (reserved for lens imports) didn't apply to them.
- Document that _ENV_FIELD_MAP is consumed by configure_telemetry_env,
  which is the function that connects a telemetry: config block to env
  vars, so a user doesn't set them by hand.
- Note in server_venv_requirements and init_telemetry's docstrings that
  neither has a caller yet in this PR; wiring lands with the follow-up
  call-sites PR.
- Guard init_telemetry's check-and-set singleton pattern with a lock:
  concurrent callers could previously both observe _INITIALISED as
  False and both call setup_telemetry, which nemo-lens raises on for a
  second call in the same process. Add a concurrency test proving the
  lock actually serializes concurrent init calls.
- Document in pyproject.toml why adding the telemetry extra bumps the
  shared opentelemetry-api floor for every install, not just ones
  requesting the extra (uv resolves one unified lockfile).

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

Copy link
Copy Markdown
Contributor

/ok to test e1da2cc

@oyilmaz-nvidia

Copy link
Copy Markdown
Contributor

/ok to test 30ea2b9

@copy-pr-bot

copy-pr-bot Bot commented Aug 26, 2026

Copy link
Copy Markdown

/ok to test 2673e7a

@oyilmaz-nvidia, there was an error processing your request: E2

See the following link for more information: https://docs.gha-runners.nvidia.com/cpr/e/2/

@oyilmaz-nvidia

Copy link
Copy Markdown
Contributor

/ok to test 74f9892

@oyilmaz-nvidia

Copy link
Copy Markdown
Contributor

/ok to test 1d1a1b0

@oyilmaz-nvidia

Copy link
Copy Markdown
Contributor

/ok to test 1d1a1b0

@copy-pr-bot

copy-pr-bot Bot commented Aug 26, 2026

Copy link
Copy Markdown

/ok to test 1d1a1b0

@oyilmaz-nvidia, there was an error processing your request: E2

See the following link for more information: https://docs.gha-runners.nvidia.com/cpr/e/2/

@oyilmaz-nvidia

Copy link
Copy Markdown
Contributor

/ok to test 89dd7af

@oyilmaz-nvidia

Copy link
Copy Markdown
Contributor

/ok to test 9bd29fe

This branch was previously deployed

1 inactive deployment
public — 9bd29fe2 Deployed Aug 26, 2026 by copy-pr-bot[bot] via release / finalize / notify #2017
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