Skip to content

fix(agent): refuse unsupported agent session seeds with a final 422 - #4680

Merged
yaoyu-33 merged 10 commits into
NVIDIA-NeMo:mainfrom
yaoyu-33:fix/agent-seed-rejection-4xx
Oct 23, 2026
Merged

yaoyu-33 merged 10 commits into
NVIDIA-NeMo:mainfrom
yaoyu-33:fix/agent-seed-rejection-4xx

Conversation

@yaoyu-33

@yaoyu-33 yaoyu-33 commented Oct 16, 2026 •

Copy link
Copy Markdown
Contributor

What changed

This PR makes an agent refuse an agent session seed it cannot serve with HTTP 422, so the episode fails once with a clear reason instead of being retried.

  • Adds AgentSeedRejectedError to nemo_gym/base_responses_api_agent.py. It subclasses both FastAPI's HTTPException (status 422) and ValueError:
    • every agent app answers it with 422, with no exception handler to register, including agents that build their own app;
    • code that validates a seed outside a request (checkpoint restore, direct calls in tests) still catches it as ValueError.
  • These refusals now use it:
    • simple_agent: sandbox access, required MCP grants, and more than one direct HTTP grant;
    • hermes_agent: MCP grants that collide with a toolset, no sandbox source, and a non-direct sandbox connection.
  • codex_agent, pi_agent and openclaw_agent already raise HTTPException(422) for their own checks, so nothing changes for them.
  • The base seed no longer has a num_workers > 1 refusal to convert: main now routes each agent session to the worker that seeded it (fix(server): route a session's requests to the worker that holds it #3905).
  • Adds nemo_gym.testing.agent_session_conformance.check_agent_seed_rejected, which posts a seed through the agent's real route and asserts a 422 with a string detail, so a missing route (404), a conflict (409) or a request-validation 422 does not pass.
  • An agent that does not implement episode sessions refuses its seed with AgentSeedRejectedError (422) instead of the NotImplementedError 500 that was retried, mirroring the close route's check.
  • The _seed_agent_session_state docstring and the agent-server integration page tell hook authors to raise AgentSeedRejectedError for a seed they cannot serve.
  • Carries the refusing server's reason into the episode failure. str(ClientResponseError) names only the status, reason phrase and URL, so failure_reason used to read 422, message='Unprocessable Content', url=... without the server's detail. The new nemo_gym.server_utils.format_exception_with_response_body appends the bounded response body. single_agent_turn uses it for every dependency failure: resources seed, agent seed, agent turn, agent close and verify. nemo_user_sim uses it for its episode failures, including participant agent-turn failures, which arrive wrapped in _ParticipantActivationError. This also carries the resources-side refusals from fix(resources): tighten the session contract for close, refusals and lost sessions #4679 (422 for bad input, 409 for conflicts).

The contract

Where the agent seed sits in an episode

The purple steps are the agent sessions API. This PR changes how step 1 fails.

sequenceDiagram
    autonumber
    participant A as Agent server
    participant E as Environment server (single_agent_turn)
    participant R as Resources server
    E->>R: POST /seed_session
    R-->>E: cookie (+ MCP tools, sandbox_access), or 422/409 refusal (#4679)
    rect rgba(91,75,183,0.12)
    E->>A: POST /v1/agent_sessions {agent_session_id, episode_id, task_id, tool_accesses, sandbox_access}
    A-->>E: 200 agent_session_id, or 422 when this agent cannot serve the seed
    end
    E->>A: POST /v1/responses
    E->>A: POST /v1/agent_sessions/close
    E->>R: POST /verify, then /close_session
Loading

Why the status code matters

single_agent_turn decides whether a failed dependency call is retryable with _is_retryable_dependency_error. It retries 5xx, 408, 425 and 429. Every other 4xx is final.

flowchart LR
    S["Seed the agent asks for something it cannot serve<br/>(sandbox, required MCP grant, no session support)"] --> B{"How the agent refuses"}
    B -->|"plain ValueError / TypeError"| F500["HTTP 500"] --> RT["single_agent_turn retries it as transient<br/>(same config error every time)"]
    B -->|"AgentSeedRejectedError"| F422["HTTP 422 + reason"] --> T["episode fails once, terminal,<br/>failure_reason carries the agent's reason"]
Loading

The resources side follows the same rule in #4679: 422 for input no retry can fix, 409 for a conflict or a closed session, 5xx only for failures a retry may fix. With format_exception_with_response_body, both sides' reasons reach failure_reason.

The rule

Seed outcome Agent must answer Environment server does
Accepted, or an identical retry 200 with the same agent_session_id continues the episode
Conflicts with an existing session (another seed for the ID, already closed, cookie mismatch) 409 (unchanged) fails the episode, no retry
Asks for something this agent cannot serve (configuration error) 422 via AgentSeedRejectedError, with an actionable message fails the episode once, no retry
Transient setup failure (sandbox start, network) 5xx retries

A refused seed binds nothing, so the same agent_session_id can still be seeded with a request the agent supports.

Linked issues

Validation

  • Formatter rename validation (810a6bc33, corrected import paths): 591 passed, 9 failed. Ran /Users/yuya/Documents/gym-codex/.venv/bin/python -u /private/tmp/pr4680-review-tests.py, which invokes pytest --import-mode=importlib -o addopts= -o log_cli=false -q tests/unit_tests/test_server_utils.py environment_servers/single_agent_turn/tests environment_servers/harbor/tests after remapping the shared venv's editable package paths to this PR checkout and asserting module locations. All nine remaining failures reproduce on unchanged parent de5398151 with the same launcher plus --lf: one macOS temporary-directory path assertion and eight verifier shell/timeout-dependent tests.

  • The earlier 590-pass/10-failure run imported SimpleAgent from another checkout. Correcting that path makes the checkpoint replay test pass; the earlier count is superseded. An intermediate launcher without a multiprocessing main guard was interrupted and is not passing evidence.

  • Two review passes, including an independent reviewer, found no rename regressions. All five changed files are AST-equivalent after normalizing only the helper/test identifier rename and helper docstring. The three environment call chains and ordinary-exception fallback were inspected; no old-name references remain.

  • pre-commit run --all-files passed after the formatter wrapped the longer function call. No old helper-name references remain in tracked files.

  • UserSim tests could not collect in the shared development environment because the optional usersim package is absent. The formatter rename changes no runtime behavior; no additional model rollout was run for this rename.

  • pytest tests/unit_tests/test_agent_sessions.py (new tests):

    • a refused seed answers 422 with its detail and keeps no session, and the same ID then seeds successfully;
    • the conformance check fails (got 500) for an agent that raises a plain ValueError;
    • AgentSeedRejectedError is still a ValueError;
    • the conformance check fails for a 404 (no session route) and for a 422 whose detail is not a string;
    • an agent that does not implement sessions answers its seed with 422 and keeps no session.
  • pytest environment_servers/single_agent_turn/tests: 60 passed. New tests:

    • 422 and 409 are final while 429 and 500 are retried;
    • an agent's 422 seed refusal fails the episode once at stage agent, terminal, with the agent's detail in failure_reason, and closes both sessions (fails without the format_exception_with_response_body change);
    • a resources server's 409 seed refusal fails the episode once at stage seed, terminal, with the server's detail in failure_reason, and the close registered before the seed still runs;
    • a refusal with a body at the agent turn, agent close and verify stages carries the server's detail into failure_reason (reverting any of those call sites to str(error) fails it).
  • pytest environment_servers/legacy_agent/tests environment_servers/single_agent_turn_legacy/tests: 5 and 18 passed.

  • pytest environment_servers/nemo_user_sim/tests in a venv built from its requirements.txt: 29 passed, including new tests that the agent's detail reaches the episode failure for an agent seed and for a participant's turn (each fails without its change).

  • pytest tests/unit_tests/test_agent_sessions.py tests/unit_tests/test_server_utils.py tests/unit_tests/test_base_responses_api_agent.py tests/unit_tests/test_checkpoint_agent.py: 249 passed, including a new test for format_exception_with_response_body (body appended for an HTTP error; unchanged without a body or for other errors).

  • pytest responses_api_agents/simple_agent/tests: 76 passed, including HTTP-level tests that a required MCP grant, sandbox access and more than one direct HTTP grant each get 422.

  • pytest responses_api_agents/{codex_agent,opencode_agent,openclaw_agent,pi_agent}/tests (after rebasing onto main on 2026-10-19): 236, 379, 388 and 246 passed. One test fails in each of codex, openclaw and pi: test_runtime_dependencies.py::test_opensandbox_sdk_is_available_in_agent_environment, which checks for the OpenSandbox SDK in the agent's own venv. It fails the same way on unmodified origin/main in the shared dev venv used here.

  • pytest responses_api_agents/hermes_agent/tests in a venv with hermes-agent installed: 301 passed, 6 skipped, including HTTP-level tests that a toolset collision and a missing sandbox source get 422.

  • pytest responses_api_agents/codex_agent/tests/test_sandbox_sessions.py, responses_api_agents/openclaw_agent/tests/test_sandbox.py and responses_api_agents/opencode_agent/tests/test_sandbox_sessions.py after merging main: 132 (6 skipped), 204 and 128 passed.

  • pytest tests/unit_tests -n 8: 8379 passed, 37 failed, 2 collection errors. All of the failures are in files this PR does not touch (opensandbox compose/cleanup/snapshots, the super35 batch launcher, CI environment, exporters, reward profile, telemetry); test_checkpoint_agent.py passes 36/36 when run alone. The same files fail the same way on unmodified origin/main in this local environment.

  • pre-commit run --files <changed files>: passed.

Rollout evidence

The planned unsupported-grant smoke passed on source 810a6bc on October 22, 2026 (macOS/Python 3.13.14). It ran the real single_agent_turn, simple_agent, and example_single_tool_call applications over localhost TCP, with Gym's ServerClient/global aiohttp transport and session routing. Module paths were asserted to come from the exact-source isolated worktree. The resources server exposed its real MCP metadata, producing a required MCP grant that SimpleAgent cannot serve.

Observed HTTP sequence for one episode:

Request Count Result
Resources /seed_session 1 200
Agent /v1/agent_sessions 1 422, Simple Agent does not support required MCP tool access: resources
Agent /v1/agent_sessions/close 1 200
Resources /close_session 1 200; resources session state empty
Environment /run 1 200 envelope containing failure.stage="agent", terminal=true, result=null, and the agent's refusal detail

No agent activation, model request, or verifier request occurred; the seed was not retried. A model endpoint tripwire would fail any attempted inference, but received zero calls. Model inference is N/A for this deliberately rejected seed: calling a model after this rejection would itself violate the behavior being tested. This is a live HTTP lifecycle smoke, not a real-model rollout or evidence for accepted episodes.

Local reproducibility/evidence: /private/tmp/pr4680-live-refusal-smoke.py, /private/tmp/pr4680-live-refusal-smoke.json, and /private/tmp/pr4680-live-refusal-smoke.log. The launcher used the shared Python with -S and source-bound PYTHONPATH; no repository source was modified.

Required source CI on this exact SHA also passed: CICD 39860673030 core/sandbox, session-routing E2E, all eight server shards, aggregate Nemo_CICD_Test, plus Lint and DCO. The workflow's overall conclusion remains failure because optional Harness conformance diagnostics failed; those are non-blocking.

Compatibility

  • AgentSeedRejectedError is a ValueError, so existing except ValueError and pytest.raises(ValueError) around direct calls keep working.
  • Over HTTP, these refusals change from 500 to 422. A client that retried on them will now see a final error, which is the intent.
  • An agent wired into an Environment Server without implementing sessions now fails each episode once with 422, instead of a retried 500.
  • check_agent_seed_rejected requires exactly 422 with a string detail. An external agent that refuses with another 4xx fails it.

🤖 Generated with Claude Code

@copy-pr-bot

copy-pr-bot Bot commented Oct 16, 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 force-pushed the fix/agent-seed-rejection-4xx branch from 9039939 to 22bf3e6 Compare October 19, 2026 17:14
@yaoyu-33
yaoyu-33 marked this pull request as ready for review October 19, 2026 21:00
yaoyu-33 and others added 3 commits October 19, 2026 16:32
Add AgentSeedRejectedError, an HTTPException (422) that is also a
ValueError. Seeds an agent cannot serve (num_workers > 1, unsupported
sandbox or grants) used to raise plain ValueError, which became a 500 that
single_agent_turn retried as transient. Use it in the base num_workers
guard, simple_agent and hermes_agent, and add check_agent_seed_rejected.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>
…ilure

AgentSeedRejectedError promises that a refused seed fails the episode once
with the agent's message, but single_agent_turn and nemo_user_sim built
failure_reason from str(ClientResponseError), which names only the status,
reason phrase, and URL. The agent's detail stayed on response_content.

Add nemo_gym.server_utils.describe_dependency_error, which appends the
bounded response body for an HTTP error, and use it for single_agent_turn's
agent seed failure and nemo_user_sim's episode failures.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>
…rn failures

Resources servers now refuse unfixable seeds and closes with 422 or 409 and
a reason in the body (NVIDIA-NeMo#4679), but single_agent_turn built
failure_reason from str(ClientResponseError) for every stage except the
agent seed, so the reason was lost. Use describe_dependency_error for the
resources seed, agent turn, agent close and verify failures too.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>
@yaoyu-33
yaoyu-33 force-pushed the fix/agent-seed-rejection-4xx branch from 12b771e to a2c91a6 Compare October 19, 2026 23:35
@yaoyu-33 yaoyu-33 added area:agent Agent harnesses and Responses API agent behavior bug Something isn't working complexity:high Cross-component or shared-contract change with a large review surface needs-review PR is ready for code review and waiting on a reviewer labels Oct 19, 2026
…d verify failures

describe_dependency_error is used at every single_agent_turn stage, but only
the two seed stages had a test, so reverting the agent turn, agent close or
verify call site to str(error) passed. Add one parametrized test that sends a
4xx with a body at each of those stages and checks the detail reaches
failure_reason.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>
@github-actions github-actions Bot added the sla:triage-overdue Review assignment is over the one-business-day SLA label Oct 20, 2026
…sal to 422

- nemo_user_sim: participant agent-turn failures are wrapped in
  _ParticipantActivationError, whose message dropped the refusing server's
  reason; build it with describe_dependency_error.
- An agent that does not implement episode sessions refuses its seed with
  AgentSeedRejectedError (final 422) instead of a NotImplementedError 500 that
  was retried.
- check_agent_seed_rejected requires 422 with a string detail, so a missing
  route (404), a conflict (409) or a request-validation 422 no longer passes.
- Tests pin each simple_agent and hermes refusal to 422 over HTTP, and the
  openclaw/opencode num_workers refusal to its detail.
- Docs: the _seed_agent_session_state docstring and the agent-server page tell
  hook authors to raise AgentSeedRejectedError.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>
@yaoyu-33

Copy link
Copy Markdown
Contributor Author

/ok to test 0c9937b

@github-actions

github-actions Bot commented Oct 21, 2026 •

Copy link
Copy Markdown
Contributor

Merge origin/main while preserving the PR runtime changes. Keep the guide reorganization from NVIDIA-NeMo#4713 and move AgentSeedRejectedError guidance into the harness integration contract, replacing the obsolete Hermes 500 caveat.

Validation: 251 focused core tests and 154 SimpleAgent/episode lifecycle tests passed; pre-commit run --all-files passed; Fern check passed (redirect checks skipped because local Fern authentication is unavailable). All 16 non-documentation PR diffs are unchanged by the merge. No model rollout was run for this documentation-only conflict resolution.
Signed-off-by: yaoyu-33 <[email protected]>
@yaoyu-33

Copy link
Copy Markdown
Contributor Author

/ok to test 3d4b76e

Resolve the test_agent_sessions.py conflict by keeping both sides: main's NVIDIA-NeMo#3729
close-response trajectory tests and this branch's seed-refusal tests.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>

@yuhezhang-ai yuhezhang-ai left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the change. Two non-blocking suggestions below: preserve the refusal detail on the Harbor path and qualify the exception-status guidance.

Comment thread nemo_gym/server_utils.py Resolved
Comment thread nemo_gym/base_responses_api_agent.py Resolved
@weijiac0619

Copy link
Copy Markdown
Contributor

environment_servers/harbor added in #3674 still builds failure_reason=str(error) so an AgentSeedRejectedError reason is lost for Harbor tasks. should those call sites use describe_dependency_error too or do we ?
For longer term, should single_agent_turn and harbor each define their own _failure() and their own copy of _is_retryable_dependency_error, and a shared helper in base_environment_server.py for “describe + classify + fail” to keep the next environment server from missing this again?
This is not a blocking issue for this PR if we only consider single_agent_turn

@github-actions github-actions Bot removed the sla:triage-overdue Review assignment is over the one-business-day SLA label Oct 22, 2026
…atus guidance

- Harbor builds failure_reason with describe_dependency_error for its seed,
  agent seed, agent turn and agent close failures, so an agent's 422 refusal
  reason reaches the episode failure there too. New Harbor tests carry the
  reason only in ClientResponseError.response_content.
- seed_agent_session logs each AgentSeedRejectedError refusal once, since a
  handled 422 never reaches the exception middleware that used to log the
  ValueError.
- The _seed_agent_session_state docstring and the harness guide say an
  HTTPException keeps its explicit status; only other, unexpected exceptions
  answer 500.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>
@yaoyu-33

Copy link
Copy Markdown
Contributor Author

Thanks @weijiac0619. Harbor is covered in this PR now (de53981): its seed, agent seed, turn and close failures use describe_dependency_error, with tests that carry the reason only in the response body.

Agreed on the longer-term helper. single_agent_turn, nemo_user_sim and harbor each have their own _failure() and their own copy of _is_retryable_dependency_error, and #4834 adds another status table. I'll take a shared "describe + classify + fail" helper in base_environment_server.py as a follow-up PR rather than widening this one.

@yaoyu-33

Copy link
Copy Markdown
Contributor Author

/ok to test de53981

@yuhezhang-ai yuhezhang-ai left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for addressing both points. The Harbor refusal details and exception-status guidance look good, and the focused checks pass. Please complete the planned smoke rollout before merging.

@yuhezhang-ai

Copy link
Copy Markdown
Contributor

/ok to test 810a6bc

@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/39863470396

@github-merge-queue
github-merge-queue Bot removed this pull request from the merge queue due to failed status checks Oct 22, 2026
@yaoyu-33
yaoyu-33 added this pull request to the merge queue Oct 22, 2026
@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/39874351152

@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/39876770798

Merged via the queue into NVIDIA-NeMo:main with commit a36f804 Oct 23, 2026
52 of 55 checks passed
@yaoyu-33
yaoyu-33 deleted the fix/agent-seed-rejection-4xx branch October 23, 2026 00:36

This branch was previously deployed

1 inactive deployment
public — 810a6bc3 Deployed Oct 22, 2026 by copy-pr-bot[bot] via release / finalize / notify #6713
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:agent Agent harnesses and Responses API agent behavior bug Something isn't working complexity:high Cross-component or shared-contract change with a large review surface needs-review PR is ready for code review and waiting on a reviewer

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants