Skip to content

Commit 047bac1

Browse files
macandro96claude
andcommitted
test(checkpoint): hold the post-tool policy call instead of a Gym test agent
The Workplace turn-recovery test needs a published checkpoint holding a turn whose calendar write was already applied. It held that boundary with a Gym checkpoint test agent that subclassed private participant internals and was switched by environment variables. A test-only proxy between Gym's policy model server and vLLM now does it through production paths. It holds the first policy call that carries a tool result: Gym counts a session at its boundary while it waits on a policy call made right after one, and a held call never blocks a checkpoint prepare. The rows use the plain workplace_assistant_simple_agent, so the test needs no Gym-side agent. After the write, the proxy forces one calendar_search_events call and then sends tool_choice none, so no turn writes a second event. The restored episode's search must find the event written before the crash exactly once, which checks that the Workplace state itself was restored, not only the model calls; its reward must be 1.0. The selector accepts only the held episode, since another episode also counts as at its boundary while its own post-tool call is in flight. The proxy forwards every path, so token capture is unaffected, and listens on the node's address so replicas on other nodes reach it. Passed with one Gym replica on one node and with two replicas on two nodes. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Anish Mahishi <[email protected]>
1 parent b28ed4a commit 047bac1

4 files changed

Lines changed: 388 additions & 17 deletions

File tree

‎examples/nemo_gym/grpo_workplace_assistant_two_replicas.yaml‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ env:
1818
port_range_high: 5999
1919
config_paths:
2020
- responses_api_models/vllm_model/configs/vllm_model_for_training.yaml
21-
- responses_api_agents/checkpoint_test_agent/configs/workplace_assistant.yaml
21+
- resources_servers/workplace_assistant/configs/workplace_assistant.yaml
2222
common_inherited_overlays:
2323
- policy_model
2424
allowed_duplicate_entries:
Lines changed: 254 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,254 @@
1+
# Copyright (c) 2026, NVIDIA CORPORATION. All rights reserved.
2+
#
3+
# Licensed under the Apache License, Version 2.0 (the "License");
4+
# you may not use this file except in compliance with the License.
5+
# You may obtain a copy of the License at
6+
#
7+
# http://www.apache.org/licenses/LICENSE-2.0
8+
#
9+
# Unless required by applicable law or agreed to in writing, software
10+
# distributed under the License is distributed on an "AS IS" BASIS,
11+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
# See the License for the specific language governing permissions and
13+
# limitations under the License.
14+
15+
"""Test-only pass-through proxy between NeMo-Gym's policy model server and vLLM.
16+
17+
The turn-recovery functional test needs a published checkpoint that holds a
18+
turn whose tool call has already changed the resources state. Gym counts a
19+
session at its boundary while it waits on a policy call made right after that
20+
boundary, and a held call never blocks a checkpoint prepare. So holding the
21+
first policy request that carries a tool result leaves Gym parked at the
22+
post-tool boundary through production code, until the test kills the process.
23+
24+
After a tool result, the proxy also decides the next call. With a
25+
``follow_up_tool``, a request whose episode has not called it yet is sent with
26+
that tool forced, and every later request with ``tool_choice: none``; without
27+
one, every request after a tool result is sent with ``tool_choice: none``.
28+
So no turn, including the one a restored episode re-issues, can call the
29+
episode's first tool a second time, and a read-only follow-up tool can report
30+
the resources state the episode continued from. Only ``tool_choice`` changes;
31+
the tool list stays, so the rendered prompt keeps the prefix token capture
32+
checks. The proxy logs each follow-up tool call it sees answered, with its
33+
arguments and result.
34+
35+
Each backend gets its own listener, so Gym's per-session endpoint choice still
36+
maps onto one backend. Listeners bind every interface and advertise this node's
37+
address, so Gym replicas on other nodes reach them too.
38+
"""
39+
40+
from __future__ import annotations
41+
42+
import asyncio
43+
import json
44+
import threading
45+
from pathlib import Path
46+
from typing import Any, Optional
47+
48+
from nemo_rl.distributed.virtual_cluster import _get_node_ip_local
49+
from tests.functional._single_controller_hook_utils import append_event
50+
51+
_SKIPPED_REQUEST_HEADERS = frozenset({"host", "content-length", "connection"})
52+
_SKIPPED_RESPONSE_HEADERS = frozenset(
53+
{"content-length", "transfer-encoding", "connection", "content-encoding"}
54+
)
55+
_STREAM_CHUNK_BYTES = 64 * 1024
56+
57+
58+
def _carries_tool_result(body: Any) -> bool:
59+
messages = body.get("messages") if isinstance(body, dict) else None
60+
return isinstance(messages, list) and any(
61+
isinstance(message, dict) and message.get("role") == "tool"
62+
for message in messages
63+
)
64+
65+
66+
def _tool_calls(body: dict[str, Any]) -> dict[str, dict[str, Any]]:
67+
"""The assistant tool calls in the conversation so far, by call ID."""
68+
calls = {}
69+
for message in body.get("messages") or []:
70+
if isinstance(message, dict) and message.get("role") == "assistant":
71+
for call in message.get("tool_calls") or []:
72+
calls[str(call.get("id"))] = call.get("function") or {}
73+
return calls
74+
75+
76+
def _tool_results(body: dict[str, Any]) -> dict[str, Any]:
77+
"""The tool results in the conversation so far, by the call ID they answer."""
78+
return {
79+
str(message.get("tool_call_id")): message.get("content")
80+
for message in body.get("messages") or []
81+
if isinstance(message, dict) and message.get("role") == "tool"
82+
}
83+
84+
85+
def _rollout_id(body: dict[str, Any]) -> Optional[str]:
86+
capture = body.get("ng_capture")
87+
if isinstance(capture, dict):
88+
rollout_id = capture.get("rollout_id")
89+
return str(rollout_id) if rollout_id is not None else None
90+
return None
91+
92+
93+
class PolicyHoldProxy:
94+
"""Forward Gym's policy calls to vLLM, holding at most one post-tool request."""
95+
96+
def __init__(
97+
self,
98+
backend_urls: list[str],
99+
*,
100+
hold_first_tool_result: bool,
101+
follow_up_tool: Optional[str],
102+
events_path: Path,
103+
) -> None:
104+
if not backend_urls:
105+
raise ValueError("the policy proxy needs at least one backend URL")
106+
self._backends = list(backend_urls)
107+
self._hold_first_tool_result = hold_first_tool_result
108+
self._follow_up_tool = follow_up_tool
109+
self._events_path = events_path
110+
self._host = _get_node_ip_local()
111+
self._ports: list[int] = []
112+
self._loop = asyncio.new_event_loop()
113+
self._started = threading.Event()
114+
self._startup_error: Optional[BaseException] = None
115+
self._thread = threading.Thread(
116+
target=self._run, name="gym-policy-hold-proxy", daemon=True
117+
)
118+
119+
@property
120+
def base_urls(self) -> list[str]:
121+
"""The proxied URLs, in backend order, in the ``http://host:port/v1`` form."""
122+
return [f"http://{self._host}:{port}/v1" for port in self._ports]
123+
124+
def start(self) -> "PolicyHoldProxy":
125+
self._thread.start()
126+
if not self._started.wait(timeout=60):
127+
raise TimeoutError("the policy proxy did not start within 60s")
128+
if self._startup_error is not None:
129+
raise RuntimeError("the policy proxy failed to start") from (
130+
self._startup_error
131+
)
132+
append_event(
133+
self._events_path,
134+
"policy_proxy_started",
135+
backends=self._backends,
136+
proxied=self.base_urls,
137+
hold_first_tool_result=self._hold_first_tool_result,
138+
follow_up_tool=self._follow_up_tool,
139+
)
140+
return self
141+
142+
def _run(self) -> None:
143+
asyncio.set_event_loop(self._loop)
144+
try:
145+
self._loop.run_until_complete(self._serve())
146+
except BaseException as error: # surfaced to start()
147+
self._startup_error = error
148+
self._started.set()
149+
return
150+
self._loop.run_forever()
151+
152+
async def _serve(self) -> None:
153+
from aiohttp import ClientSession, ClientTimeout, TCPConnector, web
154+
155+
# No limit and no timeout: the rollout layer owns deadlines, and a held
156+
# request must stay open until the process is killed.
157+
self._session = ClientSession(
158+
connector=TCPConnector(limit=0), timeout=ClientTimeout(total=None)
159+
)
160+
self._held = False
161+
for backend in self._backends:
162+
app = web.Application(client_max_size=1024**3)
163+
164+
async def handle(request: Any, backend: str = backend) -> Any:
165+
return await self._handle(request, backend)
166+
167+
app.router.add_route("*", "/{tail:.*}", handle)
168+
runner = web.AppRunner(app)
169+
await runner.setup()
170+
site = web.TCPSite(runner, host="0.0.0.0", port=0)
171+
await site.start()
172+
self._ports.append(site._server.sockets[0].getsockname()[1])
173+
self._started.set()
174+
175+
async def _handle(self, request: Any, backend: str) -> Any:
176+
from aiohttp import web
177+
178+
payload = await request.read()
179+
if request.method == "POST" and request.path == "/v1/chat/completions":
180+
body = json.loads(payload)
181+
if _carries_tool_result(body):
182+
rollout_id = _rollout_id(body)
183+
if self._hold_first_tool_result and not self._held:
184+
self._held = True
185+
append_event(
186+
self._events_path,
187+
"policy_call_held",
188+
rollout_id=rollout_id,
189+
backend=backend,
190+
)
191+
# Never answered: Gym stays at the post-tool boundary until
192+
# the process is killed.
193+
await asyncio.Event().wait()
194+
calls = _tool_calls(body)
195+
results = _tool_results(body)
196+
for call_id, function in calls.items():
197+
if (
198+
function.get("name") == self._follow_up_tool
199+
and call_id in results
200+
):
201+
append_event(
202+
self._events_path,
203+
"follow_up_tool_result",
204+
rollout_id=rollout_id,
205+
tool=self._follow_up_tool,
206+
arguments=function.get("arguments"),
207+
result=results[call_id],
208+
)
209+
followed_up = any(
210+
function.get("name") == self._follow_up_tool
211+
for function in calls.values()
212+
)
213+
tool_choice: Any = (
214+
{"type": "function", "function": {"name": self._follow_up_tool}}
215+
if self._follow_up_tool is not None and not followed_up
216+
else "none"
217+
)
218+
body["tool_choice"] = tool_choice
219+
payload = json.dumps(body).encode()
220+
append_event(
221+
self._events_path,
222+
"policy_call_tool_choice",
223+
rollout_id=rollout_id,
224+
backend=backend,
225+
tool_choice=tool_choice,
226+
)
227+
228+
headers = {
229+
name: value
230+
for name, value in request.headers.items()
231+
if name.lower() not in _SKIPPED_REQUEST_HEADERS
232+
}
233+
target = backend.removesuffix("/v1") + request.rel_url.path_qs
234+
async with self._session.request(
235+
request.method, target, data=payload, headers=headers
236+
) as upstream:
237+
response = web.StreamResponse(
238+
status=upstream.status,
239+
headers={
240+
name: value
241+
for name, value in upstream.headers.items()
242+
if name.lower() not in _SKIPPED_RESPONSE_HEADERS
243+
},
244+
)
245+
try:
246+
await response.prepare(request)
247+
async for chunk in upstream.content.iter_chunked(_STREAM_CHUNK_BYTES):
248+
await response.write(chunk)
249+
await response.write_eof()
250+
except ConnectionResetError:
251+
# The client gave up before the backend answered, as Gym's
252+
# startup probes do while vLLM loads; there is no one to tell.
253+
pass
254+
return response

‎tests/functional/_single_controller_turn_recovery_hook.py‎

Lines changed: 29 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,11 @@
1414

1515
"""Test-only SC entrypoint that records turn-recovery ownership.
1616
17-
The wrapper does not alter scheduling or checkpoint timing. It records the
17+
Gym's policy calls go through ``_gym_policy_proxy``, which holds the first one
18+
carrying a tool result when ``SC_TURN_RECOVERY_HOLD_FIRST_TOOL_RESULT=1``, so
19+
phase one always publishes a checkpoint at a post-tool Workplace boundary, and
20+
forces ``SC_TURN_RECOVERY_FOLLOW_UP_TOOL`` as each episode's next call.
21+
Otherwise the wrapper does not alter scheduling or checkpoint timing. It records the
1822
structured recovery identity once each Gym submission is marked dispatched,
1923
when Gym refuses one at checkpoint admission, after each completion has been
2024
sealed in the RL ledger (with the model calls its receipt names), and which
@@ -33,8 +37,10 @@
3337
from typing import Any
3438

3539
from examples import run_grpo_single_controller
40+
from nemo_rl.algorithms.single_controller_utils import setup as sc_setup
3641
from nemo_rl.experience.rollout_manager import RolloutCompletionCallback
3742
from nemo_rl.experience.rollout_recovery import RecoveryGranularity
43+
from tests.functional._gym_policy_proxy import PolicyHoldProxy
3844
from tests.functional._single_controller_hook_utils import append_event, find_group
3945

4046

@@ -118,6 +124,7 @@ async def _record_completion(generation_index: int, completion: Any) -> None:
118124
"completion",
119125
**common,
120126
sibling=self._sibling_fields(refreshed, generation_index),
127+
reward=completion.reward,
121128
# A continued episode keeps the calls it made before the cut.
122129
receipt_model_call_ids=[
123130
str(record["model_call_id"])
@@ -202,6 +209,27 @@ def prepare_for_restart(self, cut: Any, **kwargs: Any) -> Any:
202209
return self._prepare_for_restart(cut, **kwargs)
203210

204211

212+
_original_spinup_gym = sc_setup._spinup_gym
213+
# Kept alive for the life of the driver: Gym holds these URLs for the whole run.
214+
_policy_proxies: list[PolicyHoldProxy] = []
215+
216+
217+
def _spinup_gym_behind_policy_proxy(
218+
*args: Any, base_urls: list[str], **kwargs: Any
219+
) -> Any:
220+
proxy = PolicyHoldProxy(
221+
base_urls,
222+
hold_first_tool_result=os.environ.get("SC_TURN_RECOVERY_HOLD_FIRST_TOOL_RESULT")
223+
== "1",
224+
follow_up_tool=os.environ.get("SC_TURN_RECOVERY_FOLLOW_UP_TOOL") or None,
225+
events_path=Path(os.environ["SC_TURN_RECOVERY_TEST_EVENTS"]),
226+
).start()
227+
_policy_proxies.append(proxy)
228+
return _original_spinup_gym(*args, base_urls=proxy.base_urls, **kwargs)
229+
230+
231+
sc_setup._spinup_gym = _spinup_gym_behind_policy_proxy
232+
205233
_original_setup_single_controller = run_grpo_single_controller.setup_single_controller
206234

207235

0 commit comments

Comments
 (0)