Skip to content

feat(observability): add per-rollout model-call capture - #1715

Merged
Glorf merged 25 commits into
mainfrom
feat/model-server-observability
Jul 15, 2026
Merged

Glorf merged 25 commits into
mainfrom
feat/model-server-observability

Conversation

@Glorf

@Glorf Glorf commented Jun 24, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Adds opt-in, per-rollout model-call capture at Gym model servers.

The capture records parsed model requests and responses, token and cache usage, model-emitted tool-call requests, reasoning, latency, and errors across the Responses, Chat Completions, and Anthropic Messages APIs.

When a matching non-empty capture exists, rollout_collection attaches the derived observability data to the corresponding rollout under ng_model_call_capture. The existing agent response, reward, token IDs, and log-probability fields are not modified.

This PR does not assemble or define an agent trajectory, ATIF output, or training representation.

Motivation

External and black-box agent harnesses own their model-calling loops, so those calls can bypass Gym’s agent-level instrumentation. When a harness is configured to use a Gym model server, that server is the common observable boundary.

Capturing at that boundary gives evaluation and debugging consumers consistent model-call evidence without interpreting or modifying each harness’s internal loop.

Design

Correlation

Model calls are associated with a rollout through the URL prefix:

/ng-rollout/<rollout_id>/v1/...

The model server strips the prefix before routing the request. Unprefixed requests continue to work normally but are not captured.

The rollout ID is derived from Gym’s task, rollout, and retry-attempt indices. This PR propagates the prefix through AnyTerminal, Claude Code, Gymnasium, Hermes, and MiniSWE Agent 2, and provides a base-agent URL helper. Other callers must propagate the prefix themselves. Calls sent directly to an external provider are not captured.

The prefix is caller-supplied correlation metadata, not authentication.

Capture

A pure-ASGI middleware observes:

  • /v1/responses
  • /v1/chat/completions
  • /v1/messages

Request and response bytes are not rewritten. The middleware buffers the request and a copy of the response in memory. Streaming responses are reassembled for capture on a best-effort basis. Non-terminal stream chunks are forwarded immediately; the terminal SSE event or final non-streaming response body is released after capture finalization when capture is enabled.

Each correlated exchange on an observed route is appended to a per-rollout JSONL file. Writes are flushed and fsynced. Thread locking and POSIX advisory file locking serialize writers when supported by the shared filesystem. Producer-side capture failures are logged without replacing or failing the model response; configuration and capture-reader validation errors remain explicit failures.

Model-call records

ModelCallRecord is a derived observability view containing:

  • append-order call_index
  • model server and API dialect
  • status and error classification
  • token and cache usage
  • total latency and latency to the first response-body chunk
  • tool calls and reasoning present in the model response
  • parsed request and parsed or reconstructed response payloads

call_index represents durable append order, not causal ordering for concurrent calls.

Rollout attachment

When rollout collection receives the agent result, it reads the corresponding capture and adds:

ng_model_call_capture = {
  rollout_id,
  metrics,
  calls,
}

The attached calls omit request and response payloads by default; the parsed or reconstructed payloads remain available in the capture store.

When capture is enabled, this adds an optional top-level field to the rollout JSON. It does not rewrite the harness output, reward, NeMoGymResponse, or existing training fields.

The attached metrics contains num_calls and sums for input, output, reasoning, and total tokens plus total call latency. It does not represent rollout wall-clock duration or causal concurrency.

Fresh non-resume collection clears existing capture files for the scheduled rollouts. Retry attempts use a distinct rollout-ID suffix so their calls do not mix with previous attempts.

Configuration

Capture is configured once at the top level of the Gym configuration, applies to every SimpleResponsesAPIModel, and is off by default:

observability_enabled: true
model_call_capture_dir: /absolute/shared/path/model-calls

model_call_capture_dir is required when capture is enabled and must be absolute; there is no environment-variable or temporary-directory fallback. Model-server and rollout-collector processes must resolve it to the same shared filesystem or volume. Separate gym env start and gym eval run --no-serve invocations must use the same top-level settings.

Rollout IDs do not contain an evaluation-run namespace. Concurrent or overlapping runs must use separate capture directories.

Captured payloads are stored without redaction or a built-in retention policy. Operators are responsible for directory access, retention, and storage capacity. Repeated full conversation histories can produce quadratic storage growth over a long rollout.

Scope

This PR provides rollout-correlated model-call evidence. It does not observe:

  • actual tool execution boundaries or tool duration
  • wall-clock call timestamps or tool CPU usage
  • sandbox or environment events
  • context compaction
  • semantic turns
  • subagent or branch structure

It also does not define or normalize a token-ID or log-probability training contract, loss masks, a training projection, a unified in-memory trajectory, or ATIF export. Captured request or response payloads may already contain provider- or Gym-specific token data, but ModelCallRecord does not make it a training contract. call_index cannot serve as a stable cross-source join key for parallel calls; a future builder will require explicit call or span identifiers when combining model-call evidence with agent, tool, environment, token, and verification data.

@copy-pr-bot

copy-pr-bot Bot commented Jun 24, 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.

@Glorf
Glorf marked this pull request as ready for review June 25, 2026 11:26
@Glorf
Glorf force-pushed the feat/model-server-observability branch 2 times, most recently from 8eabc05 to deace4f Compare June 25, 2026 12:00
@Glorf
Glorf requested review from cmunley1 and ffrujeri June 25, 2026 12:03
@Glorf
Glorf force-pushed the feat/model-server-observability branch from deace4f to 9dbdfca Compare June 25, 2026 12:08
@github-actions

github-actions Bot commented Jun 25, 2026 •

Copy link
Copy Markdown
Contributor

@Glorf
Glorf force-pushed the feat/model-server-observability branch from 9dbdfca to 7de8405 Compare June 25, 2026 12:40
Comment thread nemo_gym/observability.py Resolved
@cmunley1

cmunley1 commented Jun 25, 2026 •

Copy link
Copy Markdown
Contributor

would be good to merge with the prefix merging thing like in here and support training https://github.com/NVIDIA-NeMo/Gym/compare/cmunley1/tokenid-core?expand=1

but this for training is experimental still, not ready to merge imo

for training, we should demonstrate training runs with good metrics, compare 1-1 vs the original approach, and document how this unblocks blackbox agent training.

@Glorf
Glorf force-pushed the feat/model-server-observability branch from 3adde1d to f6a2ae3 Compare June 25, 2026 14:35
@anwithk anwithk linked an issue Jun 25, 2026 that may be closed by this pull request
13 tasks
Comment thread nemo_gym/trajectory_capture.py Resolved
Comment thread nemo_gym/trajectory_capture.py Resolved
Comment thread nemo_gym/base_responses_api_agent.py Resolved
Comment thread nemo_gym/trajectory_capture.py Resolved
Comment thread nemo_gym/trajectory_capture.py Resolved

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

Thanks for the proposal — the opt-in design, typed StepRecord that tries to establish a unified contract among the three wire dialects is important we should emphasize more. And about the pure-ASGI pass-through approach. Can this be actually part of the Model Server itself?

Also, if you could clarify in general the scope of this PR? Only for evals? Could we leverage more the current infrastructure and class hierarchy and data models currently in Gym?
Leaving here a mental model how I understood the direction:

Capture store (StepRecord[])     ──assemble──▶  NeMoGymResponse items (eval view)
        │                                              │
        └── trajectory builder (future) ──▶  masked training trajectories
                                                        │
Rollout record ◀──────────────────────────────── reward + ng_trajectory_capture
  responses_create_params + response + reward

A few comments about the actual implementation on this:
default-path correctness issue*: the /ng-rollout/<id> prefix is applied to model-server calls unconditionally during eval, but the model server only strips it when observability_enabled is true (the default is false), which 404s the default path — reproduced inline. There's also a capture-directory mismatch that makes the merge silently no-op in the simplest opt-in config, plus a few smaller notes.

Comment thread nemo_gym/base_responses_api_agent.py Resolved
Comment thread nemo_gym/observability.py Resolved
Comment thread nemo_gym/observability.py Resolved
Comment thread nemo_gym/observability.py Resolved
Comment thread nemo_gym/observability.py Resolved
@Glorf
Glorf force-pushed the feat/model-server-observability branch from f6a2ae3 to fb6049a Compare June 26, 2026 13:06
@Glorf

Glorf commented Jun 26, 2026

Copy link
Copy Markdown
Contributor Author

Thanks @cmunley1 @ffrujeri , improvements. are WIP & in test, will let you know when this is ready

@Glorf
Glorf force-pushed the feat/model-server-observability branch 2 times, most recently from 877c23a to cb72c90 Compare June 29, 2026 11:44
@Glorf

Glorf commented Jun 29, 2026

Copy link
Copy Markdown
Contributor Author

Done, @AWarno @cmunley1 @ananthsub @ffrujeri could you take a look?

@ffrujeri
ffrujeri self-requested a review June 29, 2026 16:50
@Glorf
Glorf requested review from AWarno and ananthsub June 29, 2026 19:36
Comment thread nemo_gym/observability.py Resolved
Comment thread nemo_gym/trajectory_capture.py Resolved
ffrujeri
ffrujeri previously approved these changes Jun 29, 2026
@cmunley1

Copy link
Copy Markdown
Contributor

can @bxyu-nvidia take a look?

Glorf and others added 21 commits July 14, 2026 21:57
…pture dir by config key

Address P0 review feedback:
- The /ng-rollout/<id> correlation prefix is now always stripped before routing (the capture
  middleware is always installed), so a default `gym eval` with capture off no longer 404s on
  every prefixed model call. Capture still only records when observability_enabled.
- capture_dirs_from_config resolves a server's default capture dir off its config key (which
  equals the producer's config.name), instead of the "model_server" fallback, so the merge reads
  the same directory the producer wrote to. Warn once when capture is enabled but no dir resolves.

Regression tests added for both (prefix-stripped-when-disabled, resolve-by-config-key, warn-once).

Signed-off-by: Michal Bien <[email protected]>
… cache tokens, off-loop writes

- num_workers>1: flock(LOCK_EX) around the capture append+fsync so concurrent same-rollout writes
  from different worker processes can't interleave/corrupt (the in-process lock is kept).
- Anthropic prompt caching: extract_token_stats folds cache_read + cache_creation into tokens_in for
  the native /v1/messages usage shape (true prompt size) and surfaces cache_creation_tokens; OpenAI
  usage (where cached_tokens is a subset of input_tokens) is left untouched to avoid double counting.
- Offload the capture write+fsync to asyncio.to_thread so it never stalls the event loop; fsync kept
  for durability.
- Document trial_index/turn_index as reserved (step_index is the authoritative per-call index).

Regression tests: concurrent-append integrity, Anthropic fold, OpenAI no-double-count, cache_creation.

Signed-off-by: Michal Bien <[email protected]>
…mbly)

Close the remaining (P2) review threads and the streaming gap so capture is uniform across
harnesses and model providers:

- Streaming (SSE): the capture middleware now reassembles the streamed response per dialect
  (Anthropic Messages, Chat Completions, Responses), so streamed /v1/messages calls -- the path
  Claude Code always uses -- capture response, tokens_*, tool_calls, and reasoning_content just like
  a non-streamed call, and record latency_ttft_ms (time to first byte). Best-effort: an unparseable
  stream leaves response null with request/correlation/status still recorded.
- num_turns: report None when no turn_index markers exist (a turn is not a model step) instead of
  silently equating it to num_steps; num_steps stays authoritative.
- reasoning: accept the vLLM `reasoning` field alongside `reasoning_content`.
- Guard non-dict items in the Responses output loop.
- hermes run(): serialize the run body once (reused for seed + verify + rollout correlation).
- Remove the unused summarize_response/_usage helpers (and the stale "Compact CLU telemetry" note).
- Docs: tighten the turn definition, note turn_index/num_turns are reserved/null, and document that
  streamed responses are now reassembled (+ latency_ttft_ms).

Regression tests: SSE reassembly through the server (Anthropic) + per-dialect reconstruction units +
best-effort-None, num_turns-None-without-markers, reasoning alias, non-dict output guard, raised-call
capture. Affected suites green (observability/e2e 49, hermes 16, rollout 41, claude 44); ruff clean.

Signed-off-by: Michal Bien <[email protected]>
…e refs

Make the capture code self-contained for review: trim a few narrative docstrings/comments and remove
internal issue references. No behavior change.

Signed-off-by: Michal Bien <[email protected]>
…ure loops too

The Responses output loop already skipped non-dict items; apply the same guard to the Chat
Completions tool_calls and Anthropic content-block loops so a malformed payload can't crash
_tool_calls_and_reasoning.

Signed-off-by: Michal Bien <[email protected]>
…ulated fields

- turn_index is derived from user-message boundaries (a turn = control returned to the user) along a
  single linear thread; it is null for non-linear captures (sub-agent interleaving, history
  rewriting, or a delta wire's later user turn). num_turns aggregates the distinct derived turns.
- Run-scope per-rollout capture: a fresh (non-resume) run clears its rollouts' stale capture files
  first, so a re-run does not append onto a previous run's capture.
- Remove the unused trial/turn request-header path and the unpopulated trial_index / retry_count
  fields; step_index and num_steps stay the authoritative per-call / per-rollout counts.

Signed-off-by: Michal Bien <[email protected]>
…gate, SSE/output guards, error category; per-agent correlation; docs

- capture_dirs_from_config resolves a server's dir off the top-level instance key (== producer config.name) instead of the leaf impl key, so a bare observability_enabled config no longer silently no-ops; rewrote the test to drive the real producer (make_capture_store) + consumer and assert they agree.
- claude_code: gate the /ng-rollout prefix on model_server being set, so a real Anthropic endpoint no longer 404s on every call; added a test.
- capture middleware: fold the body parse + SSE reassembly into the off-loop record and guard it (a malformed body can't surface as an ASGI error after the response was sent); flag a 2xx with an unparseable body as capture_parse_error instead of a silent success.
- trajectory_capture: guard a non-list Responses output so a malformed payload can't drop the whole merge.
- correlation: wire the rollout id into mini_swe_agent_2 and gymnasium_agent (which reach the model via a manual base_url / ServerClient.post rather than the base agent); added a gymnasium correlation test.
- tests: cross-process flock regression for the multi-worker capture path.
- docs: link Trial/Turn/Step to key-terminology; correct the streamed-body "buffered" wording and the per-agent correlation note.

Signed-off-by: Michal Bien <[email protected]>
…d chat choices

Post-review follow-ups to 88cfb2c:
- install_trajectory_capture docstring still claimed streamed SSE bodies are "not buffered"; they are buffered for reassembly (the class docstring was already corrected) -- align the wording.
- _tool_calls_and_reasoning: guard the Chat Completions choices with isinstance(list) for parity with the Responses output and Anthropic content branches, so a malformed (non-list) choices can't raise and drop the rollout merge.

Signed-off-by: Michal Bien <[email protected]>
…ring)

- extract_token_stats: use a 0 base for fully-cached Anthropic responses
  (only cache_read/creation, no input_tokens) so tokens_in is preserved
  instead of dropping to null; add regression test
- doc tokens_reasoning as OpenAI/Responses-only (null != 0 for Anthropic)
  and tokens_in as a prompt-size (not cost) metric
- doc num_turns as best-effort/often-null; num_steps authoritative
- document the write-after-forward ordering: the durable capture JSONL is
  the merge's source of truth, num_steps recomputed from it

Signed-off-by: Michal Bien <[email protected]>
…ponses_api_model (#1993)

## Summary

Merges `nemo_gym/model_call_capture.py` and `nemo_gym/observability.py`
into `nemo_gym/base_responses_api_model.py` and deletes both modules.
Pure consolidation — the code moved verbatim, no behavior changes.

The model server is where capture lives: `SimpleResponsesAPIModel`
installs the middleware, the middleware writes the store, and the
record/aggregation helpers read what the middleware wrote. Splitting
that across three modules added indirection without a real seam, so
everything now has a single home.

## Changes

**`nemo_gym/base_responses_api_model.py`** now contains, in reading
order:

1. Model server base classes (`SimpleResponsesAPIModel` etc.) —
unchanged.
2. Capture configuration + rollout-keyed storage
(`ModelCallCaptureConfig`, `CaptureStore`).
3. Observability records (`ModelCallRecord`, token/cache normalization,
read/aggregate helpers).
4. Capture middleware (SSE terminal-event handling, streamed-response
reconstruction, `_CaptureMiddleware`, `install_model_call_capture`).
5. Run-level helpers used by rollout collection
(`model_call_capture_dirs_from_config`,
`clear_model_call_captures_for_rollouts`,
`merge_model_call_capture_into_record`).

**Deleted:** `nemo_gym/model_call_capture.py`,
`nemo_gym/observability.py`.

**Import sites updated:**

- `nemo_gym/rollout_collection.py` — imports the run-level helpers from
the new home.
- `nemo_gym/server_utils.py` — comment pointing at `observability.py`
updated.
- `tests/unit_tests/test_observability.py` → renamed to
`tests/unit_tests/test_base_responses_api_model_capture.py` (it tests
the capture feature of the merged module;
`test_base_responses_api_model.py` already covers the server classes),
all imports and `monkeypatch` targets rewritten.
- `responses_api_models/openai_model/tests/test_app.py` and
`fern/versions/latest/pages/model-server/model-call-capture.mdx` —
import paths updated.

One incidental cleanup: dropped `from __future__ import annotations`
(present in the old modules). The repo is Python 3.12+ so it's
unnecessary, and PEP 563 string annotations can interact badly with
FastAPI's runtime annotation evaluation on the endpoint signatures that
now share the module.

## Notes for review

- No circular imports: `base_responses_api_model`'s dependencies
(`anthropic_converter`, `openai_utils`, `server_utils`) never import
`rollout_collection`, so rollout collection importing the model-server
module is safe.
- The run-level helpers (section 5) are consumed by rollout collection
rather than the model server itself, but they read the store and record
shapes defined right above them — keeping them co-located beats
scattering them into `rollout_collection.py`.

## Testing

- Capture, model-base, and rollout-collection suites pass (97 tests).
- Full core unit suite passes (1175 passed; the 2
`test_opensandbox_provider.py` failures are pre-existing on the base
branch).
- `ruff check` and `ruff format` clean.

Signed-off-by: Felipe Vieira Frujeri <[email protected]>
…ining url_path-style agents (#1994)

Gives every agent a one-call way to correlate its model calls with a
rollout for model-call capture, and wires the remaining url_path-style
agent harnesses with it. Also addresses the PR #1715 review ask to
collapse `apply_rollout_prefix(base_url,
self.rollout_id_from_run(body))` into a single function.

Correlation is now gated on `observability_enabled`: when capture is
off, no agent emits `/ng-rollout/<id>` prefixes anywhere — URLs stay
clean instead of carrying a prefix the model server strips and ignores.

- **`url_path_for_run(url_path, body)`** — returns
`/ng-rollout/<id><url_path>` when observability is enabled and the run
body carries task/rollout indices; otherwise `url_path` unchanged. Used
for downstream calls made while handling `/run` (direct model calls or
self-calls to `/v1/responses`).
- **`base_url_for_run(base_url, body)`** — the base-URL counterpart with
identical gating, for SDK-style harnesses that configure a client once
instead of prefixing each call. This is the one-function collapse
requested in the #1715 review.
- **`url_path_for_request(url_path, request)`** — for agents whose model
calls happen inside `responses()`: carries an inbound prefixed
self-call's rollout id (from the request's path params) onto the
outgoing model call.
- **`rollout_id_from_run(body)`** now applies the observability gate
itself (fail-closed: no usable global config → uncorrelated, never an
error). This is the single gate point, so the base-URL agents already
wired on the parent branch (claude_code, anyterminal, mini_swe_agent_2)
became gated with no changes to their code. It remains public because
some flows need the bare id: claude_code and anyterminal thread it
through layers that have no run body, and hermes' `responses()` derives
it from path params.
- The prefixed self-call route `/ng-rollout/{rollout_id}/v1/responses`
is registered on every agent by the base `setup_webserver()`, so agents
no longer hand-register it (hermes' override removed).

Model calls in these harnesses are now correlated (and therefore
captured when observability is on):

- **New:** `simple_agent`, `non_executing_simple_agent`,
`tool_simulation_agent` (its `responses()` gained a `Request`
parameter), `proof_refinement_agent`, `critpt_agent`, `cvdp_agent`,
`speed_bench_agent`, `browsecomp_agent`, and `aviary_agent` (its
`responses()` receives the full run request in-process, so it uses
`url_path_for_run` directly on the model call).
- **Refactored to the helpers:** `hermes_agent` and `gymnasium_agent`
(previously hand-rolled `rollout_path_prefix` f-strings, applied
unconditionally — they now gate on observability like everyone else),
and `mini_swe_agent_2` (the #1715-flagged line is now
`self.base_url_for_run(base_url, body)`).

The wiring pattern for the common shape (model calls inside
`responses()`, `run()` self-calls `/v1/responses`): `run()` prefixes the
self-call via `url_path_for_run`, the base-registered prefixed route
carries the id in, and `responses()` re-applies it to the model call via
`url_path_for_request`.

Not wired here (bespoke model plumbing, each needs individual
treatment): `harbor_agent`, `finance_agent`, `langgraph_agent`, `tau2`,
`scicode_agent`, `stirrup_agent`, `verifiers_agent`, `swe_agents`,
`mini_swe_agent`.

Hermes and gymnasium previously applied the correlation prefix
unconditionally. Harmless in practice (the model-server middleware
strips it either way), but now the prefix appears only when
`observability_enabled: true`, consistent across all harness styles.

- New unit tests for the helpers: gate on/off, missing indices,
fail-closed on unusable config, inbound-prefix propagation (including
non-Starlette request objects), and default prefixed-route registration.
- `gym dev test`: 1178 passed, 97.27% coverage (gate ≥96%); the only 2
failures are the pre-existing `test_opensandbox_provider.py` ones.
- All touched agent suites pass: simple (6), non_executing_simple (4),
tool_simulation (2), proof_refinement (2), critpt (15), cvdp (3), aviary
(7), gymnasium (8, incl. a new gate-off test), mini_swe_agent_2 (22),
claude_code (43), anyterminal (66).
- Pre-existing failures verified unrelated by stashing: browsecomp's 3
`responses()` tests (Hydra parsing in `app.py:197`) and speed_bench's
collection error (needs its per-server venv). hermes' suite requires
`model_tools` locally; its correlation test exercises the responses-side
path, which is behaviorally unchanged.
- Docs: the correlation section of `model-call-capture.mdx` documents
the helpers and the gating.

Signed-off-by: Felipe Vieira Frujeri <[email protected]>
Signed-off-by: Michal Bien <[email protected]>
Use the canonical ModelServerRef in captured records and assign each persisted call a unique server-generated identifier. Record wall-clock bounds around the downstream ASGI invocation while retaining monotonic latency for duration measurement.

Signed-off-by: Michał Bień <[email protected]>
@Glorf
Glorf force-pushed the feat/model-server-observability branch from 7a964c3 to 5bab0f1 Compare July 14, 2026 20:12
@Glorf
Glorf enabled auto-merge (squash) July 14, 2026 20:14
@Glorf
Glorf requested review from bxyu-nvidia and piojanu July 14, 2026 20:14
@Glorf
Glorf disabled auto-merge July 15, 2026 07:10
@Glorf
Glorf merged commit 05eb7df into main Jul 15, 2026
17 checks passed
@bxyu-nvidia
bxyu-nvidia deleted the feat/model-server-observability branch August 15, 2026 00:51
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

9 participants