verifiers 0.4.1.dev80__py3-none-any.whl → 0.4.1.dev82__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -233,9 +233,19 @@ class ServerBase(Generic[ConfigT, StateT]):
233
233
  token = _call_state.set(state)
234
234
  try:
235
235
  before = self._state_adapter.dump_json(state) if sync_state else None
236
- result = fn(*args, **kwargs)
237
- if inspect.isawaitable(result):
238
- result = await result
236
+ try:
237
+ result = fn(*args, **kwargs)
238
+ if inspect.isawaitable(result):
239
+ result = await result
240
+ except Exception as e:
241
+ from mcp.server.mcpserver.exceptions import ToolError
242
+ from mcp.shared.exceptions import MCPError
243
+
244
+ if isinstance(e, (ToolError, MCPError)):
245
+ raise
246
+ # MCPServer withholds an unexpected exception's text from the client, but
247
+ # tools raise to tell the model what went wrong.
248
+ raise ToolError(str(e)) from e
239
249
  if before is not None:
240
250
  await self._push_state(before)
241
251
  return result
@@ -2,7 +2,9 @@
2
2
 
3
3
  A DEALER socket + msgpack, with a single receive loop matching replies to
4
4
  per-request futures by `request_id` and routing a run's `delta` frames to its
5
- assembly (`serve/delta.py`). Speaks the typed pydantic request/response models
5
+ assembly (`serve/delta.py`). The loop drains every queued frame per wakeup and
6
+ handles the batch in arrival order, so a busy event loop costs one turn per batch
7
+ rather than one per delta. Speaks the typed pydantic request/response models
6
8
  (`serve/types.py`) end-to-end: a request is `model_dump`ed onto the wire; a run's
7
9
  traces stream back turn by turn and the assembled record is `model_validate`d into a
8
10
  `WireEpisode` once the reply lands — `Trace`s typed as `Trace[WireTaskData]`
@@ -41,9 +43,27 @@ logger = logging.getLogger(__name__)
41
43
  ResponseT = TypeVar("ResponseT", bound=BaseResponse)
42
44
  DecodedT = TypeVar("DecodedT")
43
45
 
46
+ # How much of the queue one wakeup drains before the loop yields.
47
+ MAX_BATCH_FRAMES = 512
48
+ MAX_BATCH_BYTES = 16 << 20
49
+ INLINE_DECODE_BYTES = 1 << 20
50
+ """A batch with fewer delta bytes decodes on the loop: unpacking a turn's delta takes
51
+ microseconds, less than a worker-thread round trip on a busy loop."""
52
+
53
+
54
+ def _unpack_all(payloads: list[memoryview]) -> list[object]:
55
+ """`unpack` each payload; one that fails yields its exception instead."""
56
+ decoded: list[object] = []
57
+ for payload in payloads:
58
+ try:
59
+ decoded.append(unpack(payload))
60
+ except Exception as e: # noqa: BLE001 - logged by the caller, in arrival order
61
+ decoded.append(e)
62
+ return decoded
63
+
44
64
 
45
65
  class EnvClient:
46
- """Receive streamed episodes with bounded worker decoding."""
66
+ """Receive streamed episodes, decoding each drained batch of frames at once."""
47
67
 
48
68
  def __init__(self, address: str = "tcp://127.0.0.1:5000") -> None:
49
69
  self.address = address
@@ -67,13 +87,38 @@ class EnvClient:
67
87
  self._receiver = asyncio.create_task(self._receive_loop())
68
88
 
69
89
  async def _receive_loop(self) -> None:
70
- # The one receiver serves every in-flight request, so a bad frame or a delta
71
- # handler that raises is logged and skipped rather than allowed to end the loop.
90
+ # The one receiver serves every in-flight request. Awaiting each frame would
91
+ # cost a loop turn per delta, which a busy loop turns into a hard cap on how
92
+ # fast a server's stream drains; so each wakeup takes everything queued.
72
93
  while True:
73
94
  try:
74
- frames = await self.socket.recv_multipart(copy=False)
95
+ batch = [await self.socket.recv_multipart(copy=False)]
75
96
  except asyncio.CancelledError:
76
97
  break
98
+ size = sum(len(frame) for frame in batch[0])
99
+ while len(batch) < MAX_BATCH_FRAMES and size < MAX_BATCH_BYTES:
100
+ try:
101
+ # A non-blocking recv returns an already-resolved future.
102
+ frames = self.socket.recv_multipart(
103
+ flags=zmq.NOBLOCK, copy=False
104
+ ).result()
105
+ except zmq.Again:
106
+ break
107
+ batch.append(frames)
108
+ size += sum(len(frame) for frame in frames)
109
+ await self._handle_batch(batch)
110
+ # A recv with frames already queued resolves without yielding: give the
111
+ # rest of the loop a turn between batches of a deep backlog.
112
+ await asyncio.sleep(0)
113
+
114
+ async def _handle_batch(self, batch: list[list[zmq.Frame]]) -> None:
115
+ """Decode a batch's deltas, then apply each delta and resolve each reply in
116
+ arrival order, so a run's reply lands after its last delta. A bad frame or a
117
+ delta handler that raises is logged and skipped rather than allowed to end
118
+ the loop or lose its neighbours."""
119
+ # (request_id, data, delta handler) — a reply carries no handler
120
+ routed: list[tuple[str, zmq.Frame, Callable[[dict], None] | None]] = []
121
+ for frames in batch:
77
122
  try:
78
123
  if len(frames) != 3:
79
124
  raise ValueError(
@@ -83,20 +128,38 @@ class EnvClient:
83
128
  request_id_frame, kind_frame, data_frame = frames
84
129
  request_id = request_id_frame.bytes.decode()
85
130
  kind = kind_frame.bytes
86
- if kind == b"delta":
87
- on_delta = self._deltas.get(request_id)
88
- if on_delta is not None:
89
- # The view retains its ZMQ frame while a cancelled worker finishes.
90
- delta = await self._decode(
91
- unpack, data_frame.buffer.toreadonly()
92
- )
93
- # Cancellation may remove the handler while the worker decodes.
94
- if self._deltas.get(request_id) is on_delta:
95
- on_delta(delta)
96
- continue
131
+ except Exception: # keep receiving for the other requests
132
+ logger.warning("dropping a malformed env-server frame", exc_info=True)
133
+ continue
134
+ if kind != b"delta":
135
+ routed.append((request_id, data_frame, None))
136
+ elif (on_delta := self._deltas.get(request_id)) is not None:
137
+ routed.append((request_id, data_frame, on_delta))
138
+ # The views retain their ZMQ frames while a cancelled worker finishes.
139
+ payloads = [
140
+ data_frame.buffer.toreadonly()
141
+ for _, data_frame, on_delta in routed
142
+ if on_delta is not None
143
+ ]
144
+ if sum(payload.nbytes for payload in payloads) <= INLINE_DECODE_BYTES:
145
+ decoded = iter(_unpack_all(payloads))
146
+ else:
147
+ decoded = iter(await asyncio.to_thread(_unpack_all, payloads))
148
+ for request_id, data_frame, on_delta in routed:
149
+ if on_delta is None:
97
150
  future = self._pending.pop(request_id, None)
98
151
  if future is not None and not future.done():
99
152
  future.set_result(data_frame.bytes)
153
+ continue
154
+ delta = next(decoded)
155
+ if isinstance(delta, Exception):
156
+ logger.warning("dropping a malformed env-server frame", exc_info=delta)
157
+ continue
158
+ # Cancellation may remove the handler while the worker decodes.
159
+ if self._deltas.get(request_id) is not on_delta:
160
+ continue
161
+ try:
162
+ on_delta(delta)
100
163
  except Exception: # keep receiving for the other requests
101
164
  logger.warning("dropping a malformed env-server frame", exc_info=True)
102
165
 
@@ -145,7 +208,9 @@ class EnvClient:
145
208
  return response
146
209
 
147
210
  async def _decode(self, decode: Callable[..., DecodedT], *args: object) -> DecodedT:
148
- """Decode off the loop, sharing one slot with final episode validation."""
211
+ """Validate a finished episode off the loop, one at a time per client. The
212
+ receive loop decodes its own batches, so a large episode validating here
213
+ never holds up another run's deltas."""
149
214
  await self._decode_slots.acquire()
150
215
  decoding = asyncio.create_task(asyncio.to_thread(decode, *args))
151
216
  # Hold the slot until the worker finishes so cancellation cannot overlap decodes.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: verifiers
3
- Version: 0.4.1.dev80
3
+ Version: 0.4.1.dev82
4
4
  Summary: Verifiers: Environments for LLM Reinforcement Learning
5
5
  Project-URL: Homepage, https://github.com/primeintellect-ai/verifiers
6
6
  Project-URL: Documentation, https://github.com/primeintellect-ai/verifiers
@@ -30,7 +30,7 @@ Requires-Dist: httpx2>=2.12.0
30
30
  Requires-Dist: httpx>=0.27.0
31
31
  Requires-Dist: loguru>=0.7.0
32
32
  Requires-Dist: math-verify>=0.8.0
33
- Requires-Dist: mcp==2.0.0
33
+ Requires-Dist: mcp==2.2.0
34
34
  Requires-Dist: msgpack>=1.1.2
35
35
  Requires-Dist: numpy>=2.1.0
36
36
  Requires-Dist: openai<3.0.0,>=2.54.0
@@ -149,7 +149,7 @@ verifiers/v1/judges/rubric.py,sha256=yRaOnc6S6cqrLuySkMsgxsBFCRUA2bBjYSa5qOT-inQ
149
149
  verifiers/v1/judges/rubric.txt,sha256=3KA2ZeYYdcDweJhUGopxu9EFgARhu2aWft5S5cj8Bc8,323
150
150
  verifiers/v1/mcp/__init__.py,sha256=pm8ZWBiL1q1tY4wHvJzM_QrZ9oR8aGm-bIRWiRJsgHI,408
151
151
  verifiers/v1/mcp/launch.py,sha256=nZHHOHaHirTVcr6Vevh9iflJQQfm9xYjStHRaXp9-Q8,30574
152
- verifiers/v1/mcp/server.py,sha256=Jqi8OMT8DnoZegXqM3UNNRzhVnbdrPEwx0DjOJo_K2A,13256
152
+ verifiers/v1/mcp/server.py,sha256=DT3xRf3Gx9lpYM7IdHOrB1yUoDaylqHEAmJ1QO_HoDs,13771
153
153
  verifiers/v1/mcp/toolset.py,sha256=Il_SVt8LG-vIXfPi5TmURZ5O94lXSuNsSO-G0SjjaAI,2290
154
154
  verifiers/v1/runtimes/__init__.py,sha256=JrBktZBcRLSnnZh_Er9IuGOVBGYUybJSPHi1q_b-UrI,3386
155
155
  verifiers/v1/runtimes/base.py,sha256=9hFlybPMQn0yo3efsVLAPJshMHIttuIme4FPqfdowno,15529
@@ -165,7 +165,7 @@ verifiers/v1/runtimes/backends/docker.py,sha256=k4I_LorHi-SpXjKwBoKUaxdrU8e3URPn
165
165
  verifiers/v1/runtimes/backends/prime.py,sha256=KwsHQUDxecaRVDtEeSzTK8wKkf_-6nIwxmxJJ_1N9Zo,23862
166
166
  verifiers/v1/runtimes/backends/subprocess.py,sha256=dCfazoyJHwrfb2fMNRv6QzD6EsYlZXcEDT0x-8MAp3I,8419
167
167
  verifiers/v1/serve/__init__.py,sha256=wOKuwfugzmDT4yIniwzCXlf4G6tv6Cg8Kc--WMa38Bs,553
168
- verifiers/v1/serve/client.py,sha256=1J9DSuJd6KyEN4C-qYjGHLjlnZXeSkdPhyHzZK6Sk-A,10328
168
+ verifiers/v1/serve/client.py,sha256=v-R17h3Tfcaw5395sf9ctXKW-HF_ldH_bvrW-FXrJ7E,13513
169
169
  verifiers/v1/serve/delta.py,sha256=hj6uFfUmUWrdIAqgWI7bj-yUlej-P1UEEWaXYqTgUk8,13861
170
170
  verifiers/v1/serve/encoding.py,sha256=hBZFucAZK9riXOV3DaHcskq9zHTT8gVGkoFVOPfnr30,2499
171
171
  verifiers/v1/serve/pool.py,sha256=pUvUhAvcTkLinFuTJJOp6pqi_sQdWsjJS4clLzgkRhc,16362
@@ -207,8 +207,8 @@ verifiers/v1/utils/scope.py,sha256=bzUEiWDOVdbj7dXOwGOlzsQ_-Xu0j9NR5TalQB-8TS8,8
207
207
  verifiers/v1/utils/score.py,sha256=493yJVMw8teCu9JxapxMFPFzI0hNUqdo0Y2nGW4kckk,6200
208
208
  verifiers/v1/utils/trace_store.py,sha256=Qo9qvsJAl8PoRUavjQAfUB2VNxmUtYQtU2ejLKPzY9c,3382
209
209
  verifiers/v1/utils/version.py,sha256=-obEo_-l9-D8FLef4hYxncOe-uJpxrM1g2Hig_37Sgs,1607
210
- verifiers-0.4.1.dev80.dist-info/METADATA,sha256=mnfV3X0CeBJIqvI0Ld_Z_W6FYxaX8d0p9PhfwOSHyUA,5234
211
- verifiers-0.4.1.dev80.dist-info/WHEEL,sha256=W3fkpkm7-wf9vBI5Z-7s0eWkeM-spu78I8Neb98DeEg,87
212
- verifiers-0.4.1.dev80.dist-info/entry_points.txt,sha256=O1bIO0gyJWuLfWtTGF0h-JkNz6FkyXP7Z9iMFYnjeMI,222
213
- verifiers-0.4.1.dev80.dist-info/licenses/LICENSE,sha256=v0RrUsdV3IDoZhrRce297IXS3xMHNJ-_LdLpFAUWb9k,1072
214
- verifiers-0.4.1.dev80.dist-info/RECORD,,
210
+ verifiers-0.4.1.dev82.dist-info/METADATA,sha256=KQdLSgwMsSMJ8iBdVxdEI0YyjQWtAylahiTIczE6-H8,5234
211
+ verifiers-0.4.1.dev82.dist-info/WHEEL,sha256=W3fkpkm7-wf9vBI5Z-7s0eWkeM-spu78I8Neb98DeEg,87
212
+ verifiers-0.4.1.dev82.dist-info/entry_points.txt,sha256=O1bIO0gyJWuLfWtTGF0h-JkNz6FkyXP7Z9iMFYnjeMI,222
213
+ verifiers-0.4.1.dev82.dist-info/licenses/LICENSE,sha256=v0RrUsdV3IDoZhrRce297IXS3xMHNJ-_LdLpFAUWb9k,1072
214
+ verifiers-0.4.1.dev82.dist-info/RECORD,,