verifiers 0.4.2.dev112__py3-none-any.whl → 0.4.2.dev113__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/__init__.py CHANGED
@@ -78,6 +78,7 @@ if TYPE_CHECKING:
78
78
  HarnessError,
79
79
  InterceptionError,
80
80
  ProviderError,
81
+ RelayError,
81
82
  RolloutError,
82
83
  SandboxError,
83
84
  TaskError,
@@ -108,6 +109,7 @@ if TYPE_CHECKING:
108
109
  Runtime,
109
110
  RuntimeInfo,
110
111
  RuntimeProcess,
112
+ Snapshot,
111
113
  )
112
114
  from verifiers.v1.runtimes.compose import ComposeSpec
113
115
  from verifiers.v1.runtimes.deployment import Deployment, ServicesSpec
@@ -133,6 +135,7 @@ if TYPE_CHECKING:
133
135
  AgentInfo,
134
136
  AgentSpan,
135
137
  Branch,
138
+ Checkpoint,
136
139
  Error,
137
140
  EvalRunInfo,
138
141
  EvalWorkInfo,
@@ -224,6 +227,7 @@ _NAME_TO_MODULE = {
224
227
  "BaseConfig": "pydantic_config",
225
228
  "BindMount": "verifiers.v1.configs.runtime",
226
229
  "Branch": "verifiers.v1.trace",
230
+ "Checkpoint": "verifiers.v1.trace",
227
231
  "Client": "verifiers.v1.clients",
228
232
  "ClientConfig": "verifiers.v1.configs.client",
229
233
  "ComposeSpec": "verifiers.v1.runtimes.compose",
@@ -294,6 +298,7 @@ _NAME_TO_MODULE = {
294
298
  "RuntimeConfig": "verifiers.v1.configs.runtime",
295
299
  "RuntimeInfo": "verifiers.v1.runtimes",
296
300
  "RuntimeProcess": "verifiers.v1.runtimes",
301
+ "Snapshot": "verifiers.v1.runtimes",
297
302
  "SamplingConfig": "verifiers.v1.configs.sampling",
298
303
  "SamplerSupport": "verifiers.v1.types",
299
304
  "SandboxError": "verifiers.v1.errors",
@@ -342,6 +347,7 @@ _NAME_TO_MODULE = {
342
347
  "TrainRunInfo": "verifiers.v1.trace",
343
348
  "TrainWorkInfo": "verifiers.v1.trace",
344
349
  "TunnelError": "verifiers.v1.errors",
350
+ "RelayError": "verifiers.v1.errors",
345
351
  "TurnTokens": "verifiers.v1.types",
346
352
  "Usage": "verifiers.v1.types",
347
353
  "UserMessage": "verifiers.v1.types",
@@ -445,6 +451,7 @@ __all__ = [ # noqa: RUF022 - grouped by public API area
445
451
  "StateT",
446
452
  "MessageNode",
447
453
  "Branch",
454
+ "Checkpoint",
448
455
  "TurnTokens",
449
456
  "SamplerSupport",
450
457
  "Timing",
@@ -470,6 +477,7 @@ __all__ = [ # noqa: RUF022 - grouped by public API area
470
477
  "TaskError",
471
478
  "InterceptionError",
472
479
  "TunnelError",
480
+ "RelayError",
473
481
  # clients
474
482
  "Client",
475
483
  "BaseClientConfig",
@@ -502,6 +510,7 @@ __all__ = [ # noqa: RUF022 - grouped by public API area
502
510
  "RuntimeProcess",
503
511
  "RuntimeConfig",
504
512
  "RuntimeInfo",
513
+ "Snapshot",
505
514
  "ProgramResult",
506
515
  "SubprocessConfig",
507
516
  "DockerConfig",
@@ -3,11 +3,14 @@
3
3
  import asyncio
4
4
  import contextlib
5
5
  import json
6
+ import shlex
7
+ import time
8
+ import uuid
6
9
  from abc import abstractmethod
7
10
  from collections.abc import AsyncIterator
8
11
  from dataclasses import dataclass
9
12
  from pathlib import Path
10
- from typing import Any, TypeAlias, TypeVar, cast
13
+ from typing import Any, ClassVar, TypeAlias, TypeVar, cast
11
14
 
12
15
  from pydantic import BaseModel, ConfigDict, Field
13
16
 
@@ -16,6 +19,7 @@ from verifiers.v1.configs.harness import HarnessConfig
16
19
  from verifiers.v1.errors import HarnessError, InterceptionError
17
20
  from verifiers.v1.harness import Harness, HarnessSession
18
21
  from verifiers.v1.runtimes import ProgramResult, Runtime, RuntimeProcess
22
+ from verifiers.v1.runtimes.base import current_program
19
23
  from verifiers.v1.semantic import (
20
24
  ACP_SEMANTIC_EDGES_METADATA_KEY,
21
25
  SemanticEdgeSet,
@@ -27,6 +31,9 @@ from verifiers.v1.utils.aio import run_shielded
27
31
 
28
32
  ACP_SOURCE = (Path(__file__).resolve().parent / "runner.py").read_text()
29
33
  MAX_PACKET_BYTES = 128 * 1024 * 1024
34
+ ACP_ROOT = "/tmp/vf-acp"
35
+ """Where a detached runner keeps its socket, log and request files, per rollout."""
36
+ RUNNER_START_SECONDS = 120
30
37
  _STOP_CONDITIONS = {
31
38
  "max_tokens": "max_output_tokens",
32
39
  "max_turn_requests": "max_turns",
@@ -71,6 +78,8 @@ class ACPConfig:
71
78
  class ACPHarness(Harness[ConfigT]):
72
79
  """Harness backed by one live ACP process and native session per rollout."""
73
80
 
81
+ SUPPORTS_MEMORY_RESTORE: ClassVar[bool] = True
82
+
74
83
  async def setup(self, runtime: Runtime) -> None:
75
84
  await runtime.prepare_uv_script(
76
85
  ACP_SOURCE, {**self.config.resolved_env, "UV_FROZEN": "false"}
@@ -238,6 +247,19 @@ class ACPHarnessSession(HarnessSession):
238
247
  self._responses: dict[int, asyncio.Future] = {}
239
248
  self._request_id = 0
240
249
  self._response_task: asyncio.Task | None = None
250
+ self._detached: list[str] | None = None
251
+ """The runner's argv once it runs as a job of the box (`memory`): each request
252
+ is then a job too, since no connection from the host survives a stopped box."""
253
+ self._prompt: dict[str, Any] | None = None
254
+ """The reply file and the trace's call count of the prompt request under way."""
255
+
256
+ @property
257
+ def _dir(self) -> str:
258
+ return f"{ACP_ROOT}/{self.trace.id}"
259
+
260
+ @property
261
+ def _running(self) -> bool:
262
+ return self._process is not None or self._detached is not None
241
263
 
242
264
  async def _start(self) -> None:
243
265
  self._stderr_tail.clear()
@@ -246,6 +268,23 @@ class ACPHarnessSession(HarnessSession):
246
268
  {**self.config.env, "UV_FROZEN": "false"},
247
269
  activate=False,
248
270
  )
271
+ if self.memory:
272
+ socket = f"{self._dir}/socket"
273
+ await self.runtime.run(["mkdir", "-p", self._dir], {})
274
+ await self.runtime.run_background(
275
+ [*program, "--socket", socket],
276
+ self.config.env,
277
+ log=f"{self._dir}/runner.log",
278
+ )
279
+ deadline = time.monotonic() + RUNNER_START_SECONDS
280
+ while (await self.runtime.run(["test", "-S", socket], {})).exit_code:
281
+ if time.monotonic() > deadline:
282
+ raise RuntimeError(
283
+ f"ACP runner did not start: {await self._runner_log()}"
284
+ )
285
+ await asyncio.sleep(0.2)
286
+ self._detached = program
287
+ return
249
288
  process = await self.runtime.exec(program, self.config.env)
250
289
  self._process = process
251
290
  self._reader = _PacketReader(process.stdout)
@@ -266,7 +305,77 @@ class ACPHarnessSession(HarnessSession):
266
305
  RuntimeError(f"ACP connection closed: {error}")
267
306
  )
268
307
 
308
+ async def _runner_log(self) -> str:
309
+ with contextlib.suppress(Exception):
310
+ log = await self.runtime.run(
311
+ ["tail", "-c", "4000", f"{self._dir}/runner.log"], {}
312
+ )
313
+ return log.stdout.strip()
314
+ return ""
315
+
316
+ async def _call(self, operation: str, payload: dict[str, Any]) -> JsonObject:
317
+ """One request to the detached runner, as a job of the box."""
318
+ assert self._detached is not None
319
+ name = uuid.uuid4().hex
320
+ request, reply = f"{self._dir}/{name}.request", f"{self._dir}/{name}.reply"
321
+ await self.runtime.write(
322
+ request,
323
+ json.dumps({"id": name, "operation": operation, **payload}).encode(),
324
+ )
325
+ program = None
326
+ if operation == "prompt":
327
+ program = current_program.get()
328
+ self._prompt = {"reply": reply, "calls_before": len(self.trace.calls)}
329
+ try:
330
+ result = await self.runtime.run(
331
+ [*self._detached, "--call", f"{self._dir}/socket", request, reply],
332
+ self.config.env,
333
+ program=program,
334
+ )
335
+ finally:
336
+ if operation == "prompt":
337
+ self._prompt = None
338
+ return await self._reply(result, reply)
339
+
340
+ async def _reply(self, result: ProgramResult, reply: str) -> JsonObject:
341
+ if result.exit_code:
342
+ detail = (result.stderr or result.stdout).strip()[-1000:]
343
+ raise RuntimeError(
344
+ f"ACP runner request failed (exit {result.exit_code}): {detail}"
345
+ )
346
+ response = json.loads(await self.runtime.read(reply))
347
+ if not response.get("ok"):
348
+ self._stderr_tail[:] = (await self._runner_log()).encode()
349
+ return response
350
+
351
+ def memory_state(self) -> dict[str, Any] | None:
352
+ state = super().memory_state()
353
+ if state is None or self._prompt is None or self._detached is None:
354
+ return None
355
+ return {**state, **self._prompt, "runner": list(self._detached)}
356
+
357
+ async def _continue(self, state: dict[str, Any]) -> ProgramResult:
358
+ # The restored box runs the runner and the request's job; only their result
359
+ # is still to collect.
360
+ self._detached = list(state["runner"])
361
+ async with self._lock:
362
+ self._prompt = {
363
+ "reply": state["reply"],
364
+ "calls_before": state["calls_before"],
365
+ }
366
+ try:
367
+ result = await self.runtime.attach(state["job"], program=self.program)
368
+ response = await self._reply(result, state["reply"])
369
+ except BaseException:
370
+ await run_shielded(self._stop(graceful=False))
371
+ raise
372
+ finally:
373
+ self._prompt = None
374
+ return self._finish(response, state["calls_before"])
375
+
269
376
  async def _request(self, operation: str, **payload: Any) -> JsonObject:
377
+ if self._detached is not None:
378
+ return await self._call(operation, payload)
270
379
  process = self._process
271
380
  if process is None or self._response_task is None or self._response_task.done():
272
381
  raise RuntimeError("ACP process is not running")
@@ -290,7 +399,7 @@ class ACPHarnessSession(HarnessSession):
290
399
  raise RuntimeError("ACP session is closed")
291
400
  if not isinstance(message, str) or not message.strip():
292
401
  raise ValueError("steering requires a nonempty user message")
293
- if self._process is None:
402
+ if not self._running:
294
403
  return {"outcome": "promptRequired", "reason": "noRunningTurn"}
295
404
  response = await self._request("steer", message=message, message_id=message_id)
296
405
  if not response.get("ok"):
@@ -349,16 +458,18 @@ class ACPHarnessSession(HarnessSession):
349
458
  raise HarnessError(
350
459
  f"harness {self.harness.config.id!r} session is already closed"
351
460
  )
352
- if self._process is None:
461
+ if not self._running:
353
462
  await self._start()
354
- assert self._process is not None
355
- assert self._reader is not None
356
463
  calls_before = len(self.trace.calls)
357
464
  try:
358
465
  response = await self._request("prompt", config=config)
359
466
  except BaseException:
360
467
  await run_shielded(self._stop(graceful=False))
361
468
  raise
469
+ return self._finish(response, calls_before)
470
+
471
+ def _finish(self, response: JsonObject, calls_before: int) -> ProgramResult:
472
+ """Consume a prompt request's response as the segment's result."""
362
473
  turn = _turn_result(response)
363
474
  self.trace.root_reply = turn.reply.strip()
364
475
  self.trace.info["acp_stop_reason"] = turn.stop_reason
@@ -382,7 +493,33 @@ class ACPHarnessSession(HarnessSession):
382
493
  _require_model_turn(self.trace, calls_before, result)
383
494
  return result
384
495
 
496
+ async def _stop_detached(self, *, graceful: bool) -> dict[str, Any]:
497
+ response_metadata: dict[str, Any] = {}
498
+ try:
499
+ if graceful:
500
+ with contextlib.suppress(BaseException):
501
+ response = await asyncio.wait_for(self._call("shutdown", {}), 30)
502
+ result = response.get("result")
503
+ if response.get("ok") and isinstance(result, dict):
504
+ metadata = result.get("response_metadata")
505
+ if isinstance(metadata, dict):
506
+ response_metadata = metadata
507
+ # Best effort: the box may be gone already.
508
+ pid = shlex.quote(f"{self._dir}/socket.pid")
509
+ with contextlib.suppress(BaseException):
510
+ await asyncio.wait_for(
511
+ self.runtime.run(
512
+ ["sh", "-c", f'kill "$(cat {pid})" 2>/dev/null; true'], {}
513
+ ),
514
+ 30,
515
+ )
516
+ finally:
517
+ self._detached = None
518
+ return response_metadata
519
+
385
520
  async def _stop(self, *, graceful: bool) -> dict[str, Any]:
521
+ if self._detached is not None:
522
+ return await self._stop_detached(graceful=graceful)
386
523
  process = self._process
387
524
  response_task = self._response_task
388
525
  stderr_task, self._stderr_task = self._stderr_task, None
@@ -365,27 +365,28 @@ def write_packet(stream: Any, value: dict) -> None:
365
365
  stream.flush()
366
366
 
367
367
 
368
- async def serve_stream() -> None:
369
- session = ACPSession()
370
- reader = asyncio.StreamReader()
371
- protocol = asyncio.StreamReaderProtocol(reader)
372
- await asyncio.get_running_loop().connect_read_pipe(
373
- lambda: protocol, sys.stdin.buffer
374
- )
375
- tasks: set[asyncio.Task] = set()
376
- prompt_lock = asyncio.Lock()
368
+ class Server:
369
+ """Serves the host's session requests, over whichever transport carries them."""
370
+
371
+ def __init__(self) -> None:
372
+ self.session = ACPSession()
373
+ self.tasks: set[asyncio.Task] = set()
374
+ self.prompt_lock = asyncio.Lock()
377
375
 
378
- async def handle(request: dict) -> None:
376
+ async def handle(self, request: dict) -> dict:
377
+ session = self.session
379
378
  operation = request.get("operation")
380
379
  try:
381
380
  if operation == "prompt":
382
- async with prompt_lock:
381
+ async with self.prompt_lock:
383
382
  result = asdict(await session.run(request["config"]))
384
383
  elif operation == "steer":
385
384
  result = await session.steer(
386
385
  request["message"], request.get("message_id")
387
386
  )
388
387
  elif operation == "shutdown":
388
+ if self.tasks:
389
+ await asyncio.gather(*self.tasks, return_exceptions=True)
389
390
  result = {"response_metadata": await session.close()}
390
391
  else:
391
392
  raise ValueError(f"unknown ACP session operation: {operation!r}")
@@ -403,27 +404,111 @@ async def serve_stream() -> None:
403
404
  if operation == "prompt":
404
405
  response["result"] = asdict(session.client.turn_result())
405
406
  response["id"] = request.get("id")
407
+ return response
408
+
409
+ def spawn(self, request: dict, reply) -> asyncio.Task:
410
+ """Handle `request` in a task of its own and hand its response to `reply`."""
411
+
412
+ async def run() -> None:
413
+ reply(await self.handle(request))
414
+
415
+ task = asyncio.create_task(run())
416
+ self.tasks.add(task)
417
+ task.add_done_callback(self.tasks.discard)
418
+ return task
419
+
420
+ async def close(self) -> None:
421
+ for task in self.tasks:
422
+ task.cancel()
423
+ if self.tasks:
424
+ await asyncio.gather(*self.tasks, return_exceptions=True)
425
+ await self.session.close()
426
+
427
+
428
+ async def serve_stream() -> None:
429
+ server = Server()
430
+ reader = asyncio.StreamReader()
431
+ protocol = asyncio.StreamReaderProtocol(reader)
432
+ await asyncio.get_running_loop().connect_read_pipe(
433
+ lambda: protocol, sys.stdin.buffer
434
+ )
435
+
436
+ def reply(response: dict) -> None:
406
437
  write_packet(sys.stdout.buffer, response)
407
438
 
408
439
  try:
409
440
  while request := await read_packet(reader):
410
441
  if request.get("operation") == "shutdown":
411
- if tasks:
412
- await asyncio.gather(*tasks)
413
- await handle(request)
442
+ reply(await server.handle(request))
414
443
  break
415
- task = asyncio.create_task(handle(request))
416
- tasks.add(task)
417
- task.add_done_callback(tasks.discard)
444
+ server.spawn(request, reply)
418
445
  finally:
419
- for task in tasks:
420
- task.cancel()
421
- if tasks:
422
- await asyncio.gather(*tasks, return_exceptions=True)
423
- await session.close()
446
+ await server.close()
447
+
448
+
449
+ async def serve_socket(path: str) -> None:
450
+ """Serve session requests on a Unix socket, one per connection, until a shutdown
451
+ request: the host's memory snapshots stop the box, which no connection from the
452
+ host survives, so each request comes from a job of the box (`call`) instead."""
453
+ server = Server()
454
+ stopped = asyncio.Event()
455
+
456
+ async def connected(
457
+ reader: asyncio.StreamReader, writer: asyncio.StreamWriter
458
+ ) -> None:
459
+ try:
460
+ request = await read_packet(reader)
461
+ if request is None:
462
+ return
463
+ response = await server.handle(request)
464
+ data = json.dumps(response, ensure_ascii=False).encode()
465
+ writer.write(len(data).to_bytes(8, "big") + data)
466
+ await writer.drain()
467
+ if request.get("operation") == "shutdown":
468
+ stopped.set()
469
+ finally:
470
+ writer.close()
471
+
472
+ with suppress(FileNotFoundError):
473
+ os.unlink(path)
474
+ listener = await asyncio.start_unix_server(connected, path, limit=MAX_PACKET_BYTES)
475
+ # A few bytes, once, before any request is served.
476
+ with open(f"{path}.pid", "w") as file: # noqa: ASYNC230
477
+ file.write(f"{os.getpid()}\n")
478
+ try:
479
+ async with listener:
480
+ await stopped.wait()
481
+ finally:
482
+ await server.close()
483
+
484
+
485
+ def call(path: str, request_path: str, reply_path: str) -> None:
486
+ """Send the request in `request_path` to the server on the socket at `path` and
487
+ write its response to `reply_path`."""
488
+ import socket
489
+
490
+ with open(request_path, "rb") as file:
491
+ data = file.read()
492
+ with socket.socket(socket.AF_UNIX) as connection:
493
+ connection.connect(path)
494
+ connection.sendall(len(data).to_bytes(8, "big") + data)
495
+ stream = connection.makefile("rb")
496
+ header = stream.read(8)
497
+ if len(header) != 8:
498
+ raise EOFError(
499
+ "ACP runner closed the connection before its response header"
500
+ )
501
+ size = int.from_bytes(header, "big")
502
+ response = stream.read(size)
503
+ if len(response) != size:
504
+ raise EOFError("ACP runner closed the connection before its response")
505
+ staged = f"{reply_path}.tmp"
506
+ with open(staged, "wb") as file:
507
+ file.write(response)
508
+ os.replace(staged, reply_path)
424
509
 
425
510
 
426
- async def main() -> None:
511
+ async def main(socket_path: str | None) -> None:
427
512
  task = asyncio.current_task()
428
513
  loop = asyncio.get_running_loop()
429
514
  if task is not None:
@@ -431,8 +516,15 @@ async def main() -> None:
431
516
  with suppress(NotImplementedError):
432
517
  loop.add_signal_handler(sig, task.cancel)
433
518
  with suppress(asyncio.CancelledError):
434
- await serve_stream()
519
+ if socket_path is None:
520
+ await serve_stream()
521
+ else:
522
+ await serve_socket(socket_path)
435
523
 
436
524
 
437
525
  if __name__ == "__main__":
438
- asyncio.run(main())
526
+ arguments = sys.argv[1:]
527
+ if arguments[:1] == ["--call"]:
528
+ call(*arguments[1:4])
529
+ else:
530
+ asyncio.run(main(arguments[1] if arguments[:1] == ["--socket"] else None))