Skip to content

feat(episode): report terminal calls and rewards per agent instance - #5254

Open
pthombre wants to merge 2 commits into
pranav/agent-instance-05-agent-session-bindingfrom
pranav/agent-instance-06-per-agent-results
Open

pthombre wants to merge 2 commits into
pranav/agent-instance-05-agent-session-bindingfrom
pranav/agent-instance-06-per-agent-results

Conversation

@pthombre

@pthombre pthombre commented Oct 29, 2026 •

Copy link
Copy Markdown
Contributor

What changed and why

A trainer that trains on one or several agent instances needs, per agent instance, the call it ended on and, optionally, its reward. This PR adds them to the episode result and delivers each captured agent instance's rebuilt response. Gym still decides nothing about which agent instance is trained: it records, and the trainer selects.

  • Result schema. BaseEpisodeResponse gains an optional agent_instances map of AgentInstanceResult (terminal_response_id, optional reward), validated against the name grammar and omitted when unset. Rollout collection copies it onto the result row next to the top-level reward, which stays. An agent's own /run keeps its flat fields.

    {
      "reward": 1.0,
      "agent_instances": {
        "assistant": {"terminal_response_id": "resp_...", "reward": 1.0},
        "user":      {"terminal_response_id": "resp_..."}
      }
    }
  • Terminal ids, filled automatically. While an environment server runs an episode, ServerClient records the response id of every named agent activation it sends, and run_request fills each agent instance's terminal_response_id from its last activation, keeping values and rewards the environment set. nemo_user_sim and SWE-Together need no code of their own. A failed episode reports none.

  • Rewards per agent instance are optional and set by the environment; without one, the trainer chooses the fallback (for example the episode reward).

  • Finalize. Delivery resolves each captured agent instance's terminal against its own calls, using its terminal_response_id, and records the outcome per agent instance. One that names another agent instance's call is recorded as terminal_conflict and masks that agent instance, never a match. One that names no captured call (an agent that minted its own response id) leaves attribution to the chain instead of masking.

  • Gym-side delivery (finalize_rollout_token_capture) puts each named agent instance's rebuilt response, mask_sample and capture metrics into its agent_instances entry, masked per agent instance (PR 3). The top-level response, terminal_response_id and _ng_terminal_model_call_id keep referring to the unnamed agent, or to assistant in a named episode (deviation B1 below).

How it works

Where this PR sits in the overall flow; the highlighted part is what this PR changes.

flowchart LR
  ENV["Environment server<br/>seeds and activates agent sessions"]
  AG["Agent server<br/>session bound to its agent instance"]
  RS["Resources server<br/>verify(), judges"]
  MS["Model server<br/>capture middleware"]
  CM["nemo_gym.correlation<br/>resolve / encode"]
  LG[("Capture ledger and token store<br/>rows carry agent_instance, model_ref")]
  DL["Delivery and manifest<br/>chains and outcomes per agent instance"]
  RR["Episode result<br/>agent_instances map"]
  ENV -->|"/ng-rollout/k/ng-agent-instance/user/v1/responses"| AG
  AG -->|"model calls named user"| MS
  RS -->|"verify.&lt;id&gt; and judge calls"| MS
  MS --> CM
  MS --> LG --> DL --> RR
  ENV --> RR
  classDef this fill:#fde68a,stroke:#b45309,stroke-width:2px,color:#1f2937
  class DL,RR this
Loading
flowchart LR
  ENV["Environment server run_request<br/>recording_agent_activations()"] -->|"named activations via ServerClient"| REC["last response id per agent instance"]
  REC --> RESP["EpisodeResponse.agent_instances<br/>terminal_response_id (+ env rewards)"]
  RESP --> ROW["result row<br/>agent_instances"]
  ROW --> FIN["finalize_rollout_token_capture"]
  SNAP["frozen capture snapshot"] --> FIN
  FIN --> TOP["top-level response<br/>(unnamed agent or assistant)"]
  FIN --> PER["agent_instances.&lt;name&gt;<br/>response, mask_sample, _ng_token_capture"]
Loading

Where this sits in the stack

This is one PR in a stack of draft PRs that implements agent instance identity from the Gym capture identity design (draft 2): several agent instances (assistant, judge, simulated user, debaters) can call model servers in one episode, every record says which one made each call, capture computes lineage and outcomes per agent instance, and the trainer chooses which agent instances it trains on. Gym records; trainers select. Single-agent episodes do not change: an agent's own /run names no agent instance, and its records differ from main only by the new model_ref column.

Each PR is one commit, and its base is the branch of the PR before it, so each diff shows only that PR's change.

  1. refactor(capture): name capture keys capture_key on the ledger control surface #5248 (pranav/agent-instance-00-capture-key-rename): refactor(capture): name capture keys capture_key on the ledger control surface
  2. feat(core): add a correlation module that reads and builds the rollout path #5249 (pranav/agent-instance-01-correlation-module): feat(core): add a correlation module that reads and builds the rollout path
  3. feat(model): record agent instance, agent kind and model server on every capture and model-call record #5250 (pranav/agent-instance-02-record-identity): feat(model): record agent instance, agent kind and model server on every capture and model-call record
  4. feat(capture): compute lineage, terminal chains and outcomes per agent instance and model server #5251 (pranav/agent-instance-03-per-agent-capture): feat(capture): compute lineage, terminal chains and outcomes per agent instance and model server
  5. feat(core): let callers name an agent instance on model calls #5252 (pranav/agent-instance-04-direct-call-names): feat(core): let callers name an agent instance on model calls
  6. feat(agent): bind agent sessions to an agent instance at seed time #5253 (pranav/agent-instance-05-agent-session-binding): feat(agent): bind agent sessions to an agent instance at seed time
  7. feat(episode): report terminal calls and rewards per agent instance #5254 (pranav/agent-instance-06-per-agent-results): feat(episode): report terminal calls and rewards per agent instance (this PR)
  8. refactor(core): read and build every rollout path through the correlation module #5255 (pranav/agent-instance-07-migrate-readers): refactor(core): read and build every rollout path through the correlation module

The first PR's base is main @ 0b8783981. External dependencies: #5083 (session lifecycle names, open) for PR 5. #4969 (rollout prefix hooks for fixed-base-URL clients, open) needs one small change in whichever of #4969 and PRs 1 and 4 lands second: with_rollout_prefix detects an existing prefix with resolve and takes the name from agent_instance_context.

The NeMo RL follow-up (selecting agent instances to train on, one RolloutReceipt per selected agent instance, per-agent rewards) is separate; until NeMo RL bumps its Gym pin, none of these PRs affect NeMo RL training runs.

Issue

No tracking issue exists; the work follows the Gym capture identity design (draft 2) and its implementation plan.

Validation

Tests ran on Slurm (one node, rl-gym.nightly container), each branch against a baseline worktree of main @ 0b8783981:

  • Baseline core suite (python -m pytest -n 32 tests/unit_tests): 33 failed, 12,191 passed, 4 errors. Every one is environmental in this container (docker-compose, OpenSandbox compose, Harbor compose overlay, eval resubmit, reward profile, dataset orchestrator and sandbox supervisor tests, and four exporter modules that fail to import), and the same set fails on every branch of the stack. The docker-compose tests are flaky: one or two of them pass or fail from run to run.
  • Server-local suites ran in one venv per server built from its requirements.txt or pyproject.toml, as gym env test does.
  • pre-commit could not fetch its hook repositories from the build environment, so ruff check --fix, ruff check --select I --fix and ruff format ran with ruff 0.9.9 (the hook's pinned version) on every changed file. The guardwords and end-of-file hooks did not run here; CI runs them.
  • Every commit carries a Signed-off-by line.
  • Core suite on this branch: 33 failed, 12,353 passed, 4 errors, the baseline set exactly.
  • test_agent_instance_results.py (new):
    • an environment server that activates assistant, user, assistant through a real ServerClient reports each agent instance's last activation as its terminal, keeps the reward it set, and ignores unnamed activations and non-agent servers; the result row carries the map;
    • a failed episode reports no map; a single-agent result row is unchanged; invalid names are refused;
    • delivery rebuilds and masks each agent instance on its own: the judge's declared terminal is used when it names the judge's call, ignored when it names no captured call, and recorded as a terminal_conflict (masking only the judge) when it names the assistant's call; the top-level response stays the assistant's.

Rollout evidence

Not yet run. Before this leaves draft: a nemo_user_sim rollout with capture on and the user simulator opted in, checking that both agent instances get terminal ids automatically and that each captured agent instance has its own rebuilt response and mask in the result row.

Compatibility

  • New optional fields: BaseEpisodeResponse.agent_instances and the result row's agent_instances; absent for single-agent episodes.
  • Deviation B1 (for the design's authors): the design has top-level terminal_response_id, _ng_terminal_model_call_id and the rebuilt response belong to the unnamed group only. Here they refer to assistant in a named episode, so consumers that read only top-level fields keep working when nemo_user_sim, tau2, pinchbench and SWE-Together start naming their assistant. Accept as a compatibility rule, or set a removal date.

🤖 Generated with Claude Code

@pthombre pthombre added feature New capabilities, enhancements, or enablement work area:environment Individual environments, benchmarks, verifiers, and environment-specific resources servers area:training Training framework integrations and training-data interfaces complexity:medium Single-domain change with interacting parts or a moderate review surface labels Oct 29, 2026
@copy-pr-bot

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

@marcromeyn marcromeyn 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 from the observability side. The shape works for us: agent_instances[name] = {terminal_response_id, reward?}, single-agent results keep their flat fields, and nothing in aggregation, ng_perf or the health summary reads these entries, so no double counting. One problem:

Terminal ownership is keyed only by response_id (token_capture/consumer.py:331). Two agents on different model servers can get the same response id (each server numbers its own), so the later entry overwrites the first and the first agent is masked with terminal_conflict set to the other. It reproduces with an assistant and a judge on two servers returning the same id. Resolving within each agent and model server first, and reporting a cross-agent conflict only when there's no local match, would fix it; a two-server test would pin it.

@pthombre
pthombre force-pushed the pranav/agent-instance-06-per-agent-results branch from 728a6ad to b2d18b5 Compare November 3, 2026 15:07
@pthombre
pthombre force-pushed the pranav/agent-instance-06-per-agent-results branch from b2d18b5 to 1decce2 Compare November 3, 2026 15:22
@pthombre
pthombre force-pushed the pranav/agent-instance-06-per-agent-results branch 2 times, most recently from 231b229 to c88a010 Compare November 4, 2026 01:33
@ananthsub
ananthsub force-pushed the pranav/agent-instance-06-per-agent-results branch from c88a010 to 3c30736 Compare November 4, 2026 06:08
@pthombre
pthombre force-pushed the pranav/agent-instance-06-per-agent-results branch 2 times, most recently from e576a85 to 9ca171d Compare November 16, 2026 20:45
pthombre and others added 2 commits November 17, 2026 01:08
- BaseEpisodeResponse gains an optional `agent_instances` map of
  AgentInstanceResult (`terminal_response_id`, optional `reward`), validated
  against the name grammar and omitted when unset. Rollout collection copies
  it onto the result row next to the top-level reward, which stays. An
  agent's own /run keeps its flat fields.
- Terminal ids are filled automatically: while an environment server runs an
  episode, ServerClient records the response id of every named agent
  activation it sends, and run_request fills each agent instance's
  `terminal_response_id` from its last activation, keeping values and
  rewards the environment set. nemo_user_sim and SWE-Together need no code
  of their own.
- Delivery resolves each captured agent instance's terminal call against
  its own calls, using its `terminal_response_id`; one that names another
  agent instance's call is recorded as `terminal_conflict` and masks that
  agent instance, and one that names no captured call (an agent that minted
  its own id) leaves attribution to the chain. Each named agent instance's
  rebuilt response, mask and capture metrics go into its `agent_instances`
  entry; the top-level fields keep referring to the unnamed agent, or to
  `assistant` in a named episode.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Pranav Prashant Thombre <[email protected]>
…trip per-agent responses before aggregation

- capture: a declared terminal is a conflict only when the declaring agent instance holds no call with that response id, so two agent instances served the same id no longer mask each other (or the top-level result) depending on capture order
- collection and reverification: the rows sent to /aggregate_metrics drop each agent instance's rebuilt response, as they drop the top-level response
- tests: shared response ids in both capture orders, per-agent and top-level terminals, a lost agent instance's entry, delivery without a primary, single-agent rows, environment-set terminals, and tagged activations

Co-Authored-By: Claude Fable 5.2 <[email protected]>
Signed-off-by: Pranav Thombre <[email protected]>
@pthombre
pthombre force-pushed the pranav/agent-instance-06-per-agent-results branch from 9ca171d to 47339d7 Compare November 17, 2026 09:45
@pthombre
pthombre marked this pull request as ready for review November 20, 2026 17:59

@svcnvidia-nemo-ci svcnvidia-nemo-ci 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.

SHIP WITH CARE

The historical shared-response-ID conflict is fixed in the current source. The ownership check now allows both agents to hold the same ID, and the added regressions cover both capture orders.

I inspected all 14 changed files and traced the affected producer, delivery and aggregation paths. This was source inspection only; I did not execute tests or model rollouts.

RISK: Required real-rollout evidence is missing

The PR explicitly says the planned smoke rollout has not run. AGENTS.md requires representative real smoke rollouts for behavior-changing environment or agent work. The changed episode finalization now obtains public terminal metadata through HTTP response handling, which the mocked activation tests do not validate across running servers.

Could you attach the planned nemo_user_sim rollout with capture enabled, both participants opted in, and training_agent_instances: [assistant, user]? Inspect the saved row and show that both terminal IDs identify their last activations, each captured entry contains its own generation tokens and capture verdict, and the top-level response belongs to the assistant. Also check a single-agent rollout still omits agent_instances. Keep episode rewards unchanged by terminal recording and capture delivery. Unit-test counts do not replace this missing validation.

NOTE: Document the public result contract

Could you extend the existing multi-agent capture guide with a result-row example? It explains naming and capture selection but not the new agent_instances output. Document optional per-agent rewards and trainer-selected fallback, the delivered response and mask fields, and the top-level primary-agent compatibility rule. Distinguish the episode response from the enriched saved row. Static acceptance: the example agrees with the wire schema and still shows that unnamed single-agent results omit the map.


Inline comments (escaped v1):

  • nemo_gym/models/token_capture/delivery.py line 236: RISK: A token-bearing primary response skips every named delivery.

    A row with native assistant tokens in response.output and a captured user root returns through the existing-token shortcut, so this new delivery call never runs. agent_instances.user keeps its terminal ID but gets no response, mask or metrics. The returned _redundant_capture=True also makes retirement succeed, allowing the user's undelivered token records to be deleted. The shortcut previously covered one response; it no longer proves the whole snapshot is redundant.

    Could you make the shortcut response-specific? Keep native top-level tokens unchanged, but build and deliver captured named entries that still need their responses and verdicts. Do not classify the snapshot as wholly redundant while a named sample is undelivered. Simply removing the shortcut is insufficient because a user-only capture must not replace or mask a healthy native assistant response. The exact restructuring needs that distinction, so I am not suggesting a replacement patch.

    Proposed regression: finalize a token-bearing assistant row with one captured user root. Assert unchanged assistant output and the user's own generation tokens, mask and metrics in its entry. Finalize again and assert unchanged outputs. Retain unnamed single-agent existing-token behavior, and check that a failed named build is not retired as successful redundant capture. These checks were not executed.

  • nemo_gym/models/token_capture/consumer.py line 323: RISK: An entirely lost named capture receives no per-agent failure entry.

    With only a pending judge intent, freezing produces entries=() and incomplete_agent_instances={"judge"}. This early return bypasses the loop that creates failed named builds. Finalization sets only the top-level mask, so agent_instances.judge receives neither mask_sample=True nor capture failure metrics. The added lost-judge regression misses this because it also commits an assistant entry.

    Could you let named lost intents reach the existing per-agent loop by replacing this guard with:

        if not snapshot.entries and not any(
            name is not None for name in snapshot.incomplete_agent_instances
        ):
    

    Keep the current failed-build return beneath it. The downstream loop already creates each lost agent's failed build and applies its incompleteness. Empty and purely unnamed snapshots still take the existing branch. Please verify this source-based suggestion before adopting it.

    Proposed regressions: create pending assistant and judge intents without committing either record. Finalize a row carrying their terminal IDs and rewards; assert both entries are masked, have no response, report error="capture contains no token records" and capture_incomplete=True, and keep their reported values. Cover a judge-only pending intent too. Retain the mixed successful-assistant/lost-judge assertions and empty unnamed-capture masking. These checks were not executed.

  • nemo_gym/models/token_capture/delivery.py line 258: RISK: Secondary responses are labeled with the primary agent's model.

    This assignment publishes each complete rebuilt response, but finalization reads model only from the top-level response, and _build_snapshot passes it to every agent. If assistant and judge entries have TokenEntry.model values assistant-model and judge-model, while top-level response.model is assistant-model, the delivered judge response contains judge tokens but says model="assistant-model". Without a top-level model it says model="", despite capture recording the model.

    Could you derive each newly delivered named response's model from its selected captured terminal or delivered chain? Keep the existing top-level response metadata precedence. Do not use snapshot order or model_ref.name: capture order is immaterial, and that name identifies the configured server rather than the model. The exact plumbing between projection and delivery needs a design choice, so I am not suggesting a guessed fallback patch.

    Proposed regression: give assistant and judge entries distinct nonempty model values and assert that each delivered named response has its own model and tokens while the top-level model stays unchanged. Also cover judge-only capture without top-level model metadata and one agent using two model-server groups whose declared terminal selects the second group. Retain shared-response-ID isolation in both capture orders. These checks were not executed.

Review generated by codex. This was a full review. Request a full review with /review reset=true.

@svcnvidia-nemo-ci svcnvidia-nemo-ci added the waiting-on-customer Waiting on the original author to respond label Nov 20, 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

area:environment Individual environments, benchmarks, verifiers, and environment-specific resources servers area:training Training framework integrations and training-data interfaces complexity:medium Single-domain change with interacting parts or a moderate review surface feature New capabilities, enhancements, or enablement work waiting-on-customer Waiting on the original author to respond

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants