|
| 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 |
0 commit comments