Skip to content

Add runtime and request-cycle telemetry for Gym performance bottlenecks #3155

Open

Description

@ananthsub

Parent

#2999 — Performance workstream: core Gym infrastructure

Umbrella: #2998 — Performance opportunities across the NeMo Gym server stack

Goal

Add enough low-overhead telemetry to identify where Gym stops scaling as rollout concurrency increases.

The telemetry must distinguish work waiting in the driver, HTTP client, server event loop, agent, model adapter, and resources implementation. It must also show whether Python runtime pressure such as garbage collection or memory growth explains the slowdown.

This issue defines the shared instrumentation contract. Individual agents, resources servers, and model adapters can add implementation-specific measurements through that contract.

Current visibility

Gym already initializes one NeMo Lens telemetry handle in each agent, model, and resources-server process. It propagates trace context across Gym HTTP calls and records rollout, verification, model-call, and HTTP server durations.

The current integration does not expose:

  • event-loop scheduling lag or resident task count;
  • active requests or queued outbound HTTP calls;
  • garbage-collection pauses;
  • process CPU, memory, thread, or file-descriptor pressure;
  • driver admission wait and resident rollout tasks;
  • payload item counts and bytes at each boundary;
  • queue wait separately from execution time inside resources implementations.

Without these measurements, a throughput plateau cannot be attributed to Gym admission, one saturated server event loop, HTTP connection pooling, payload validation, serialization, a resources-server queue, or the downstream model.

Request path to observe

flowchart LR
    Driver["Rollout driver"] -->|"Admission wait"| Agent["Agent server"]
    Agent -->|"Connector wait"| Model["Model adapter"]
    Agent -->|"Connector wait"| Resources["Resources server"]
    Model -->|"Upstream inference"| Engine["Inference endpoint"]
    Resources -->|"Queue and execution"| Worker["Judge, executor, or subprocess"]
    Agent --> Driver
Loading

Shared runtime observer

Add an opt-in runtime observer to every Gym server process.

Attach it through a composed FastAPI lifespan in SimpleServer. Do not replace an application's existing lifespan. Register the same observer explicitly for the internal head server because it does not use SimpleServer.run_webserver().

The observer should emit:

  • gym.runtime.event_loop.lag — histogram in seconds. Measure the positive difference between a monotonic deadline and when the sampling coroutine resumes.
  • gym.runtime.event_loop.tasks — last-value gauge. Report len(asyncio.all_tasks(loop)). Describe this as resident task count, not queue depth.
  • gym.runtime.gc.pause — histogram in seconds with generation.
  • gym.runtime.gc.collections — monotonic counter with generation.
  • gym.runtime.gc.collected — monotonic counter with generation.
  • gym.runtime.gc.uncollectable — monotonic counter with generation.
  • gym.runtime.gc.count — last-value gauge with generation, populated from gc.get_count().
  • process.cpu.time — process CPU seconds split by user/system where the existing process metrics convention supports it.
  • process.memory.usage — current RSS in bytes.
  • process.thread.count — current process thread count.
  • process.open_file_descriptor.count — current descriptor count where the platform supports it.

psutil is already a Gym dependency and is portable across supported platforms. Process metric collection must still degrade safely when one measurement is unavailable.

The sampling interval must be configurable and must use monotonic time. One second is an appropriate initial default for diagnostic runs. Runtime telemetry must remain separately opt-in until its overhead is measured.

gc.callbacks is process-global. Store the exact callback object, handle unmatched stop events safely, and remove only that callback during shutdown. Observer startup, sampling, and cleanup failures must never prevent the server from serving.

Do not inspect private asyncio fields such as loop._ready, loop._scheduled, or Task._fut_waiter.

Request and HTTP client telemetry

The pinned FastAPI instrumentation records request duration but does not expose an active-request instrument. Add one lightweight ASGI wrapper around HTTP scopes:

  • gym.server.requests.in_flight — up/down counter.
  • gym.server.requests.cancelled — monotonic counter.
  • gym.server.requests.failed — monotonic counter for failures that escape the application.

Do not attach rollout IDs, URLs, session IDs, exception text, or task names to metrics. Server identity belongs in process resource attributes. Route and status remain available from existing HTTP spans and duration metrics.

Use supported aiohttp.TraceConfig callbacks on Gym's global client to measure:

  • gym.http.client.requests.in_flight — up/down counter.
  • gym.http.client.queue.duration — histogram in seconds for connector queue wait.
  • gym.http.client.connection.duration — histogram in seconds for new connection establishment.

Do not read private connector queues. Preserve the existing explicit CLIENT spans and traceparent propagation.

Rollout-driver telemetry

Instrument the driver around the existing admission, task creation, and persistence boundaries:

  • gym.driver.rollouts.offered — monotonic counter.
  • gym.driver.rollouts.resident — last-value gauge for created but unfinished rollout tasks.
  • gym.driver.rollouts.active — last-value gauge for requests inside the active concurrency limit.
  • gym.driver.admission.duration — histogram in seconds for time waiting to enter the active window.
  • gym.driver.output.write.duration — histogram in seconds.
  • gym.driver.output.write.bytes — histogram in bytes.
  • gym.driver.materialize.duration — histogram in seconds, recorded separately from rollout execution.

These measurements support #3006. They must not change task admission, persistence, ordering, resume, or return-value behavior.

Payload and phase measurements

Record low-cardinality histograms at request boundaries:

  • input item count;
  • output item count;
  • request bytes;
  • response bytes;
  • agent turns;
  • model calls;
  • tool/resources calls.

Use per-request span attributes for exact values and histograms for fleet-level distributions. Item type may be attached only as a bounded enum and only when one record describes one item type; do not encode arbitrary type sets as metric attributes.

Define a shared resources-operation contract:

  • queue wait duration;
  • execution duration;
  • active work;
  • bounded queue depth;
  • timeout, cancellation, crash, and worker-restart counters.

Attributes must use bounded values for operation and executor such as verify, tool, judge, thread, process, or subprocess. This contract should be reusable by the process-pool work in #3038 and multi-worker work in #3039.

Configuration

Extend the existing telemetry: block rather than adding unrelated top-level settings:

telemetry:
  enabled: true
  metrics_enabled: true
  runtime_metrics_enabled: true
  runtime_metrics_interval_seconds: 1.0

Propagate these values through the existing NEMO_GYM_OTEL_* environment path so every spawned process receives one configuration.

Implementation locations

Expected shared locations include:

  • nemo_gym/telemetry/config.py
  • nemo_gym/telemetry/setup.py
  • a new nemo_gym/telemetry/runtime.py
  • nemo_gym/telemetry/metrics.py
  • nemo_gym/telemetry/contrib.py
  • nemo_gym/server_utils.py
  • nemo_gym/rollout_collection.py
  • focused tests under tests/unit_tests/telemetry/

Implementation-specific call sites should remain in their owning agent, model, or resources server.

Correctness and overhead constraints

  • Telemetry disabled must preserve the current import, startup, request, and shutdown paths.
  • Telemetry failures must never fail a request or server startup.
  • Multi-worker servers must report one observer per worker with distinguishable process resource attributes.
  • Metrics must remain low-cardinality.
  • Sampling must not enumerate task stacks or capture request bodies.
  • GC callbacks and sampler tasks must not survive server shutdown.
  • Existing trace context, cookies, rollout IDs, response metadata, cancellation, and exception handling must remain unchanged.

Acceptance criteria

  • Every agent, model, and resources-server worker reports event-loop lag, resident tasks, GC, and process metrics when runtime metrics are enabled.
  • The internal head server either reports the same runtime metrics or has a documented reason and follow-up issue.
  • In-flight server requests and outbound connector queue wait are visible without private-library introspection.
  • Driver metrics distinguish offered, resident, active, waiting, and persisted work.
  • Payload counts and bytes can be correlated with request and rollout spans.
  • A shared queue-wait/execution contract is documented and exercised by one representative resources server.
  • Tests cover enablement, no-op behavior, metric values and attributes, GC callback pairing/removal, lifespan composition, cancellation, multi-worker identity, and partial metric failures.
  • A disabled-telemetry benchmark shows no material regression. Report the confidence interval instead of relying on one timing.
  • An enabled-without-export benchmark quantifies observer overhead before runtime metrics become default.
  • Documentation explains that task count is not event-loop queue depth and that lag is the scheduler-pressure signal.

Out of scope

  • Capturing coroutine stacks or task-local request contents.
  • Using private asyncio or aiohttp internals.
  • Changing rollout admission, resources execution, or worker counts.
  • Replacing NeMo Lens or the existing OpenTelemetry propagation path.
  • Making runtime telemetry default-on before its overhead is measured.

Related work

  • #2998 — performance umbrella
  • #3006 — bounded rollout task admission
  • #3014 — agent multi-worker serving
  • #3038 — shared process pool
  • #3039 — resources-server multi-worker serving

Delivered memory telemetry — September 2026

#3584, merged 2026-09-23, implements the centralized memory portion of this issue: host used/available/total and sampled peaks, logical-server process-tree RSS/PSS and sampled peaks, and process counts. Delivery attribution: Ananth (@ananthsub).

This is partial completion only. Runtime GC, event-loop and request-cycle telemetry remain outstanding; the existing performance parent and issue workflow state are preserved. Related observability delivery epic: FEP-1474 / GitHub #2831.

Activity

  1. added
    core-infra
    on Sep 8, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

Platformcore-infra

Type

No type

Projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions