Skip to content

feat(episodes): enforce generation budgets across rollout retries - #6453

Closed
gerryche123 wants to merge 1 commit into
NVIDIA-NeMo:mainfrom
gerryche123:tongc/episode-generation-budget
Closed

gerryche123 wants to merge 1 commit into
NVIDIA-NeMo:mainfrom
gerryche123:tongc/episode-generation-budget

Conversation

@gerryche123

Copy link
Copy Markdown
Contributor

What does this PR do?

A task-specific generation limit must not cap unrelated episodes sharing a model server, and retrying an episode must not reset its allowance. This adds optional max_model_calls to the existing single-agent environment servers. They carry the limit, their configured agent server, and the typed EpisodeId.rollout_id through the existing correlation URL. The model server atomically admits calls against that logical rollout and stops the explicit owner using the current attempt's capture key once the allowance is exhausted.

The model server's generation_budget_state_dir supplies shared storage only. Episodes without a budget remain uncapped on the same server. Failed backend dispatches consume their reserved admission; an ambiguous transport failure cannot safely refund a generation. Budgeted requests require one completion. The refused request creates no generation/capture intent.

This reuses the merged rollout-stop lifecycle from #5145, the existing supervisor timeout/file-collection path, and the capture store's filesystem locking. It connects the six remaining sandboxed adapters to the shared stop hook (Codex already does so) and gives Docker uploads independent bounded CLI capacity, including parent-directory creation. The provider must be able to deliver the expiry marker while its normal exec slots are occupied. No new agent loop, proxy, task, scorer, model-output rewrite or scheduler is introduced.

This is the core dependency requested in the budget review of #6254. It contains no CAD task/configuration/scorer files, shared image-converter changes, or Hermes image-runtime feature. #5838's resource episode-status polling is not needed for generation admission and is not included.

Compatibility and benchmark impact

max_model_calls is unset by default. Sampling and task contents remain unchanged. Every model server serving capped calls must use the same fresh, run-specific budget directory and retain it until all requests for that run are retired. Distinct samples must have distinct logical rollout IDs; task IDs are not counter keys. Retries share their original typed rollout ID without new suffix guessing. Missing storage, malformed budgets and inconsistent logical identity fail before backend dispatch. Stop failures remain failures rather than being treated as successful grading.

Only explicitly capped episodes stop early. A cap is a count of generation admissions, including auxiliary calls carrying that episode's URL, not tool actions or guaranteed successful responses. The existing environment remains responsible for verification and scoring after the agent stops.

Validation

  • On this upstream-only core tree: 781 tests passed, 2 skipped across correlation, sampling, ServerClient, agent sessions/stops, single-agent environments, budget dispatch/capture, Docker provider and Claude sandbox modules.
  • CPU HTTP control: first attempt6 calls + retry4 calls; call11 is refused and targets the retry's owning session. A separate sample of the same task gets its own allowance. Eleven uncapped calls on the same ModelServer succeed without a counter. Sampling0.6/0.95/64 survives environment URL → agent middleware/URL builder → model dispatch.
  • Existing concurrent-process counter, failed-stop, no-refused-capture-intent and ten-call receipt controls remain covered. No policy generation or native CLI rollout is claimed by these fixtures.
  • Full pre-commit run --all-files: all available hooks passed, including import-linter. The private guardword hook reported its catalog unavailable and skipped that check.
  • Representative real-model sandboxed-harness smoke on final source is still pending. This prepared dependency must not be described as seven-client real-model acceptance or training-token qualification.

Source provenance

The atomic budget implementation and associated model-base/test code were originally adapted from NVIDIA NeMo Gym (Apache-2.0), revision d8c548915431e59169890d34cd8cea56ef2a905e, at https://gitlab-master.nvidia.com/tongc/gym/-/tree/d8c548915431e59169890d34cd8cea56ef2a905e. Original and affected paths are nemo_gym/models/rollout_budget.py, nemo_gym/models/base_responses_api_model.py, tests/unit_tests/models/test_rollout_budget.py, and tests/unit_tests/models/test_rollout_budget_integration.py; their provenance headers remain. The episode budget/correlation changes reuse this repository's own APIs.

Extract the core dependency requested by CAD PR NVIDIA-NeMo#6254. Episodes carry an optional generation limit and explicit stop owner; retries share their typed logical rollout identity. Reuse atomic capture-store locking and the existing native rollout-stop lifecycle. Includes the adapter stop hooks and independent Docker upload capacity; excludes CAD and image feature changes.

Validation: 781 tests passed with two optional skips. Full pre-commit passed available hooks; private guardword catalog unavailable. Real-model client qualification remains pending.
Signed-off-by: Tong Che <[email protected]>
@copy-pr-bot

copy-pr-bot Bot commented Nov 19, 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.

@nemo-automation-bot nemo-automation-bot Bot added the community-request Issue reported or requested by someone from the community label Nov 19, 2026
@svcnvidia-nemo-ci svcnvidia-nemo-ci added risk:high Autobot PR risk: high feature New capabilities, enhancements, or enablement work area:core Shared APIs, servers, telemetry, health, and registries labels Nov 19, 2026
@yfw
yfw marked this pull request as ready for review November 19, 2026 19:06
@yfw
yfw requested a review from a team as a code owner November 19, 2026 19:06

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

HOLD. With max_model_calls set, no capped episode can start today. After that fix, retries and repeated runs are scored with part of their allowance already used.

Please rebase on main first. Two merged PRs now conflict with this one. #6410 conflicts in the except of DockerProvider._run, where main already kills a cancelled docker command with kill_cancelled_command (provider.py L361-L363). #6020 conflicts in the final return of ClaudeCodeAgent._sandbox_response (app.py L897), where the report_rollout_stop call needs to be added again.

Thank you for splitting the budget out of #6254 into its own core PR. It takes up both asks of that review: stop support for each listed agent, and a cap that the environment server carries for each episode. The shape is right. Only the model server sees the calls of a sandboxed harness. The stop reuses the rollout-stop route from #5145, and Docker uses the existing upload capability. With max_model_calls unset, the budget adds no path segment and no file I/O. The parser and capture tests give the same results at the base and at head.

What blocks the merge:

Process state: the PR is a draft. CI has not run yet, because it waits for a maintainer to approve CI for the full head SHA. DCO passes. A local pre-commit run --all-files at head passes with no rewrites. Our local runs were CPU only.

Generated by Claude Code

agent_create_http_response = await self.server_client.post(
server_name=self.config.agent_server.name,
url_path="/v1/agent_sessions",
url_path=self._budget_path(request, "/v1/agent_sessions"),

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.

environment_servers/single_agent_turn/app.py:618

With max_model_calls set, the agent seed goes to a path that no agent serves, so every capped episode fails with a 404.

How the seed path breaks:

  1. _budget_path puts /ng-rollout/<capture key> in front of /v1/agent_sessions and then adds the budget segment (L920-L928).
  2. On the agent, GenerationBudgetMiddleware removes only the budget segment (generation_budget.py L25-L29). The path is now /ng-rollout/<capture key>/v1/agent_sessions.
  3. Agents serve the seed only at the plain /v1/agent_sessions (base_responses_api_agent.py L959-L961). Only /v1/responses has /ng-rollout/{rollout_id} routes (L934-L935). So the agent answers 404.
  4. A 404 is not retried (base_environment_server.py L228-L233). The episode ends as a terminal agent failure with no reward, and gym eval submit ends with "EVAL FAILED".

The real Pi, OpenCode, Claude Code and Codex agent apps all answer 404 to this path. With max_model_calls unset, the seed goes to the plain /v1/agent_sessions, which they serve.

Suggested fix:

Suggested change
url_path=self._budget_path(request, "/v1/agent_sessions"),
url_path="/v1/agent_sessions",

No agent that can be stopped needs the budget at seed time. The agents that can be stopped add it to their harness's model URL during the agent's /v1/responses call, and that call still carries the budget.

Please also add this regression test to environment_servers/single_agent_turn/tests/test_app.py, with the two imports at the top of the file. _Client, _environment_server and _request are already imported there. The test sends the seed to a real agent app and gives its reply to the environment server. It fails at head with a 404 and passes with the fix.

from fastapi.testclient import TestClient

from tests.unit_tests.agents.test_agent_sessions import _stoppable_agent


async def test_a_capped_episode_seeds_a_real_agent() -> None:
    agent = _stoppable_agent([])
    agent._installed.set()
    agent_http = TestClient(agent.setup_webserver())
    seed_statuses = []

    class _SeedForwardingClient(_Client):
        async def post(self, server_name: str, url_path: str, **kwargs):
            if not url_path.endswith("/v1/agent_sessions"):
                return await super().post(server_name, url_path, **kwargs)
            reply = agent_http.post(url_path, json=kwargs["json"])
            seed_statuses.append(reply.status_code)
            canned = await super().post(server_name, "/v1/agent_sessions", **kwargs)
            return type(canned)(reply.json(), canned.headers)

    environment_server, _ = _environment_server(client_type=_SeedForwardingClient)
    environment_server.config.max_model_calls = 10

    result = await environment_server.run_request(_request())

    assert seed_statuses == [200]
    assert result.failure is None, result.failure

A second seed route at /ng-rollout/{rollout_id}/v1/agent_sessions is not a good fix. With several workers, the session router finds the session of a seed only on paths that match its seed pattern (session_routing.py L156, L690-L694). The budget segment breaks that match, so the seeded session gets no owner.

Why the PR's tests pass

Comment on lines +917 to +929
def _budget_path(self, request: SingleAgentTurnRequest, path: str) -> str:
if self.config.max_model_calls is None:
return path
if not path.startswith("/ng-rollout/"):
path = f"/ng-rollout/{request.episode_id.capture_key}{path}"
return with_generation_budget(
path,
EpisodeGenerationBudget(
max_calls=self.config.max_model_calls,
rollout_id=request.episode_id.rollout_id,
agent_server=self.config.agent_server.name,
),
)

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.

environment_servers/single_agent_turn/app.py:917-929

The counter is per rollout ID, so a retry or rerun starts with calls it never made, can be stopped early, and is still scored.

reserve names the counter file after EpisodeId.rollout_id (rollout_budget.py L41-L42), and every attempt of a rollout has the same ID. A budget stop ends as an incomplete response, and the outcome policy sends every response that is not failed to verification (agent_outcome.py L137-L138). Only the ng_rollout_stop metadata marks the stop, and no code in Gym reads it. With the seed path fixed, the first three cases below ran, and each episode was scored after fewer than max_model_calls calls. The fourth case comes from reading NeMo RL's code.

  • A retry after an infrastructure failure. The retry gets a new attempt index (rollout_records.py L977) and new sessions (app.py L238-L242), but keeps the rollout ID. With a cap of 10, a first attempt that failed after 7 calls left its retry 3 calls. A first attempt that failed after 10 calls left its retry 0 calls, so the retry was graded with no model output.
  • A second gym eval run against the same running servers. Default IDs such as 0-0 repeat in every run (rollout_collection.py L535). Rows that needed 8 calls in the first run were stopped after 2 calls in the second run.
  • A crash restart. All seven harnesses are restart_only (base_responses_api_agent.py L761), so a crash starts the episode again from its input. The new attempt inherits the count of the crashed attempt.
  • NeMo RL. A resume of the path without token capture restores the task index (single_controller.py L542-L543) that names those rollouts (rollout_manager.py L1272). Dataset rows that carry _ng_task_index keep it in every epoch (rollouts.py L2474-L2487). These episodes start with old counts, and NeMo RL trains on them with their reward.

The first case turns an infrastructure failure into a low score. AGENTS.md asks to "Separate infrastructure failures from task failures" (AGENTS.md L219).

This fix replaces the PR's rule that "retrying an episode must not reset its allowance". The retries in the #6254 review came from the broken stop, which answered 501 past the cap. With a working stop, a budget stop is graded and causes no retry. A retry then follows a real failure, such as an infrastructure error, and needs the full cap. Each graded attempt still makes at most max_model_calls calls.

Suggested fix: count calls per agent session. SessionHandles.new() makes a new agent_session_id for each episode that starts from its input (app.py L122-L128). The change:

  • EpisodeGenerationBudget gets a required agent_session_id field.
  • _invoke_agent passes the episode's handles to _budget_path, which fills agent_session_id from them. _budget_path no longer adds /ng-rollout/, because its only caller is the agent's /v1/responses path, which already has that prefix.
  • In rollout_budget.py, reserve names its key argument agent_session_id and uses it for the counter path and the lock (L34-L42).
  • admit passes budget.agent_session_id to reserve (L68). It keeps rollout_id for its 422 refusal of a call that names another rollout.
  • In the docstring of reserve, "late retries" becomes "the session's late calls" (L38-L39).
  • The glossary row and the "Retries share the logical rollout's counter" sentence now describe one count per agent session.

The rollout_budget.py edits are listed above. The diff below covers the other three files, so it is a plain diff. It assumes that the seed at L618 already posts to the plain /v1/agent_sessions. With it, the retry and second-run cases above finished their tasks, and a retry that used all 10 calls was still stopped.

The diff (code and docs)
--- a/nemo_gym/core/generation_budget.py
+++ b/nemo_gym/core/generation_budget.py
@@ -14,12 +14,13 @@
 
 
 class EpisodeGenerationBudget(BaseModel):
-    """A cap shared by all attempts of one logical rollout, with its explicit stop owner."""
+    """A cap on one agent session's generations, with its explicit stop owner."""
 
     model_config = ConfigDict(extra="forbid", frozen=True, strict=True)
     max_calls: int = Field(gt=0)
     rollout_id: str = Field(min_length=1, pattern=r"^[A-Za-z0-9][A-Za-z0-9._-]*$")
     agent_server: str = Field(min_length=1)
+    agent_session_id: str = Field(min_length=1, pattern=r"^[A-Za-z0-9][A-Za-z0-9._-]*$")
 
     def segment(self) -> str:
         return base64.urlsafe_b64encode(self.model_dump_json().encode()).decode().rstrip("=")
--- a/environment_servers/single_agent_turn/app.py
+++ b/environment_servers/single_agent_turn/app.py
@@ -660,7 +660,7 @@
         try:
             agent_http_response = await self.server_client.post(
                 server_name=self.config.agent_server.name,
-                url_path=self._agent_responses_path(request),
+                url_path=self._budget_path(request, self._agent_responses_path(request), handles),
                 json=params,
                 cookies=handles.agent_cookies,
                 # The episode's only activation.
@@ -910,21 +910,18 @@
         capture_segment = f"/{TOKEN_CAPTURE_PATH_SEGMENT}" if token_capture else ""
         # The agent is the one the training framework trains, so its model calls carry the episode's values.
         sampling_segment = model_sampling_path_segment(self.model_sampling_segment(request, trained=True))
-        return self._budget_path(
-            request, f"/ng-rollout/{request.episode_id.capture_key}{capture_segment}{sampling_segment}/v1/responses"
-        )
+        return f"/ng-rollout/{request.episode_id.capture_key}{capture_segment}{sampling_segment}/v1/responses"
 
-    def _budget_path(self, request: SingleAgentTurnRequest, path: str) -> str:
+    def _budget_path(self, request: SingleAgentTurnRequest, path: str, handles: "SessionHandles") -> str:
         if self.config.max_model_calls is None:
             return path
-        if not path.startswith("/ng-rollout/"):
-            path = f"/ng-rollout/{request.episode_id.capture_key}{path}"
         return with_generation_budget(
             path,
             EpisodeGenerationBudget(
                 max_calls=self.config.max_model_calls,
                 rollout_id=request.episode_id.rollout_id,
                 agent_server=self.config.agent_server.name,
+                agent_session_id=handles.agent_session_id,
             ),
         )
 
--- a/fern/versions/latest/pages/about/concepts/key-terminology.mdx
+++ b/fern/versions/latest/pages/about/concepts/key-terminology.mdx
@@ -71,3 +71,3 @@
 | **Resources session** / **agent session** | The per-episode state a resources server or an agent server holds, named by `resources_session_id` or `agent_session_id`. | Resources Server session |
-| **Episode generation budget** | A limit on generation admissions shared by every retry of one `EpisodeId.rollout_id`; its owning agent is stopped through the existing rollout-stop route when no admission remains. | per-model cap, tool-action limit |
+| **Episode generation budget** | A limit on the generation admissions of one agent session, after which its agent is stopped through the existing rollout-stop route. | per-model cap, tool-action limit |
 | **Episode session** / **episode seed** | A session an environment server seeds through `/seed_session` or `/v1/agent_sessions`, and that seed. | typed session, typed seed, Environment Server session |
@@ -132,5 +132,5 @@
 `single_agent_turn` and `single_agent_turn_legacy` accept optional `max_model_calls` (unset by default).
-The environment server carries that limit, the explicit agent server name, and the logical rollout ID
-in `/ng-generation-budget/<values>` alongside the existing correlation and sampling segments.
-Retries share the logical rollout's counter; different samples must retain their distinct rollout IDs.
+The environment server carries that limit, the agent server name, the logical rollout ID and the episode's agent
+session ID in `/ng-generation-budget/<values>`. It sits beside the existing correlation and sampling segments.
+The model server counts calls per agent session, so a retry that starts from the task input gets its own count.
 The current attempt's capture key still identifies the agent to stop. A task ID is not a budget identity.
Test changes that go with the diff
  1. Every EpisodeGenerationBudget(...) in test_rollout_budget.py and test_rollout_budget_integration.py names agent_session_id, and the tests that fill a counter first reserve that session's key.
  2. Rename test_episode_budget_survives_agent_url_and_retry_but_not_uncapped_episode (L217) to test_episode_budget_survives_agent_url_and_counts_each_attempt_but_not_uncapped_episode, and give each attempt its own SessionHandles.new().
  3. In that test, the first attempt makes 6 calls and the retry makes its own 10. The retry's 11th call is refused, and the stop goes to /rollouts/sample-one-a1/stop. The counter files hold 6, 10 and 1 (first attempt, retry, other sample), and no file is named after a rollout ID.
  4. Drop the seed-path parse (L322-L325), because the seed carries no budget.
  5. In the same test, import _environment_server from tests.helpers.single_agent_turn instead of from the server's tests/test_app.py (L219). The current import adds that whole test module to the core coverage run.

except Exception:
LOGGER.warning("Failed to close PTY session %s of %r", session.session_id, name, exc_info=True)

def uploads_independent_of_execs(self) -> bool:

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_gym/sandbox/providers/docker/provider.py:883

Docker now declares independent uploads, so an existing core test that expects the old answer for Docker fails, and the core CI job goes red.

test_which_sandboxes_can_stop_a_running_harness[docker-None-False] lists Docker under "Uploads share the CLI slots or worker threads that running commands hold" (test_sandbox_session.py L1020-L1021). It asserts not issubclass(provider_class, SupportsSandboxIndependentUploads) (L1034). With uploads_independent_of_execs on DockerProvider, it fails with assert not True. It passes at the base. The test has no sandbox marker, so the core CI job runs it.

Suggested fix: move Docker to the rows that can stop a running harness, and let the test build a real DockerProvider. The file is outside the PR's diff, so this is a plain diff:

--- a/tests/unit_tests/agents/test_sandbox_session.py
+++ b/tests/unit_tests/agents/test_sandbox_session.py
@@ -1017,8 +1017,8 @@
         ("opensandbox", {"operations": {"background_exec": True}}, True),
         # A running foreground command holds one of the shared HTTP pool's connections.
         ("opensandbox", {"operations": {"background_exec": False}}, False),
+        ("docker", {}, True),
         # Uploads share the CLI slots or worker threads that running commands hold.
-        ("docker", None, False),
         ("apptainer", None, False),
         ("enroot", None, False),
         ("openshell", None, False),
@@ -1028,7 +1028,8 @@
         ("ecs_fargate", None, False),
     ],
 )
-def test_which_sandboxes_can_stop_a_running_harness(name, options, independent):
+def test_which_sandboxes_can_stop_a_running_harness(name, options, independent, monkeypatch):
+    monkeypatch.setattr("nemo_gym.sandbox.providers.docker.provider._require_docker", lambda: "docker")
     provider_class = get_provider_class(name)
     if options is None:
         assert not issubclass(provider_class, SupportsSandboxIndependentUploads)

The monkeypatch of _require_docker lets the test build the provider where the core CI job has no docker binary. A MagicMock(spec=DockerProvider) row is weaker: its uploads_independent_of_execs() returns a mock that counts as true, so that row still passes if Docker's method returns False.

raise failure
return self._response_from_output(body, items, model, run_metadata, status=status)
response = self._response_from_output(body, items, model, run_metadata, status=status)
return self.report_rollout_stop(response, state.session)

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.

responses_api_agents/claude_code_agent/app.py:890

report_rollout_stop reads session.expired, and four Claude Code tests build fake sessions without that field, so they fail with AttributeError.

report_rollout_stop reads session.expired first (base_responses_api_agent.py L1661). The PR added expired=False to the fake sessions in tests/test_sandbox.py, but not to these three:

The error is AttributeError: 'types.SimpleNamespace' object has no attribute 'expired'. gym env test for claude_code_agent gives 4 failed and 246 passed at head, and 250 passed at the base.

Suggested fix: add expired=False to those fake sessions. Both files are outside the PR's diff, so this is a plain diff:

--- a/responses_api_agents/claude_code_agent/tests/test_app.py
+++ b/responses_api_agents/claude_code_agent/tests/test_app.py
@@ -1385,6 +1385,7 @@
             ),
             runtime="/runtime",
             session=SimpleNamespace(
+                expired=False,
                 session_dir="/tmp/session",
                 workdir="/app",
                 artifacts=artifacts,
@@ -1415,6 +1416,7 @@
             ),
             runtime="/runtime",
             session=SimpleNamespace(
+                expired=False,
                 session_dir="/tmp/session",
                 workdir="/app",
                 artifacts=artifacts,
--- a/responses_api_agents/claude_code_agent/tests/test_observability.py
+++ b/responses_api_agents/claude_code_agent/tests/test_observability.py
@@ -506,7 +506,7 @@
                 task_id={"taskset": "fixture", "task_id": "task"},
             ),
             runtime="/runtime",
-            session=SimpleNamespace(session_dir="/tmp/session", workdir="/app", cleanup=None),
+            session=SimpleNamespace(expired=False, session_dir="/tmp/session", workdir="/app", cleanup=None),
         )
         monkeypatch.setattr(ClaudeCodeSandboxSession, "execute", AsyncMock(return_value=artifacts))
         monkeypatch.setattr(ClaudeCodeAgent, "_resolve_call_base_url", lambda *args: None)

@pytest.mark.parametrize("during_seed", [False, True])
async def test_native_adapter_stops_its_owned_supervisor(monkeypatch, name, agent_name, state_name, during_seed):
try:
module = import_module(f"responses_api_agents.{name}_agent.app")

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_tests/agents/test_native_rollout_stop.py:34

This test imports seven agent apps into the core coverage run, and local coverage drops from 94.48% (base) to 85.93%, against a 95% gate.

The core CI job runs pytest --cov=. (dev.py L40). The coverage configuration omits tests/* but not responses_api_agents/* (pyproject.toml L758-L771). The combined gate reports every measured file that git tracks (combine_core_coverage.py L22-L30) and fails below fail_under = 95.0 (pyproject.toml L787). The import_module on this line brings in 39 agent files, about 8,800 statements, and about 7,400 of them do not run. The integration test also imports the server's tests/test_app.py (test_rollout_budget_integration.py L219), about 1,300 more statements. Local core and sandbox runs on one machine gave 85.93% at head and 94.48% at the base. CI has not run yet, so the CI number is a projection.

Two more problems in this file:

  • The Hermes and NOOA cases always skip in the core CI job, because model_tools and nooa exist only in those agents' own venvs (L35-L37). In the Hermes venv, the Hermes case fails: its MagicMock configuration gives TypeError: str expected, not MagicMock in HermesAgent.model_post_init (hermes_agent/app.py L530).
  • "native" in the file and test names goes against the AGENTS.md naming rule (AGENTS.md L42-L44).

Suggested fix: move each agent's case into that agent's own tests, through one helper in tests/helpers/.

  • Delete tests/unit_tests/agents/test_native_rollout_stop.py.
  • Add tests/helpers/agent_rollout_stop.py with check_agent_rollout_stop.
  • Add tests/test_rollout_stop.py to the Codex, Claude Code, Pi, OpenClaw and OpenCode agents. Each one calls the helper.
  • Add the Hermes case to responses_api_agents/hermes_agent/tests/test_sandbox.py, so it uses the real agent fixture of that file.
  • In the integration test, import _environment_server from tests.helpers.single_agent_turn (L219).

With these changes, combined coverage was 94.50% (base 94.48%). Each moved test passed in its agent's venv, and deleting _rollout_sandbox_session from Hermes or Pi turns its test red. The helper has no NOOA branch, because a sandboxed NOOA run cannot report a stop at head.

The helper and the per-agent tests
--- /dev/null
+++ b/tests/helpers/agent_rollout_stop.py
@@ -0,0 +1,86 @@
+# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
+# SPDX-License-Identifier: Apache-2.0
+"""Check that a sandboxed agent hands its sandbox session to the shared rollout-stop lifecycle."""
+
+import asyncio
+from types import ModuleType
+from unittest.mock import AsyncMock, MagicMock
+
+import pytest
+from fastapi import HTTPException
+
+from nemo_gym.agents.base_responses_api_agent import AgentSessionState, RolloutStopRequest, SimpleResponsesAPIAgent
+from nemo_gym.agents.utils.sandbox_session import SandboxSession
+from nemo_gym.core.responses_api_types import NeMoGymResponse
+from tests.unit_tests.agents.test_agent_sessions import _seed_request
+
+
+async def check_agent_rollout_stop(
+    monkeypatch: pytest.MonkeyPatch,
+    module: ModuleType,
+    agent_name: str,
+    state_name: str,
+    *,
+    during_seed: bool,
+    agent: SimpleResponsesAPIAgent | None = None,
+) -> None:
+    """Seed ``agent_name`` from ``module``, stop its rollout, and check the stop reaches the session's supervisor.
+
+    Pass ``agent`` for an agent whose construction needs a real config.
+    """
+    agent_type = getattr(module, agent_name)
+    state_type = getattr(module, state_name)
+    seed = _seed_request()
+    sandbox = MagicMock(uploads_independent_of_execs=True, upload=AsyncMock())
+    session = SandboxSession(sandbox=sandbox, session_dir="/session", workdir="/app", harness=agent_name)
+    kwargs = {"request": seed, "session": session}
+    if "runtime" in state_type.__dataclass_fields__:
+        kwargs["runtime"] = "/runtime"
+    state = state_type(**kwargs)
+    installed = asyncio.Event()
+    if not during_seed:
+        installed.set()
+        session.launch_started = True
+
+    async def seed_state(self, body):
+        await installed.wait()
+        return state
+
+    monkeypatch.setattr(agent_type, "_seed_agent_session_state", seed_state)
+    if agent is None:
+        agent = agent_type.model_construct(config=MagicMock(num_workers=1, concurrency=1), server_client=MagicMock())
+    assert agent._rollout_sandbox_session(AgentSessionState(request=seed)) is None
+    task = asyncio.create_task(agent.seed_agent_session(MagicMock(session={}), seed))
+    await asyncio.sleep(0)
+    with pytest.raises(HTTPException) as unknown:
+        await agent.stop_rollout("another-rollout")
+    assert unknown.value.status_code == 404
+    first = await agent.stop_rollout("rollout-a2", RolloutStopRequest(reason="budget"))
+    second = await agent.stop_rollout("rollout-a2", RolloutStopRequest(reason="other"))
+    assert first.stopped and not second.stopped
+    installed.set()
+    await task
+    assert session.expire_reason == "budget"
+    if during_seed:
+        sandbox.upload.assert_not_awaited()
+    else:
+        sandbox.upload.assert_awaited_once()
+        assert sandbox.upload.await_args.args[1] == "/session/expire.request"
+    # A completed supervisor receipt, not the stop acknowledgement, makes this a timeout.
+    assert not session.expired
+    session.cleanup = {"timed_out": True}
+    assert session.expired
+    response = NeMoGymResponse(
+        id="served",
+        created_at=0,
+        model="model",
+        object="response",
+        output=[],
+        tool_choice="auto",
+        parallel_tool_calls=True,
+        tools=[],
+        status="incomplete",
+        metadata={"existing": "retained"},
+    )
+    reported = agent.report_rollout_stop(response, session)
+    assert reported.metadata == {"existing": "retained", "ng_rollout_stop": '{"reason":"budget"}'}
--- /dev/null
+++ b/responses_api_agents/codex_agent/tests/test_rollout_stop.py
@@ -0,0 +1,11 @@
+# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
+# SPDX-License-Identifier: Apache-2.0
+import pytest
+
+from responses_api_agents.codex_agent import app
+from tests.helpers.agent_rollout_stop import check_agent_rollout_stop
+
+
+@pytest.mark.parametrize("during_seed", [False, True])
+async def test_a_rollout_stop_reaches_the_sandbox_session(monkeypatch, during_seed):
+    await check_agent_rollout_stop(monkeypatch, app, "CodexAgent", "CodexSandboxSession", during_seed=during_seed)
--- /dev/null
+++ b/responses_api_agents/claude_code_agent/tests/test_rollout_stop.py
@@ -0,0 +1,13 @@
+# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
+# SPDX-License-Identifier: Apache-2.0
+import pytest
+
+from responses_api_agents.claude_code_agent import app
+from tests.helpers.agent_rollout_stop import check_agent_rollout_stop
+
+
+@pytest.mark.parametrize("during_seed", [False, True])
+async def test_a_rollout_stop_reaches_the_sandbox_session(monkeypatch, during_seed):
+    await check_agent_rollout_stop(
+        monkeypatch, app, "ClaudeCodeAgent", "ClaudeCodeSandboxSession", during_seed=during_seed
+    )
--- /dev/null
+++ b/responses_api_agents/pi_agent/tests/test_rollout_stop.py
@@ -0,0 +1,11 @@
+# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
+# SPDX-License-Identifier: Apache-2.0
+import pytest
+
+from responses_api_agents.pi_agent import app
+from tests.helpers.agent_rollout_stop import check_agent_rollout_stop
+
+
+@pytest.mark.parametrize("during_seed", [False, True])
+async def test_a_rollout_stop_reaches_the_sandbox_session(monkeypatch, during_seed):
+    await check_agent_rollout_stop(monkeypatch, app, "PiAgent", "PiSandboxSession", during_seed=during_seed)
--- /dev/null
+++ b/responses_api_agents/openclaw_agent/tests/test_rollout_stop.py
@@ -0,0 +1,13 @@
+# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
+# SPDX-License-Identifier: Apache-2.0
+import pytest
+
+from responses_api_agents.openclaw_agent import app
+from tests.helpers.agent_rollout_stop import check_agent_rollout_stop
+
+
+@pytest.mark.parametrize("during_seed", [False, True])
+async def test_a_rollout_stop_reaches_the_sandbox_session(monkeypatch, during_seed):
+    await check_agent_rollout_stop(
+        monkeypatch, app, "OpenClawAgent", "OpenClawSandboxSession", during_seed=during_seed
+    )
--- /dev/null
+++ b/responses_api_agents/opencode_agent/tests/test_rollout_stop.py
@@ -0,0 +1,13 @@
+# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
+# SPDX-License-Identifier: Apache-2.0
+import pytest
+
+from responses_api_agents.opencode_agent import app
+from tests.helpers.agent_rollout_stop import check_agent_rollout_stop
+
+
+@pytest.mark.parametrize("during_seed", [False, True])
+async def test_a_rollout_stop_reaches_the_sandbox_session(monkeypatch, during_seed):
+    await check_agent_rollout_stop(
+        monkeypatch, app, "OpenCodeAgent", "OpenCodeSandboxSession", during_seed=during_seed
+    )
--- a/responses_api_agents/hermes_agent/tests/test_sandbox.py
+++ b/responses_api_agents/hermes_agent/tests/test_sandbox.py
@@ -1921,3 +1921,13 @@
     )
     assert recovered.status == "completed"
     (agent._run_sandbox_episode if sandbox else agent._create_response).assert_awaited_once()
+
+
+@pytest.mark.parametrize("during_seed", [False, True])
+async def test_a_rollout_stop_reaches_the_sandbox_session(agent, monkeypatch, during_seed):
+    from responses_api_agents.hermes_agent import app
+    from tests.helpers.agent_rollout_stop import check_agent_rollout_stop
+
+    await check_agent_rollout_stop(
+        monkeypatch, app, "HermesAgent", "HermesSandboxSession", during_seed=during_seed, agent=agent
+    )

os.close(directory)
return used + 1

async def admit(self, request: Request, server_client: ServerClient) -> int:

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_gym/models/rollout_budget.py:61

The PR shows no real-model run of a capped episode, and its body says that the smoke run on the final source is still pending.

AGENTS.md asks for "representative real smoke rollouts with a model" for behavior-changing environment or agent work. It adds: "Green unit tests alone are not enough" (AGENTS.md L14-L16). This PR changes how six agents stop and how the model server admits calls. One real capped episode hits the 404 at the agent seed at once, and the unit tests in this PR do not.

Suggested fix: before you mark the PR ready, please run single_agent_turn with a small cap, for example max_model_calls: 3, on Docker. Run it once for each harness that can be stopped: Codex, Claude Code with a Gym model server, OpenCode, Pi, OpenClaw and Hermes. For each run, please show these in the PR body:

  • Call 4 is refused: the model server sends it to no backend.
  • The model server sends the stop request to the agent.
  • The response carries ng_rollout_stop.
  • /verify runs on that response.

Comment on lines +138 to +142
Model servers receiving capped episodes must configure `generation_budget_state_dir` to the same fresh,
run-specific shared directory. This setting supplies storage, not a cap: an episode without the segment
is unaffected, even on the same model server. Keep the directory until the run and all late requests
are retired. Failed backend dispatches consume admissions, because a failed transport cannot prove that
no generation occurred. A budgeted request must ask for only one completion.

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.

fern/versions/latest/pages/about/concepts/key-terminology.mdx:138-142

The docs ask every model server for one shared directory, and on Lustre the budget lock holds across nodes only with the -o flock mount option.

Model servers receiving capped episodes must configure generation_budget_state_dir to the same fresh, run-specific shared directory.

The counter takes an exclusive fcntl.flock through TokenCaptureStore._locked (store.py L127-L134). On Lustre, that lock holds across nodes only on clients mounted with -o flock. With localflock, it holds within one node only. In a two-node simulation, one of five trials admitted 11 calls under a cap of 10, and the other four failed. With noflock, every capped call fails with a 500. Each admitted call also adds two flock calls, two fsync calls (file and folder), a file create and a rename. Nothing deletes the counter files.

A shared directory is needed only when the model servers that one episode calls run on more than one node. NeMo RL starts each shard's Gym servers on one node (nemo_gym_shards.py L14-L18), so a node-local directory is enough there.

Suggested fix:

Suggested change
Model servers receiving capped episodes must configure `generation_budget_state_dir` to the same fresh,
run-specific shared directory. This setting supplies storage, not a cap: an episode without the segment
is unaffected, even on the same model server. Keep the directory until the run and all late requests
are retired. Failed backend dispatches consume admissions, because a failed transport cannot prove that
no generation occurred. A budgeted request must ask for only one completion.
Every model server that one capped episode calls must set `generation_budget_state_dir` to the same absolute
directory. Use a new directory for each run. Put it on the node's local disk when one node runs all of those
model servers. Otherwise every node must see the same directory, and its `flock` must hold
across them. On Lustre, mount with `-o flock`, since `localflock` only holds within one node. Each admitted call
adds a lock, two `fsync` calls, a file create and a rename there. This setting supplies storage, not a cap: an
episode without the segment is unaffected, even on the same model server. Keep the directory until the run and all
late requests are retired. Failed backend dispatches consume admissions, because a failed transport cannot prove
that no generation occurred. A budgeted request must ask for only one completion.
Sources for the lock and Lustre facts
  • localflock "only provides locally consistent flock locks": lustre/llite/file.c L6278 at v2_16_1.
  • noflock returns -ENOSYS from ll_file_noflock (file.c L5622-L5639), and Python raises OSError, so reserve raises.
  • Python 3.13.14 calls the real flock(2) (fcntlmodule.c L306-L311).
  • Gym states the same rule for the checkpoint state folder: "The filesystem's flock must hold across every node that runs the server" (_checkpoint/sandbox.py L64-L69).
  • The file operations come from strace of reserve on local disk. A later admitted call makes 4 opens, 1 stat, 2 flock calls, 2 fsync calls, 1 create and 1 rename. A refused call makes no fsync.
  • The two-node result comes from a simulation with one lock per node and a shared counter. It used 2 nodes with 4 processes each and a cap of 10. One of 5 trials admitted 11 calls, and 4 of 5 trials raised FileNotFoundError from os.replace.



class BaseResponsesAPIModelConfig(BaseRunServerInstanceConfig):
generation_budget_state_dir: str | None = None

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_gym/models/base_responses_api_model.py:288

generation_budget_state_dir accepts an empty or relative path, so the counters land in each model server's own source folder.

Each server process starts with cd into its own folder (server_venv.py L296, L428). With "", the counter and lock files go straight into that folder. With budget, each model server type counts in a different budget/ folder, although the docs ask for one directory. The two folders that model servers already share both refuse a relative path: model_call_capture_dir (model_call_capture.py L129-L130) and the training-token capture folder (token_capture/config.py L260-L261).

Suggested fix:

Suggested change
generation_budget_state_dir: str | None = None
generation_budget_state_dir: str | None = Field(
default=None,
pattern=r"^/",
description=(
"Absolute directory for episode generation budget counters. Every model server that serves the same "
"capped episodes must use the same directory."
),
)

It refuses "", budget, ./budget and ~/budget with "String should match pattern '^/'", and it accepts None and every absolute path.

self._probe = _coerce_config(probe, DockerProbeConfig)
self._binary = _require_docker()
self._semaphore = asyncio.Semaphore(self._exec_config.concurrency)
self._upload_semaphore = asyncio.Semaphore(self._exec_config.concurrency)

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_gym/sandbox/providers/docker/provider.py:312

The Docker change reaches every Docker user, with or without a budget, and the Docker README and the harness guide still describe the old behavior.

For every Docker run, uploads (the parent mkdir -p and docker cp) now take their own semaphore of exec.concurrency slots. Up to twice concurrency docker CLI processes can then run at once. The PR body's Compatibility section does not name this change.

Suggested fix: update the three doc lines and the PR body.

  • README L106 says concurrency is the "Upper bound on concurrent docker subprocesses (shared semaphore)". Please say that execs and uploads each get concurrency slots, so up to twice that many docker processes can run.
  • README L137 says the upload runs mkdir -p <parent> "via exec". Please change it to "mkdir -p <parent> (docker exec on the upload slots)".
  • add-or-update-a-harness.mdx L175 lists Docker among the providers where "a stop of a running harness answers HTTP 501". It also says stops work "as Codex does; other agents answer HTTP 501". Please list Docker with Local and OpenSandbox in background mode, and remove it from the 501 list. Please also name the agents that can now stop a running harness.
  • Add one line about the separate upload semaphore to the Compatibility section of the PR body.


class RolloutGenerationBudget:
def __init__(self, state_dir: str | Path) -> None:
self.store = TokenCaptureStore(state_dir)

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_gym/models/rollout_budget.py:32

The budget builds a whole TokenCaptureStore only to borrow its private _locked, so the hard cap's lock changes whenever the capture store's lock changes.

_locked is private to the capture store (store.py L127-L134), and it names the lock file <id>.tokens.lock (L124-L125). So the budget directory gets capture-named lock files next to its counters. reserve also copies the private _fsync_root of the store (L54-L58, store.py L248-L253). The per-call locks and fsync calls of the capture store are a known load on Lustre, so they are a likely place for change. A change there also changes the lock of the cap, and no test or caller shows it. Gym's other file-based state keeps its own short lock, for example the session router's owner files (SessionOwners._exclusive) (session_routing.py L408-L417).

Suggested fix: give the budget its own short lock and drop TokenCaptureStore. Add these imports with the other standard library imports:

import fcntl
from collections.abc import Iterator
from contextlib import contextmanager

Replace __init__ with this:

    def __init__(self, state_dir: str | Path) -> None:
        self.root = Path(state_dir)
        self.root.mkdir(parents=True, exist_ok=True)

    @contextmanager
    def _locked(self, key: str) -> Iterator[None]:
        with (self.root / f"{key}.generation-count.lock").open("a") as handle:
            fcntl.flock(handle.fileno(), fcntl.LOCK_EX)
            yield

Then, in the same file:

  • Change the store import (L24) to from nemo_gym.models.token_capture.store import validate_rollout_id.
  • In reserve, use self.root for both uses of self.store.root: the counter path (L41) and the folder fsync (L54).
  • In reserve, use self._locked(...) for self.store._locked(...) (L42).
  • Delete the docstring line "Reuse the capture store's filesystem lock protocol, in a separate directory." (L37).

reserve still refuses a bad key before the lock opens, because the path line calls validate_rollout_id. Closing the file releases the lock. With this change, the budget tests pass, and the folder holds <key>.generation-count and <key>.generation-count.lock, with no .tokens.lock.

Making _locked public is not enough, because the budget then still depends on the capture store and keeps the .tokens.lock names.

@svcnvidia-nemo-ci svcnvidia-nemo-ci added the needs-review PR is ready for code review and waiting on a reviewer label Nov 19, 2026
context = current_capture_context()
if context is not None:
context.refused = True
response = await server_client.post(

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.

When a rollout runs out of calls, the model server sends POST /rollouts/{capture_key}/stop to an agent server. The name of that agent server, and the cap itself, come from the base64 segment in the incoming URL. Nothing under nemo_gym/models calls another server today, so this makes the model server, which many episodes share, responsible for stopping an episode it does not own.

Any fault in that call now fails the model request. For example, an agent server that is slow to answer /stop, or an environment server that names the wrong agent, turns into a model-call failure. A caller that builds its own URL can also point the stop at any agent server in the registry.

Please make the model server refuse only. When the count is used up, return a typed error that clients do not retry, such as a 409 with {"code": "model_call_budget_exhausted"}, and make no outbound call. The agent adapter already classifies how its harness ended, so it can map that code to a completed, budget-stopped run and then take its usual file-collection and verification path.

if stopped.get("rollout_id") != episode.capture_key:
raise RuntimeError("Budget stop returned a different rollout identity")
# Let the existing supervisor timeout path collect the artifact before the CLI sees a refusal.
for _ in range(300):

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.

After the stop call, this loop holds the model request open for up to 30 seconds, so that the supervisor can collect the harness's files before the command-line tool sees the refusal. Correctness then depends on the supervisor finishing inside that window, and every refused call holds a model-server request open while it waits.

Please remove the wait. Once the model server only refuses (see the comment on the stop call), the agent adapter decides when to collect files, so the model server has nothing to wait for.


model_config = ConfigDict(extra="forbid")

max_model_calls: int | None = Field(default=None, gt=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.

max_model_calls is a fixed setting of the environment server, not a value per dataset row. It reaches the model server through a new correlation path segment, new middleware on every agent and model server, and path rewriting of every model call in ServerClient.

The episode seed already carries this kind of per-episode budget. The environment server sets AgentSeedSessionRequest.agent_timeout_sec (base_responses_api_agent.py) for each episode, as Harbor does (harbor/app.py), and the agent may read it.

Please carry the cap the same way, as an optional seed field. The agent then adds it only to the base URL it gives its harness. Agent servers need no new middleware, and ServerClient stops rewriting model calls for servers that never use a cap.

@ananthsub

Copy link
Copy Markdown
Contributor

Requesting changes on the design of the budget, in addition to the code-level blockers already raised.

A cap on model calls per episode has to be counted where the calls land, because a sandboxed harness calls the model server directly. That part is right. The problem is what the model server does with the count. It calls back into the agent server to stop the rollout, holds the refused request for up to 30 seconds, shares the counter across retries (existing thread), and keeps its counters in shared files that nothing deletes (existing thread). Each of these makes the model server, which many episodes share, responsible for the lifecycle of one episode.

The recommended direction:

  • The model server counts per attempt, or per agent session as the existing thread suggests, and only refuses, with a typed error that clients do not retry.
  • The agent adapter maps that error to a completed, budget-stopped run and takes its usual file-collection and verification path.
  • The environment server carries the cap in the episode seed, the way it carries agent_timeout_sec.
  • Each counter has an end of life.

Before reworking, please also state in #6254 whether the DeepCAD score is defined by exactly 10 model calls. If the cap is only there to control cost or time, the harnesses' own turn limits plus agent_timeout_sec on the CAD agent servers do the job with no change to Gym core.

The new inline comments on the stop call, the 30-second wait and max_model_calls have the details.

@gerryche123

Copy link
Copy Markdown
Contributor Author

Thanks for the review, and for the question about #6254. The DeepCAD score is not defined by exactly 10 model calls. The 10 in the original CAD recipe is OpenCode's max_steps (a harness turn limit), and nothing in the verifier depends on it. A cap here was only for cost and time.

So I'm taking your suggestion: no change to Gym core. #6254 now relies on each harness's own turn limit plus agent_timeout_sec, and I plan to close this PR rather than rework it. If a hard per-episode call budget is needed later for Codex, Pi or OpenClaw, I'll start from your design: the model server counts and refuses with a typed error, and the agent adapter turns it into a budget-stopped run.

@gerryche123

Copy link
Copy Markdown
Contributor Author

Closing: #6254 no longer depends on a generation budget (the 10-call limit was OpenCode's own step limit), so this change is not needed. If a hard per-episode call cap is wanted later, it can restart from the design discussed above.

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

Labels

area:core Shared APIs, servers, telemetry, health, and registries community-request Issue reported or requested by someone from the community feature New capabilities, enhancements, or enablement work needs-review PR is ready for code review and waiting on a reviewer risk:high Autobot PR risk: high

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants