Repository navigation
test(checkpoint): add a checkpoint test agent for deterministic turn recovery - #4773
macandro96 wants to merge 1 commit into
Conversation
…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]>
|
/ok to test 1a979d5 |
| metadata.pop(key, None) | ||
| return body.model_copy(update={"metadata": metadata or None}) | ||
|
|
||
| def _prepare_model_request_for_turn( |
There was a problem hiding this comment.
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_choiceand letmax_steps: 2end 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) |
There was a problem hiding this comment.
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: |
There was a problem hiding this comment.
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"]
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: |
There was a problem hiding this comment.
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" |
There was a problem hiding this comment.
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() |
There was a problem hiding this comment.
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"] |
There was a problem hiding this comment.
_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.
|
@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 containsIt bundles two changes that can be reviewed and landed separately.
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 Reaching the same checkpoint without agent codeThe 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"]
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 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 If an agent stays in GymIf 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 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]>
|
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 |
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]>
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]>
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]>
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:
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 productionAgentSessionParticipant, and stays parked until the process is killed. Every later checkpoint still exports that turn.NEMO_GYM_TEST_WORKPLACE_PREFIX_AFTER_MUTATION=1, turns after the first are sent withtool_choice: noneand no parallel tool calls, so the restored turn closes at its natural length without changing the resources state again.setup_agent_checkpointis called from both the web server and the participant setup, so the agent installs its participant once, as the base does.configs/workplace_assistant.yamlpairs it with the real Workplace Assistant resources server, behind alegacy_agentenvironment server.The only change outside the new agent is a
_prepare_model_request_for_turn(body, *, turn_index)hook insimple_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 passedresponses_api_agents/simple_agent/tests: 73 passedruff checkandruff format --checkon the changed Python files, with Gym's config: clean.NeMo RL
tests/functional/grpo_async_gym_single_controller_turn_recovery.shpasses with this agent: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
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.git commit -s) (so the DCO check passes).🤖 Generated with Claude Code