verifiers 0.4.2.dev96__py3-none-any.whl → 0.4.2.dev108__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.
- verifiers/v1/graph.py +4 -2
- verifiers/v1/harnesses/utils/core.py +94 -10
- verifiers/v1/interception/server.py +20 -8
- verifiers/v1/rollout.py +3 -4
- verifiers/v1/session.py +425 -117
- verifiers/v1/trace.py +17 -1
- verifiers/v1/utils/decorators.py +5 -4
- {verifiers-0.4.2.dev96.dist-info → verifiers-0.4.2.dev108.dist-info}/METADATA +1 -1
- {verifiers-0.4.2.dev96.dist-info → verifiers-0.4.2.dev108.dist-info}/RECORD +12 -12
- {verifiers-0.4.2.dev96.dist-info → verifiers-0.4.2.dev108.dist-info}/WHEEL +0 -0
- {verifiers-0.4.2.dev96.dist-info → verifiers-0.4.2.dev108.dist-info}/entry_points.txt +0 -0
- {verifiers-0.4.2.dev96.dist-info → verifiers-0.4.2.dev108.dist-info}/licenses/LICENSE +0 -0
verifiers/v1/graph.py
CHANGED
|
@@ -683,8 +683,9 @@ class PendingTurn:
|
|
|
683
683
|
"""The request failed or was cancelled before a commit: its preview goes."""
|
|
684
684
|
self.trace.clear_preview(self)
|
|
685
685
|
|
|
686
|
-
def commit_prompt(self) -> None:
|
|
687
|
-
"""Record an input that terminated before model inference
|
|
686
|
+
def commit_prompt(self) -> int | None:
|
|
687
|
+
"""Record an input that terminated before model inference; returns the last
|
|
688
|
+
prompt node's id, or None when the prompt was empty."""
|
|
688
689
|
parent = self.prefix_node_ids[-1] if self.prefix_node_ids else None
|
|
689
690
|
_head_index(self.trace, self.dialect)
|
|
690
691
|
for message in self.tail:
|
|
@@ -711,6 +712,7 @@ class PendingTurn:
|
|
|
711
712
|
}.values()
|
|
712
713
|
)
|
|
713
714
|
self.trace.clear_preview(self)
|
|
715
|
+
return parent
|
|
714
716
|
|
|
715
717
|
|
|
716
718
|
def prepare_turn(
|
|
@@ -2,14 +2,19 @@
|
|
|
2
2
|
|
|
3
3
|
import argparse
|
|
4
4
|
import asyncio
|
|
5
|
+
import fcntl
|
|
5
6
|
import json
|
|
6
7
|
import logging
|
|
7
8
|
import os
|
|
9
|
+
import select
|
|
8
10
|
import selectors
|
|
11
|
+
import struct
|
|
9
12
|
import subprocess
|
|
13
|
+
import termios
|
|
14
|
+
import threading
|
|
10
15
|
import time
|
|
11
16
|
import traceback
|
|
12
|
-
from contextlib import AsyncExitStack
|
|
17
|
+
from contextlib import AsyncExitStack, suppress
|
|
13
18
|
from pathlib import Path
|
|
14
19
|
from typing import TYPE_CHECKING
|
|
15
20
|
|
|
@@ -199,25 +204,94 @@ class _BashOutput:
|
|
|
199
204
|
self.size += len(chunk)
|
|
200
205
|
|
|
201
206
|
|
|
207
|
+
BASH_TIMEOUT = 3600
|
|
208
|
+
|
|
209
|
+
EXIT_GRACE = 0.5
|
|
210
|
+
"""Seconds to keep reading after bash exits, e.g. for a process substitution."""
|
|
211
|
+
|
|
212
|
+
BACKGROUND_NOTE = "[a process started by this command is still running and holds its output; later output is not shown]"
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
def _pending(fd: int) -> int:
|
|
216
|
+
"""Bytes waiting in a pipe right now."""
|
|
217
|
+
return struct.unpack("i", fcntl.ioctl(fd, termios.FIONREAD, b"\0" * 4))[0]
|
|
218
|
+
|
|
219
|
+
|
|
220
|
+
def _at_end(fd: int) -> bool:
|
|
221
|
+
"""Whether every writer has closed the pipe; late bytes read here are dropped."""
|
|
222
|
+
poller = select.poll() # select.select rejects fds >= 1024
|
|
223
|
+
poller.register(fd, select.POLLIN)
|
|
224
|
+
if not poller.poll(0):
|
|
225
|
+
return False
|
|
226
|
+
return not os.read(fd, 65536)
|
|
227
|
+
|
|
228
|
+
|
|
229
|
+
def _discard_until_eof(fd: int) -> None:
|
|
230
|
+
"""Read a held pipe to EOF, so its writer neither blocks nor gets SIGPIPE."""
|
|
231
|
+
with open(fd, "rb", buffering=0) as pipe:
|
|
232
|
+
while pipe.read(65536):
|
|
233
|
+
pass
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
def _drain_in_background(fd: int) -> None:
|
|
237
|
+
"""Drain a held pipe on a daemon thread; never raises."""
|
|
238
|
+
try:
|
|
239
|
+
copy = os.dup(fd)
|
|
240
|
+
except OSError:
|
|
241
|
+
return
|
|
242
|
+
try:
|
|
243
|
+
threading.Thread(target=_discard_until_eof, args=(copy,), daemon=True).start()
|
|
244
|
+
except Exception: # noqa: BLE001 - e.g. no more threads
|
|
245
|
+
with suppress(OSError):
|
|
246
|
+
os.close(copy)
|
|
247
|
+
|
|
248
|
+
|
|
202
249
|
def run_bash(command: str) -> str:
|
|
250
|
+
held_open = False
|
|
203
251
|
try:
|
|
204
252
|
with subprocess.Popen(
|
|
205
253
|
["bash", "-c", command],
|
|
254
|
+
stdin=subprocess.DEVNULL,
|
|
206
255
|
stdout=subprocess.PIPE,
|
|
207
256
|
stderr=subprocess.PIPE,
|
|
208
257
|
) as process:
|
|
209
258
|
stdout, stderr = _BashOutput(), _BashOutput()
|
|
210
|
-
deadline = time.monotonic() +
|
|
259
|
+
deadline = time.monotonic() + BASH_TIMEOUT
|
|
260
|
+
exited = None
|
|
211
261
|
try:
|
|
212
262
|
with selectors.DefaultSelector() as selector:
|
|
213
263
|
assert process.stdout is not None and process.stderr is not None
|
|
214
264
|
selector.register(process.stdout, selectors.EVENT_READ, stdout)
|
|
215
265
|
selector.register(process.stderr, selectors.EVENT_READ, stderr)
|
|
216
266
|
while selector.get_map():
|
|
217
|
-
|
|
218
|
-
if
|
|
219
|
-
|
|
220
|
-
|
|
267
|
+
now = time.monotonic()
|
|
268
|
+
if exited is None and process.poll() is not None:
|
|
269
|
+
exited = now
|
|
270
|
+
if exited is None:
|
|
271
|
+
if now >= deadline:
|
|
272
|
+
raise subprocess.TimeoutExpired(
|
|
273
|
+
process.args, BASH_TIMEOUT
|
|
274
|
+
)
|
|
275
|
+
wait = min(deadline - now, 0.1)
|
|
276
|
+
elif now - exited < EXIT_GRACE:
|
|
277
|
+
# A process bash did not wait for may still be writing.
|
|
278
|
+
wait = exited + EXIT_GRACE - now
|
|
279
|
+
else:
|
|
280
|
+
# A pipe still open is held by a job left running.
|
|
281
|
+
for key in list(selector.get_map().values()):
|
|
282
|
+
pending = _pending(key.fd)
|
|
283
|
+
while pending > 0:
|
|
284
|
+
chunk = os.read(key.fd, min(pending, 65536))
|
|
285
|
+
if not chunk:
|
|
286
|
+
break
|
|
287
|
+
pending -= len(chunk)
|
|
288
|
+
key.data.add(chunk)
|
|
289
|
+
selector.unregister(key.fileobj)
|
|
290
|
+
if not _at_end(key.fd):
|
|
291
|
+
held_open = True
|
|
292
|
+
_drain_in_background(key.fd)
|
|
293
|
+
break
|
|
294
|
+
for key, _ in selector.select(wait):
|
|
221
295
|
chunk = os.read(key.fd, 8192)
|
|
222
296
|
if chunk:
|
|
223
297
|
key.data.add(chunk)
|
|
@@ -230,19 +304,29 @@ def run_bash(command: str) -> str:
|
|
|
230
304
|
process.kill()
|
|
231
305
|
process.wait()
|
|
232
306
|
size = stdout.size + stderr.size
|
|
233
|
-
|
|
307
|
+
# Leave room for the note.
|
|
308
|
+
budget = TOOL_OUTPUT_MAX_BYTES - (
|
|
309
|
+
len(BACKGROUND_NOTE.encode()) + 1 if held_open else 0
|
|
310
|
+
)
|
|
311
|
+
if size <= budget:
|
|
312
|
+
# A held pipe may be cut mid-character.
|
|
234
313
|
text = "".join(
|
|
235
|
-
output.head.decode(
|
|
314
|
+
output.head.decode(errors="replace")
|
|
315
|
+
.replace("\r\n", "\n")
|
|
316
|
+
.replace("\r", "\n")
|
|
236
317
|
for output in (stdout, stderr)
|
|
237
318
|
)
|
|
238
319
|
else:
|
|
239
320
|
marker = f"\n[... bash output truncated; {size} bytes total ...]\n"
|
|
240
|
-
keep = (
|
|
321
|
+
keep = (budget - len(marker.encode())) // 2
|
|
241
322
|
# Preserve stdout-then-stderr ordering, including when just one is large.
|
|
242
323
|
head = (stdout.head + stderr.head)[:keep].decode(errors="ignore")
|
|
243
324
|
tail = (stdout.tail + stderr.tail)[-keep:].decode(errors="ignore")
|
|
244
325
|
text = head + marker + tail
|
|
245
|
-
|
|
326
|
+
text = text.replace("\r\n", "\n").replace("\r", "\n")
|
|
327
|
+
if held_open:
|
|
328
|
+
text += ("\n" if text and not text.endswith("\n") else "") + BACKGROUND_NOTE
|
|
329
|
+
return text
|
|
246
330
|
except Exception as e: # noqa: BLE001 - tool failures are returned to the model
|
|
247
331
|
return f"error: {e}"
|
|
248
332
|
|
|
@@ -872,7 +872,7 @@ class InterceptionServer(Interception):
|
|
|
872
872
|
model_request, request_rewrites, stopped = await session.rewrite_request(
|
|
873
873
|
model_request, dialect=dialect.name
|
|
874
874
|
)
|
|
875
|
-
session.
|
|
875
|
+
session.stage_rewrites(replay_key, request_rewrites)
|
|
876
876
|
# A pinned tool result changes the request without a fresh record.
|
|
877
877
|
if stopped is None and model_request != original_request:
|
|
878
878
|
dialect.rewrite_request(body, original_request, model_request)
|
|
@@ -897,13 +897,17 @@ class InterceptionServer(Interception):
|
|
|
897
897
|
except BaseException:
|
|
898
898
|
raise
|
|
899
899
|
if stopped is not None:
|
|
900
|
+
stop_name, stop_info = stopped
|
|
900
901
|
turn = graph.prepare_turn(
|
|
901
902
|
session.trace, model_request.messages, model_request.tools, dialect.name
|
|
902
903
|
)
|
|
903
|
-
|
|
904
|
-
|
|
905
|
-
|
|
904
|
+
session.commit_rewrites(
|
|
905
|
+
turn, turn.commit_prompt(), request_rewrites, replay_key=replay_key
|
|
906
|
+
)
|
|
907
|
+
session.trace.stop(stop_name, info=stop_info)
|
|
908
|
+
return _error_response(dialect, f"rollout stopped: {stop_name}", status=400)
|
|
906
909
|
|
|
910
|
+
pre_mediation_request = model_request
|
|
907
911
|
try:
|
|
908
912
|
body, policy_paths = self.mediate_capabilities(session, dialect, body)
|
|
909
913
|
# Restricted mediation can mutate the body without reporting policy paths.
|
|
@@ -1006,16 +1010,24 @@ class InterceptionServer(Interception):
|
|
|
1006
1010
|
status=400,
|
|
1007
1011
|
)
|
|
1008
1012
|
node = turn.commit(call_response)
|
|
1009
|
-
session.
|
|
1010
|
-
|
|
1013
|
+
session.commit_rewrites(
|
|
1014
|
+
turn,
|
|
1015
|
+
session.trace.nodes[node].parent,
|
|
1016
|
+
request_rewrites,
|
|
1017
|
+
response_rewrites,
|
|
1018
|
+
node,
|
|
1019
|
+
pre_request=pre_mediation_request,
|
|
1020
|
+
replay_key=replay_key,
|
|
1021
|
+
)
|
|
1011
1022
|
if stopped is None:
|
|
1012
1023
|
stopped = await session.gate_tool_calls(
|
|
1013
1024
|
node, dialect.name, harness_history
|
|
1014
1025
|
)
|
|
1015
1026
|
if stopped is not None:
|
|
1016
|
-
|
|
1027
|
+
stop_name, stop_info = stopped
|
|
1028
|
+
session.trace.stop(stop_name, info=stop_info)
|
|
1017
1029
|
return _error_response(
|
|
1018
|
-
dialect, f"rollout stopped: {
|
|
1030
|
+
dialect, f"rollout stopped: {stop_name}", status=400
|
|
1019
1031
|
)
|
|
1020
1032
|
except RolloutError as e:
|
|
1021
1033
|
# Stash the real cause; the rollout re-raises it after the harness returns.
|
verifiers/v1/rollout.py
CHANGED
|
@@ -502,11 +502,10 @@ class Rollout:
|
|
|
502
502
|
has_system = system_prompt is not None
|
|
503
503
|
if has_system:
|
|
504
504
|
messages.insert(0, SystemMessage(content=system_prompt))
|
|
505
|
-
prepared,
|
|
505
|
+
prepared, _ = await self._session.prepare_users(
|
|
506
506
|
Request(messages=messages)
|
|
507
507
|
)
|
|
508
508
|
messages = prepared.messages
|
|
509
|
-
self.trace.request_rewrites.extend(rewrites)
|
|
510
509
|
if has_system:
|
|
511
510
|
messages = messages[1:]
|
|
512
511
|
rewritten_prompt = (
|
|
@@ -614,11 +613,10 @@ class Rollout:
|
|
|
614
613
|
async with deadline:
|
|
615
614
|
assert self._harness_session is not None
|
|
616
615
|
if messages is not None and self._session.request_interceptors:
|
|
617
|
-
prepared,
|
|
616
|
+
prepared, _ = await self._session.prepare_users(
|
|
618
617
|
Request(messages=messages)
|
|
619
618
|
)
|
|
620
619
|
messages = prepared.messages
|
|
621
|
-
self.trace.request_rewrites.extend(rewrites)
|
|
622
620
|
if self._session.stopped:
|
|
623
621
|
return False
|
|
624
622
|
self._session.on_turn_input = on_input
|
|
@@ -811,6 +809,7 @@ class Rollout:
|
|
|
811
809
|
)
|
|
812
810
|
if not self._agent_finished():
|
|
813
811
|
await self._close_harness()
|
|
812
|
+
self._session.flush_rewrites()
|
|
814
813
|
trace.notify()
|
|
815
814
|
if not self._failed and self._opened:
|
|
816
815
|
assert runtime is not None
|
verifiers/v1/session.py
CHANGED
|
@@ -15,15 +15,18 @@ or the graph.
|
|
|
15
15
|
"""
|
|
16
16
|
|
|
17
17
|
import asyncio
|
|
18
|
+
import copy
|
|
18
19
|
import hashlib
|
|
19
20
|
import inspect
|
|
20
21
|
import json
|
|
21
22
|
from collections import Counter
|
|
22
|
-
from collections.abc import
|
|
23
|
+
from collections.abc import Callable, Iterable, Iterator, Mapping, Sequence
|
|
23
24
|
from contextlib import AbstractAsyncContextManager
|
|
24
25
|
from dataclasses import dataclass, field, replace
|
|
26
|
+
from difflib import SequenceMatcher
|
|
25
27
|
from functools import cached_property
|
|
26
|
-
from
|
|
28
|
+
from itertools import chain
|
|
29
|
+
from typing import Any, TypeVar, get_origin, get_type_hints
|
|
27
30
|
|
|
28
31
|
from pydantic import TypeAdapter
|
|
29
32
|
|
|
@@ -31,14 +34,17 @@ from verifiers.v1 import graph
|
|
|
31
34
|
from verifiers.v1.clients import Client, ModelContext, ModelRoute
|
|
32
35
|
from verifiers.v1.configs.harness import DialectName
|
|
33
36
|
from verifiers.v1.configs.runtime import NetworkPolicyConfig
|
|
37
|
+
from verifiers.v1.dialects.base import CAPABILITY_NOTICE
|
|
34
38
|
from verifiers.v1.errors import HarnessError, RolloutError, TaskError
|
|
35
39
|
from verifiers.v1.harnesses.utils.compaction import bound_tool_message
|
|
36
40
|
from verifiers.v1.trace import InterceptRecord, Trace
|
|
37
41
|
from verifiers.v1.types import (
|
|
38
42
|
AssistantMessage,
|
|
43
|
+
Message,
|
|
39
44
|
Messages,
|
|
40
45
|
Request,
|
|
41
46
|
Response,
|
|
47
|
+
TextContentPart,
|
|
42
48
|
ToolCall,
|
|
43
49
|
ToolMessage,
|
|
44
50
|
UserMessage,
|
|
@@ -55,6 +61,9 @@ logger = get_logger(__name__)
|
|
|
55
61
|
|
|
56
62
|
MCPProxy = Callable[[str], AbstractAsyncContextManager[str]]
|
|
57
63
|
ToolResultKey = tuple[int | str, str]
|
|
64
|
+
StopVerdict = tuple[str, dict[str, Any]]
|
|
65
|
+
PendingRewrite = tuple[int | None, InterceptRecord]
|
|
66
|
+
HookT = TypeVar("HookT", Request, Response, bool)
|
|
58
67
|
|
|
59
68
|
|
|
60
69
|
def hook_boundary(handler: Callable, *, allow_trace: bool) -> type:
|
|
@@ -79,6 +88,157 @@ async def call_hook(handler: Callable, available: dict[type, object]) -> object:
|
|
|
79
88
|
return await result if inspect.isawaitable(result) else result
|
|
80
89
|
|
|
81
90
|
|
|
91
|
+
def unpack_hook(result: object, expected: type[HookT]) -> tuple[HookT, dict[str, Any]]:
|
|
92
|
+
"""Unpack `value` or `(value, metadata)` returned by an `@intercept` or `@stop` hook."""
|
|
93
|
+
match result:
|
|
94
|
+
case (value, Mapping() as info) if all(isinstance(k, str) for k in info):
|
|
95
|
+
pass
|
|
96
|
+
case tuple():
|
|
97
|
+
raise TypeError(f"expected ({expected.__name__}, dict[str, Any])")
|
|
98
|
+
case value:
|
|
99
|
+
info = {}
|
|
100
|
+
if not isinstance(value, expected):
|
|
101
|
+
raise TypeError(f"expected {expected.__name__}, got {type(value).__name__}")
|
|
102
|
+
return value, copy.deepcopy(dict(info))
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def _tool_calls(messages: Iterable[Message]) -> dict[str, ToolCall]:
|
|
106
|
+
calls: dict[str, ToolCall] = {}
|
|
107
|
+
for msg in messages:
|
|
108
|
+
if isinstance(msg, AssistantMessage) and msg.tool_calls:
|
|
109
|
+
calls.update((call.id, call) for call in msg.tool_calls)
|
|
110
|
+
return calls
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def _tool_call(calls: dict[str, ToolCall], message: Message) -> ToolCall | None:
|
|
114
|
+
if not isinstance(message, ToolMessage):
|
|
115
|
+
return None
|
|
116
|
+
return calls.get(
|
|
117
|
+
message.tool_call_id,
|
|
118
|
+
ToolCall(id=message.tool_call_id, name=message.name or "", arguments=""),
|
|
119
|
+
)
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def _make_record(
|
|
123
|
+
handler: Callable,
|
|
124
|
+
node: int | None,
|
|
125
|
+
pos: int,
|
|
126
|
+
calls: dict[str, ToolCall],
|
|
127
|
+
message: Message,
|
|
128
|
+
info: dict[str, Any],
|
|
129
|
+
) -> PendingRewrite:
|
|
130
|
+
rec = InterceptRecord(
|
|
131
|
+
handler=handler.__name__,
|
|
132
|
+
node=node,
|
|
133
|
+
tool_call=_tool_call(calls, message),
|
|
134
|
+
info=copy.deepcopy(info),
|
|
135
|
+
)
|
|
136
|
+
return (pos if node is None else None, rec)
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def _role_key(message: Message) -> tuple[type, str]:
|
|
140
|
+
return (
|
|
141
|
+
type(message),
|
|
142
|
+
message.tool_call_id if isinstance(message, ToolMessage) else "",
|
|
143
|
+
)
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def _align_role_slice(
|
|
147
|
+
before: Messages, after: Messages, nodes: list[int]
|
|
148
|
+
) -> Iterator[tuple[int, int]]:
|
|
149
|
+
b_keys = [_role_key(m) for m in before]
|
|
150
|
+
a_keys = [_role_key(m) for m in after]
|
|
151
|
+
for tag, i1, i2, j1, j2 in SequenceMatcher(
|
|
152
|
+
None, b_keys, a_keys, autojunk=False
|
|
153
|
+
).get_opcodes():
|
|
154
|
+
if tag == "equal":
|
|
155
|
+
yield from zip(range(i1, i2), nodes[j1:j2])
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def _strip_notice(message: Message) -> Message:
|
|
159
|
+
if not isinstance(message, UserMessage):
|
|
160
|
+
return message
|
|
161
|
+
if isinstance(message.content, str):
|
|
162
|
+
if message.content.startswith(CAPABILITY_NOTICE):
|
|
163
|
+
return message.model_copy(update={"content": ""})
|
|
164
|
+
head, sep, _ = message.content.partition(f"\n\n{CAPABILITY_NOTICE}")
|
|
165
|
+
return message.model_copy(update={"content": head}) if sep else message
|
|
166
|
+
if (
|
|
167
|
+
message.content
|
|
168
|
+
and isinstance(last := message.content[-1], TextContentPart)
|
|
169
|
+
and last.text.startswith(CAPABILITY_NOTICE)
|
|
170
|
+
):
|
|
171
|
+
return message.model_copy(update={"content": message.content[:-1]})
|
|
172
|
+
return message
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def _align_nodes(
|
|
176
|
+
before: Messages, after: Messages, prompt_nodes: list[int]
|
|
177
|
+
) -> dict[int, int]:
|
|
178
|
+
"""Map pre-mediation message indices in `before` to committed `prompt_nodes`."""
|
|
179
|
+
trimmed = (
|
|
180
|
+
after[:-1]
|
|
181
|
+
if after
|
|
182
|
+
and isinstance(after[-1], UserMessage)
|
|
183
|
+
and not any(isinstance(m, UserMessage) for m in before)
|
|
184
|
+
else after
|
|
185
|
+
)
|
|
186
|
+
if [_role_key(m) for m in before] == [_role_key(m) for m in trimmed]:
|
|
187
|
+
return {i: prompt_nodes[i] for i in range(len(trimmed))}
|
|
188
|
+
b_hashes = [graph.message_hash(m) for m in before]
|
|
189
|
+
a_hashes = [graph.message_hash(_strip_notice(m)) for m in trimmed]
|
|
190
|
+
mapping: dict[int, int] = {}
|
|
191
|
+
for tag, i1, i2, j1, j2 in SequenceMatcher(
|
|
192
|
+
None, b_hashes, a_hashes, autojunk=False
|
|
193
|
+
).get_opcodes():
|
|
194
|
+
if tag == "equal":
|
|
195
|
+
mapping.update(zip(range(i1, i2), prompt_nodes[j1:j2]))
|
|
196
|
+
elif tag == "replace":
|
|
197
|
+
mapping.update(
|
|
198
|
+
(i1 + rel_i, nid)
|
|
199
|
+
for rel_i, nid in _align_role_slice(
|
|
200
|
+
before[i1:i2], trimmed[j1:j2], prompt_nodes[j1:j2]
|
|
201
|
+
)
|
|
202
|
+
)
|
|
203
|
+
return mapping
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
def _diff_request_rewrite(
|
|
207
|
+
current: Request, result: Request, active: set[int]
|
|
208
|
+
) -> list[int]:
|
|
209
|
+
"""Validate a request rewrite in place and return the positions that changed."""
|
|
210
|
+
if len(result.messages) != len(current.messages):
|
|
211
|
+
raise ValueError("request interceptors cannot add or remove messages")
|
|
212
|
+
if result.tools != current.tools:
|
|
213
|
+
raise ValueError("request interceptors cannot rewrite tools")
|
|
214
|
+
changed: list[int] = []
|
|
215
|
+
for pos, (before, after) in enumerate(
|
|
216
|
+
zip(current.messages, result.messages, strict=True)
|
|
217
|
+
):
|
|
218
|
+
if before == after:
|
|
219
|
+
continue
|
|
220
|
+
if pos not in active:
|
|
221
|
+
raise ValueError(
|
|
222
|
+
"request interceptors can only rewrite new user or tool messages"
|
|
223
|
+
)
|
|
224
|
+
if type(after) is not type(before):
|
|
225
|
+
raise TypeError(
|
|
226
|
+
f"expected {type(before).__name__}, got {type(after).__name__}"
|
|
227
|
+
)
|
|
228
|
+
if isinstance(after, ToolMessage):
|
|
229
|
+
assert isinstance(before, ToolMessage)
|
|
230
|
+
after = ToolMessage.model_validate(bound_tool_message(after.model_dump()))
|
|
231
|
+
result.messages[pos] = after
|
|
232
|
+
if after.tool_call_id != before.tool_call_id or after.name != before.name:
|
|
233
|
+
raise ValueError(
|
|
234
|
+
"request interceptors cannot change a tool-call ID or name"
|
|
235
|
+
)
|
|
236
|
+
if after == before:
|
|
237
|
+
continue
|
|
238
|
+
changed.append(pos)
|
|
239
|
+
return changed
|
|
240
|
+
|
|
241
|
+
|
|
82
242
|
def same_arguments(call: ToolCall, arguments: object) -> bool:
|
|
83
243
|
"""Whether a gate's view of a call's arguments is the model's call, ignoring JSON form."""
|
|
84
244
|
try:
|
|
@@ -166,9 +326,7 @@ class RolloutSession:
|
|
|
166
326
|
trace: Trace
|
|
167
327
|
network_policy: NetworkPolicyConfig = field(default_factory=NetworkPolicyConfig)
|
|
168
328
|
"""The resolved execution policy, including task-level restrictions."""
|
|
169
|
-
trace_stops: list[Callable
|
|
170
|
-
default_factory=list
|
|
171
|
-
)
|
|
329
|
+
trace_stops: list[Callable] = field(default_factory=list)
|
|
172
330
|
limits: RolloutLimits = field(default_factory=RolloutLimits)
|
|
173
331
|
request_interceptors: list[Callable] = field(default_factory=list)
|
|
174
332
|
response_interceptors: list[Callable] = field(default_factory=list)
|
|
@@ -221,6 +379,17 @@ class RolloutSession:
|
|
|
221
379
|
tool_issuers: dict[tuple[str, str], set[int]] = field(default_factory=dict)
|
|
222
380
|
"""Sampled nodes that issued a call ID under a replay-equivalent prefix."""
|
|
223
381
|
prepared_users: Counter[str] = field(default_factory=Counter)
|
|
382
|
+
prepared_rewrites: list[tuple[int, InterceptRecord]] = field(default_factory=list)
|
|
383
|
+
"""`(user_slot, record)` pairs from `prepare_users` awaiting their prompt commit."""
|
|
384
|
+
_prepared_user_count: int = 0
|
|
385
|
+
pinned_rewrites: list[tuple[ToolResultKey, InterceptRecord]] = field(
|
|
386
|
+
default_factory=list
|
|
387
|
+
)
|
|
388
|
+
"""`(tool_key, record)` pairs for pinned tool results awaiting their node commit."""
|
|
389
|
+
inflight_rewrites: dict[str, list[tuple[int, InterceptRecord]]] = field(
|
|
390
|
+
default_factory=dict
|
|
391
|
+
)
|
|
392
|
+
"""Unpinned `(pos, record)` pairs keyed by `replay_key`, flushed if the turn never commits."""
|
|
224
393
|
last_request: tuple[list, Messages] = ((), [])
|
|
225
394
|
"""The last chat request's raw messages (copied: the server rewrites a body in place) and
|
|
226
395
|
their parse, which the next request's equal prefix reuses instead of parsing again."""
|
|
@@ -246,7 +415,7 @@ class RolloutSession:
|
|
|
246
415
|
self,
|
|
247
416
|
request: Request,
|
|
248
417
|
dialect: DialectName | None = None,
|
|
249
|
-
known_path: Sequence[int] = (),
|
|
418
|
+
known_path: Sequence[int] | Mapping[int, int] = (),
|
|
250
419
|
) -> dict[int, ToolResultKey]:
|
|
251
420
|
"""Use the sampled node and call ID for a model-issued tool. A harness-supplied
|
|
252
421
|
call outside the sampled graph uses its conversation prefix instead."""
|
|
@@ -273,14 +442,18 @@ class RolloutSession:
|
|
|
273
442
|
)
|
|
274
443
|
if isinstance(message, AssistantMessage) and message.tool_calls:
|
|
275
444
|
prefix_hash = prefix.hexdigest()
|
|
445
|
+
issuer_node: int | None = (
|
|
446
|
+
known_path.get(position)
|
|
447
|
+
if isinstance(known_path, Mapping)
|
|
448
|
+
else (known_path[position] if position < len(known_path) else None)
|
|
449
|
+
)
|
|
276
450
|
for call in message.tool_calls:
|
|
277
451
|
alias = (prefix_hash, call.id)
|
|
278
452
|
if (
|
|
279
|
-
|
|
280
|
-
and self.trace.nodes[
|
|
453
|
+
issuer_node is not None
|
|
454
|
+
and self.trace.nodes[issuer_node].sampled
|
|
281
455
|
):
|
|
282
|
-
|
|
283
|
-
calls[call.id] = (issuer, call.id)
|
|
456
|
+
calls[call.id] = (issuer_node, call.id)
|
|
284
457
|
else:
|
|
285
458
|
calls[call.id] = alias
|
|
286
459
|
return keys
|
|
@@ -313,6 +486,43 @@ class RolloutSession:
|
|
|
313
486
|
changed = True
|
|
314
487
|
return request.model_copy(update={"messages": messages}) if changed else request
|
|
315
488
|
|
|
489
|
+
async def _rewrite_boundary(
|
|
490
|
+
self,
|
|
491
|
+
current: Request,
|
|
492
|
+
active: set[int],
|
|
493
|
+
node: int | None,
|
|
494
|
+
) -> tuple[Request, list[PendingRewrite]]:
|
|
495
|
+
calls = _tool_calls((*(n.message for n in self.trace.nodes), *current.messages))
|
|
496
|
+
records: list[PendingRewrite] = []
|
|
497
|
+
for handler in self.request_interceptors if active else ():
|
|
498
|
+
raw = await call_hook(
|
|
499
|
+
handler, {Request: current.model_copy(deep=True), Trace: self.trace}
|
|
500
|
+
)
|
|
501
|
+
if raw is None:
|
|
502
|
+
continue
|
|
503
|
+
result, info = unpack_hook(raw, Request)
|
|
504
|
+
changed = _diff_request_rewrite(current, result, active)
|
|
505
|
+
if not changed:
|
|
506
|
+
continue
|
|
507
|
+
current = result
|
|
508
|
+
records.extend(
|
|
509
|
+
_make_record(handler, node, pos, calls, current.messages[pos], info)
|
|
510
|
+
for pos in changed
|
|
511
|
+
)
|
|
512
|
+
return current, records
|
|
513
|
+
|
|
514
|
+
async def _check_request_stops(self, current: Request) -> StopVerdict | None:
|
|
515
|
+
for stop in self.request_stops:
|
|
516
|
+
triggered, info = unpack_hook(
|
|
517
|
+
await call_hook(
|
|
518
|
+
stop, {Request: current.model_copy(deep=True), Trace: self.trace}
|
|
519
|
+
),
|
|
520
|
+
bool,
|
|
521
|
+
)
|
|
522
|
+
if triggered:
|
|
523
|
+
return stop.__name__, info
|
|
524
|
+
return None
|
|
525
|
+
|
|
316
526
|
async def rewrite_request(
|
|
317
527
|
self,
|
|
318
528
|
request: Request,
|
|
@@ -320,7 +530,8 @@ class RolloutSession:
|
|
|
320
530
|
run_stops: bool = True,
|
|
321
531
|
dialect: DialectName | None = None,
|
|
322
532
|
known_path: Sequence[int] = (),
|
|
323
|
-
|
|
533
|
+
node: int | None = None,
|
|
534
|
+
) -> tuple[Request, list[PendingRewrite], StopVerdict | None]:
|
|
324
535
|
"""Run typed request interceptors and stops over one canonical request. Only the
|
|
325
536
|
uncommitted tail's user and tool messages may change; a rewritten tool result is
|
|
326
537
|
pinned for the rest of the rollout."""
|
|
@@ -357,77 +568,23 @@ class RolloutSession:
|
|
|
357
568
|
if not boundaries or boundaries[-1] != len(request.messages):
|
|
358
569
|
boundaries.append(len(request.messages))
|
|
359
570
|
messages = list(request.messages)
|
|
360
|
-
records: list[
|
|
571
|
+
records: list[PendingRewrite] = []
|
|
361
572
|
previous = 0
|
|
362
573
|
try:
|
|
363
574
|
for end in boundaries:
|
|
364
|
-
active = {
|
|
365
|
-
position for position in candidates if previous <= position < end
|
|
366
|
-
}
|
|
575
|
+
active = {pos for pos in candidates if previous <= pos < end}
|
|
367
576
|
current = request.model_copy(update={"messages": messages[:end]})
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
)
|
|
373
|
-
if result is None:
|
|
374
|
-
continue
|
|
375
|
-
if not isinstance(result, Request):
|
|
376
|
-
raise TypeError(
|
|
377
|
-
f"expected Request, got {type(result).__name__}"
|
|
378
|
-
)
|
|
379
|
-
if len(result.messages) != len(current.messages):
|
|
380
|
-
raise ValueError(
|
|
381
|
-
"request interceptors cannot add or remove messages"
|
|
382
|
-
)
|
|
383
|
-
if result.tools != current.tools:
|
|
384
|
-
raise ValueError("request interceptors cannot rewrite tools")
|
|
385
|
-
for position, (before, after) in enumerate(
|
|
386
|
-
zip(current.messages, result.messages, strict=True)
|
|
387
|
-
):
|
|
388
|
-
if before == after:
|
|
389
|
-
continue
|
|
390
|
-
if position not in active:
|
|
391
|
-
raise ValueError(
|
|
392
|
-
"request interceptors can only rewrite new user or tool messages"
|
|
393
|
-
)
|
|
394
|
-
if type(after) is not type(before):
|
|
395
|
-
raise TypeError(
|
|
396
|
-
f"expected {type(before).__name__}, got {type(after).__name__}"
|
|
397
|
-
)
|
|
398
|
-
if isinstance(after, ToolMessage):
|
|
399
|
-
after = ToolMessage.model_validate(
|
|
400
|
-
bound_tool_message(after.model_dump())
|
|
401
|
-
)
|
|
402
|
-
result.messages[position] = after
|
|
403
|
-
if isinstance(before, ToolMessage) and (
|
|
404
|
-
after.tool_call_id != before.tool_call_id
|
|
405
|
-
or after.name != before.name
|
|
406
|
-
):
|
|
407
|
-
raise ValueError(
|
|
408
|
-
"request interceptors cannot change a tool-call ID or name"
|
|
409
|
-
)
|
|
410
|
-
if result != current:
|
|
411
|
-
current = result
|
|
412
|
-
records.append(InterceptRecord(handler=handler.__name__))
|
|
413
|
-
|
|
577
|
+
current, step_records = await self._rewrite_boundary(
|
|
578
|
+
current, active, node
|
|
579
|
+
)
|
|
580
|
+
records.extend(step_records)
|
|
414
581
|
messages[:end] = current.messages
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
582
|
+
if run_stops and (stopped := await self._check_request_stops(current)):
|
|
583
|
+
return (
|
|
584
|
+
request.model_copy(update={"messages": messages}),
|
|
585
|
+
records,
|
|
586
|
+
stopped,
|
|
420
587
|
)
|
|
421
|
-
if not isinstance(result, bool):
|
|
422
|
-
raise TypeError(
|
|
423
|
-
f"@stop must return bool, got {type(result).__name__}"
|
|
424
|
-
)
|
|
425
|
-
if result:
|
|
426
|
-
return (
|
|
427
|
-
request.model_copy(update={"messages": messages}),
|
|
428
|
-
records,
|
|
429
|
-
stop.__name__,
|
|
430
|
-
)
|
|
431
588
|
previous = end
|
|
432
589
|
except RolloutError:
|
|
433
590
|
raise
|
|
@@ -437,6 +594,7 @@ class RolloutSession:
|
|
|
437
594
|
) from error
|
|
438
595
|
current = request.model_copy(update={"messages": messages})
|
|
439
596
|
tool_keys = self.tool_result_keys(current, dialect, known_path)
|
|
597
|
+
pinned_positions: dict[int, ToolResultKey] = {}
|
|
440
598
|
for position in candidates:
|
|
441
599
|
after = current.messages[position]
|
|
442
600
|
if (
|
|
@@ -444,16 +602,147 @@ class RolloutSession:
|
|
|
444
602
|
and after != request.messages[position]
|
|
445
603
|
and position in tool_keys
|
|
446
604
|
):
|
|
447
|
-
|
|
605
|
+
tkey = tool_keys[position]
|
|
606
|
+
self.pinned_tool_results[tkey] = after
|
|
607
|
+
pinned_positions[position] = tkey
|
|
608
|
+
if node is None and pinned_positions:
|
|
609
|
+
replaced = set(pinned_positions.values())
|
|
610
|
+
self.pinned_rewrites = [
|
|
611
|
+
item for item in self.pinned_rewrites if item[0] not in replaced
|
|
612
|
+
]
|
|
613
|
+
for pos, rec in records:
|
|
614
|
+
if pos in pinned_positions:
|
|
615
|
+
self.pinned_rewrites.append((pinned_positions[pos], rec))
|
|
448
616
|
return current, records, None
|
|
449
617
|
|
|
450
|
-
def
|
|
451
|
-
|
|
452
|
-
|
|
618
|
+
def stage_rewrites(
|
|
619
|
+
self, replay_key: str, records: Iterable[PendingRewrite]
|
|
620
|
+
) -> None:
|
|
621
|
+
"""Hold in-request rewrites in case the model call fails before commit."""
|
|
622
|
+
staged = [(pos, rec) for pos, rec in records if pos is not None]
|
|
623
|
+
if staged:
|
|
624
|
+
self.inflight_rewrites[replay_key] = staged
|
|
625
|
+
else:
|
|
626
|
+
self.inflight_rewrites.pop(replay_key, None)
|
|
627
|
+
|
|
628
|
+
def commit_rewrites(
|
|
629
|
+
self,
|
|
630
|
+
turn: graph.PendingTurn,
|
|
631
|
+
last_prompt_node: int | None,
|
|
632
|
+
request_rewrites: Iterable[PendingRewrite] = (),
|
|
633
|
+
response_rewrites: Iterable[InterceptRecord] = (),
|
|
634
|
+
assistant_node: int | None = None,
|
|
635
|
+
*,
|
|
636
|
+
pre_request: Request | None = None,
|
|
637
|
+
replay_key: str | None = None,
|
|
638
|
+
) -> None:
|
|
639
|
+
"""Consume prepared user turns and attach committed node ids in execution order."""
|
|
640
|
+
pending_in_turn = list(
|
|
641
|
+
self.inflight_rewrites.pop(replay_key, ())
|
|
642
|
+
if replay_key is not None
|
|
643
|
+
else request_rewrites
|
|
644
|
+
)
|
|
645
|
+
for message in turn.tail:
|
|
453
646
|
if isinstance(message, UserMessage) and self.prepared_users:
|
|
454
647
|
key = graph.message_hash(message)
|
|
455
648
|
if self.prepared_users[key]:
|
|
456
649
|
self.prepared_users[key] -= 1
|
|
650
|
+
prompt_nodes = (
|
|
651
|
+
[]
|
|
652
|
+
if last_prompt_node is None
|
|
653
|
+
else graph.path_node_ids(self.trace, last_prompt_node)
|
|
654
|
+
)
|
|
655
|
+
tail_nodes = prompt_nodes[turn.tail_start :]
|
|
656
|
+
base = pre_request if pre_request is not None else Request(messages=turn.prompt)
|
|
657
|
+
node_by_pos = _align_nodes(base.messages, turn.prompt, prompt_nodes)
|
|
658
|
+
in_turn: list[InterceptRecord] = []
|
|
659
|
+
in_turn_ids: set[int] = set()
|
|
660
|
+
in_turn_nodes: set[int] = set()
|
|
661
|
+
for pos, rec in pending_in_turn:
|
|
662
|
+
if pos is None:
|
|
663
|
+
continue
|
|
664
|
+
nid = node_by_pos.get(pos)
|
|
665
|
+
rec.node = nid
|
|
666
|
+
if nid is not None:
|
|
667
|
+
in_turn_nodes.add(nid)
|
|
668
|
+
in_turn.append(rec)
|
|
669
|
+
in_turn_ids.add(id(rec))
|
|
670
|
+
aligned_nodes = set(node_by_pos.values())
|
|
671
|
+
users = [
|
|
672
|
+
nid
|
|
673
|
+
for nid in tail_nodes
|
|
674
|
+
if nid in aligned_nodes
|
|
675
|
+
and isinstance(self.trace.nodes[nid].message, UserMessage)
|
|
676
|
+
and nid not in in_turn_nodes
|
|
677
|
+
]
|
|
678
|
+
if self._prepared_user_count and users:
|
|
679
|
+
if self.prepared_rewrites:
|
|
680
|
+
targets = users[-self._prepared_user_count :]
|
|
681
|
+
for slot, rec in self.prepared_rewrites:
|
|
682
|
+
rec.node = targets[min(slot, len(targets) - 1)]
|
|
683
|
+
self.trace.request_rewrites.append(rec)
|
|
684
|
+
self.prepared_rewrites.clear()
|
|
685
|
+
self._prepared_user_count = 0
|
|
686
|
+
if self.pinned_rewrites:
|
|
687
|
+
tool_nodes = {
|
|
688
|
+
tkey: node_by_pos[pos]
|
|
689
|
+
for pos, tkey in self.tool_result_keys(
|
|
690
|
+
base, turn.dialect, node_by_pos
|
|
691
|
+
).items()
|
|
692
|
+
if pos in node_by_pos
|
|
693
|
+
}
|
|
694
|
+
if any(
|
|
695
|
+
tkey not in tool_nodes and isinstance(tkey[0], str)
|
|
696
|
+
for tkey, _ in self.pinned_rewrites
|
|
697
|
+
):
|
|
698
|
+
for pos, tkey in self.tool_result_keys(base, turn.dialect).items():
|
|
699
|
+
if pos in node_by_pos:
|
|
700
|
+
tool_nodes.setdefault(tkey, node_by_pos[pos])
|
|
701
|
+
remaining: list[tuple[ToolResultKey, InterceptRecord]] = []
|
|
702
|
+
committed_pinned: set[int] = set()
|
|
703
|
+
for tkey, rec in self.pinned_rewrites:
|
|
704
|
+
if id(rec) in in_turn_ids:
|
|
705
|
+
continue
|
|
706
|
+
if (nid := tool_nodes.get(tkey)) is None:
|
|
707
|
+
remaining.append((tkey, rec))
|
|
708
|
+
continue
|
|
709
|
+
rec.node = nid
|
|
710
|
+
self.trace.request_rewrites.append(rec)
|
|
711
|
+
committed_pinned.add(id(rec))
|
|
712
|
+
self.pinned_rewrites = remaining
|
|
713
|
+
if committed_pinned and self.inflight_rewrites:
|
|
714
|
+
self.inflight_rewrites = {
|
|
715
|
+
key: kept
|
|
716
|
+
for key, items in self.inflight_rewrites.items()
|
|
717
|
+
if (
|
|
718
|
+
kept := [
|
|
719
|
+
item
|
|
720
|
+
for item in items
|
|
721
|
+
if id(item[1]) not in committed_pinned
|
|
722
|
+
]
|
|
723
|
+
)
|
|
724
|
+
}
|
|
725
|
+
self.trace.request_rewrites.extend(in_turn)
|
|
726
|
+
for rec in response_rewrites:
|
|
727
|
+
rec.node = assistant_node
|
|
728
|
+
self.trace.response_rewrites.append(rec)
|
|
729
|
+
|
|
730
|
+
def flush_rewrites(self) -> None:
|
|
731
|
+
"""Flush any request rewrites whose prompt never committed (`node=None`)."""
|
|
732
|
+
seen = {id(rec) for rec in self.trace.request_rewrites}
|
|
733
|
+
pending = chain(
|
|
734
|
+
(rec for _, rec in self.prepared_rewrites),
|
|
735
|
+
(rec for _, rec in self.pinned_rewrites),
|
|
736
|
+
(rec for _, rec in chain.from_iterable(self.inflight_rewrites.values())),
|
|
737
|
+
)
|
|
738
|
+
for rec in pending:
|
|
739
|
+
if id(rec) not in seen:
|
|
740
|
+
seen.add(id(rec))
|
|
741
|
+
self.trace.request_rewrites.append(rec)
|
|
742
|
+
self.prepared_rewrites.clear()
|
|
743
|
+
self._prepared_user_count = 0
|
|
744
|
+
self.pinned_rewrites.clear()
|
|
745
|
+
self.inflight_rewrites.clear()
|
|
457
746
|
|
|
458
747
|
async def prepare_users(
|
|
459
748
|
self, request: Request
|
|
@@ -465,34 +754,37 @@ class RolloutSession:
|
|
|
465
754
|
else []
|
|
466
755
|
)
|
|
467
756
|
branch = [self.trace.nodes[i].message for i in known_path]
|
|
468
|
-
rewritten,
|
|
757
|
+
rewritten, pending, _ = await self.rewrite_request(
|
|
469
758
|
Request(messages=[*branch, *request.messages]),
|
|
470
759
|
run_stops=False,
|
|
471
760
|
known_path=known_path,
|
|
472
761
|
)
|
|
473
762
|
tail = rewritten.messages[len(branch) :]
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
763
|
+
user_slots: dict[int, int] = {}
|
|
764
|
+
for offset, message in enumerate(tail):
|
|
765
|
+
if isinstance(message, UserMessage):
|
|
766
|
+
self.prepared_users[graph.message_hash(message)] += 1
|
|
767
|
+
user_slots[len(branch) + offset] = self._prepared_user_count
|
|
768
|
+
self._prepared_user_count += 1
|
|
769
|
+
records: list[InterceptRecord] = []
|
|
770
|
+
for pos, rec in pending:
|
|
771
|
+
records.append(rec)
|
|
772
|
+
if pos in user_slots:
|
|
773
|
+
self.prepared_rewrites.append((user_slots[pos], rec))
|
|
479
774
|
return Request(messages=tail), records
|
|
480
775
|
|
|
481
776
|
async def rewrite_response(
|
|
482
777
|
self, response: Response
|
|
483
|
-
) -> tuple[Response, list[InterceptRecord],
|
|
778
|
+
) -> tuple[Response, list[InterceptRecord], StopVerdict | None]:
|
|
484
779
|
"""Run typed response interceptors and stops before harness delivery."""
|
|
485
780
|
records: list[InterceptRecord] = []
|
|
486
781
|
try:
|
|
487
782
|
for handler in self.response_interceptors:
|
|
488
783
|
candidate = response.model_copy(deep=True)
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
)
|
|
492
|
-
if result is None:
|
|
784
|
+
raw = await call_hook(handler, {Response: candidate, Trace: self.trace})
|
|
785
|
+
if raw is None:
|
|
493
786
|
continue
|
|
494
|
-
|
|
495
|
-
raise TypeError(f"expected Response, got {type(result).__name__}")
|
|
787
|
+
result, info = unpack_hook(raw, Response)
|
|
496
788
|
if result == response:
|
|
497
789
|
continue
|
|
498
790
|
unchanged = result.model_copy(
|
|
@@ -514,17 +806,16 @@ class RolloutSession:
|
|
|
514
806
|
"response interceptors must return an inert text-only message"
|
|
515
807
|
)
|
|
516
808
|
response = result.model_copy(update={"finish_reason": "stop"})
|
|
517
|
-
records.append(InterceptRecord(handler=handler.__name__))
|
|
809
|
+
records.append(InterceptRecord(handler=handler.__name__, info=info))
|
|
518
810
|
|
|
519
811
|
for stop in self.response_stops:
|
|
520
812
|
candidate = response.model_copy(deep=True)
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
return response, records, stop.__name__
|
|
813
|
+
triggered, info = unpack_hook(
|
|
814
|
+
await call_hook(stop, {Response: candidate, Trace: self.trace}),
|
|
815
|
+
bool,
|
|
816
|
+
)
|
|
817
|
+
if triggered:
|
|
818
|
+
return response, records, (stop.__name__, info)
|
|
528
819
|
except RolloutError:
|
|
529
820
|
raise
|
|
530
821
|
except Exception as error:
|
|
@@ -538,12 +829,12 @@ class RolloutSession:
|
|
|
538
829
|
node: int,
|
|
539
830
|
dialect: DialectName | None = None,
|
|
540
831
|
harness_history: Messages | None = None,
|
|
541
|
-
) ->
|
|
832
|
+
) -> StopVerdict | None:
|
|
542
833
|
"""Police the tool calls the assistant committed at `node` before the harness sees
|
|
543
834
|
them: the request hooks run over the branch plus an empty result for each call, so a
|
|
544
835
|
`@stop` refuses the whole response and a rewrite becomes that call's verdict — the
|
|
545
836
|
harness's gate denies it and the model sees the rewritten result instead. Returns
|
|
546
|
-
the
|
|
837
|
+
the stop verdict that fired, if any."""
|
|
547
838
|
assistant = self.trace.nodes[node].message
|
|
548
839
|
if not (self.request_interceptors or self.request_stops):
|
|
549
840
|
return None
|
|
@@ -576,9 +867,10 @@ class RolloutSession:
|
|
|
576
867
|
raise HarnessError(
|
|
577
868
|
f"tool call id {call.id!r} was reused in the same assistant turn"
|
|
578
869
|
)
|
|
579
|
-
request,
|
|
580
|
-
request, dialect=dialect, known_path=known_path
|
|
870
|
+
request, pending, stopped = await self.rewrite_request(
|
|
871
|
+
request, dialect=dialect, known_path=known_path, node=node
|
|
581
872
|
)
|
|
873
|
+
records = [rec for _, rec in pending]
|
|
582
874
|
self.trace.request_rewrites.extend(records)
|
|
583
875
|
if stopped is not None:
|
|
584
876
|
return stopped
|
|
@@ -590,7 +882,7 @@ class RolloutSession:
|
|
|
590
882
|
if not self.gates_tools:
|
|
591
883
|
# The harness would run the call regardless; only ending the rollout keeps
|
|
592
884
|
# the transcript and the sandbox in agreement.
|
|
593
|
-
return records[-1].handler
|
|
885
|
+
return records[-1].handler, records[-1].info
|
|
594
886
|
self.tool_decisions[key] = verdict
|
|
595
887
|
return None
|
|
596
888
|
|
|
@@ -653,26 +945,34 @@ class RolloutSession:
|
|
|
653
945
|
f"{len(matches)} proposed calls"
|
|
654
946
|
)
|
|
655
947
|
else:
|
|
656
|
-
|
|
948
|
+
spawn_node = leaves[0][0]
|
|
949
|
+
known_path = graph.path_node_ids(self.trace, spawn_node)
|
|
657
950
|
*branch, assistant = [self.trace.nodes[i].message for i in known_path]
|
|
658
951
|
assert isinstance(assistant, AssistantMessage)
|
|
659
|
-
|
|
952
|
+
args = arguments if isinstance(arguments, str) else json.dumps(arguments)
|
|
953
|
+
call = ToolCall(id=tool_call_id, name=name, arguments=args)
|
|
660
954
|
assistant = assistant.model_copy(
|
|
661
955
|
update={"tool_calls": [*(assistant.tool_calls or []), call]}
|
|
662
956
|
)
|
|
663
957
|
probe = ToolMessage(tool_call_id=call.id, content="", name=name)
|
|
664
|
-
request,
|
|
958
|
+
request, pending, stopped = await self.rewrite_request(
|
|
665
959
|
Request(
|
|
666
960
|
messages=[*branch, assistant, probe],
|
|
667
961
|
tools=self.trace.nodes[known_path[0]].tools or None,
|
|
668
962
|
),
|
|
669
|
-
dialect=self.tool_dialects.get(
|
|
963
|
+
dialect=self.tool_dialects.get(spawn_node),
|
|
670
964
|
known_path=known_path[:-1],
|
|
965
|
+
node=spawn_node,
|
|
671
966
|
)
|
|
967
|
+
records = [rec for _, rec in pending]
|
|
672
968
|
self.trace.request_rewrites.extend(records)
|
|
673
969
|
if stopped is not None:
|
|
674
|
-
|
|
675
|
-
|
|
970
|
+
stop_name, stop_info = stopped
|
|
971
|
+
self.trace.stop(stop_name, info=stop_info)
|
|
972
|
+
self.trace.notify()
|
|
973
|
+
return {"action": "stop", "reason": stop_name}
|
|
974
|
+
if records:
|
|
975
|
+
self.trace.notify()
|
|
676
976
|
verdict = request.messages[-1]
|
|
677
977
|
assert isinstance(verdict, ToolMessage)
|
|
678
978
|
if verdict == probe:
|
|
@@ -706,6 +1006,7 @@ class RolloutSession:
|
|
|
706
1006
|
self.released = True
|
|
707
1007
|
for task in list(self.tasks):
|
|
708
1008
|
task.cancel()
|
|
1009
|
+
self.flush_rewrites()
|
|
709
1010
|
|
|
710
1011
|
async def refused(self) -> str | None:
|
|
711
1012
|
"""The framework's limits (turns / token budget) and `@stop` checks, run before each
|
|
@@ -718,11 +1019,18 @@ class RolloutSession:
|
|
|
718
1019
|
logger.debug("Reached the %s limit", limit)
|
|
719
1020
|
return limit
|
|
720
1021
|
for stop in self.trace_stops:
|
|
721
|
-
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
|
|
1022
|
+
try:
|
|
1023
|
+
triggered, info = unpack_hook(
|
|
1024
|
+
await call_hook(stop, {Trace: self.trace}), bool
|
|
1025
|
+
)
|
|
1026
|
+
except RolloutError:
|
|
1027
|
+
raise
|
|
1028
|
+
except Exception as error:
|
|
1029
|
+
raise TaskError(
|
|
1030
|
+
f"@stop {stop.__name__} failed: {type(error).__name__}: {error}"
|
|
1031
|
+
) from error
|
|
1032
|
+
if triggered:
|
|
1033
|
+
self.trace.stop(stop.__name__, info=info)
|
|
726
1034
|
logger.debug("Stopped by @stop %s", stop.__name__)
|
|
727
1035
|
return stop.__name__
|
|
728
1036
|
return None
|
verifiers/v1/trace.py
CHANGED
|
@@ -41,6 +41,7 @@ from verifiers.v1.types import (
|
|
|
41
41
|
Messages,
|
|
42
42
|
SamplerSupport,
|
|
43
43
|
Tool,
|
|
44
|
+
ToolCall,
|
|
44
45
|
ToolMessage,
|
|
45
46
|
Usage,
|
|
46
47
|
content_text,
|
|
@@ -330,6 +331,13 @@ class TraceTask(BaseModel, Generic[DataT]):
|
|
|
330
331
|
|
|
331
332
|
class InterceptRecord(BaseModel):
|
|
332
333
|
handler: str
|
|
334
|
+
node: int | None = None
|
|
335
|
+
"""Index into `Trace.nodes` of the intercepted message node, or the issuing
|
|
336
|
+
assistant node when a tool call was gated before execution."""
|
|
337
|
+
tool_call: ToolCall | None = None
|
|
338
|
+
"""The tool call whose execution or output was intercepted, when applicable."""
|
|
339
|
+
info: dict[str, Any] = Field(default_factory=dict)
|
|
340
|
+
"""Hook-supplied metadata (for example matched rule or reason)."""
|
|
333
341
|
|
|
334
342
|
|
|
335
343
|
class Reward(BaseModel):
|
|
@@ -636,6 +644,8 @@ class Trace(BaseModel, Generic[DataT, StateT, AgentConfigT]):
|
|
|
636
644
|
"""Whether the trace completed successfully."""
|
|
637
645
|
stop_condition: str | None = None
|
|
638
646
|
"""What stopped the trace."""
|
|
647
|
+
stop_info: dict[str, Any] = Field(default_factory=dict)
|
|
648
|
+
"""Metadata attached when stopping (for example matched rule or reason)."""
|
|
639
649
|
is_timeout: bool = False
|
|
640
650
|
"""Whether a stage deadline (setup, agent, finalize, or scoring) expired."""
|
|
641
651
|
errors: list[Error] = Field(default_factory=list)
|
|
@@ -957,12 +967,18 @@ class Trace(BaseModel, Generic[DataT, StateT, AgentConfigT]):
|
|
|
957
967
|
if response.usage is not None:
|
|
958
968
|
self.extra_usage.append(response.usage)
|
|
959
969
|
|
|
960
|
-
def stop(
|
|
970
|
+
def stop(
|
|
971
|
+
self,
|
|
972
|
+
condition: str,
|
|
973
|
+
override: bool = False,
|
|
974
|
+
info: Mapping[str, Any] | None = None,
|
|
975
|
+
) -> None:
|
|
961
976
|
"""Stop the trace with a stop condition. The first condition wins unless
|
|
962
977
|
`override` replaces it."""
|
|
963
978
|
self.is_completed = True
|
|
964
979
|
if override or self.stop_condition is None:
|
|
965
980
|
self.stop_condition = condition
|
|
981
|
+
self.stop_info = copy.deepcopy(dict(info)) if info else {}
|
|
966
982
|
|
|
967
983
|
def drop(self, reason: str) -> None:
|
|
968
984
|
"""Leave the trace out of reward means and training batches. The first reason
|
verifiers/v1/utils/decorators.py
CHANGED
|
@@ -91,9 +91,9 @@ def stop(
|
|
|
91
91
|
def stop(
|
|
92
92
|
func: F | None = None, priority: int = 0, skip_scoring: bool = False
|
|
93
93
|
) -> F | Callable[[F], F]:
|
|
94
|
-
"""Stop when a typed `Request`, `Response`, or `Trace` predicate returns true
|
|
95
|
-
`
|
|
96
|
-
its reward is 0."""
|
|
94
|
+
"""Stop when a typed `Request`, `Response`, or `Trace` predicate returns true (or
|
|
95
|
+
`(True, metadata)` to populate `trace.stop_info`). With `skip_scoring`, a trace
|
|
96
|
+
this stop ends skips task scoring: it keeps no rewards, so its reward is 0."""
|
|
97
97
|
decorator = mark("stop", stop_priority=priority, stop_skip_scoring=skip_scoring)
|
|
98
98
|
return decorator if func is None else decorator(func)
|
|
99
99
|
|
|
@@ -103,7 +103,8 @@ def intercept(func: F, priority: int = 0) -> F: ...
|
|
|
103
103
|
@overload
|
|
104
104
|
def intercept(func: None = None, priority: int = 0) -> Callable[[F], F]: ...
|
|
105
105
|
def intercept(func: F | None = None, priority: int = 0) -> F | Callable[[F], F]:
|
|
106
|
-
"""Inspect a typed boundary; return its replacement or
|
|
106
|
+
"""Inspect a typed boundary; return its replacement (or `(replacement, metadata)`)
|
|
107
|
+
or None to leave it unchanged."""
|
|
107
108
|
decorator = mark("intercept", intercept_priority=priority)
|
|
108
109
|
return decorator if func is None else decorator(func)
|
|
109
110
|
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.5
|
|
2
2
|
Name: verifiers
|
|
3
|
-
Version: 0.4.2.
|
|
3
|
+
Version: 0.4.2.dev108
|
|
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
|
|
@@ -6,17 +6,17 @@ verifiers/v1/env.py,sha256=-MTenM7sDjIccPqkjrv6M_STe4Z8CflNkrNfM-n0L8k,20163
|
|
|
6
6
|
verifiers/v1/episode.py,sha256=Tqjo8aQDOh4sM03he2WMXzEhmn2ybzwwtUS_QSvESsA,6983
|
|
7
7
|
verifiers/v1/errors.py,sha256=OieUBIOZ6FW7oKygbXIRoag6RrPxKYpMPfEYPcCnVVE,5863
|
|
8
8
|
verifiers/v1/grading.py,sha256=RV-j71EIeQNC1AeKIDQkS1Y_KTtjJg9x8zF7n2cWr_Y,10100
|
|
9
|
-
verifiers/v1/graph.py,sha256=
|
|
9
|
+
verifiers/v1/graph.py,sha256=_IEMMdOJ7TAy2TM9H9LZBAeYCgV9-Uo8XtfTUdg_aBI,48582
|
|
10
10
|
verifiers/v1/harness.py,sha256=4uyatJvxvX6IIusF3PIn7GTYYGpoBTJgs7QQlO1vECQ,17144
|
|
11
11
|
verifiers/v1/judge.py,sha256=T-TyYVcLGIoyUADYKy_pCBj2CTLhERlct5pmmWqPpTA,10507
|
|
12
|
-
verifiers/v1/rollout.py,sha256=
|
|
12
|
+
verifiers/v1/rollout.py,sha256=XufK3YsWoTfVklNCSxtdGr2cF-twXIHebvB_a2daZJk,49724
|
|
13
13
|
verifiers/v1/semantic.py,sha256=nqKPPUoPL5Oh8Es_XjtcbDiQiIMKTYayXEm-EPB-jAE,5129
|
|
14
|
-
verifiers/v1/session.py,sha256=
|
|
14
|
+
verifiers/v1/session.py,sha256=7fcnwXKdEdor93FU4VjpNAiuChZtjLb1YOru_Vf0Fv8,45553
|
|
15
15
|
verifiers/v1/state.py,sha256=EckF2bWp-vV4b1jYJ9sLI5xrfGuI5spIgYYwW926toI,595
|
|
16
16
|
verifiers/v1/submission.py,sha256=zgSRbGVz82Efwz4nX4tlJ-i02AmjtKyu_vHfwfLaByw,7989
|
|
17
17
|
verifiers/v1/task.py,sha256=zcWjBjhJrkGIL29JTnxxw6v2pbJoiek_tF5RVAVV2ZY,15919
|
|
18
18
|
verifiers/v1/taskset.py,sha256=PRwMfPtUL0Sg9pwKzJYnpLBDqJCmQ4skQPhF1oocyyw,9504
|
|
19
|
-
verifiers/v1/trace.py,sha256=
|
|
19
|
+
verifiers/v1/trace.py,sha256=gpxRZUqGLNJbVjyWj07KKx1w1g_0RutBnjywZdTPxCY,41520
|
|
20
20
|
verifiers/v1/types.py,sha256=PsYLhqy_19JZUT7uP9a8A2h-qKo7-9_KLQ_B0PqhkYg,13303
|
|
21
21
|
verifiers/v1/acp/__init__.py,sha256=590Ppv8KCCc3MB6yKJDHIAxx8UabwHy2D7LnJ_P5eo8,16912
|
|
22
22
|
verifiers/v1/acp/runner.py,sha256=jQeaUaF6PL_BzFQ4a28F-wKVgirXTSkPEfkAq8VzjlA,15792
|
|
@@ -112,7 +112,7 @@ verifiers/v1/harnesses/stirrup/harness.py,sha256=Bcm7m1IzFnseiAa6xRKHSFKYrqSRpvx
|
|
|
112
112
|
verifiers/v1/harnesses/stirrup/program.py,sha256=0xj35Teph6BW_4ydW921J18MPCBRXNfI62J21nh0dFw,15148
|
|
113
113
|
verifiers/v1/harnesses/utils/__init__.py,sha256=eTS-Ft2HwoLiYn5u1t_KueLmaZB_W12cdYmcVsE-G5A,364
|
|
114
114
|
verifiers/v1/harnesses/utils/compaction.py,sha256=DeY6CYLEsv7-vJm26sT2mRaPHu3W2ywiZhvFr_pi6Hg,10495
|
|
115
|
-
verifiers/v1/harnesses/utils/core.py,sha256=
|
|
115
|
+
verifiers/v1/harnesses/utils/core.py,sha256=Q3xsnk3PtYYcA73p6by7QbjfcfaQVIhRyg3Qi6Ca-H4,26923
|
|
116
116
|
verifiers/v1/harnesses/utils/install.py,sha256=EESYSh_e9L4gj6N4GvAbQY2kb4ckven7tmtlQEErPiQ,3563
|
|
117
117
|
verifiers/v1/harnesses/utils/launch.py,sha256=2KuLnNruUqH6vcW2Ru661P86ffRzaqslNs-kDMn7B6U,5670
|
|
118
118
|
verifiers/v1/harnesses/utils/mcp.py,sha256=EtDraHEqgsOB6xKvcF2z9C6HlQyKoST0ZDvmy47NWgM,7450
|
|
@@ -120,7 +120,7 @@ verifiers/v1/harnesses/utils/replay.py,sha256=m2EXxd24aH3Y5DAi9tEV1teREXGcPHsXhp
|
|
|
120
120
|
verifiers/v1/interception/__init__.py,sha256=jQ9ZbUr4Nx9JFhdcx0rNcR_jkMFcdzBrTpeSFK84YF0,4020
|
|
121
121
|
verifiers/v1/interception/base.py,sha256=KlXpWgcpAs_vzJxXRTVArZ9ilSV_vNfsX6vlZ35Y7kc,2249
|
|
122
122
|
verifiers/v1/interception/pool.py,sha256=Ao3iFTOcPZDfTfPH_sApVzA23u-FIaX6-FPIKOWo3c8,6701
|
|
123
|
-
verifiers/v1/interception/server.py,sha256=
|
|
123
|
+
verifiers/v1/interception/server.py,sha256=O6tKJT-qmPG3clqobjxjTAQndLOXcHep60H3ld_aHc8,54004
|
|
124
124
|
verifiers/v1/interception/tunnel/__init__.py,sha256=4ZqR9F7cmLUg17qvk4sXtLpWAN4epdiMgA2l9jetMbU,721
|
|
125
125
|
verifiers/v1/interception/tunnel/base.py,sha256=UrHXwbpB_qdh4WHWZHpi2D-wEHcHgg06_0U66XFqm3M,2370
|
|
126
126
|
verifiers/v1/interception/tunnel/custom.py,sha256=SJ3F592zwmrLKrbNktWgkB_84Xfozf6tUWoGmWCitLk,817
|
|
@@ -166,7 +166,7 @@ verifiers/v1/utils/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuF
|
|
|
166
166
|
verifiers/v1/utils/aio.py,sha256=0yNFOqB2oO6Qktc6NI_ZSAGuo1aHsIK_wuT1BtmoZ3I,1532
|
|
167
167
|
verifiers/v1/utils/artifacts.py,sha256=8-OGbVRFwRyYftpgszV1WQ20qEjMZG92aETcQuZOkN8,25216
|
|
168
168
|
verifiers/v1/utils/compile.py,sha256=wHGk9BKykVsniyXLr1fBQGRjnfG9QzEVEc92HYfT1V4,5219
|
|
169
|
-
verifiers/v1/utils/decorators.py,sha256=
|
|
169
|
+
verifiers/v1/utils/decorators.py,sha256=kfRielPFG9ekNIGMFB5eSm_kzBjlu5XD_ucH3y1spoc,5697
|
|
170
170
|
verifiers/v1/utils/env.py,sha256=tMqfwFNRcJPijzrjkbE2VYvBH8eONRtYCWVkXHKpGZQ,1023
|
|
171
171
|
verifiers/v1/utils/eval.py,sha256=lXBsir3rastL31CuXkJi522v6ypAI1ZGQ82IoTkm8IQ,1237
|
|
172
172
|
verifiers/v1/utils/format.py,sha256=ij6sMMitJL7JCfGPSJp60gBZPYRVOpMGlTaiiV_UPag,594
|
|
@@ -185,8 +185,8 @@ verifiers/v1/utils/scope.py,sha256=zbs4pj6AVk4jywlAJ3AX0Q0_kzB9dBB02nY-9H4ELdQ,8
|
|
|
185
185
|
verifiers/v1/utils/score.py,sha256=493yJVMw8teCu9JxapxMFPFzI0hNUqdo0Y2nGW4kckk,6200
|
|
186
186
|
verifiers/v1/utils/trace_store.py,sha256=7F6xMhYgl3qmylnCU8-ekqswH16fUat1uegeM1OR9QQ,2563
|
|
187
187
|
verifiers/v1/utils/version.py,sha256=-obEo_-l9-D8FLef4hYxncOe-uJpxrM1g2Hig_37Sgs,1607
|
|
188
|
-
verifiers-0.4.2.
|
|
189
|
-
verifiers-0.4.2.
|
|
190
|
-
verifiers-0.4.2.
|
|
191
|
-
verifiers-0.4.2.
|
|
192
|
-
verifiers-0.4.2.
|
|
188
|
+
verifiers-0.4.2.dev108.dist-info/METADATA,sha256=uItOUeAepRbbzzE8x5sTtYdNHuu0l13mA0JeVmrg2ug,5118
|
|
189
|
+
verifiers-0.4.2.dev108.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
190
|
+
verifiers-0.4.2.dev108.dist-info/entry_points.txt,sha256=qdMg7ajiFpDsHf7tuPMRclJXizu1J6LTWawS5YS0B0I,137
|
|
191
|
+
verifiers-0.4.2.dev108.dist-info/licenses/LICENSE,sha256=v0RrUsdV3IDoZhrRce297IXS3xMHNJ-_LdLpFAUWb9k,1072
|
|
192
|
+
verifiers-0.4.2.dev108.dist-info/RECORD,,
|
|
File without changes
|
|
File without changes
|
|
File without changes
|