verifiers 0.4.2.dev57__py3-none-any.whl → 0.4.2.dev58__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
@@ -47,7 +47,6 @@ if TYPE_CHECKING:
47
47
  PrimeConfig,
48
48
  PrimeVolume,
49
49
  RuntimeConfig,
50
- SubprocessConfig,
51
50
  )
52
51
  from verifiers.v1.configs.sampling import Sampling, SamplingConfig
53
52
  from verifiers.v1.configs.scoring import ScoringConfig
@@ -305,7 +304,6 @@ _NAME_TO_MODULE = {
305
304
  "State": "verifiers.v1.state",
306
305
  "StateT": "verifiers.v1.state",
307
306
  "StopFunctionConfig": "verifiers.v1.configs.task",
308
- "SubprocessConfig": "verifiers.v1.configs.runtime",
309
307
  "SystemMessage": "verifiers.v1.types",
310
308
  "TRACE_VERSION": "verifiers.v1.trace",
311
309
  "Task": "verifiers.v1.task",
@@ -496,7 +494,6 @@ __all__ = [ # noqa: RUF022 - grouped by public API area
496
494
  "RuntimeConfig",
497
495
  "RuntimeInfo",
498
496
  "ProgramResult",
499
- "SubprocessConfig",
500
497
  "DockerConfig",
501
498
  "BindMount",
502
499
  "CustomRuntimeConfig",
verifiers/v1/cli/debug.py CHANGED
@@ -25,7 +25,7 @@ from verifiers.v1.cli.resolve import (
25
25
  with_positional_taskset,
26
26
  )
27
27
  from verifiers.v1.configs.cli.debug import DebugConfig
28
- from verifiers.v1.runtimes import ProgramResult, Runtime, make_backend
28
+ from verifiers.v1.runtimes import ProgramResult, Runtime, backend_cls, make_backend
29
29
  from verifiers.v1.state import state_cls
30
30
  from verifiers.v1.task import Task
31
31
  from verifiers.v1.trace import AgentInfo, Error, Trace, TraceTask
@@ -39,7 +39,7 @@ logger = get_logger(__name__)
39
39
 
40
40
  USAGE = (
41
41
  "usage: uv run vf-debug [<taskset-id>] (--command <cmd> | --script-path <path>) "
42
- "[--runtime.type subprocess] [options] [@ file.toml]\n"
42
+ "[--runtime.type docker] [options] [@ file.toml]\n"
43
43
  " runs setup, then one command or uploaded host script, and saves traces"
44
44
  )
45
45
 
@@ -173,9 +173,8 @@ async def run_action(runtime: Runtime, config: DebugConfig) -> dict[str, Any]:
173
173
  **(await run_timed(runtime.run(["sh", "-lc", config.command], {}), config)),
174
174
  }
175
175
  assert config.script_path is not None
176
- # /tmp keyed by the (run-unique) runtime name: outside the task workdir so the script
177
- # doesn't show up in the repo state being inspected, and never shared between runs on
178
- # the subprocess runtime, where an absolute path is a host path.
176
+ # Keep the script outside the task workdir so it doesn't appear in the repo
177
+ # state being inspected; the runtime name separates concurrent runs.
179
178
  remote_path = f"/tmp/{runtime.name}-script.sh"
180
179
  quoted = shlex.quote(remote_path)
181
180
  command = f"chmod +x {quoted} && {quoted}"
@@ -275,7 +274,7 @@ async def run_debug(config: DebugConfig) -> list[Trace]:
275
274
  f"{type(taskset).__name__} is infinite - bound the run with -n"
276
275
  )
277
276
  tasks = list(taskset)
278
- if isinstance(config.runtime, vf.SubprocessConfig) and any(
277
+ if not backend_cls(config.runtime).SUPPORTS_TASK_IMAGES and any(
279
278
  type(t).NEEDS_CONTAINER or t.data.image for t in tasks
280
279
  ):
281
280
  raise SystemExit(
@@ -35,7 +35,7 @@ from verifiers.v1.grading import (
35
35
  scoring_network,
36
36
  verifier_runtime,
37
37
  )
38
- from verifiers.v1.runtimes import make_backend
38
+ from verifiers.v1.runtimes import backend_cls, make_backend
39
39
  from verifiers.v1.runtimes.deployment import Deployment
40
40
  from verifiers.v1.state import state_cls
41
41
  from verifiers.v1.task import Task
@@ -63,7 +63,7 @@ ResultRow = dict[str, Any]
63
63
 
64
64
  USAGE = (
65
65
  "usage: uv run vf-validate [<taskset-id>] [--only-setup | --only-gold | --only-noop] "
66
- "[-o <output-dir>] [--runtime.type subprocess] [options] [@ file.toml]\n"
66
+ "[-o <output-dir>] [--runtime.type docker] [options] [@ file.toml]\n"
67
67
  " uv run vf-validate @ <run-dir>/configs/validate.json --resume (re-run missing/errored/timed-out tasks)\n"
68
68
  " runs persisted gold and noop (untouched scoring) checks per task (no agent)"
69
69
  )
@@ -448,7 +448,7 @@ async def run_validate(config: ValidateConfig) -> list[dict]:
448
448
  f"{type(taskset).__name__} is infinite - bound the run with -n"
449
449
  )
450
450
  tasks = list(taskset)
451
- if isinstance(config.runtime, vf.SubprocessConfig) and any(
451
+ if not backend_cls(config.runtime).SUPPORTS_TASK_IMAGES and any(
452
452
  type(t).NEEDS_CONTAINER or t.data.image for t in tasks
453
453
  ):
454
454
  raise SystemExit(
@@ -152,10 +152,6 @@ class NetworkPolicyConfig(BaseConfig):
152
152
  return type(self).model_validate({**values, "allow": allow, "block": block})
153
153
 
154
154
 
155
- class SubprocessConfig(BaseConfig):
156
- type: Literal["subprocess"] = "subprocess"
157
-
158
-
159
155
  class DockerConfig(NetworkPolicyConfig):
160
156
  type: Literal["docker"] = "docker"
161
157
  image: str = "python:3.11-slim"
@@ -275,7 +271,7 @@ class CustomRuntimeConfig(BaseConfig):
275
271
  # Serialized by the runtime type, so a custom runtime's typed config keeps its fields.
276
272
  RuntimeConfig = SerializeAsAny[
277
273
  Annotated[
278
- SubprocessConfig | DockerConfig | PrimeConfig | CustomRuntimeConfig,
274
+ DockerConfig | PrimeConfig | CustomRuntimeConfig,
279
275
  Field(discriminator="type"),
280
276
  ]
281
277
  ]
verifiers/v1/env.py CHANGED
@@ -30,7 +30,7 @@ from verifiers.v1.interception import (
30
30
  requires_tunnel,
31
31
  )
32
32
  from verifiers.v1.mcp import SharedToolServer, serve_shared
33
- from verifiers.v1.runtimes import SubprocessConfig, runtime_is_local
33
+ from verifiers.v1.runtimes import runtime_is_local
34
34
  from verifiers.v1.task import Task
35
35
  from verifiers.v1.trace import Error, Trace, TraceTask
36
36
  from verifiers.v1.utils.format import format_time
@@ -131,22 +131,6 @@ class Env(ABC, Generic[ConfigT]):
131
131
  if key not in loaded:
132
132
  loaded[key] = load_harness(cfg)
133
133
  self._harnesses[name] = loaded[key]
134
- warned: set[str] = set()
135
- for name, harness in self._harnesses.items():
136
- # Warn once per distinct harness; tool-less chat loops are exempt.
137
- if (
138
- harness.EXECUTES_CODE
139
- and isinstance(self._agent_specs[name].runtime, SubprocessConfig)
140
- and harness.config.id not in warned
141
- ):
142
- warned.add(harness.config.id)
143
- logger.warning(
144
- "Harness %r is running in the subprocess runtime on the local system. "
145
- "Local files and settings may affect the evaluation; use subprocess only "
146
- "for debugging. Use --env.<role>.runtime.type docker or prime "
147
- "for an isolated run.",
148
- harness.config.id,
149
- )
150
134
  # Serving resources, live only inside `serving()`; the env's agents borrow them.
151
135
  self._shared_tools: dict[str, SharedToolServer] = {}
152
136
  self._interception: Interception | None = None
@@ -23,6 +23,7 @@ from verifiers.v1.judges.rubric import (
23
23
  score_verdicts,
24
24
  weighted_score,
25
25
  )
26
+ from verifiers.v1.runtimes import backend_cls
26
27
  from verifiers.v1.utils.compile import validate_pairing
27
28
 
28
29
  VERDICT_FILE = "/tmp/verdict.json"
@@ -317,7 +318,7 @@ class AgenticJudgeEnv(vf.Env[AgenticJudgeEnvConfig]):
317
318
  workspace = (
318
319
  policy.runtime if policy.mode == "isolated" else None
319
320
  ) or self.config.solver.runtime
320
- if isinstance(workspace, vf.SubprocessConfig):
321
+ if not backend_cls(workspace).SUPPORTS_TASK_IMAGES:
321
322
  raise TypeError("agentic judging requires a container scoring workspace")
322
323
  validate_pairing(self._harnesses["judge"], JudgeTask, workspace)
323
324
 
@@ -5,16 +5,12 @@ import contextlib
5
5
  import math
6
6
  import secrets
7
7
  import shlex
8
- import shutil
9
- import subprocess
10
8
  import sys
11
- import sysconfig
12
- import tempfile
13
9
  import uuid
14
10
  from collections.abc import AsyncIterator, Mapping
15
11
  from dataclasses import dataclass, field
16
12
  from functools import cache
17
- from importlib.metadata import PathDistribution, distribution, packages_distributions
13
+ from importlib.metadata import distribution, packages_distributions
18
14
  from pathlib import Path, PurePosixPath
19
15
  from typing import TYPE_CHECKING
20
16
  from urllib.parse import parse_qsl, urlencode, urlsplit, urlunsplit
@@ -22,6 +18,7 @@ from urllib.parse import parse_qsl, urlencode, urlsplit, urlunsplit
22
18
  from verifiers.v1.configs.runtime import NetworkPolicyConfig
23
19
  from verifiers.v1.errors import ToolsetError
24
20
  from verifiers.v1.interception.tunnel import PrimeTunnel
21
+ from verifiers.v1.mcp.packages import install_package
25
22
  from verifiers.v1.mcp.server import (
26
23
  STATE_ROUTE_PARAM,
27
24
  STATE_SIGNATURE_PARAM,
@@ -46,22 +43,6 @@ if TYPE_CHECKING:
46
43
 
47
44
  logger = get_logger(__name__)
48
45
 
49
- _PACKAGE_BUILD_TIMEOUT_SECONDS = 300
50
-
51
-
52
- @dataclass
53
- class _PackageBuildState:
54
- lock: asyncio.Lock = field(default_factory=asyncio.Lock)
55
- build: asyncio.Task[tuple[str, bytes]] | None = None
56
- users: int = 0
57
-
58
-
59
- # Coordination and caching are process-local. Separate worker processes each
60
- # build once; within an event loop, concurrent rollouts share the completed artifact.
61
- _PACKAGE_BUILD_STATES: dict[
62
- tuple[Path, asyncio.AbstractEventLoop], _PackageBuildState
63
- ] = {}
64
-
65
46
  # Any HTTP response, including MCP's 406 to a bare GET, proves the server is listening.
66
47
  _PROBE = """
67
48
  import sys, time, urllib.error, urllib.request
@@ -105,165 +86,18 @@ def _package_dir(cls: type) -> str:
105
86
  )
106
87
 
107
88
 
108
- @cache
109
- def _build_package(src: Path) -> tuple[str, bytes]:
110
- """Transfer installed wheel files or build a source project's PEP 517 sdist."""
111
- with tempfile.TemporaryDirectory(prefix="vf-package-") as directory:
112
- out = Path(directory)
113
- if src.suffix == ".dist-info":
114
- dist = PathDistribution(src)
115
- files = dist.files
116
- if not files:
117
- raise ToolsetError(f"cannot package {src}: missing RECORD")
118
- package = out / "package"
119
- scripts = {
120
- entry.name
121
- for entry in dist.entry_points
122
- if entry.group in {"console_scripts", "gui_scripts"}
123
- }
124
- for file in files:
125
- # Installers regenerate entry-point scripts for the target Python.
126
- if ".." in file.parts or file.is_absolute():
127
- if (
128
- file.name in scripts
129
- and Path(file.locate()).parent.resolve()
130
- == Path(sysconfig.get_path("scripts")).resolve()
131
- ):
132
- continue
133
- raise ToolsetError(
134
- f"cannot package {src}: installed file outside site-packages: {file}"
135
- )
136
- if file.suffix == ".pyc" or (
137
- file.parent.name == src.name
138
- and file.name
139
- in {
140
- "RECORD",
141
- "RECORD.jws",
142
- "RECORD.p7s",
143
- "INSTALLER",
144
- "REQUESTED",
145
- "direct_url.json",
146
- "uv_cache.json",
147
- }
148
- ):
149
- continue
150
- target = package / file
151
- target.parent.mkdir(parents=True, exist_ok=True)
152
- shutil.copy2(file.locate(), target)
153
- command = [
154
- "uv",
155
- "tool",
156
- "run",
157
- "--from",
158
- "wheel==0.48.0",
159
- "wheel",
160
- "pack",
161
- "--dest-dir",
162
- str(out),
163
- str(package),
164
- ]
165
- else:
166
- command = [
167
- "uv",
168
- "build",
169
- "--sdist",
170
- "--no-create-gitignore",
171
- "--color",
172
- "never",
173
- "--out-dir",
174
- str(out),
175
- ".",
176
- ]
177
- try:
178
- # Run from the source root so uv discovers this project's workspace,
179
- # uv.toml, indexes, constraints, and Python configuration rather than
180
- # inheriting configuration from the launcher's working directory.
181
- result = subprocess.run(
182
- command,
183
- cwd=src,
184
- capture_output=True,
185
- text=True,
186
- check=False,
187
- timeout=_PACKAGE_BUILD_TIMEOUT_SECONDS,
188
- )
189
- except FileNotFoundError as e:
190
- raise ToolsetError(
191
- f"cannot build package for {src}: uv is not installed"
192
- ) from e
193
- except subprocess.TimeoutExpired as e:
194
- raise ToolsetError(
195
- "package build timed out after "
196
- f"{_PACKAGE_BUILD_TIMEOUT_SECONDS}s for {src}"
197
- ) from e
198
- if result.returncode != 0:
199
- detail = "\n".join(
200
- part.strip() for part in (result.stdout, result.stderr) if part.strip()
201
- )
202
- raise ToolsetError(f"package build failed for {src}: {detail[-2000:]}")
203
- artifacts = [path for path in out.iterdir() if path.is_file()]
204
- if len(artifacts) != 1:
205
- names = ", ".join(sorted(path.name for path in artifacts)) or "none"
206
- raise ToolsetError(
207
- f"package build for {src} produced {len(artifacts)} distributions: {names}"
208
- )
209
- artifact = artifacts[0]
210
- return artifact.name, artifact.read_bytes()
211
-
212
-
213
- async def _cached_package(src: Path) -> tuple[str, bytes]:
214
- """Build once per source without parking waiters in the thread pool."""
215
- src = src.resolve()
216
- key = (src, asyncio.get_running_loop())
217
- state = _PACKAGE_BUILD_STATES.get(key)
218
- if state is None:
219
- state = _PackageBuildState()
220
- _PACKAGE_BUILD_STATES[key] = state
221
- state.users += 1
222
- try:
223
- async with state.lock:
224
- # Coordinate before entering the default executor so concurrent
225
- # same-source waiters do not occupy executor threads.
226
- if state.build is None:
227
- state.build = asyncio.create_task(
228
- asyncio.to_thread(_build_package, src)
229
- )
230
- build = state.build
231
- try:
232
- return await asyncio.shield(build)
233
- except asyncio.CancelledError:
234
- # Cancelling to_thread does not stop its worker. Keep the lock until
235
- # that worker exits so a replacement caller cannot overlap the build.
236
- with contextlib.suppress(Exception):
237
- await build
238
- raise
239
- finally:
240
- state.users -= 1
241
- if state.users == 0 and _PACKAGE_BUILD_STATES.get(key) is state:
242
- del _PACKAGE_BUILD_STATES[key]
243
-
244
-
245
89
  async def _install_in_sandbox(server: ServerBase, agent_runtime: Runtime) -> str:
246
- # Install as root; the agent user only runs the server.
247
- runtime = (
248
- agent_runtime if agent_runtime.user is None else agent_runtime.with_user(None)
249
- )
250
- # Prime VMs mount /tmp as a small tmpfs, while the runtime workdir lives on
251
- # the VM's root disk. Keep source, build scratch space, and uv's cache on the
252
- # durable runtime filesystem so ordinary dependency installs cannot exhaust
253
- # the tmpfs.
254
- # Every runtime runs commands in its working directory; not every config names it.
255
- located = await runtime.run(["pwd"], {})
256
- workdir = located.stdout.strip()
257
- if located.exit_code or not workdir:
258
- raise ToolsetError(
259
- f"server {server.server_name!r}: cannot locate the runtime's working "
260
- f"directory: {located.stderr.strip()}"
261
- )
262
- root = str(PurePosixPath(workdir) / ".vf-src")
263
- temp = str(PurePosixPath(workdir) / ".vf-tmp")
264
- cache = str(PurePosixPath(workdir) / ".vf-uv-cache")
265
- venv = str(PurePosixPath(workdir) / ".vf-venv")
266
- python_dir = str(PurePosixPath(workdir) / ".vf-python")
90
+ # Dependency installation is trusted setup as the backend's default user.
91
+ # The server itself keeps the agent's user and filesystem policy when launched.
92
+ runtime = agent_runtime.backend.bind(env=agent_runtime.env)
93
+ # Prime mounts /tmp as a small tmpfs. Keep dependencies on the root disk,
94
+ # outside the task workspace so its files contain only the task's work.
95
+ support = "/var/tmp/tool-service"
96
+ root = f"{support}/src"
97
+ temp = f"{support}/tmp"
98
+ cache = f"{support}/uv-cache"
99
+ venv = f"{support}/venv"
100
+ python_dir = f"{support}/python"
267
101
  root_q, temp_q, cache_q, venv_q = map(shlex.quote, (root, temp, cache, venv))
268
102
  # Servers in the same service install into one physical environment.
269
103
  # Serialize its mutations and only remember sources after a successful install.
@@ -275,29 +109,27 @@ async def _install_in_sandbox(server: ServerBase, agent_runtime: Runtime) -> str
275
109
  if source not in runtime.backend.cache.mcp_sources
276
110
  ]
277
111
  if pending:
112
+ env = {"TMPDIR": temp, "UV_CACHE_DIR": cache}
113
+ if agent_runtime.user is not None:
114
+ env["UV_PYTHON_INSTALL_DIR"] = python_dir
278
115
  setup = (
279
116
  f"set -e; mkdir -p {root_q} {temp_q} {cache_q}; "
280
- f"export TMPDIR={temp_q} UV_CACHE_DIR={cache_q}; "
281
117
  'export PATH="$HOME/.local/bin:$PATH"; '
282
118
  )
283
- if agent_runtime.user is not None:
284
- setup += f"export UV_PYTHON_INSTALL_DIR={shlex.quote(python_dir)}; "
285
119
  if not runtime.backend.cache.mcp_sources:
286
120
  # Failed installs can leave the venv behind; retain it when retrying.
287
121
  setup += f"{_ENSURE_UV}; uv venv --allow-existing {venv_q}; "
288
- # Drain remote writes and installs before cancellation releases the lock.
289
- for source in pending:
290
- name, data = await _cached_package(Path(source))
291
- remote = f"{root}/{name}"
292
- await run_shielded(runtime.write(remote, data))
293
- setup += f"uv pip install --python {venv_q} {shlex.quote(remote)}; "
294
- result = await run_shielded(runtime.run(["sh", "-c", setup], {}))
122
+ result = await run_shielded(runtime.run(["sh", "-c", setup], env))
295
123
  if result.exit_code != 0:
296
124
  raise ToolsetError(
297
- f"server {server.server_name!r} install failed in runtime: "
125
+ f"server {server.server_name!r} environment setup failed in runtime: "
298
126
  f"{(result.stderr or result.stdout).strip()[-2000:]}"
299
127
  )
300
- runtime.backend.cache.mcp_sources.update(pending)
128
+ for source in pending:
129
+ await install_package(
130
+ runtime, Path(source), root, env, python=f"{venv}/bin/python"
131
+ )
132
+ runtime.backend.cache.mcp_sources.add(source)
301
133
  if agent_runtime.user is not None:
302
134
  # Root's uv lives in its home; copy it into the venv, open to the agent.
303
135
  python_q = shlex.quote(python_dir)
@@ -364,10 +196,6 @@ async def serve_in_runtime(
364
196
  "VF_STATE_URL": state_url or "",
365
197
  "VF_STATE_SECRET": state_secret,
366
198
  }
367
- if runtime.type == "subprocess":
368
- # Keep provider temp files in the runtime workdir so cleanup removes them.
369
- assert runtime.info.id is not None
370
- env["TMPDIR"] = runtime.info.id
371
199
  if listen_all or (exposed and runtime.published_port is not None):
372
200
  env["MCP_HOST"] = "0.0.0.0"
373
201
  fixed = runtime.published_port if exposed else None
@@ -377,24 +205,19 @@ async def serve_in_runtime(
377
205
  else:
378
206
  port_file = runtime.temp_path(f"tool-port-{uuid.uuid4().hex}", env=env)
379
207
  env["MCP_PORT_FILE"] = port_file
380
- python = sys.executable
381
- if runtime.type != "subprocess":
382
- python = await _install_in_sandbox(server, runtime)
208
+ python = await _install_in_sandbox(server, runtime)
383
209
  command = [python, "-m", type(server).__module__]
384
- if runtime.type != "subprocess":
385
- # Providers may invoke uv after the install shell exits, so preserve its PATH.
386
- path = "$HOME/.local/bin:$PATH"
387
- if runtime.user is not None:
388
- path = f"{PurePosixPath(python).parent}:{path}"
389
- command = [
390
- "sh",
391
- "-c",
392
- f'export PATH="{path}"; exec {shlex.join(command)}',
393
- ]
394
- log = f"vf_tool_{server.server_name}.log"
210
+ # Providers may invoke uv after the install shell exits, so preserve its PATH.
211
+ path = "$HOME/.local/bin:$PATH"
395
212
  if runtime.user is not None:
396
- # The agent user may not be able to write the workdir.
397
- log = f"/tmp/vf_tool_{server.server_name}-{uuid.uuid4().hex[:8]}.log"
213
+ path = f"{PurePosixPath(python).parent}:{path}"
214
+ command = [
215
+ "sh",
216
+ "-c",
217
+ f'export PATH="{path}"; exec {shlex.join(command)}',
218
+ ]
219
+ # Keep infrastructure logs out of task artifacts and support read-only workdirs.
220
+ log = runtime.temp_path(f"tool-{uuid.uuid4().hex}.log", env=env)
398
221
  loop = asyncio.get_running_loop()
399
222
  # Servers without a toolset config, such as custom `ServerBase` subclasses, keep the default.
400
223
  timeouts = (