Skip to content

test(checkpoint): add a checkpoint test agent for deterministic turn recovery - #4773

Closed
macandro96 wants to merge 1 commit into
mainfrom
amahishi/checkpoint-test-agent
Closed

macandro96 wants to merge 1 commit into
mainfrom
amahishi/checkpoint-test-agent

Conversation

@macandro96

Copy link
Copy Markdown
Contributor

What does this PR do?

Adds checkpoint_test_agent, a Simple Agent for deterministic crash/restore tests of turn-level checkpoint recovery. NeMo RL's turn-level recovery functional test (NVIDIA-NeMo/RL#4500, NVIDIA-NeMo/RL#4501) depends on it; until now it lived only on an RL pin branch.

A restore test needs a published checkpoint that holds a turn whose resources mutation has already been applied. With a real policy model, whether a checkpoint lands before, during or after that tool call depends on timing. This agent removes the timing dependence:

  • Hold the first mutated boundary. With NEMO_GYM_TEST_HOLD_FIRST_MUTATED_BOUNDARY=1, the first session that reaches a boundary after its first tool call waits there until a real checkpoint prepare asks it to park, parks through the production AgentSessionParticipant, and stays parked until the process is killed. Every later checkpoint still exports that turn.
  • A closing turn without another mutation. With NEMO_GYM_TEST_WORKPLACE_PREFIX_AFTER_MUTATION=1, turns after the first are sent with tool_choice: none and no parallel tool calls, so the restored turn closes at its natural length without changing the resources state again.
  • One participant per app. setup_agent_checkpoint is called from both the web server and the participant setup, so the agent installs its participant once, as the base does.

configs/workplace_assistant.yaml pairs it with the real Workplace Assistant resources server, behind a legacy_agent environment server.

The only change outside the new agent is a _prepare_model_request_for_turn(body, *, turn_index) hook in simple_agent/app.py. It is a no-op by default and runs on each turn's fully built model request.

Validation

  • In the RL CI Gym image (rl-gym.nightly), against this branch, each server run on its own:

    • responses_api_agents/checkpoint_test_agent/tests: 6 passed
    • responses_api_agents/simple_agent/tests: 73 passed
  • ruff check and ruff format --check on the changed Python files, with Gym's config: clean.

  • NeMo RL tests/functional/grpo_async_gym_single_controller_turn_recovery.sh passes with this agent:

    • on 1 node, with one Gym replica;
    • on 2 nodes × 2 Gym replicas (examples/nemo_gym/grpo_workplace_assistant_two_replicas.yaml), with restored episodes split 3/3 and each resumed on its original replica.

    Both runs used the RL pin branch amahishi/rl-gym-turn-recovery-pin, whose checkpoint test agent and Simple Agent hook are identical to this PR's.

Rollouts

N/A. This is a test fixture, and the agent is enabled only by the environment variables above. Without them it behaves as Simple Agent, and the new Simple Agent hook is a no-op.

Compatibility and benchmark impact

None. It adds a new agent and a default no-op hook; no existing config, benchmark or behavior changes.

Checklist

  • I have read the contributing guidelines.
  • The change is focused; unrelated "drive-by" edits are tracked as separate issues/PRs.
  • Tests added or updated and pass locally, or N/A for docs-only / non-code changes (so CI unit/server checks pass when applicable).
  • Documentation added or updated, or N/A with justification. N/A: an internal test fixture, documented in its module docstring and config comments.
  • Pre-commit checks pass locally (pre-commit run --all-files) (so CI lint/format checks pass). Ruff lint and format pass on the changed files; the full pre-commit suite was not run.
  • New source files include the required Apache-2.0 SPDX header.
  • All commits have DCO sign-off (git commit -s) (so the DCO check passes).

🤖 Generated with Claude Code

…recovery

A crash/restore test needs a published checkpoint that holds a turn whose
resources mutation has already been applied. With a real policy model,
whether a checkpoint lands before, during or after that tool call depends
on timing, so the test cannot rely on it.

checkpoint_test_agent is a Simple Agent that, with
NEMO_GYM_TEST_HOLD_FIRST_MUTATED_BOUNDARY=1, holds the first session that
reaches a boundary after its first tool call. It waits there until a real
checkpoint prepare asks it to park, parks through the production
participant, and stays parked until the process is killed, so every later
checkpoint still exports that turn.

With NEMO_GYM_TEST_WORKPLACE_PREFIX_AFTER_MUTATION=1, turns after the first
are sent with tool_choice none and no parallel tool calls, so the restored
turn closes without another mutation. Simple Agent gains a
_prepare_model_request_for_turn hook, a no-op by default, for this.

The agent installs its checkpoint participant once per app, as the base
does, since setup_agent_checkpoint is called from both the web server and
the participant setup.

configs/workplace_assistant.yaml pairs it with the real Workplace Assistant
resources server behind a legacy_agent environment server. NeMo RL's
turn-level recovery functional test uses this configuration.

Signed-off-by: Anish Mahishi <[email protected]>
@copy-pr-bot

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

@macandro96
macandro96 requested a review from ananthsub October 20, 2026 04:12
@yaoyu-33 yaoyu-33 added area:agent Agent harnesses and Responses API agent behavior ci CI, automation, test queue, or workflow infrastructure work complexity:medium Single-domain change with interacting parts or a moderate review surface needs-review PR is ready for code review and waiting on a reviewer labels Oct 20, 2026
@github-actions github-actions Bot added the sla:review-overdue Review response is over the one-business-day SLA label Oct 21, 2026
@ananthsub

Copy link
Copy Markdown
Contributor

/ok to test 1a979d5

metadata.pop(key, None)
return body.model_copy(update={"metadata": metadata or None})

def _prepare_model_request_for_turn(

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.

This adds a protected hook to Simple Agent's turn loop for one test fixture, and that fixture's only consumer never turns it on. CheckpointTestAgent rewrites the request only when NEMO_GYM_TEST_WORKPLACE_PREFIX_AFTER_MUTATION=1, but NeMo RL's grpo_async_gym_single_controller_turn_recovery.sh (NVIDIA-NeMo/RL#4500, NVIDIA-NeMo/RL#4501) sets only NEMO_GYM_TEST_HOLD_FIRST_MUTATED_BOUNDARY=1. The pin branch amahishi/rl-gym-turn-recovery-pin does not set it either. In the runs the description cites, the hook therefore returned every request unchanged, and the closing-turn mode has never run end to end.

The consequence is that the behavior the description promises does not happen in that run. The RL script builds its dataset with tool_choice = {"type": "function", "name": "calendar_create_event"} on every row. After a restore, the second model call is still forced to call calendar_create_event, so the restored turn writes a second calendar event, the loop reaches max_steps: 2, and the episode ends incomplete. The RL test passes anyway because it checks the calendar only in the checkpoint, before the restore.

Simple Agent is the base most agents build on, so every new protected hook in its loop becomes surface that later refactors must keep, even when nothing in production calls it. Please drop _prepare_model_request_for_turn and the WORKPLACE_PREFIX_AFTER_MUTATION mode. If the closing turn must not call tools, the test can arrange that without Simple Agent:

  • The RL dataset can stop forcing tool_choice and let max_steps: 2 end the episode after the closing turn.
  • The component that holds the second policy call (see the comment on at_boundary) can also rewrite that one request before it reaches the model.

metadata={"existing": "value"},
)

first = agent._prepare_model_request_for_turn(request, turn_index=1)

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.

This test calls _prepare_model_request_for_turn directly, so it checks the override but not that Simple Agent's loop ever calls the hook. Deleting the new_body = self._prepare_model_request_for_turn(...) call from SimpleAgent.responses leaves every test in checkpoint_test_agent/tests and simple_agent/tests passing. If the hook stays, it needs a Simple Agent test that runs the loop and observes the rewritten request reaching the model server. Removing the hook, as the comment on simple_agent/app.py asks, makes this test unnecessary.

super().__init__(hooks)
self._hold_first_mutated_boundary = os.environ.get(HOLD_FIRST_MUTATED_BOUNDARY_ENV) == "1"

async def at_boundary(self, session: _Session, snapshot: Callable[[], dict[str, Any]]) -> 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.

CheckpointTestParticipant holds the session by overriding AgentSessionParticipant.at_boundary and working on the participant's private state. It imports _Session and calls _require_live. After park returns at resume, it also writes session.state = "at_boundary" itself, so the session looks parked to readiness() and _export_boundary() without having gone through park. All of this lives in nemo_gym._checkpoint, which is private, and any change to how park, readiness or the session states work can break this agent without touching it.

The production path already reaches the same state when the second policy call is held instead of the session. After the first tool round, Simple Agent records the post-tool boundary and then makes the next policy call inside _call_policy, which enters activation.awaiting_model(). While that call is waiting, the session counts as at_boundary and session.boundary is still the post-tool snapshot. The policy model participant never waits for an undelivered generation in prepare, so every checkpoint exports that boundary, and a restored session re-issues the call. Gym's test_resources_state_is_restored_with_the_episode in tests/e2e/checkpoint does exactly this: the counter resources server is incremented, the fake backend holds the next model call with /_ctl/hold {"after_calls": 1}, and the test crashes, restores and checks the restored counter, with a negative control.

flowchart TD
    A["first model call returns a tool call"] --> B["tool runs and mutates the resources state"]
    B --> C["Simple Agent records the post-tool boundary"]
    C --> D["second policy call enters awaiting_model"]
    D -->|"test holds this call until the process is killed"| E["session counts as at_boundary"]
    E --> F["every checkpoint exports the post-tool boundary"]
    F --> G["after restore the agent re-issues the second call"]
Loading

Please hold the second policy request in the test instead of in the agent. This moves the hold rather than removing it: vLLM has no hold control, and the fake backend's after_calls count is global, so the RL test needs a hold keyed to one request. The turn-recovery functional test hook, which already patches the controller, can hold the first generation whose prompt contains a tool result. That change lives in the RL test, and the Gym fixture then needs no participant subclass, no copy of setup_agent_checkpoint, and no agent of its own: the config can use simple_agent with max_steps: 2.

# EOS leaves near-tied argmax tokens that flip between otherwise identical runs.
return body.model_copy(update={"tool_choice": "none", "parallel_tool_calls": False})

def setup_agent_checkpoint(self, app: FastAPI) -> 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.

This override copies SimpleResponsesAPIAgent.setup_agent_checkpoint so that it can construct CheckpointTestParticipant instead of AgentSessionParticipant, because the base method has no way to choose the participant class. The copy also leaves out the base's checkpoint_sessions_supported branch, which is harmless for a Simple Agent subclass but is one more difference to keep in mind. The copy keeps today's num_workers == 1 check and calls install_participant. #3909 changes the base method: it drops that check and installs through install_server_participant(..., num_workers=...). The two pull requests merge without a textual conflict, so after #3909 lands this agent silently keeps the old installation path, along with any later change to the base method. Holding the policy call instead, as the comment on at_boundary suggests, removes the need for this override.

from responses_api_agents.simple_agent.app import SimpleAgent


HOLD_FIRST_MUTATED_BOUNDARY_ENV = "NEMO_GYM_TEST_HOLD_FIRST_MUTATED_BOUNDARY"

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.

Two process environment variables switch this agent's behavior, and neither shows up anywhere Gym reports its configuration. gym env resolve and the resolved config show an ordinary agent, while the hold depends on whether NEMO_GYM_TEST_HOLD_FIRST_MUTATED_BOUNDARY reached this server's process. The two variables are also read at different times. The hold is read once, when CheckpointTestParticipant is built. The request rewrite is read on every turn. Any value other than the exact string "1", such as true, turns a mode off without an error.

Whether the variable reaches the process depends on the launcher rather than on Gym. In the RL test it is exported in the driver's shell and reaches Gym servers that Ray starts on the same node. A Gym replica on another node gets it only if that node's Ray processes were started with it, and if they were not, that replica silently does not hold.

If an agent remains after the other comments, please make its behavior agent config instead, for example hold_first_post_tool_boundary: false in SimpleAgentConfig's subclass for this agent. A test enables it with a Hydra override, which every replica receives through its config, which gym env resolve shows, and which Pydantic validates.



if __name__ == "__main__":
CheckpointTestAgent.run_webserver()

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.

This entrypoint has no module-level app and does not override multiple_workers_unsupported_reason. #4885 adds tests/unit_tests/test_multiple_workers_contract.py, which checks every responses_api_agents/*/app.py for one or the other. With #4885 and this pull request merged together, that test fails on responses_api_agents/checkpoint_test_agent/app.py: CheckpointTestAgent has neither the module-level app that multi-worker uvicorn imports nor a refusal. Whichever of the two lands second goes red.

If the agent stays, it needs a refusal, because its hold keeps state in one process. multiple_workers_unsupported_reason can return that reason. This goes away if the fixture becomes a simple_agent config.

def _after_first_tool_call(snapshot: Callable[[], dict[str, Any]]) -> bool:
"""Whether a Simple Agent loop boundary follows at least one executed tool call."""
state = snapshot()
return state["step"] >= 1 and not state["pending_tools"]

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_first_tool_call accepts any boundary with step >= 1 and no pending tools, and the hold is spent on the first session that matches. The predicate does not check that the tool call succeeded. Invalid JSON arguments produce an error tool output, and a resources server error is returned to the model as tool output, so a session whose tool call wrote nothing can still take the one hold. No other session is held after that. The RL selector then never finds a snapshot with exactly one sentinel event. With the script's stall watchdog (stall_timeout_s=300, stall_action=abort), phase one most likely aborts after a few minutes and the selector reports "phase one exited before publishing a recoverable Workplace turn", which points away from the tool call. Forced tool_choice at temperature 0.1 makes this unlikely, so it is a diagnosability problem rather than a frequent flake.

If the hold stays in Gym, it should require a completed tool record in the snapshot (tool_records[-1]["status"] == "completed") before spending itself. With the hold moved to the second policy call, the RL test can check the tool result before it holds.

@ananthsub

Copy link
Copy Markdown
Contributor

@macandro96 thanks for moving this fixture out of the RL pin branch. A Gym-side way to make the turn-recovery test deterministic is worth having. The concern with this version is how it gets there: it adds a protected hook to Simple Agent for one test, drives the fixture through process environment variables, and holds the session by subclassing private checkpoint internals. The same deterministic checkpoint is reachable with no agent code at all, so the suggestion is to drop the core change and the agent and hold the second policy call in the test instead.

What this pull request contains

It bundles two changes that can be reviewed and landed separately.

  • A Simple Agent hook. _prepare_model_request_for_turn(body, *, turn_index) is a protected method on SimpleAgent, called in the turn loop on every fully built model request. It is a no-op by default. Nothing else in the repository overrides or calls it, and no Simple Agent test checks that the loop calls it: deleting the call leaves every test in simple_agent/tests and checkpoint_test_agent/tests passing. It does not change production behavior, but it adds permanent surface to the base most agents build on, for one fixture.
  • The checkpoint_test_agent fixture. It contains a participant subclass that holds the first post-tool boundary, a copy of setup_agent_checkpoint that installs that participant, a request rewrite behind a second environment variable, and a Workplace Assistant config.

The hook exists only for the request rewrite, and NeMo RL's turn-recovery test (NVIDIA-NeMo/RL#4500, NVIDIA-NeMo/RL#4501) never sets NEMO_GYM_TEST_WORKPLACE_PREFIX_AFTER_MUTATION, so in the runs the description cites, including the pin branch run, the hook did nothing and the closing-turn mode has never run end to end. Because that script forces tool_choice to calendar_create_event on every row, the restored turn is sent with the forced tool choice and writes a second event before max_steps: 2 ends it. The RL test does not notice because it checks the calendar only inside the checkpoint.

Reaching the same checkpoint without agent code

The fixture needs a published checkpoint that holds a turn whose tool call has already changed the resources state. Holding the second policy call produces exactly that through production code:

flowchart TD
    A["first model call returns a tool call"] --> B["tool runs and mutates the resources state"]
    B --> C["Simple Agent records the post-tool boundary"]
    C --> D["second policy call enters awaiting_model"]
    D -->|"test holds this call until the process is killed"| E["session counts as at_boundary"]
    E --> F["every checkpoint exports the post-tool boundary"]
    F --> G["after restore the agent re-issues the second call"]
Loading

While a policy call made right after a boundary is outstanding, the agent participant counts the session at that boundary, and the policy model participant never waits for an undelivered generation in prepare. Gym's own test_resources_state_is_restored_with_the_episode in tests/e2e/checkpoint already uses this pattern with a stateful resources server and a negative control, so Gym's coverage of turn recovery does not need a test agent.

For the RL test this moves the hold rather than removing it, since vLLM has no hold control and the hold must be keyed to one request. It can sit in the functional-test hook, which already patches the controller, around the first generation whose prompt carries a tool result. The Gym side is then a config using simple_agent with max_steps: 2 and the Workplace Assistant resources server, either in RL or as a config next to the Workplace Assistant server. If the closing turn must not call tools, the RL dataset can stop forcing tool_choice, or the same hold can rewrite that one request.

If an agent stays in Gym

If the policy-call hold does not work for RL, please keep Simple Agent unchanged and narrow the agent:

Overlap with other pull requests

Validation done for this review

  • The agent's tests and Simple Agent's tests, on this branch merged onto current main, each in a virtual environment that resolves the branch's own responses_api_agents: both pass.
  • The same with the hook's call removed from Simple Agent's loop: both still pass.
  • tests/unit_tests/test_multiple_workers_contract.py from feat(server): refuse several workers in servers that cannot share state #4885 with this branch merged: fails on checkpoint_test_agent/app.py.
  • scripts/update_env_list.py: the README environment table does not change, so the second Workplace Assistant resources server entry in the config does not leak into it.

@github-actions github-actions Bot removed the sla:review-overdue Review response is over the one-business-day SLA label Oct 22, 2026
macandro96 added a commit to NVIDIA-NeMo/RL that referenced this pull request Oct 23, 2026
The pin no longer needs commits that exist only on an unmerged branch. The
turn-recovery test holds its boundary through a policy-call proxy, so it no
longer uses the checkpoint test agent (NVIDIA-NeMo/Gym#4773), and the agent
commit reply's run_episode_ids (NVIDIA-NeMo/Gym#4690) is on main. The other
pin-only commits, the indirect prompt injection and proof refinement
checkpoint exports (NVIDIA-NeMo/Gym#3897, #3898), are for environments RL's
tests do not use.

Gym's pyproject.toml is identical to the previous pin's, so uv.lock is
unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Anish Mahishi <[email protected]>
@macandro96

Copy link
Copy Markdown
Contributor Author

Closing in favour of the approach suggested above: NeMo RL's turn-recovery test now holds the post-tool policy call through a test-only proxy in RL's functional-test hook, and uses the plain simple_agent Workplace config, so Gym needs no test agent or Simple Agent hook (NVIDIA-NeMo/RL@047bac1822). One correction to the review: the closing-turn mode did have a consumer, NeMo RL's prefix-recovery parity test (NVIDIA-NeMo/RL#4507), but the same proxy covers it by sending post-tool calls with tool_choice: none. Thanks for the detailed review.

@macandro96 macandro96 closed this Oct 23, 2026
macandro96 added a commit to NVIDIA-NeMo/RL that referenced this pull request Oct 26, 2026
The pin no longer needs commits that exist only on an unmerged branch. The
turn-recovery test holds its boundary through a policy-call proxy, so it no
longer uses the checkpoint test agent (NVIDIA-NeMo/Gym#4773), and the agent
commit reply's run_episode_ids (NVIDIA-NeMo/Gym#4690) is on main. The other
pin-only commits, the indirect prompt injection and proof refinement
checkpoint exports (NVIDIA-NeMo/Gym#3897, #3898), are for environments RL's
tests do not use.

Gym's pyproject.toml is identical to the previous pin's, so uv.lock is
unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Anish Mahishi <[email protected]>
macandro96 added a commit to NVIDIA-NeMo/RL that referenced this pull request Oct 27, 2026
The pin no longer needs commits that exist only on an unmerged branch. The
turn-recovery test holds its boundary through a policy-call proxy, so it no
longer uses the checkpoint test agent (NVIDIA-NeMo/Gym#4773), and the agent
commit reply's run_episode_ids (NVIDIA-NeMo/Gym#4690) is on main. The other
pin-only commits, the indirect prompt injection and proof refinement
checkpoint exports (NVIDIA-NeMo/Gym#3897, #3898), are for environments RL's
tests do not use.

Gym's pyproject.toml is identical to the previous pin's, so uv.lock is
unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Anish Mahishi <[email protected]>
macandro96 added a commit to NVIDIA-NeMo/RL that referenced this pull request Oct 28, 2026
The pin no longer needs commits that exist only on an unmerged branch. The
turn-recovery test holds its boundary through a policy-call proxy, so it no
longer uses the checkpoint test agent (NVIDIA-NeMo/Gym#4773), and the agent
commit reply's run_episode_ids (NVIDIA-NeMo/Gym#4690) is on main. The other
pin-only commits, the indirect prompt injection and proof refinement
checkpoint exports (NVIDIA-NeMo/Gym#3897, #3898), are for environments RL's
tests do not use.

Gym's pyproject.toml is identical to the previous pin's, so uv.lock is
unchanged.

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

This branch was previously deployed

1 inactive deployment
public — 1a979d5b Deployed Oct 22, 2026 by copy-pr-bot[bot] via release / finalize / notify #6699
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 ci CI, automation, test queue, or workflow infrastructure work complexity:medium Single-domain change with interacting parts or a moderate 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