Skip to content

feat: route native tasks through environment servers - #3721

Merged
yaoyu-33 merged 15 commits into
mainfrom
ananthsub/episode-orchestration-10-rollout-routing
Sep 30, 2026
Merged

yaoyu-33 merged 15 commits into
mainfrom
ananthsub/episode-orchestration-10-rollout-routing

Conversation

@ananthsub

@ananthsub ananthsub commented Sep 28, 2026 •

Copy link
Copy Markdown
Contributor

What does this PR do?

Routes flat and materialized rows per row, stores Environment Server results without knowing their fields, and keeps the Environment Server that ran each rollout on its record so readers no longer need agent_ref.

Routing:

  • Materialized rows route through environment_server_routes and are sent as episode requests.
  • Flat rows keep compatibility routing through the Environment Server fronting their Agent.

Stored records:

  • An Environment Server result is stored as returned. Rollout collection adds only its own _ng_* keys: _ng_task_id, _ng_environment_server, and _ng_result_type, the implementation name under environment_servers:. A result that uses a collector key is rejected.
  • Every record, including a flat row routed by its Agent, names the Environment Server that ran it and that server's type.
  • Every Environment Server type is scored the same way: through the result's top-level reward, with optional top-level reward_components. A reward nested elsewhere in the result is stored as data, and a result without a top-level reward is unscored rather than scored as zero. Progress output averages each metric over the results that report it, so unscored results do not lower the printed averages or the exported progress reward.
  • Episode failures go to the failure sidecar with terminal and retry semantics.
  • When an Agent sends no trajectory record, collection builds one turn per captured model call that returned a response, from the call's request and response. Health checks and ng_perf then cover Agents that report only invocations, such as Simple Agent sessions and Hermes, or nothing, such as external harnesses. An Agent that sends its own trajectory, such as Terminus-2, keeps its turns, including an empty list when no turn completed.

Readers:

  • Aggregation groups records by _ng_environment_server and resolves Agent-routed rows from a map built once.
  • Reward profiling and reverification group rollouts by _ng_environment_server, falling back to agent_ref for records written before the stamp. Aggregation and these tools share one labelling rule: a run is labelled by its Agent's name only when that name identifies exactly one run, and every run of an Agent that several Environment Servers front is labelled by its own Environment Server. A label that would still repeat also falls back to the server name. Labels do not depend on row order and are unique. Runs with one Environment Server per Agent keep their existing labels. Profiling no longer requires a response.
  • ATIF export and debug output name the Agent that acted in each rollout, or its Environment Server when the row has no agent_ref.
  • Reverification routes a stamped row to its Environment Server's Resources Server and rebuilds the verify body from a materialized row's task_input. A record with no response fails with an error that names its _ng_result_type.
  • Task-data validation, for committed datasets and at collate time, checks a materialized row's task_input.task_data against the Resources Server's schema instead of reading the row as a flat dataset row. A materialized row whose task_data is missing or is not an object is reported as an invalid row.
  • Shard globs exclude *_failures.jsonl sidecars.

Single-agent-turn collection flow

This diagram describes single-agent-turn collection. Other Environment Server types return their own result shapes, which are stored the same way.

sequenceDiagram
    participant C as RolloutCollector
    participant E as EnvironmentServer

    C->>C: Route and stamp each row
    C->>E: POST episode request
    E-->>C: Result or typed failure
    C->>C: Store the result with _ng_* keys, or write a failure sidecar row
    C->>E: Aggregate this server's records
Loading

Stack position

Part 2 of 3. Previous: #3720. Next: #3722.

No issue is linked because this is one layer of the Environment Server stack.

Validation

  • uv run pytest tests/unit_tests/test_rollout_collection.py tests/unit_tests/test_global_config.py tests/unit_tests/test_reward_profile.py tests/unit_tests/test_episode_types.py -q
  • uv run pytest tests/unit_tests/test_rollout_reverification.py tests/unit_tests/test_atif_export.py tests/unit_tests/test_rollout_health.py -q
  • uv run pytest tests/unit_tests/test_task_data.py tests/unit_tests/test_train_data_utils.py -q
  • uv run pytest responses_api_agents/terminus_2_sandboxed_agent/tests -q, in that Agent's own environment, which checks that an Agent's own turns are kept.
  • Tests cover storing a result as returned, rejecting collector keys, stamping Agent-routed rows, building turns from Responses and chat-completions calls, skipping calls that returned nothing, profiling rows without agent_ref, keeping two Environment Servers that front one Agent apart in profiles and aggregation regardless of row order, unique labels when a server name matches another Agent's name, reverification routing and payloads for materialized rows, the reverification error for a record without a response, task-data validation of materialized rows, including malformed and falsey non-object task_data, progress reward that mixed scored and unscored results do not dilute, and scoring only through a result's top-level reward.
  • Aggregating 50,000 flat rows no longer rescans the config per row.

Rollouts

Real-model rollouts through this collector are on #3722.

Compatibility and benchmark impact

Flat rows keep compatibility routing, and records from an Agent's /run keep their shape. They gain _ng_environment_server and _ng_result_type. Materialized rows require explicit taskset routes. Episode failures are no longer stored as zero-reward successes.

Episode records now hold the result fields at the top level with _ng_task_id, instead of a nested result, episode_id, task_id, and _ng_taskset. Rollout files written by earlier revisions of this stack are not readable in the new shape.

@ananthsub
ananthsub added this pull request to stack #3723 September 28, 2026 15:38
@nemo-automation-bot
nemo-automation-bot Bot requested review from a team September 28, 2026 15:38
@ananthsub
ananthsub force-pushed the ananthsub/episode-orchestration-10-rollout-routing branch from 4771fdd to 29fa0c4 Compare September 28, 2026 15:41
@ananthsub
ananthsub removed this pull request from stack #3723 September 28, 2026 15:41
@ananthsub
ananthsub added this pull request to stack #3725 September 28, 2026 15:43
@yaoyu-33 yaoyu-33 added area:evaluation Evaluation, rollout collection, reward profiling, comparison, and exporters complexity:high Cross-component or shared-contract change with a large review surface feature New capabilities, enhancements, or enablement work needs-review PR is ready for code review and waiting on a reviewer labels Sep 28, 2026
@ananthsub
ananthsub force-pushed the ananthsub/episode-orchestration-10-rollout-routing branch from 29fa0c4 to c106b77 Compare September 28, 2026 15:48
@ananthsub
ananthsub force-pushed the ananthsub/episode-orchestration-10-rollout-routing branch from c106b77 to 03839e9 Compare September 28, 2026 16:03
ananthsub and others added 14 commits September 29, 2026 23:25
…ts per row (#3576)

## What does this PR do?

Lets one rollout-collection batch mix native (materialized) tasksets and
compatibility-routed flat rows, with no new agent × resources pairing,
and keeps the chosen environment server's identity on every row through
shards, retries and results.

- A materialized task (`task_id.taskset` plus `task_input`) now routes
by `environment_server_routes` in **every** `environment_routing_mode`;
it is the native episode request and no agent-server `/run` accepts it.
- A flat row keeps following the mode: `agent` (default) resolves the
row's own environment server at dispatch, as today; `legacy` sends every
flat row to `environment_server_name`; `taskset` stays native-only and
rejects flat rows, so a native run cannot silently pick up legacy input.
- A materialized row whose taskset has no entry in
`environment_server_routes` fails at preprocessing with the missing
route named. (#3491 no longer has a `tasksets` config block, so routes
are the only declaration.)
- Two knobs that cannot apply to a materialized row now fail with the
fix named instead of a `KeyError`: `num_repeats_add_seed` (the seed
lives in the top-level prompt, which a materialized row keeps under
`task_input`).
- No config or YAML changes: routes point at existing environment-server
deployments, and flat rows reach the `legacy_agent` servers that #3490
generates in front of each existing pairing.

The `_ng_environment_server` stamp, written once at preprocessing,
already reaches the materialized input file, resume retries
(`_load_from_cache` re-reads the stamped rows) and result rows; this PR
does not change that path.

## Interaction flow

```mermaid
sequenceDiagram
    participant C as Rollout collector
    participant N as Native environment server, one per taskset route
    participant L as legacy_agent environment server, one per pairing
    participant A as Agent server

    Note over C: preprocess stamps _ng_environment_server once per row
    Note over C: materialized row routes by task_id.taskset, flat row follows the routing mode
    C->>N: POST /run with the episode request, episode_id plus task
    C->>L: POST /run with today's flat row
    L->>A: relay /run
    N-->>C: SingleAgentEpisodeResponse
    L-->>C: legacy result
```

## Stack position

Stacks on #3491 (part 12,
`ananthsub/episode-orchestration-10-rollout-routing`) and touches only
`nemo_gym/rollout_collection.py`, which #3492 does not modify. It can be
squashed into #3491 if preferred, since it changes the semantics of the
routing mode that PR introduces.

Follow-up (separate PR): aggregate metrics grouped by
`_ng_environment_server` instead of `agent_ref.name`, and native
`failure` replies written to the failures sidecar, so identity also
persists through `gym eval aggregate` and retries of native episodes.

## Validation

- `pytest tests/unit_tests/test_rollout_collection.py
tests/unit_tests/test_global_config.py -q` → 383 passed.
- Adversarial review (four lenses, two independent refuters per finding,
each reproduced against the code): the two surviving findings
attributable to this PR are fixed in the second commit.
- New tests in `TestEnvironmentServerRouting`: a mixed batch dispatches
the native row to its taskset's route as an episode request and the flat
row to the server fronting its agent as today's flat body; a
materialized row without a route fails before dispatch; `legacy` mode
stamps flat rows with `environment_server_name` and materialized rows by
taskset, then dispatches both through `run_examples` against a
`legacy_agent` server that binds no resources server;
`num_repeats_add_seed` on a materialized row fails before dispatch;
`taskset` mode still rejects flat rows.
- `ruff check` and `ruff format --check` pass.

## Compatibility and benchmark impact

Default behavior for flat-only batches is unchanged. Materialized rows
in `agent` mode previously had no route and could not be dispatched;
they now require `environment_server_routes`, which is what `taskset`
mode already required.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Signed-off-by: Adil Asif <[email protected]>
Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
…tive failures, retries and aggregation

A native environment-server reply (`BaseEpisodeResponse`) is projected when the
collector persists it: a handled `failure` becomes a failures-sidecar row with
`_ng_failure_class=environment_server_failed`, `_ng_failure_terminal` from the
reply, and the row's `_ng_environment_server` stamp, so resume retries a
non-terminal failure on the same server and never a terminal one; a `result`
keeps the native record and gains the top-level `reward` and mask flag that
progress accounting and the health check read.

`/aggregate_metrics` is grouped by the environment server stamped on each row,
falling back to the server that fronts the row's agent as before, and native
records are unwrapped to their `result.verification` before scoring. Each entry
in `_aggregate_metrics.json` now names its `_ng_environment_server` beside the
`agent_ref` label, and `gym eval aggregate` inherits the grouping because result
rows carry the stamp across shards.

A run that configures `environment_server_routes` sets up the environment-server
client even in the default routing mode, so stamped rows resolve against the
merged config.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Signed-off-by: Adil Asif <[email protected]>
…agent observations, keep aggregate labels distinct

Projection of a BaseEpisodeResponse now happens only for rows the collector
dispatched as native episode requests, and the shape check requires object
identities, so a legacy verify reply that echoes identity fields is never
turned into a sidecar row. A non-object `failure` fails with the episode
named instead of an AttributeError outside the dispatch guard.

A native result lifts `result.agent_observations` to `ng_agent_observations`,
as the legacy adapter does, so trajectory capture and the health check see
the agent's evidence. Collector-stamped `ng_perf` travels with the unwrapped
record into `/aggregate_metrics`.

Aggregation labels: two environment servers bound to one agent (a native
server and its legacy_agent twin) produced duplicate `agent_ref` entries,
which `gym eval compare` rejects; the second is now labelled by its own
name. A stamped server missing from the aggregate-time config fails naming
the server and the available ones instead of an omegaconf KeyError.

The end-to-end resume test no longer installs a global-config fallback, so it
fails if a run with routes does not set up the environment-server client.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Signed-off-by: Adil Asif <[email protected]>
… config scans

Aggregation resolved the environment server for every unstamped flat
row by scanning the whole config, and resolved a native server's bound
agent for every row. At 50k flat rows this took about 17 seconds in
default agent routing, including `gym eval aggregate` over shards.

Build the agent-to-server map once per aggregation and resolve each
server's bound agent once. Grouping and labels are unchanged.

Signed-off-by: Ananth Subramaniam <[email protected]>
…urned

The collector projected single-agent-turn replies field by field: it
copied reward and mask_sample next to the nested result, lifted agent
observations, and unwrapped `result.verification` again for
aggregation. Records stored reward twice, kept a dead `failure: null`,
and lacked the `response` that profiling, health checks, token capture,
and reverification read.

Store any Environment Server result as returned. The collector adds only
its own `_ng_*` keys: `_ng_task_id`, `_ng_environment_server`, and
`_ng_result_type`, the implementation name under `environment_servers:`.
A result that uses a collector key is rejected. Every record, including
agent-routed flat rows, names the Environment Server that ran it. A
result without a reward is unscored rather than scored as zero.

Readers that required agent_ref now label a rollout by its agent when
the row names one and by its Environment Server otherwise, so existing
labels do not change. Profiling tolerates a missing response.
Reverification routes stamped rows to their Environment Server's
Resources Server and rebuilds the verify body from a materialized task.

Signed-off-by: Ananth Subramaniam <[email protected]>
Health checks read per-turn evidence: each model call's question,
answer, reasoning, and tool calls. Only agents that assembled their own
trajectory record had turns. Agents that report only invocations, such
as Simple Agent sessions and Hermes, or nothing, such as external
harnesses, got a turns_unavailable gap and unobserved health checks.

When an agent sends no trajectory record, build one turn per captured
model call that returned a response. A call belongs to the invocation
whose model_calls reference it, or to the only invocation, or to root
when there are none. A call that cannot be attributed to one of several
invocations is skipped. An agent that sends its own trajectory keeps
its turns, including an empty list when no turn completed.

Signed-off-by: Ananth Subramaniam <[email protected]>
Reward profiling, reverification, and ATIF export labelled a rollout by
its agent_ref first. Records from two Environment Servers that front
the same Agent, such as a legacy_agent relay and a single-agent-turn
server for Hermes, were therefore merged into one group, while
aggregation already kept them apart.

Group by the Environment Server stamp, falling back to agent_ref for
older records, and label groups the way aggregation does: by the Agent's
name, unless another Environment Server already uses it. Runs with one
Environment Server per Agent keep their existing labels. ATIF export and
debug lines still name the Agent that acted in each rollout.

Reverification now names a record's result type when the record has no
`response`, instead of failing with a KeyError.

Signed-off-by: Ananth Subramaniam <[email protected]>
Task-data validation read every committed row as a flat dataset row.
A materialized task, `{task_id, task_input}`, was therefore reported as
carrying undeclared `task_id` and `task_input` keys, and its actual task
data was never checked.

Validate `task_input.task_data` against the schema for a materialized
row. Its fields are already in their final position, so the legacy
misplacement check does not apply.

Signed-off-by: Ananth Subramaniam <[email protected]>
Run labels for aggregation, profiling, and reverification gave an
Agent's name to whichever Environment Server appeared first, so twin
servers swapped labels with row order. A stamped record and an older
record of the same Agent could also both be labelled with the Agent's
name.

Label a run by its Agent's name only when that name identifies exactly
one run. Every run of an Agent that several Environment Servers front
is labelled by its own Environment Server, and a label that would still
repeat falls back to the server name. Aggregation and the report tools
share this rule, and every label is unique.

Task-data validation also records a materialized row whose
`task_input.task_data` is not an object as an invalid row, instead of
failing while converting it.

Signed-off-by: Ananth Subramaniam <[email protected]>
A materialized row's `task_input.task_data` was defaulted with `or {}`
before the object check, so `[]`, `""`, `0`, `False`, `None`, or a
missing value validated as empty task data whenever the schema had no
required fields.

Check the raw value: anything other than an object is an invalid row.

Signed-off-by: Ananth Subramaniam <[email protected]>
…eport them

Progress output divided every metric's sum by the number of results.
A result without a reward, which is now unscored rather than a zero,
still counted toward that total, so mixed scored and unscored results
lowered the printed averages and the exported progress reward.

Count, per agent, how many results report each metric and average over
that count. Reward progress and its lower bound use the number of
results that report a reward, and are omitted while none do.

Signed-off-by: Ananth Subramaniam <[email protected]>
…ored

Every Environment Server type is scored through its result's top-level reward and optional reward_components. A reward nested elsewhere in the result is stored as data, and a result without a top-level reward is unscored. A test pins the rule.

Signed-off-by: Ananth Subramaniam <[email protected]>
…urns

Do not assign unreferenced judge or auxiliary captures to the sole invocation or an invented root. Preserve all captured calls, but synthesize turns only from explicit call-ID or response-ID references. Harnesses without ownership evidence retain the turns_unavailable gap.

Add regression coverage for policy/judge separation, token health and coverage, no-invocation captures, and call-ID/response-ID matching. No changes to scoring, dispatch, or reverification.

Signed-off-by: yaoyu-33 <[email protected]>
@copy-pr-bot

copy-pr-bot Bot commented Sep 29, 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.

yaoyu-33
yaoyu-33 previously approved these changes Sep 29, 2026

@yaoyu-33 yaoyu-33 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 after 5963f0c. Synthesized turns now require explicit ownership; judge/unowned captures remain raw evidence, and missing ownership remains unobserved. 1,400 targeted tests and full pre-commit passed. No model rerun (collector-only change). The split-binding reverify edge case remains a non-blocking follow-up.

Resolve conflicts with bounded rollout admission (#3497). The collection loop keeps
main's bounded, optionally non-retaining structure and applies this branch's changes
inside it: episode replies become records, records carry the Environment Server name
and type, rows are counted by the server they dispatch to, metrics are averaged over
the results that report them, and token capture resolves the agent through the row's
server. run_examples accepts both environment_server_name and max_resident_tasks.

Signed-off-by: Ananth Subramaniam <[email protected]>
@ananthsub

Copy link
Copy Markdown
Contributor Author

/ok to test 6bc9aa9

@github-actions

Copy link
Copy Markdown
Contributor

🔄 Merge queue validation started! You can track the progress here: https://github.com/NVIDIA-NeMo/Gym/actions/runs/36650406375

This branch was previously deployed

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

Labels

area:evaluation Evaluation, rollout collection, reward profiling, comparison, and exporters complexity:high Cross-component or shared-contract change with a large review surface feature New capabilities, enhancements, or enablement work needs-review PR is ready for code review and waiting on a reviewer sla:triage-overdue Review assignment is over the one-business-day SLA

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants