Skip to content

feat(telemetry): add executor and event-loop diagnostics - #4732

Open
macandro96 wants to merge 3 commits into
mainfrom
amahishi/feat-lens-async-runtime-diagnostics
Open

macandro96 wants to merge 3 commits into
mainfrom
amahishi/feat-lens-async-runtime-diagnostics

Conversation

@macandro96

@macandro96 macandro96 commented Oct 14, 2026 •

Copy link
Copy Markdown
Contributor

What does this PR do ?

Expose where selected asynchronous work spends time: waiting for the existing default executor, executing in a thread, and waiting for its successful result to reach the coroutine.

A reusable nemo_rl.telemetry.runtime helper publishes bounded, process-scoped Lens metrics:

  • rl.executor.queue_wait, rl.executor.execution, and rl.executor.result_delivery: histograms in milliseconds.
  • rl.executor.pending: queued/running task counts.
  • rl.event_loop.lag: scheduling lateness of a scoped one-second probe, in milliseconds.

Instrumented sites are non-streaming vLLM terminal capture, controller replay-index loading, and synchronous local data-plane calls explicitly offloaded through call_data_plane. The helpers observe the existing default executor; they do not create a thread pool or globally patch asyncio. Context propagation, return values, exceptions, and cancellation are preserved. A cancelled caller does not stop a running thread, which remains counted until completion.

Controller and vLLM HTTP loop probes are cancelled and awaited on owner exit. The HTTP wrapper preserves the final FastAPI lifespan, including yielded state, after API/refit initialization. Trace-only or disabled-telemetry runs create no probe or offload bookkeeping. Labels are bounded call-site names, not request/checkpoint IDs, and no per-request file writes are added.

High queue wait identifies backlog; execution time includes CPU work and blocking I/O; result delivery plus loop lag helps identify delayed coroutine scheduling. These measurements do not identify a GIL holder or prove storage is slow. A blocked loop reports its lateness only once it runs again, so this is not an independent hang watchdog.

This PR targets main independently of completed rollout checkpoint metric export in #4730. Neither PR requires the other.

Issues

No separate issue; add bounded runtime diagnostics to the existing Lens integration.

Usage

Enable the existing telemetry configuration:

telemetry:
  enabled: true
  metrics_enabled: true

Instrument additional bounded call sites with run_in_thread("fixed_call_site", function, ...) and scoped monitor_event_loop("fixed_loop_name"); for a FastAPI server, call monitor_app_event_loop(app, "fixed_loop_name") after every other lifespan registration. Executor series carry the call-site label as rl.executor.site. Use the normal Lens/OTLP destination. Aggregate histogram distributions across processes rather than averaging per-worker percentiles. Histogram resolution depends on exporter/SDK aggregation; the helpers do not install custom SDK views.

Validation

  • Standalone telemetry suite on Python 3.13.14: 188 passed, 4 skipped, 1 deselected. Ray/SFT integration modules were excluded from the lightweight environment; four optional metric-owner imports were skipped and the vLLM engine-scalar test was deselected because it needs training dependencies.
  • Tests cover real executor queueing/execution/result delivery, ContextVars, errors, cancellation before/during execution and a launch/cancellation race, disabled metric export, probe cleanup, and the actual HTTP setup/lifespan code using lightweight engine fakes.
  • Local/coroutine/Ray-style data-plane dispatch compatibility: 4 passed.
  • Focused Pyrefly checks of runtime.py, metrics.py, setup.py, and async_utils.py: 0 errors. Existing controller/vLLM type-check errors were compared against main while validating the original identical runtime implementation; no new errors were introduced.
  • Changed-file Ruff lint/format, Python syntax, copyright headers, and git diff --check pass.
  • Full engine/GPU integration validation remains for CI.

An indicative microbenchmark of this identical runtime implementation used 2,048 no-op offloads, concurrency 16, and forward/reverse case order on a shared CPU. Average elapsed time per offload was 123 us for plain asyncio.to_thread, 125 us with metrics disabled, and 399 us with enabled in-memory metric collection. This is instrumentation cost, not a checkpoint speedup claim; results were noisy and exclude network export. Enable diagnostics when that overhead is acceptable for the workload.

Only part of that cost lands on the event-loop thread: two of the seven metric writes per call (the queued count before submit and result delivery after resumption) run there, and the other five run on the worker thread. A rerun on a different host (2,048 no-op offloads, concurrency 16, five alternating-order repetitions, medians) measured 46 us for asyncio.to_thread, 46 us with metrics disabled, and 106 us with in-memory collection enabled. Timed in isolation and uncontended, the two loop-thread writes took 7.9 us per call, about 13% of the ~60 us added. A serving run with metrics on vs. off remains a follow-up.

Before your PR is "Ready for review"

  • Read and followed contributor guidelines; commit is DCO signed off.
  • Added necessary tests.
  • Ran the relevant standalone unit tests locally; full functional tests remain for CI.
  • Updated observability and extension documentation.

@copy-pr-bot

copy-pr-bot Bot commented Oct 14, 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.

@macandro96 macandro96 added the CI:L0 Run doctests and unit tests label Oct 14, 2026
@macandro96

Copy link
Copy Markdown
Contributor Author

/ok to test fb530cd

@github-actions github-actions Bot added the Documentation Improvements or additions to documentation label Oct 14, 2026
@nemo-automation-bot
nemo-automation-bot Bot requested a review from a team October 14, 2026 21:55
@macandro96
macandro96 requested review from rrs45 and saumishr October 15, 2026 17:21

@mehraakash mehraakash 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.

Reviewed the executor/event-loop diagnostics end to end: run_in_thread, monitor_event_loop, the three instrumented call sites, the controller and vLLM lifespan wrappers, and the telemetry_metrics_exporting() switch. Worth merging; nothing blocks. The telemetry unit suite (test_runtime, test_setup) passes locally with nemo-lens installed, and 30 repeated runs of the new tests showed no flakiness.

11 inline comments: 3 should-fix (a swallowed owner cancellation in the probe's shutdown path, deriving the five registry keys from the series names, and the docs section landing above the page intro) and 8 nits (docstrings, a helper for the lifespan wrapper, optional reuse of the metrics switch, naming, one more overhead number, and three cheap test additions).

Heads-up: this PR and #4730 both edit the top of docs/observability/metrics.md, _metric_specs in nemo_rl/telemetry/metrics.py, and tests/unit/telemetry/conftest.py, so whichever lands second will need a small rebase.

Generated by Claude Code

Comment thread nemo_rl/telemetry/runtime.py Outdated
yield
finally:
probe.cancel()
with suppress(asyncio.CancelledError):

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.

nemo_rl/telemetry/runtime.py:205

A cancel that lands while the probe is being shut down is swallowed

1 action item. PR-introduced, low severity.

On exit, this waits for the probe task inside suppress(CancelledError). In asyncio, cancelling a task that is awaiting another task is delivered through the inner task: the outer cancel cancels the probe, and the probe's CancelledError is what surfaces in the owner (tasks.py L229, L373). The suppress eats it, and the owner returns normally with task.cancelling() == 1 left set.

Shown: a standalone script using the real monitor_event_loop prints BUG: owner cancel() was swallowed; task returned 'owner completed normally'; cancelling()=1 cancelled()=False. With the change below it prints that the cancellation propagated and the probe still finished.

Why low: the window is one loop tick and only opens after the body has already finished, so the only visible effect is a cancel in that tick being reported as a normal completion. No state is lost and the probe exits on its own either way. Still worth the one-liner, since the docstring promises cleanup on cancellation paths.

        probe.cancel()
        await asyncio.wait({probe})

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 8a43871: exit now does probe.cancel(); await asyncio.wait({probe}), so the owner's cancel propagates. Added test_cancel_during_probe_shutdown_reaches_the_owner; I reverted to the old suppress code and confirmed it fails there.

),
)
)
specs.extend(

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.

nemo_rl/telemetry/metrics.py:216

Derive the five registry keys instead of typing them next to the series names

1 action item. PR-introduced.

Each new row types both a registry key (executor_queue_wait) and a series name (rl.executor.queue_wait) by hand. The rows a few lines above derive the key from the name with registry_key(name), which exists so "a row cannot name its series one thing and record against another" (vocabulary.py L64). Nothing tests for a mismatch here, so a typo in one column would silently record against an undeclared key.

Action: drop the key column from the five tuples and build each spec with registry_key(name), matching L142-144. Moving the declarations into runtime.py was considered and rejected: it would reintroduce the frozen-registry import-order hazard. Optionally, hoist the four attribute strings in runtime.py (rl.executor, .state, .status, rl.event_loop) into module constants like the existing RL_*_ATTR names.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in 8a43871. The five names are now RL_*_METRIC constants in metrics.py. The specs and the *_KEY constants that runtime.py imports are both built with registry_key(name), so there's no hand-typed key column left. I also moved the attribute strings into module constants in runtime.py: RL_EXECUTOR_SITE_ATTR, RL_EXECUTOR_STATE_ATTR, RL_EXECUTOR_STATUS_ATTR and RL_EVENT_LOOP_ATTR.

Comment thread docs/observability/metrics.md Outdated
# Metrics

NeMo-RL emits five namespaces of metrics: async efficiency metrics (`rl.efficiency.*`), startup phase durations (`rl.setup.duration`), training scalars (`rl.reward.*`, `rl.policy.*`, …), vLLM engine metrics (`rl.vllm.*`), and driver-side vLLM generation metrics (`gen_ai.*`, following the OTel GenAI semantic conventions).
## Async runtime diagnostics

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.

docs/observability/metrics.md:3

New section sits above the page introduction; one sentence mixes up two labels

2 action items. PR-introduced.

The page used to open with the one-paragraph overview of every metric family and the "emitted only when telemetry is exporting" note. This section now comes first and that overview has moved to L44-46, so the reader meets a sub-feature before learning what the page covers.

At L16-17, "rl.executor.state or rl.executor.status (success, error)" lists only the status values. state is queued/running and appears only on rl.executor.pending; status appears only on rl.executor.execution; the other three series carry just the call-site label. Every other statement in the section checks out against the code.

Action: move this section to after Startup phases and restore the overview paragraphs as the opener; replace the labels sentence with the text below. Heads-up: PR #4730 also inserts a new section directly under this title, so whichever merges second will conflict here, in _metric_specs and in the telemetry conftest.

Executor dimensions: every series carries `rl.executor` (a bounded call-site label); `rl.executor.pending` adds `rl.executor.state` (`queued`, `running`) and `rl.executor.execution` adds `rl.executor.status` (`success`, `error`). Sites

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in 8a43871. The page opens with the overview paragraphs again, and the runtime section now comes after Startup phases. The labels sentence now says which series carry state and which carry status. It uses rl.executor.site because of the rename in the other thread.

async def run_in_thread(
executor: str, function: Callable[..., _T], /, *args: Any, **kwargs: Any
) -> _T:
"""Observe one default-executor call without changing asyncio semantics.

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.

nemo_rl/telemetry/runtime.py:108

Docstring puts prose after Args and has no Returns

1 action item. PR-introduced; the repo's lint guide asks for Google style.

Four sentences of description follow the Args: block, which the docs build renders as a detached paragraph, and there is no Returns:. monitor_event_loop at L191 has no Args: for name.

Action: reorder as below; add Args: name: Bounded loop label, such as controller or vllm_http. to monitor_event_loop.

    """Observe one default-executor call without changing asyncio semantics.

    Records queue wait, execution time and queued/running counts. Successful
    calls also record completion-to-coroutine-resumption delay. Cancellation
    does not pretend to stop an already-running thread: it remains counted
    until the function exits. With metrics off, delegates to ``asyncio.to_thread``.

    Args:
        executor: A bounded call-site label, such as ``generation_terminal``.
            It identifies work sharing an executor, not a dedicated thread pool.
        function: Synchronous function to offload.
        *args: Positional arguments forwarded to the function.
        **kwargs: Keyword arguments forwarded to the function.

    Returns:
        The function's return value.
    """

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in 8a43871. run_in_thread is reordered and has a Returns: section, and monitor_event_loop now documents name under Args:.

server_lifespan = app.router.lifespan_context

@asynccontextmanager
async def lifespan(

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.

nemo_rl/models/generation/vllm/vllm_worker_async.py:1605

Make the lifespan wrapper a helper so its test does not have to exec production source

1 action item. PR-introduced.

The only test of this wrapper (test_runtime.py L310-392) parses this file, extracts _setup_vllm_server, and executes it in a hand-built namespace of eleven names. The wrapper uses module-level names (monitor_event_loop, asynccontextmanager, AsyncIterator, Mapping, Any, cast) that exist in the test only because it binds them, so any future module-level name used in this function breaks the test and not production.

Secondary: the Dynamo token wrapper, the TRT-LLM HTTP server and the vLLM sparse-refit server are FastAPI apps with the same shape and would copy these ten lines if instrumented.

Action: move the composition into runtime.py as monitor_app_event_loop(app, name) (one way to do it, below) and call it here. The test then becomes a direct test on a bare FastAPI() with a stub lifespan.

def monitor_app_event_loop(app: "FastAPI", name: str) -> None:
    """Wrap ``app``'s final lifespan so a loop probe runs on the serving loop.

    Call after every other lifespan/handler registration; preserves yielded state.
    """
    inner = app.router.lifespan_context

    @asynccontextmanager
    async def lifespan(server_app: "FastAPI") -> AsyncIterator[Mapping[str, Any] | None]:
        async with monitor_event_loop(name):
            async with inner(server_app) as state:
                yield state

    app.router.lifespan_context = cast("Lifespan[FastAPI]", lifespan)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in 8a43871. I added runtime.monitor_app_event_loop(app, name), and _setup_vllm_server calls it after API and refit setup. The test now runs on a bare FastAPI(lifespan=...) with no exec, and the vLLM file no longer needs the extra imports. extending.md points other FastAPI servers at the helper.

)


async def run_in_thread(

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.

nemo_rl/telemetry/runtime.py:105

Optional: the parameter is called executor but the docs say it is not one

1 optional action item. PR-introduced.

The first parameter is executor and the attribute is rl.executor, while the docstring and the docs page say it is a call-site label that does not select or size an executor. A dashboard filter on rl.executor="checkpoint_replay_load" reads as a dedicated pool.

If you take it: rename to site / rl.executor.site, matching the dotted rl.executor.state and rl.executor.status. A Literal or enum would not fit, since the data_plane.<method> label is built dynamically on purpose.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Taken in 8a43871. The parameter is now site and the attribute is rl.executor.site, matching rl.executor.state and rl.executor.status. Docs updated.

Comment thread nemo_rl/telemetry/runtime.py Outdated

submission = _Submission(executor, 0.0)
_emit(
{"executor_pending": 1.0},

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.

nemo_rl/telemetry/runtime.py:127

One more number would help: how much of the overhead lands on the event-loop thread

1 ask, not blocking.

The 123 to 399 microsecond benchmark isolates per-call cost well. Each call makes seven metric writes; this one and the result-delivery write at L166-175 run on the event-loop thread, the other five on the worker thread. Only the loop-thread share serialises request handling on the vLLM server, so that is the number that tells a reader what enabling this costs per request.

Ask: time just the two loop-side writes in the same microbenchmark and add the split to the description. A serving run with metrics on versus off would be a nice follow-up, not a requirement.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I reran the microbenchmark: 2,048 no-op offloads, concurrency 16, five alternating-order repetitions, on a different host from the original numbers. Medians: 46 us for to_thread, 46 us with metrics off, 106 us with metrics on. Timed alone and uncontended, the two loop-thread writes (the queued +1 before submit and result_delivery after resumption) take 7.9 us per call. That's about 13% of the ~60 us added; the rest runs on the worker thread. I've added this to the description, and a serving run with metrics on vs. off stays a follow-up.

):
from nemo_rl.telemetry import setup

if metrics_only_off:

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.

tests/unit/telemetry/test_runtime.py:246

The "metrics switched off" variant stops at the same check as the "telemetry off" variant

1 action item. PR-introduced test.

This variant builds a handle with metrics disabled but never sets _METRICS_ENABLED, which the shared fixture leaves False. Both parametrisations therefore short-circuit on the same flag, and the case this one is named for is proven only by test_setup.py L105-127.

Action: drive this variant through the real initialiser so the resolved switch is what gates the helper (below), or drop the parametrisation since the setup test already covers it.

    if metrics_only_off:
        from nemo_rl.telemetry.setup import init_telemetry_driver
        from tests.unit.telemetry.test_setup import _FakeMasterConfig  # or inline a stub
        init_telemetry_driver(
            _FakeMasterConfig(TelemetryConfig(enabled=True, metrics_enabled=False, exporter="console")),
            "grpo",
        )

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in 8a43871. That variant now goes through init_telemetry_driver with metrics_enabled=False and asserts the handle is exporting. It still checks delegation and that no probe is created. If telemetry_metrics_exporting() ignores the metrics switch, the test now fails.

return await remote(**kwargs)
if offload_sync:
result = await asyncio.to_thread(method, **kwargs)
result = await run_in_thread(f"data_plane.{method_name}", method, **kwargs)

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.

nemo_rl/data_plane/async_utils.py:53

No test passes keyword arguments through the rerouted offload

1 action item. Coverage gap on a PR-changed line; the test file is outside the diff.

All seven offload_sync=True call sites pass keyword arguments, but the only existing offload test (test_async_utils.py L53) calls a zero-argument method, so the **kwargs hand-off that now goes through run_in_thread is never exercised.

Action: add the test below to tests/unit/data_plane/test_async_utils.py. It passes and did not flake in 30 runs.

class _LocalClient:
    ...
    def thread_and_value(self, *, value: int) -> tuple[int, int]:
        return threading.get_ident(), value


def test_offloaded_sync_call_forwards_keyword_arguments() -> None:
    caller_thread_id = threading.get_ident()
    thread_id, value = asyncio.run(
        call_data_plane(_LocalClient(), "thread_and_value", offload_sync=True, value=5)
    )
    assert thread_id != caller_thread_id
    assert value == 5

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added in 8a43871 as suggested.

assert calls == [((), {"x": 7})]


def test_probe_detects_blocked_loop_and_stops_on_exit(reader, monkeypatch):

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.

tests/unit/telemetry/test_runtime.py:270

The probe is tested only when the loop is blocked, not when it is healthy

1 action item. PR-introduced coverage.

This asserts large lag on a blocked loop. A deadline-arithmetic bug that reported a full interval of lag on an idle loop would still pass. One cheap upper-bound test closes that; it passed 30 of 30 runs.

def test_probe_reports_near_zero_lag_on_an_idle_loop(reader, monkeypatch):
    interval = 0.1
    monkeypatch.setattr(runtime, "_EVENT_LOOP_PROBE_INTERVAL_S", interval)

    async def scenario():
        async with runtime.monitor_event_loop("controller"):
            await asyncio.sleep(interval * 2.5)

    asyncio.run(scenario())
    lag = points(reader, "rl.event_loop.lag")
    assert lag[0].count >= 2
    assert lag[0].max < interval * 1000 / 2

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added in 8a43871 as suggested. The runtime suite passed in all 15 repeated local runs.

- Propagate a cancel that lands while monitor_event_loop awaits its probe
  (asyncio.wait instead of suppress(CancelledError) around await probe).
- Derive the five executor/event-loop registry keys from their series names
  via registry_key, and hoist the attribute names into module constants.
- Rename the call-site label to site / rl.executor.site so it no longer reads
  as a dedicated executor.
- Move the FastAPI lifespan wrapper into runtime.monitor_app_event_loop and
  test it directly instead of exec'ing the vLLM worker source.
- Google-style docstrings for run_in_thread and monitor_event_loop.
- Docs: restore the metrics page opener, move runtime diagnostics after
  Startup phases, and correct which series carry state/status.
- Tests: drive the metrics-only-off case through init_telemetry_driver, add
  idle-loop lag, owner-cancel-during-exit, and data-plane kwargs coverage.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Anish Mahishi <[email protected]>
Resolve conflicts with main: keep the controller loop probe around the job span (now keyed by RL_ALGORITHM), offload terminal capture through run_in_thread inside main's abort-on-cancel guard, keep host-memory shutdown alongside the metrics-switch reset, and fold rl.executor.*/rl.event_loop.* into the metrics page's namespace overview.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Anish Mahishi <[email protected]>
@macandro96

Copy link
Copy Markdown
Contributor Author

/ok to test 01a5304

macandro96 added a commit that referenced this pull request Oct 21, 2026
Base the integration on RL #4762 at 71d3b46. Preserve the integrated #4730 metrics and #4732 runtime diagnostics, the integration metric mappings, and Gym a2d8d9f0559faf14a05e8d4add2a00624c0dbcbd with ToolSimulationAgent recovery.

Standalone telemetry: 279 passed, 5 skipped. Real local Ray telemetry: 5 passed. Syntax, lint, imports and formatting pass. Production-container prefix CPU tests are pending in Slurm job 1356058; GPU save/restore validation remains outstanding.

Signed-off-by: Anish Mahishi <[email protected]>
@terrykong terrykong added CI:L1 Run doctests, unit tests, and functional tests CI:Lfast Runs a fast test suite and re-use nightly `main` container (but sync dependencies to PRs version) and removed CI:L0 Run doctests and unit tests CI:L1 Run doctests, unit tests, and functional tests labels Nov 5, 2026
@terrykong terrykong removed the Documentation Improvements or additions to documentation label Nov 28, 2026

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

CI:Lfast Runs a fast test suite and re-use nightly `main` container (but sync dependencies to PRs version)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants