verifiers 0.4.2.dev140__py3-none-any.whl → 0.4.2.dev142__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/agent.py CHANGED
@@ -924,13 +924,15 @@ class Agent:
924
924
  snapshots.update((s.id, s) for s in run.rewound_snapshots)
925
925
  # An owner's snapshots (`save_all`) are the owner's to delete.
926
926
  snapshots.update(
927
- (c.snapshot.id, c.snapshot)
927
+ (s.id, s)
928
928
  for c in trace.checkpoints
929
929
  if not c.pinned
930
+ for s in c.snapshots.values()
930
931
  )
931
932
  for c in trace.checkpoints:
932
933
  if c.pinned:
933
- snapshots.pop(c.id, None)
934
+ for s in c.snapshots.values():
935
+ snapshots.pop(s.id, None)
934
936
  deleted.update(run.deleted_snapshots)
935
937
  if target is not None and (
936
938
  any(error.stage == "setup" for error in trace.errors[seen:])
@@ -49,9 +49,10 @@ class RolloutCheckpointConfig(BaseConfig):
49
49
  snapshot stops the box for a few seconds and resets its open connections to the
50
50
  outside. It needs a runtime that takes memory snapshots
51
51
  (`SUPPORTS_MEMORY_SNAPSHOTS`), a harness that runs detached from the host
52
- (`Harness.SUPPORTS_MEMORY_RESTORE`) and a rollout without tool servers or services
53
- of its own. Elsewhere a retry starts over. Every snapshot is deleted once the run
54
- is final."""
52
+ (`Harness.SUPPORTS_MEMORY_RESTORE`), and a rollout without services or shared tools
53
+ whose tool servers, if any, run on Prime VMs of their own: those stop with the box
54
+ and restore beside it. Elsewhere a retry starts over. Every snapshot is deleted once
55
+ the run is final."""
55
56
 
56
57
  interval: PositiveFloat | None = Field(default=None, allow_inf_nan=False)
57
58
  """Seconds between memory snapshots during execution. A held owner save can
@@ -17,7 +17,9 @@ from verifiers.v1.types import Message
17
17
  OPENCODE_DIR = "/var/tmp/vf-opencode"
18
18
  STATE_ROOT = "/tmp/vf-opencode-runs"
19
19
  KEY_VAR = "VF_OPENCODE_API_KEY"
20
- MCP_READY = (Path(__file__).resolve().parent / "mcp-ready.js").read_bytes()
20
+ HERE = Path(__file__).resolve().parent
21
+ MCP_READY = (HERE / "mcp-ready.js").read_bytes()
22
+ UNSIGNED_THINKING = (HERE / "unsigned-thinking.js").read_bytes()
21
23
 
22
24
  INSTALL = r"""
23
25
  set -e
@@ -111,10 +113,23 @@ class OpenCodeHarness(ACPHarness[OpenCodeHarnessConfig]):
111
113
  "share": "disabled",
112
114
  "snapshots": False,
113
115
  }
116
+ # OpenCode drops thinking blocks with an empty signature on replay over
117
+ # Anthropic messages unless the model opts out of requiring one, and its
118
+ # config schema strips that option. Non-Claude models behind interception
119
+ # (e.g. DeepSeek) return unsigned thinking. Recheck on version bumps:
120
+ # https://github.com/anomalyco/opencode/blob/v2.3.2/packages/ai/src/protocols/anthropic-messages.ts#L922-L927
121
+ thinking_dir = f"{root}/unsigned-thinking"
122
+ await runtime.write(f"{thinking_dir}/index.js", UNSIGNED_THINKING)
123
+ plugins = [
124
+ {
125
+ "package": thinking_dir,
126
+ "options": {"provider": "intercept", "model": "model"},
127
+ }
128
+ ]
114
129
  if mcp_urls:
115
130
  plugin_dir = f"{root}/mcp-ready"
116
131
  await runtime.write(f"{plugin_dir}/index.js", MCP_READY)
117
- settings["plugins"] = [
132
+ plugins.append(
118
133
  {
119
134
  "package": plugin_dir,
120
135
  "options": {
@@ -122,7 +137,8 @@ class OpenCodeHarness(ACPHarness[OpenCodeHarnessConfig]):
122
137
  "timeout": int(self.config.tool_timeout * 1000),
123
138
  },
124
139
  }
125
- ]
140
+ )
141
+ settings["plugins"] = plugins
126
142
  return ACPConfig(
127
143
  command=[
128
144
  f"{OPENCODE_DIR}/{self.config.version}/node_modules/.bin/opencode",
@@ -0,0 +1,12 @@
1
+ import { Effect } from "effect";
2
+
3
+ export default {
4
+ id: "verifiers.unsigned-thinking",
5
+ effect: Effect.fn(function* (ctx) {
6
+ yield* ctx.model.transform((editor) => {
7
+ editor.update(ctx.options.provider, ctx.options.model, (model) => {
8
+ model.compatibility = { ...model.compatibility, requireSignature: false };
9
+ });
10
+ });
11
+ }),
12
+ };
@@ -6,7 +6,10 @@ swaps the harness's bearer tokens for the upstream's, so the host can move the h
6
6
  to a new URL or new secrets without the harness noticing: `Relay.reroute`.
7
7
 
8
8
  Each rollout runs its own relay, under `RELAY_ROOT/<name>` and on a port of its own, so
9
- rollouts that share a box never share one.
9
+ rollouts that share a box never share one. A rollout that can continue from a memory
10
+ snapshot also reaches each tool server VM through a relay of its own (`direct`): the
11
+ harness's connections then end in the box, and a restore moves only the relay. The host
12
+ holds those relays while it snapshots the box with its tool server VMs (`Relay.hold`).
10
13
  """
11
14
 
12
15
  from __future__ import annotations
@@ -14,6 +17,7 @@ from __future__ import annotations
14
17
  import asyncio
15
18
  import contextlib
16
19
  import json
20
+ import math
17
21
  import shlex
18
22
  import time
19
23
  import uuid
@@ -29,14 +33,45 @@ RELAY_SOURCE = (Path(__file__).resolve().parent / "server.py").read_text()
29
33
  RELAY_ROOT = "/tmp/vf-relay"
30
34
  RELAY_START_SECONDS = 60
31
35
  """How long a launched relay gets to accept connections."""
36
+ RELEASE_ATTEMPTS = 5
37
+ """Attempts to end a relay's hold, 1 s apart and doubling: about 15 s in all."""
32
38
 
33
39
 
34
- def relay_config(upstream: str, tokens: dict[str, str]) -> bytes:
35
- """A relay's config file: the upstream base URL, and the harness's tokens mapped to
36
- the upstream's."""
40
+ def route_config(upstream: str, tokens: dict[str, str]) -> bytes:
41
+ """Where a process in a VM reaches the host: the upstream base URL, and named
42
+ tokens for it. A relay maps the harness's tokens to the upstream's."""
37
43
  return json.dumps({"upstream": upstream, "tokens": tokens}).encode()
38
44
 
39
45
 
46
+ def read_route(path: str) -> tuple[str, dict[str, str]]:
47
+ """The upstream and tokens of a route config (`route_config`)."""
48
+ with open(path) as f:
49
+ route = json.load(f)
50
+ return route["upstream"], route["tokens"]
51
+
52
+
53
+ async def write_route(
54
+ runtime: Runtime,
55
+ path: str,
56
+ upstream: str,
57
+ tokens: dict[str, str],
58
+ *,
59
+ then: str = "",
60
+ ) -> None:
61
+ """Move whatever in `runtime` reads the route config at `path` to `upstream`, as
62
+ after the host moved: a relay, or a tool server that reads it on each call. Written
63
+ whole, then moved, so a reader never sees a partial config; `then` runs after the
64
+ move in the same call (a relay's reload)."""
65
+ staged = f"{path}.next"
66
+ await runtime.write(staged, route_config(upstream, tokens))
67
+ move = f"mv {shlex.quote(staged)} {shlex.quote(path)}"
68
+ result = await runtime.run(["sh", "-c", f"{move} && {then}" if then else move], {})
69
+ if result.exit_code:
70
+ raise RelayError(
71
+ f"the route at {path} did not move: {result.stderr.strip()[-500:]}"
72
+ )
73
+
74
+
40
75
  class Relay:
41
76
  """A rollout's relay in its box. It launches when created, before its upstream is
42
77
  known, so its start overlaps the harness setup once its program is installed
@@ -44,11 +79,19 @@ class Relay:
44
79
  `stop` ends it."""
45
80
 
46
81
  def __init__(
47
- self, runtime: Runtime, name: str, *, running: dict[str, str] | None = None
82
+ self,
83
+ runtime: Runtime,
84
+ name: str,
85
+ *,
86
+ running: dict[str, str] | None = None,
87
+ direct: bool = False,
48
88
  ) -> None:
49
89
  """`running` is the `state` of a relay the box already runs (a box restored
50
- from a memory snapshot): nothing is launched, and `connect` moves that relay."""
90
+ from a memory snapshot): nothing is launched, and `connect` moves that relay.
91
+ `direct` launches one for an upstream the box reaches without a tunnel
92
+ (`server.py`)."""
51
93
  self.runtime = runtime
94
+ self.direct = direct
52
95
  self.dir = f"{RELAY_ROOT}/{name}" if running is None else running["dir"]
53
96
  self.url = "" if running is None else running["url"]
54
97
  """The base URL the harness reaches the interception server at, once launched."""
@@ -83,18 +126,31 @@ class Relay:
83
126
  """Where the relay appends the reason for each request it gives up on."""
84
127
  return f"{self.dir}/failures"
85
128
 
129
+ @property
130
+ def hold_path(self) -> str:
131
+ """Present while the host holds the relay (`hold`)."""
132
+ return f"{self.dir}/hold"
133
+
134
+ @property
135
+ def drained_path(self) -> str:
136
+ """Present while the relay is held and has no request open."""
137
+ return f"{self.dir}/drained"
138
+
86
139
  async def _start(self) -> None:
87
140
  # Each launch reads its port from a file of its own: a relay an earlier attempt
88
141
  # left in the box can never answer for this one.
89
142
  ready = f"{self.dir}/port-{uuid.uuid4().hex}"
90
143
  # The gateway creates the directory. Nothing listens on port 9 (discard).
91
144
  await self.runtime.write(
92
- self.config_path, relay_config("http://127.0.0.1:9", {})
145
+ self.config_path, route_config("http://127.0.0.1:9", {})
93
146
  )
94
147
  program = await self.runtime.prepare_uv_script(RELAY_SOURCE, activate=False)
95
148
  self._installed.set()
96
149
  args = ["--config", self.config_path, "--port", "0", "--ready", ready]
97
150
  args += ["--failures", self.failures_path]
151
+ if self.direct:
152
+ args += ["--direct", "--hold", self.hold_path]
153
+ args += ["--drained", self.drained_path]
98
154
  await self.runtime.run_background(
99
155
  [*program, *args, "--pid", self.pid_path], {}, log=f"{self.dir}/relay.log"
100
156
  )
@@ -158,18 +214,56 @@ class Relay:
158
214
  await self._write_config(upstream, tokens)
159
215
 
160
216
  async def _write_config(self, upstream: str, tokens: dict[str, str]) -> None:
161
- # Written whole, then moved: the relay must never read a partial config.
162
- staged = f"{self.config_path}.next"
163
- await self.runtime.write(staged, relay_config(upstream, tokens))
164
- config, pid = shlex.quote(self.config_path), shlex.quote(self.pid_path)
165
- reload = f'mv {shlex.quote(staged)} {config} && kill -HUP "$(cat {pid})"'
166
- result = await self.runtime.run(["sh", "-c", reload], {})
167
- if result.exit_code:
168
- raise RelayError(
169
- f"the relay did not reload: {result.stderr.strip()[-500:]}"
217
+ pid = shlex.quote(self.pid_path)
218
+ try:
219
+ await write_route(
220
+ self.runtime,
221
+ self.config_path,
222
+ upstream,
223
+ tokens,
224
+ then=f'kill -HUP "$(cat {pid})"',
170
225
  )
226
+ except RelayError as e:
227
+ raise RelayError(f"the relay did not reload: {e}") from e
171
228
  self.upstream, self.tokens = upstream, tokens
172
229
 
230
+ async def hold(self, timeout: float) -> bool:
231
+ """Make the relay send no new request upstream, and wait up to `timeout`
232
+ seconds until no tool call is open. False when one still is. The relay stays held
233
+ until `release`, also in a box that a snapshot taken meanwhile restores."""
234
+ pid, drained = shlex.quote(self.pid_path), shlex.quote(self.drained_path)
235
+ script = (
236
+ f"touch {shlex.quote(self.hold_path)} || exit 2; "
237
+ f'kill -USR1 "$(cat {pid})" || exit 2; '
238
+ f"end=$(($(date +%s) + {math.ceil(timeout)})); "
239
+ f"until [ -e {drained} ]; do "
240
+ '[ "$(date +%s)" -ge "$end" ] && exit 1; sleep 0.05; done'
241
+ )
242
+ result = await self.runtime.run(["sh", "-c", script], {})
243
+ if result.exit_code == 2:
244
+ raise RelayError(f"the relay did not hold: {result.stderr.strip()[-500:]}")
245
+ return result.exit_code == 0
246
+
247
+ async def release(self, *, attempts: int = RELEASE_ATTEMPTS) -> None:
248
+ """End a `hold`. Retried: a relay left held sends none of the harness's calls
249
+ again."""
250
+ pid, hold = shlex.quote(self.pid_path), shlex.quote(self.hold_path)
251
+ delay = 1.0
252
+ for attempt in range(attempts):
253
+ try:
254
+ result = await self.runtime.run(
255
+ ["sh", "-c", f'rm -f {hold} && kill -USR1 "$(cat {pid})"'], {}
256
+ )
257
+ if not result.exit_code:
258
+ return
259
+ error = result.stderr.strip()[-500:]
260
+ except Exception as e: # noqa: BLE001 - raised after the last attempt
261
+ error = repr(e)
262
+ if attempt + 1 < attempts:
263
+ await asyncio.sleep(delay)
264
+ delay *= 2
265
+ raise RelayError(f"the relay did not release: {error}")
266
+
173
267
  async def failure(self) -> RelayError | None:
174
268
  """The relay's failure, if it gave up on a request or exited; for a harness that
175
269
  died, so the trace names the relay rather than the harness."""
@@ -19,8 +19,21 @@ request for up to `RETRY_SECONDS`, so the harness does not see a tunnel that is
19
19
  reconnecting or being replaced. A retry is marked as one (`x-stainless-retry-count`),
20
20
  so the interception server joins it to the request it already serves.
21
21
 
22
+ With `--direct` the upstream is a server the box reaches without a tunnel (a tool
23
+ server VM on the box's private network), which answers its own errors and does not
24
+ join retries: the relay forwards every status as the answer, and retries a request
25
+ only before it was sent or when a reload aborted it.
26
+
27
+ While the `--hold` file exists the relay holds: it sends no new request upstream, and
28
+ once no MCP tool call (`tools/call`) is open it creates the `--drained` file. Only a tool
29
+ call counts: an MCP client keeps a stream of server notifications open for good (a GET,
30
+ or a `subscriptions/listen` POST). The relay checks the file on SIGUSR1, so the host
31
+ creates or removes it and then signals, and signals that arrive out of order do no
32
+ harm. The host holds the relay to a tool
33
+ server VM while it snapshots the box and the VM, so no call between them spans the stop.
34
+
22
35
  Usage: relay_server.py --config <path> --port <port> [--ready <path>] [--pid <path>]
23
- [--failures <path>]
36
+ [--failures <path>] [--direct] [--hold <path> --drained <path>]
24
37
 
25
38
  The config file is JSON: `{"upstream": "https://host/base", "tokens": {"<box token>":
26
39
  "<upstream token>"}}`. Once listening, the relay writes its port to `--ready` and its
@@ -152,7 +165,8 @@ class Config:
152
165
  class Upstream:
153
166
  """One in-flight upstream attempt, abortable from another thread."""
154
167
 
155
- def __init__(self) -> None:
168
+ def __init__(self, call: bool) -> None:
169
+ self.call = call
156
170
  self.lock = threading.Lock()
157
171
  self.sock: socket.socket | None = None
158
172
  self.aborted = False
@@ -180,8 +194,19 @@ def shutdown(sock: socket.socket) -> None:
180
194
 
181
195
 
182
196
  class Relay:
183
- def __init__(self, path: str, failures: str | None = None) -> None:
197
+ def __init__(
198
+ self,
199
+ path: str,
200
+ failures: str | None = None,
201
+ direct: bool = False,
202
+ hold: str | None = None,
203
+ drained: str | None = None,
204
+ ) -> None:
184
205
  self.path = path
206
+ self.direct = direct
207
+ self.hold_path = hold
208
+ self.drained = drained
209
+ self.held = False
185
210
  self.failures = failures
186
211
  self.failures_lock = threading.Lock()
187
212
  self.failed = False
@@ -190,11 +215,13 @@ class Relay:
190
215
  self.changed = threading.Condition()
191
216
  self.upstreams: set[Upstream] = set()
192
217
 
193
- def begin(self) -> tuple[Upstream, Config]:
218
+ def begin(self, call: bool) -> tuple[Upstream, Config]:
194
219
  """Register an attempt on the current config, atomically with reading it, so a
195
- reload aborts every attempt that still uses the config it replaces."""
220
+ reload aborts every attempt that still uses the config it replaces. Waits while
221
+ the relay is held."""
196
222
  with self.changed:
197
- upstream = Upstream()
223
+ self.changed.wait_for(lambda: not self.held)
224
+ upstream = Upstream(call)
198
225
  self.upstreams.add(upstream)
199
226
  return upstream, self.config
200
227
 
@@ -221,6 +248,31 @@ class Relay:
221
248
  def end(self, upstream: Upstream) -> None:
222
249
  with self.changed:
223
250
  self.upstreams.discard(upstream)
251
+ self.mark_drained()
252
+
253
+ def sync_hold(self) -> None:
254
+ """Hold while the `--hold` file exists, and release once it is gone."""
255
+ held = self.hold_path is not None and os.path.exists(self.hold_path)
256
+ with self.changed:
257
+ if held == self.held:
258
+ return
259
+ self.held = held
260
+ if held:
261
+ self.mark_drained()
262
+ open_calls = self.open_calls()
263
+ else:
264
+ if self.drained is not None:
265
+ with contextlib.suppress(OSError):
266
+ os.remove(self.drained)
267
+ self.changed.notify_all()
268
+ log(f"held, {open_calls} tool calls open" if held else "released")
269
+
270
+ def open_calls(self) -> int:
271
+ return sum(upstream.call for upstream in self.upstreams)
272
+
273
+ def mark_drained(self) -> None:
274
+ if self.held and not self.open_calls() and self.drained is not None:
275
+ write_file(self.drained, "")
224
276
 
225
277
  def wait(self, config: Config, timeout: float) -> None:
226
278
  with self.changed:
@@ -418,6 +470,9 @@ class Handler(BaseHTTPRequestHandler):
418
470
  if upstream.aborted:
419
471
  self.retries += 1
420
472
  log(f"{self.command} {self.label}: aborted, retrying")
473
+ elif relay.direct:
474
+ self.fail("the upstream response broke")
475
+ return
421
476
  else:
422
477
  if time.monotonic() - opened > BACKOFF_CAP_SECONDS:
423
478
  # The response was up a while: this is a new outage.
@@ -431,6 +486,19 @@ class Handler(BaseHTTPRequestHandler):
431
486
  log(f"{self.command} {self.label}: client went away")
432
487
  self.close_connection = True
433
488
 
489
+ @property
490
+ def tool_call(self) -> bool:
491
+ """Whether the request carries an MCP tool call (a JSON-RPC message or batch)."""
492
+ try:
493
+ body = json.loads(self.body)
494
+ except (ValueError, RecursionError):
495
+ return False
496
+ messages = body if isinstance(body, list) else [body]
497
+ return any(
498
+ isinstance(message, dict) and message.get("method") == "tools/call"
499
+ for message in messages
500
+ )
501
+
434
502
  @property
435
503
  def label(self) -> str:
436
504
  return self.target.partition("?")[0]
@@ -467,8 +535,9 @@ class Handler(BaseHTTPRequestHandler):
467
535
  ) -> tuple[Upstream, http.client.HTTPConnection, http.client.HTTPResponse]:
468
536
  relay = self.server.relay
469
537
  while True:
470
- upstream, config = relay.begin()
538
+ upstream, config = relay.begin(call=self.tool_call)
471
539
  connection = config.connection()
540
+ requested = False
472
541
  try:
473
542
  connection.connect()
474
543
  assert connection.sock is not None
@@ -478,6 +547,8 @@ class Handler(BaseHTTPRequestHandler):
478
547
  connection.sock.settimeout(
479
548
  SILENT_UPSTREAM_SECONDS if self.keeps_client_alive else None
480
549
  )
550
+ # Set first: a request that broke while it was sent may have arrived.
551
+ requested = True
481
552
  connection.request(
482
553
  self.command,
483
554
  config.prefix + self.target,
@@ -493,9 +564,13 @@ class Handler(BaseHTTPRequestHandler):
493
564
  self.retries += 1
494
565
  log(f"{self.command} {self.label}: aborted, retrying")
495
566
  continue
567
+ if requested and relay.direct:
568
+ raise UpstreamError(
569
+ f"the upstream broke before its response: {error!r}"
570
+ )
496
571
  self.unreachable(config, f"{error!r}")
497
572
  continue
498
- if is_edge_error(response):
573
+ if not relay.direct and is_edge_error(response):
499
574
  # Not read: an edge that stalls its page must not block the retry.
500
575
  self.sent -= 1
501
576
  relay.end(upstream)
@@ -715,11 +790,21 @@ def main() -> None:
715
790
  parser.add_argument("--ready")
716
791
  parser.add_argument("--pid")
717
792
  parser.add_argument("--failures")
793
+ parser.add_argument("--direct", action="store_true")
794
+ parser.add_argument("--hold")
795
+ parser.add_argument("--drained")
718
796
  args = parser.parse_args()
719
- relay = Relay(args.config, args.failures)
797
+ relay = Relay(
798
+ args.config,
799
+ args.failures,
800
+ direct=args.direct,
801
+ hold=args.hold,
802
+ drained=args.drained,
803
+ )
804
+ actions = {signal.SIGHUP: relay.reload, signal.SIGUSR1: relay.sync_hold}
720
805
  # Blocked before any thread starts, so threads inherit the mask and only the
721
- # `sigwait` below takes SIGHUP: a reload then never interrupts a handler.
722
- signal.pthread_sigmask(signal.SIG_BLOCK, {signal.SIGHUP})
806
+ # `sigwait` below takes them: a signal then never interrupts a handler.
807
+ signal.pthread_sigmask(signal.SIG_BLOCK, set(actions))
723
808
  server = Server(("127.0.0.1", args.port), relay)
724
809
  port = server.server_address[1]
725
810
  threading.Thread(target=server.serve_forever, daemon=True).start()
@@ -729,8 +814,7 @@ def main() -> None:
729
814
  write_file(args.ready, f"{port}\n")
730
815
  log(f"listening on 127.0.0.1:{port}, upstream {relay.config.origin}")
731
816
  while True:
732
- signal.sigwait({signal.SIGHUP})
733
- relay.reload()
817
+ actions[signal.sigwait(set(actions))]()
734
818
 
735
819
 
736
820
  if __name__ == "__main__":
@@ -627,8 +627,10 @@ class InterceptionServer(Interception):
627
627
  selects the wire format (see `dialects.DIALECTS`)."""
628
628
 
629
629
  async def handler(request: web.Request) -> web.StreamResponse:
630
+ session = self.sessions.get(dialect.secret(request.headers))
630
631
  try:
631
- response = await self.handle_request(request, dialect)
632
+ with session.waits() if session else contextlib.nullcontext():
633
+ response = await self.handle_request(request, dialect)
632
634
  except BaseException:
633
635
  _finish_idempotent_attempt(request, None)
634
636
  raise
@@ -774,18 +776,24 @@ class InterceptionServer(Interception):
774
776
  if session.released:
775
777
  return web.json_response({"error": "rollout concluded"}, status=409)
776
778
  body = from_json(await request.read())
777
- await session.flowing.wait()
778
- try:
779
- return web.json_response(
780
- await session.decide_tool(
781
- str(body.get("tool_call_id", "")),
782
- body.get("name"),
783
- body.get("arguments"),
784
- )
785
- )
786
- except RolloutError as error:
787
- session.error = error
788
- return web.json_response({"error": str(error)}, status=400)
779
+ with session.waits():
780
+ await session.flowing.wait()
781
+ try:
782
+ # A verdict's request hooks can write to the trace while a snapshot
783
+ # begins: it records the trace only once they are done, and the box
784
+ # gets the verdict only once it runs again.
785
+ with session.committing():
786
+ verdict = await session.decide_tool(
787
+ str(body.get("tool_call_id", "")),
788
+ body.get("name"),
789
+ body.get("arguments"),
790
+ )
791
+ except RolloutError as error:
792
+ session.error = error
793
+ await session.flowing.wait()
794
+ return web.json_response({"error": str(error)}, status=400)
795
+ await session.flowing.wait()
796
+ return web.json_response(verdict)
789
797
 
790
798
  def record_call(
791
799
  self,
@@ -21,10 +21,12 @@ from urllib.parse import parse_qsl, urlencode, urlsplit, urlunsplit
21
21
 
22
22
  from verifiers.v1.configs.runtime import NetworkPolicyConfig
23
23
  from verifiers.v1.errors import ToolsetError
24
+ from verifiers.v1.interception.relay import write_route
24
25
  from verifiers.v1.interception.tunnel import PrimeTunnel
25
26
  from verifiers.v1.mcp.server import (
26
27
  STATE_ROUTE_PARAM,
27
28
  STATE_SIGNATURE_PARAM,
29
+ STATE_TOKEN,
28
30
  STATE_URL_PARAM,
29
31
  ServerBase,
30
32
  state_signature,
@@ -342,6 +344,11 @@ async def _read_back_port(runtime: Runtime, path: str, deadline: float) -> int:
342
344
  await asyncio.sleep(min(1, remaining))
343
345
 
344
346
 
347
+ def state_route_path(server: ServerBase) -> str:
348
+ """Where a server on a VM of its own reads its state channel, as a route config."""
349
+ return f"/tmp/vf-state-route-{server.server_name}.json"
350
+
351
+
345
352
  async def serve_in_runtime(
346
353
  server: ServerBase,
347
354
  runtime: Runtime,
@@ -350,12 +357,15 @@ async def serve_in_runtime(
350
357
  listen_all: bool = False,
351
358
  state_url: str | None = None,
352
359
  state_secret: str = "",
360
+ state_file: str | None = None,
353
361
  ) -> int:
354
362
  """Start a server and return its bound port.
355
363
 
356
364
  Exposed servers use the runtime's forwarded port when one is configured. Otherwise,
357
365
  the OS chooses a port and reports it through a file. With a state channel, the server
358
- fetches the current rollout task from the adjacent `/task` endpoint.
366
+ fetches the current rollout task from the adjacent `/task` endpoint. With
367
+ `state_file`, the server reads the channel from that file in its runtime, which a
368
+ restore from a memory snapshot rewrites.
359
369
  """
360
370
  # A shared server has a private service secret but no fixed state URL. Set
361
371
  # both controls explicitly so a subprocess cannot inherit stale host values.
@@ -364,6 +374,11 @@ async def serve_in_runtime(
364
374
  "VF_STATE_URL": state_url or "",
365
375
  "VF_STATE_SECRET": state_secret,
366
376
  }
377
+ if state_file is not None:
378
+ await write_route(
379
+ runtime, state_file, state_url or "", {STATE_TOKEN: state_secret}
380
+ )
381
+ env["VF_STATE_FILE"] = state_file
367
382
  if runtime.type == "subprocess":
368
383
  # Keep provider temp files in the runtime workdir so cleanup removes them.
369
384
  assert runtime.info.id is not None
@@ -464,6 +479,7 @@ async def _serve(
464
479
  services: Mapping[str, Runtime] | None = None,
465
480
  hosts: Mapping[str, str] | None = None,
466
481
  placements: Mapping[str, Runtime] | None = None,
482
+ restored: Mapping[str, str] | None = None,
467
483
  ):
468
484
  cfg = server.config
469
485
  service = getattr(cfg, "service", None)
@@ -507,17 +523,30 @@ async def _serve(
507
523
  backend = await stack.enter_async_context(provision_backend(cfg.runtime))
508
524
  runtime = backend.bind()
509
525
 
526
+ state_url = (
527
+ runtime.host_url(f"{state_base.rstrip('/')}/state") if state_base else None
528
+ )
529
+ if own_vm is not None and server.server_name in (restored or {}):
530
+ # The VM continues a memory snapshot and still runs the server, on its
531
+ # first port: move it to this rollout's state channel.
532
+ await write_route(
533
+ runtime,
534
+ state_route_path(server),
535
+ state_url or "",
536
+ {STATE_TOKEN: state_secret},
537
+ )
538
+ first = urlsplit(restored[server.server_name])
539
+ url = first._replace(netloc=f"{host}:{first.port}").geturl()
540
+ yield _ServedServer(url, runtime)
541
+ return
510
542
  port = await serve_in_runtime(
511
543
  server,
512
544
  runtime,
513
545
  exposed=host is None,
514
546
  listen_all=host is not None,
515
- state_url=(
516
- runtime.host_url(f"{state_base.rstrip('/')}/state")
517
- if state_base
518
- else None
519
- ),
547
+ state_url=state_url,
520
548
  state_secret=state_secret,
549
+ state_file=state_route_path(server) if own_vm is not None else None,
521
550
  )
522
551
  if host is not None:
523
552
  yield _ServedServer(f"http://{host}:{port}/mcp", runtime)
@@ -556,6 +585,7 @@ async def serve(
556
585
  services: Mapping[str, Runtime] | None = None,
557
586
  hosts: Mapping[str, str] | None = None,
558
587
  placements: Mapping[str, Runtime] | None = None,
588
+ restored: Mapping[str, str] | None = None,
559
589
  ):
560
590
  """Serve one MCP server and yield the URL visible to its consumer."""
561
591
  async with _serve(
@@ -568,6 +598,7 @@ async def serve(
568
598
  services=services,
569
599
  hosts=hosts,
570
600
  placements=placements,
601
+ restored=restored,
571
602
  ) as served:
572
603
  yield served.url
573
604
 
@@ -679,6 +710,7 @@ async def serve_tools(
679
710
  services: Mapping[str, Runtime] | None = None,
680
711
  hosts: Mapping[str, str] | None = None,
681
712
  placements: Mapping[str, Runtime] | None = None,
713
+ restored: Mapping[str, str] | None = None,
682
714
  ):
683
715
  """Bring up a rollout's tool servers and yield `{name: url}` the harness reaches: the
684
716
  task-scoped `toolsets` own their connections through `Toolset.serve`, and
@@ -686,7 +718,10 @@ async def serve_tools(
686
718
  join under their per-rollout state tag.
687
719
  `state_secret` is private to task-scoped servers; shared servers keep an
688
720
  eval-level service secret and receive only signed `state_route` coordinates.
689
- `state_base` is universally reachable from either placement."""
721
+ `state_base` is universally reachable from either placement. `restored` maps the
722
+ servers whose VMs continue a memory snapshot to the URL they were first served at:
723
+ they still run, so they only move to this rollout's state channel, and are served
724
+ at their new VM's name."""
690
725
  urls: dict[str, str] = {}
691
726
  async with contextlib.AsyncExitStack() as stack:
692
727
  for name, server in (shared or {}).items():
@@ -716,6 +751,7 @@ async def serve_tools(
716
751
  services=services,
717
752
  hosts=hosts,
718
753
  placements=placements,
754
+ restored=restored,
719
755
  )
720
756
  )
721
757
  logger.debug("Connected tool server %s", name)