verifiers 0.4.2.dev54__py3-none-any.whl → 0.4.2.dev56__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
@@ -106,6 +106,7 @@ if TYPE_CHECKING:
106
106
  SemanticEdgeSet,
107
107
  )
108
108
  from verifiers.v1.state import State, StateT
109
+ from verifiers.v1.submission import run_submission
109
110
  from verifiers.v1.task import (
110
111
  Task,
111
112
  TaskData,
@@ -191,6 +192,7 @@ if TYPE_CHECKING:
191
192
  )
192
193
 
193
194
  _NAME_TO_MODULE = {
195
+ "run_submission": "verifiers.v1.submission",
194
196
  "ACPConfig": "verifiers.v1.acp",
195
197
  "ACPHarness": "verifiers.v1.acp",
196
198
  "ACPInfo": "verifiers.v1.semantic",
@@ -542,6 +544,7 @@ __all__ = [ # noqa: RUF022 - grouped by public API area
542
544
  "capture_patch",
543
545
  "resolve_head",
544
546
  "grade_submission",
547
+ "run_submission",
545
548
  # grading artifacts
546
549
  "ARTIFACTS_DIR",
547
550
  "Artifact",
@@ -32,20 +32,22 @@ def requires_tunnel(
32
32
  """Whether the interception must be exposed via a tunnel — some consumer is off the
33
33
  host network: the harness itself, a live `shared` server in a remote runtime, or a
34
34
  tool server config placing one there (each reaches the `/state` channel from
35
- its own runtime). Skipped as non-consumers: a `colocated` server (shares the
36
- harness's runtime, covered by `harness_is_local`), a config-`url` server (external —
35
+ its own runtime). Task-format adapters share the harness's locality. Skipped as
36
+ non-consumers: a config-`url` server (external —
37
37
  it connects out), and an `external` shared server (outside the state machinery
38
38
  entirely). False means every consumer reaches the server at localhost."""
39
+ from verifiers.v1.mcp.toolset import BaseToolsetConfig
40
+
39
41
  if not harness_is_local:
40
42
  return True
41
43
  if any(not s.external and not s.local for s in shared):
42
44
  return True
43
- for config in server_configs:
44
- if getattr(config, "url", None) or config.colocated:
45
- continue
46
- if not runtime_is_local(config.runtime):
47
- return True
48
- return False
45
+ return any(
46
+ isinstance(config, BaseToolsetConfig)
47
+ and not config.url
48
+ and not runtime_is_local(config.runtime)
49
+ for config in server_configs
50
+ )
49
51
 
50
52
 
51
53
  def make_interception(
@@ -265,7 +265,7 @@ async def _install_in_sandbox(server: ServerBase, agent_runtime: Runtime) -> str
265
265
  venv = str(PurePosixPath(workdir) / ".vf-venv")
266
266
  python_dir = str(PurePosixPath(workdir) / ".vf-python")
267
267
  root_q, temp_q, cache_q, venv_q = map(shlex.quote, (root, temp, cache, venv))
268
- # Colocated servers and borrowed views install into one physical environment.
268
+ # Servers in the same service install into one physical environment.
269
269
  # Serialize its mutations and only remember sources after a successful install.
270
270
  async with runtime.backend.cache.mcp_lock:
271
271
  sources = dict.fromkeys((_package_dir(ServerBase), _package_dir(type(server))))
@@ -353,9 +353,9 @@ async def serve_in_runtime(
353
353
  ) -> int:
354
354
  """Start a server and return its bound port.
355
355
 
356
- Exposed remote servers must use the runtime's forwarded port. Local or colocated servers let
357
- the OS choose and report the result through a file. With a state channel, the server fetches
358
- the current rollout task from the adjacent `/task` endpoint rather than a launch argument.
356
+ Exposed servers use the runtime's forwarded port when one is configured. Otherwise,
357
+ 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.
359
359
  """
360
360
  # A shared server has a private service secret but no fixed state URL. Set
361
361
  # both controls explicitly so a subprocess cannot inherit stale host values.
@@ -435,21 +435,9 @@ async def reachable_url(
435
435
  service_runtime: Runtime,
436
436
  port: int,
437
437
  *,
438
- colocated: bool,
439
438
  consumer_is_local: bool,
440
439
  ) -> AsyncIterator[str]:
441
- """Yield the URL a consumer uses to reach the server at (`service`, `port`), over two
442
- primitives: `Runtime.expose` (publish a port out of a sandbox) and a host `Tunnel` (reach
443
- into the host from a remote runtime). `colocated` = the server shares the consumer's
444
- runtime; `consumer_is_local` = the consumer can use a host-local URL without a tunnel.
445
-
446
- - `colocated` -> localhost (same runtime, in-sandbox or host loopback);
447
- - else the runtime publishes the port (`expose`): a remote sandbox's URL is reachable
448
- anywhere, a host-local URL directly by a local consumer and through a host tunnel
449
- by a remote one."""
450
- if colocated:
451
- yield f"http://127.0.0.1:{port}"
452
- return
440
+ """Publish a service port, tunneling host-local URLs for remote consumers."""
453
441
  url = await service_runtime.expose(port)
454
442
  if service_runtime.is_local and not consumer_is_local:
455
443
  async with PrimeTunnel().expose(urlsplit(url).port or 80) as public:
@@ -478,34 +466,52 @@ async def _serve(
478
466
  placements: Mapping[str, Runtime] | None = None,
479
467
  ):
480
468
  cfg = server.config
481
- colocated = getattr(cfg, "colocated", False)
482
469
  service = getattr(cfg, "service", None)
483
470
  own_vm = (placements or {}).get(server.server_name)
484
- if service is not None or own_vm is not None:
485
- # The harness reaches the server over the deployment's network: a Compose
486
- # service by its name, a VM of its own by its LAN name.
487
- if own_vm is not None:
488
- runtime = own_vm
489
- host = (hosts or {})[server.server_name]
490
- elif services is None or service not in services:
491
- raise ToolsetError(
492
- f"server {server.server_name!r} runs in service {service!r}, "
493
- "which needs a task whose services define it"
494
- )
471
+ async with contextlib.AsyncExitStack() as stack:
472
+ host = None
473
+ if service is not None or own_vm is not None:
474
+ if own_vm is not None:
475
+ runtime = own_vm
476
+ host = (hosts or {})[server.server_name]
477
+ elif services is None or service not in services:
478
+ raise ToolsetError(
479
+ f"server {server.server_name!r} runs in service {service!r}, "
480
+ "which needs a task whose services define it"
481
+ )
482
+ else:
483
+ runtime = services[service]
484
+ host = (hosts or {}).get(service, service)
485
+ if runtime.is_local:
486
+ raise ToolsetError(
487
+ f"server {server.server_name!r} runs in service {service!r}, "
488
+ "which needs a native Prime service VM"
489
+ )
495
490
  else:
496
- runtime = services[service]
497
- host = (hosts or {}).get(service, service)
498
- if runtime.is_local:
499
- # A local service cannot reach the host-loopback state channel.
500
- raise ToolsetError(
501
- f"server {server.server_name!r} runs in service {service!r}, "
502
- "which needs a native Prime service VM"
503
- )
491
+ if (
492
+ isinstance(cfg.runtime, NetworkPolicyConfig)
493
+ and cfg.runtime.network_restricted
494
+ ):
495
+ raise ToolsetError(
496
+ f"server {server.server_name!r} restricts its runtime's network, "
497
+ "which needs a Prime runtime of its own beside a Prime workspace "
498
+ "without a task service spec (it then joins the rollout's "
499
+ "private network)"
500
+ )
501
+ if not backend_cls(cfg.runtime).SUPPORTS_PORT_EXPOSURE:
502
+ raise ToolsetError(
503
+ f"server {server.server_name!r} runs in its own runtime, but the "
504
+ f"{cfg.runtime.type} runtime cannot expose a port; "
505
+ "use a runtime that supports port exposure"
506
+ )
507
+ backend = await stack.enter_async_context(provision_backend(cfg.runtime))
508
+ runtime = backend.bind()
509
+
504
510
  port = await serve_in_runtime(
505
511
  server,
506
512
  runtime,
507
- exposed=False,
508
- listen_all=True,
513
+ exposed=host is None,
514
+ listen_all=host is not None,
509
515
  state_url=(
510
516
  runtime.host_url(f"{state_base.rstrip('/')}/state")
511
517
  if state_base
@@ -513,82 +519,27 @@ async def _serve(
513
519
  ),
514
520
  state_secret=state_secret,
515
521
  )
516
- yield _ServedServer(f"http://{host}:{port}/mcp", runtime)
517
- return
518
- async with contextlib.AsyncExitStack() as stack:
519
- # Colocated servers inherit the harness cut. A separately provisioned filtered
520
- # server has neither that lifecycle nor a published port after isolation;
521
- # reject it instead of silently leaving its requested policy unenforced.
522
- if (
523
- isinstance(cfg.runtime, NetworkPolicyConfig)
524
- and cfg.runtime.network_restricted
525
- and not (colocated and harness_runtime is not None)
526
- ):
527
- raise ToolsetError(
528
- f"server {server.server_name!r} restricts its runtime's network, which "
529
- "needs the server colocated with the harness, or on a Prime runtime "
530
- "of its own beside a Prime workspace without a task service spec (it then "
531
- "joins the rollout's private network)"
532
- )
533
- if colocated and harness_runtime is not None:
534
- runtime = harness_runtime
535
- elif not backend_cls(cfg.runtime).SUPPORTS_PORT_EXPOSURE:
536
- raise ToolsetError(
537
- f"server {server.server_name!r} runs in its own runtime, but the "
538
- f"{cfg.runtime.type} runtime cannot expose a port; colocate it with the "
539
- "harness or use a supported runtime"
540
- )
541
- else:
542
- backend = await stack.enter_async_context(provision_backend(cfg.runtime))
543
- runtime = backend.bind()
544
- # Only consumers outside the server runtime need its fixed published port. Colocated tools
545
- # use independent OS-assigned ports, avoiding clashes on the runtime's service port.
546
- exposed = runtime is not harness_runtime
547
- # The shared-state channel: every server reaches the interception at the rollout's
548
- # `state_base`, which is universally reachable (the interception is exposed via a tunnel
549
- # whenever any consumer is remote). Eval-level shared servers get no per-rollout channel
550
- # (`state_base` is None for them).
551
- state_url = (
552
- runtime.host_url(f"{state_base.rstrip('/')}/state") if state_base else None
553
- )
554
- port = await serve_in_runtime(
555
- server,
556
- runtime,
557
- exposed=exposed,
558
- state_url=state_url,
559
- state_secret=state_secret,
560
- )
561
- # The harness consumes the server, and decides reachability: colocated when the
562
- # server shares the harness's runtime, reached with the harness's locality (read
563
- # off the harness runtime when there is one, else `harness_is_local` for an
564
- # eval-level shared tool).
565
- colocated = runtime is harness_runtime
522
+ if host is not None:
523
+ yield _ServedServer(f"http://{host}:{port}/mcp", runtime)
524
+ return
525
+
566
526
  consumer_is_local = (
567
527
  harness_runtime.is_local
568
528
  if harness_runtime is not None
569
529
  else harness_is_local
570
530
  )
571
- if (
572
- proxy_mcp is not None
573
- and runtime.is_local
574
- and not colocated
575
- and not consumer_is_local
576
- ):
577
- backend = await runtime.expose(port)
578
- # Register after startup, and revoke/drain before releasing the runtime.
531
+ if proxy_mcp is not None and runtime.is_local and not consumer_is_local:
532
+ backend_url = await runtime.expose(port)
533
+ # Revoke and drain the proxy before releasing the runtime.
579
534
  url = await stack.enter_async_context(
580
- proxy_mcp(f"{backend.rstrip('/')}/mcp")
535
+ proxy_mcp(f"{backend_url.rstrip('/')}/mcp")
581
536
  )
582
537
  yield _ServedServer(url, runtime)
583
538
  return
584
539
  base = await stack.enter_async_context(
585
- reachable_url(
586
- runtime, port, colocated=colocated, consumer_is_local=consumer_is_local
587
- )
540
+ reachable_url(runtime, port, consumer_is_local=consumer_is_local)
588
541
  )
589
- if colocated and harness_runtime is not None and runtime.network_restricted:
590
- base = base.replace("127.0.0.1", "localhost", 1)
591
- elif not colocated and harness_runtime is not None:
542
+ if harness_runtime is not None:
592
543
  base = harness_runtime.host_url(base)
593
544
  yield _ServedServer(f"{base.rstrip('/')}/mcp", runtime)
594
545
 
@@ -730,10 +681,9 @@ async def serve_tools(
730
681
  placements: Mapping[str, Runtime] | None = None,
731
682
  ):
732
683
  """Bring up a rollout's tool servers and yield `{name: url}` the harness reaches: the
733
- task-scoped `toolsets` are launched by `serve` (placement off each one's `config`; the
734
- server fetches its task over the interception `/task` channel), and the
735
- taskset-scoped `shared` servers — already
736
- running eval-level (see `serve_shared`) — join under their per-rollout state tag.
684
+ task-scoped `toolsets` own their connections through `Toolset.serve`, and
685
+ taskset-scoped `shared` servers, already running eval-level (see `serve_shared`),
686
+ join under their per-rollout state tag.
737
687
  `state_secret` is private to task-scoped servers; shared servers keep an
738
688
  eval-level service secret and receive only signed `state_route` coordinates.
739
689
  `state_base` is universally reachable from either placement."""
@@ -757,22 +707,16 @@ async def serve_tools(
757
707
  f"tool server name '{name}' is declared both taskset-scoped (shared) "
758
708
  f"and task-scoped — pick one scope, or give one a distinct TOOL_PREFIX"
759
709
  )
760
- cfg = toolset.config
761
- if cfg.url:
762
- urls[name] = harness_runtime.host_url(cfg.url)
763
- logger.debug("Using remote tool server %s url=%s", name, cfg.url)
764
- else:
765
- urls[name] = await stack.enter_async_context(
766
- serve(
767
- toolset,
768
- harness_runtime,
769
- state_secret=state_secret,
770
- state_base=state_base,
771
- proxy_mcp=proxy_mcp,
772
- services=services,
773
- hosts=hosts,
774
- placements=placements,
775
- )
710
+ urls[name] = await stack.enter_async_context(
711
+ toolset.serve(
712
+ harness_runtime,
713
+ state_secret=state_secret,
714
+ state_base=state_base,
715
+ proxy_mcp=proxy_mcp,
716
+ services=services,
717
+ hosts=hosts,
718
+ placements=placements,
776
719
  )
777
- logger.debug("Started tool server %s", name)
720
+ )
721
+ logger.debug("Connected tool server %s", name)
778
722
  yield urls
@@ -1,5 +1,7 @@
1
1
  from __future__ import annotations
2
2
 
3
+ from collections.abc import AsyncIterator
4
+ from contextlib import asynccontextmanager
3
5
  from typing import TYPE_CHECKING
4
6
 
5
7
  from pydantic import Field, model_validator
@@ -13,6 +15,8 @@ from verifiers.v1.utils.decorators import discover_decorated
13
15
  if TYPE_CHECKING:
14
16
  from mcp.server.mcpserver import MCPServer
15
17
 
18
+ from verifiers.v1.runtimes import Runtime
19
+
16
20
 
17
21
  class ToolsetTimeoutConfig(BaseConfig):
18
22
  """Timeouts (in seconds) for a launched tool server; `None` waits indefinitely."""
@@ -22,7 +26,7 @@ class ToolsetTimeoutConfig(BaseConfig):
22
26
 
23
27
 
24
28
  class BaseToolsetConfig(BaseConfig):
25
- """Settings every tool server has, whether per-task or shared."""
29
+ """Runtime and connection settings for per-task and shared tool servers."""
26
30
 
27
31
  runtime: RuntimeConfig = SubprocessConfig()
28
32
  """Where the server runs: the evaluator by default."""
@@ -35,7 +39,6 @@ class ToolsetConfig(BaseToolsetConfig):
35
39
  service spec is a VM of the server's own that joins the workspace over the rollout's
36
40
  private network, under its own egress policy."""
37
41
 
38
- colocated: bool = False
39
42
  service: str | None = None
40
43
  """Run the server in a named native Prime service VM. The harness reaches it
41
44
  over the deployment's private network, using its LAN hostname."""
@@ -44,9 +47,9 @@ class ToolsetConfig(BaseToolsetConfig):
44
47
  def _one_placement(self):
45
48
  if self.service is None:
46
49
  return self
47
- if self.colocated or self.url:
50
+ if self.url:
48
51
  raise ValueError(
49
- "a tool server placed in a service is neither colocated nor remote"
52
+ "a tool server placed in a service cannot use a remote URL"
50
53
  )
51
54
  # The service is the server's runtime; another one, or its policy, would go unused.
52
55
  if not isinstance(self.runtime, SubprocessConfig):
@@ -62,6 +65,17 @@ class SharedToolsetConfig(BaseToolsetConfig):
62
65
 
63
66
 
64
67
  class Toolset(ServerBase[ConfigT, StateT]):
68
+ @asynccontextmanager
69
+ async def serve(self, runtime: Runtime, **kwargs) -> AsyncIterator[str]:
70
+ """Connect a rollout to this server; task-format adapters own their transport."""
71
+ from verifiers.v1.mcp.launch import serve
72
+
73
+ if self.config.url:
74
+ yield runtime.host_url(self.config.url)
75
+ else:
76
+ async with serve(self, runtime, **kwargs) as url:
77
+ yield url
78
+
65
79
  def register(self, mcp: MCPServer) -> None:
66
80
  for fn in discover_decorated(self, "tool"):
67
81
  mcp.add_tool(
@@ -209,6 +209,8 @@ class DockerBackend(RuntimeBackend):
209
209
 
210
210
  SUPPORTS_TASK_IMAGES: ClassVar[bool] = True
211
211
  SUPPORTS_USER_SWITCHING: ClassVar[bool] = True
212
+ SUPPORTS_STOP_CONFIRMATION: ClassVar[bool] = True
213
+ SUPPORTS_MEMORY_LIMIT: ClassVar[bool] = True
212
214
  SUPPORTS_PORT_EXPOSURE: ClassVar[bool] = True
213
215
  SUPPORTS_COMPOSE: ClassVar[bool] = True
214
216
  is_local = True
@@ -624,6 +626,22 @@ class DockerBackend(RuntimeBackend):
624
626
  await self._proxy.stop()
625
627
  await super().teardown()
626
628
 
629
+ async def verify_stopped(self) -> None:
630
+ if not self.stopped or self.info.borrowed:
631
+ raise SandboxError(
632
+ "cannot confirm termination of a live or borrowed container"
633
+ )
634
+ if self._container is None:
635
+ return
636
+ async with asyncio.timeout(60):
637
+ result = await cli("docker", "container", "inspect", self._container)
638
+ if result.exit_code and any(
639
+ message in result.stderr
640
+ for message in ("No such container:", "No such object:")
641
+ ):
642
+ return
643
+ raise SandboxError("could not confirm Docker container removal")
644
+
627
645
  def _exec_argv(
628
646
  self, env: dict[str, str], *, stdin: bool = False, user: str | None = None
629
647
  ) -> list[str]:
@@ -140,6 +140,9 @@ class PrimeProcess(RuntimeProcess):
140
140
  class PrimeBackend(RuntimeBackend):
141
141
  SUPPORTS_TASK_IMAGES: ClassVar[bool] = True
142
142
  SUPPORTS_USER_SWITCHING: ClassVar[bool] = True
143
+ SUPPORTS_STOP_CONFIRMATION: ClassVar[bool] = True
144
+ SUPPORTS_MEMORY_LIMIT: ClassVar[bool] = True
145
+ SUPPORTS_DISK_LIMIT: ClassVar[bool] = True
143
146
  SUPPORTS_COMPOSE: ClassVar[bool] = True
144
147
  SUPPORTS_PORT_EXPOSURE: ClassVar[bool] = True
145
148
 
@@ -553,3 +556,32 @@ class PrimeBackend(RuntimeBackend):
553
556
  )
554
557
  finally:
555
558
  await _release_client(client)
559
+
560
+ async def verify_stopped(self) -> None:
561
+ from prime_sandboxes.core import APIError
562
+
563
+ if not self.stopped or self.info.borrowed:
564
+ raise SandboxError(
565
+ "cannot confirm termination of a live or borrowed sandbox"
566
+ )
567
+ if self.info.id is None:
568
+ return
569
+ try:
570
+ async with asyncio.timeout(60), leased_client() as client:
571
+ delay = 0.2
572
+ while True:
573
+ try:
574
+ sandbox = await client.get(self.info.id)
575
+ except APIError as error:
576
+ if str(error).startswith("HTTP 404"):
577
+ return
578
+ raise
579
+ if (
580
+ sandbox.status in {"TERMINATED", "TIMEOUT"}
581
+ and sandbox.terminated_at is not None
582
+ ):
583
+ return
584
+ await asyncio.sleep(delay)
585
+ delay = min(delay * 2, 3)
586
+ except Exception as error:
587
+ raise SandboxError("could not confirm Prime sandbox termination") from error
@@ -175,6 +175,15 @@ class RuntimeBackend(ABC):
175
175
  SUPPORTS_USER_SWITCHING: ClassVar[bool] = False
176
176
  """Whether handles can bind another existing user."""
177
177
 
178
+ SUPPORTS_STOP_CONFIRMATION: ClassVar[bool] = False
179
+ """Whether `verify_stopped` can confirm the provider resource was terminated."""
180
+
181
+ SUPPORTS_MEMORY_LIMIT: ClassVar[bool] = False
182
+ """Whether a positive `config.memory` enforces a runtime-wide memory ceiling."""
183
+
184
+ SUPPORTS_DISK_LIMIT: ClassVar[bool] = False
185
+ """Whether a positive `config.disk` enforces a runtime-wide storage ceiling."""
186
+
178
187
  SUPPORTS_PORT_EXPOSURE: ClassVar[bool] = False
179
188
  """Whether `expose` can publish a port inside this runtime to the outside, so a
180
189
  server here is reachable from another runtime."""
@@ -261,6 +270,12 @@ class RuntimeBackend(ABC):
261
270
  source of truth for teardown: usable from the atexit backstop where async machinery
262
271
  is dead, and run off the event loop by `stop` on the normal path. Default no-op."""
263
272
 
273
+ async def verify_stopped(self) -> None:
274
+ """Confirm provider termination after `stop`, or raise without returning a
275
+ result whose safety depends on cleanup. Ordinary rollout cleanup remains
276
+ best-effort; callers that execute untrusted submissions use this check."""
277
+ raise SandboxError(f"the {self.type} runtime cannot confirm termination")
278
+
264
279
  @abstractmethod
265
280
  async def exec(
266
281
  self, runtime: Runtime, argv: list[str], env: dict[str, str]
@@ -37,13 +37,15 @@ def tool_vms(
37
37
  network, by server name: those on Prime runtimes of their own beside a Prime
38
38
  workspace of the rollout's own, without a task service spec. Any other server keeps its
39
39
  runtime's published port, which takes no network policy."""
40
+ from verifiers.v1.mcp.toolset import ToolsetConfig
41
+
40
42
  if composed or borrowed or not isinstance(workspace, PrimeConfig):
41
43
  return {}
42
44
  vms = {
43
45
  toolset.server_name: toolset.config.runtime
44
46
  for toolset in toolsets
45
- if isinstance(toolset.config.runtime, PrimeConfig)
46
- and not toolset.config.colocated
47
+ if isinstance(toolset.config, ToolsetConfig)
48
+ and isinstance(toolset.config.runtime, PrimeConfig)
47
49
  and not toolset.config.url
48
50
  and toolset.config.service is None
49
51
  }
@@ -0,0 +1,197 @@
1
+ """Execute a submission in a disposable runtime containing no grader state."""
2
+
3
+ import asyncio
4
+ import math
5
+ from collections.abc import Mapping
6
+ from pathlib import PurePosixPath
7
+
8
+ from verifiers.v1.configs.runtime import NetworkPolicyConfig, RuntimeConfig
9
+ from verifiers.v1.errors import SandboxError
10
+ from verifiers.v1.runtimes import ProgramResult, backend_cls, make_backend
11
+ from verifiers.v1.utils.aio import run_shielded
12
+ from verifiers.v1.utils.artifacts import MAX_ARTIFACT_BYTES
13
+
14
+
15
+ async def run_submission(
16
+ config: RuntimeConfig,
17
+ argv: list[str],
18
+ files: Mapping[str, bytes],
19
+ *,
20
+ user: str = "nobody",
21
+ timeout: float = 60,
22
+ max_output_bytes: int = 1024 * 1024,
23
+ ) -> ProgramResult:
24
+ """Run untrusted files as a non-root user in a fresh, offline box.
25
+
26
+ `config.image` must be a clean execution image, without tests, reference
27
+ solutions, or secrets. The backend must enforce finite positive `memory` and
28
+ `disk` limits; an advisory disk request is insufficient. Input names are
29
+ relative to `/submission`. Files belong to `user` and have mode 0644; invoke
30
+ scripts through their interpreter or explicitly chmod them in the command.
31
+ The caller's runtime, mounts, environment, and scoring files never enter this
32
+ box. Both output streams share a byte ceiling. `timeout` bounds command
33
+ execution after trusted setup, uploads, and network-policy preparation.
34
+ Teardown is confirmed on every exit, including failures and cancellation,
35
+ before returning or raising.
36
+ """
37
+ backend = backend_cls(config)
38
+ if (
39
+ not backend.SUPPORTS_TASK_IMAGES
40
+ or not backend.SUPPORTS_USER_SWITCHING
41
+ or not backend.SUPPORTS_STOP_CONFIRMATION
42
+ ):
43
+ raise ValueError(
44
+ "submission execution requires isolation, user switching, and confirmed teardown"
45
+ )
46
+ if not isinstance(config, NetworkPolicyConfig):
47
+ raise TypeError("submission execution requires enforced network restrictions")
48
+ if not backend.SUPPORTS_MEMORY_LIMIT or not backend.SUPPORTS_DISK_LIMIT:
49
+ raise ValueError(
50
+ "submission execution requires enforced memory and disk limits; "
51
+ f"the {config.type} runtime does not provide both"
52
+ )
53
+ for name in ("memory", "disk"):
54
+ value = getattr(config, name, None)
55
+ if (
56
+ not isinstance(value, (int, float))
57
+ or not math.isfinite(value)
58
+ or value <= 0
59
+ ):
60
+ raise ValueError(
61
+ f"submission execution requires a finite positive {name} limit"
62
+ )
63
+ if getattr(config, "mounts", None) or getattr(config, "checkpoint", None):
64
+ raise ValueError(
65
+ "submission execution requires a clean image without mounts or checkpoints"
66
+ )
67
+ if (
68
+ not argv
69
+ or not user
70
+ or not math.isfinite(timeout)
71
+ or timeout <= 0
72
+ or not isinstance(max_output_bytes, int)
73
+ or max_output_bytes <= 0
74
+ ):
75
+ raise ValueError(
76
+ "submission execution requires a command, user, and positive limits"
77
+ )
78
+ if sum(len(data) for data in files.values()) > MAX_ARTIFACT_BYTES:
79
+ raise ValueError("submission inputs exceed the artifact byte limit")
80
+ for name in files:
81
+ path = PurePosixPath(name)
82
+ if (
83
+ not name
84
+ or path.is_absolute()
85
+ or ".." in path.parts
86
+ or "\x00" in name
87
+ or path == PurePosixPath(".")
88
+ ):
89
+ raise ValueError(f"submission file must be a relative path: {name!r}")
90
+ config = type(config).model_validate(
91
+ {**config.model_dump(), "workdir": "/submission", "allow": [], "block": ["*"]}
92
+ )
93
+ # Own the backend before start: provisioning may allocate a resource and then
94
+ # fail before a provision_runtime context can yield its Runtime handle.
95
+ resource = make_backend(config)
96
+ primary_error: BaseException | None = None
97
+
98
+ async def stop_and_confirm() -> None:
99
+ try:
100
+ await resource.stop()
101
+ finally:
102
+ await resource.verify_stopped()
103
+
104
+ try:
105
+ await resource.start()
106
+ # Images may select a non-root default USER; trusted directory ownership
107
+ # setup needs root, while every submitted file and command uses `user`.
108
+ runtime = resource.bind(env={}).with_user("0")
109
+ # The execution image is trusted; submitted bytes are inert until all
110
+ # provisioning and privilege checks have completed.
111
+ child = runtime.with_user(user)
112
+ identity = await child.run(["sh", "-c", "id -u; id -g"], {})
113
+ ids = identity.stdout.split()
114
+ if (
115
+ identity.exit_code
116
+ or len(ids) != 2
117
+ or not all(value.isdigit() for value in ids)
118
+ or int(ids[0]) == 0
119
+ ):
120
+ raise SandboxError("submission user must resolve to a non-root account")
121
+ prepared = await runtime.run(
122
+ [
123
+ "sh",
124
+ "-c",
125
+ 'mkdir -p /submission && chown "$1:$2" /submission && chmod 700 /submission',
126
+ "submission",
127
+ *ids,
128
+ ],
129
+ {},
130
+ )
131
+ if prepared.exit_code:
132
+ raise SandboxError("could not prepare the submission directory")
133
+ for name, data in files.items():
134
+ path = str(PurePosixPath("/submission") / name)
135
+ await child.write(path, data)
136
+ permissions = await child.run(["chmod", "0644", "--", path], {})
137
+ if permissions.exit_code:
138
+ raise SandboxError(
139
+ f"could not set submission input permissions: {name!r}"
140
+ )
141
+ await runtime.backend.prepare_execution([])
142
+ async with asyncio.timeout(timeout):
143
+ process = await child.exec(
144
+ [
145
+ "env",
146
+ "-i",
147
+ "PATH=/usr/local/bin:/usr/bin:/bin",
148
+ "HOME=/submission",
149
+ "TMPDIR=/submission",
150
+ "sh",
151
+ "-c",
152
+ 'exec "$@" < /dev/null',
153
+ "sh",
154
+ *argv,
155
+ ],
156
+ {},
157
+ )
158
+ used = 0
159
+
160
+ async def drain(stream) -> bytes:
161
+ nonlocal used
162
+ chunks = []
163
+ async for chunk in stream:
164
+ used += len(chunk)
165
+ if used > max_output_bytes:
166
+ raise SandboxError("submission exceeded its output byte limit")
167
+ chunks.append(chunk)
168
+ return b"".join(chunks)
169
+
170
+ try:
171
+ async with asyncio.TaskGroup() as group:
172
+ stdout = group.create_task(drain(process.stdout))
173
+ stderr = group.create_task(drain(process.stderr))
174
+ status = group.create_task(process.wait())
175
+ except ExceptionGroup as failed:
176
+ # Keep framework errors catchable just as in other native task
177
+ # groups; the group remains the context for concurrent failures.
178
+ raise failed.exceptions[0] from failed
179
+ return ProgramResult(
180
+ status.result(),
181
+ stdout.result().decode(errors="replace"),
182
+ stderr.result().decode(errors="replace"),
183
+ )
184
+ except BaseException as error:
185
+ primary_error = error
186
+ raise
187
+ finally:
188
+ # Stop and confirmation form one shielded operation. Cancellation during
189
+ # either must not interrupt the other or leave it running as an orphan.
190
+ try:
191
+ await run_shielded(stop_and_confirm())
192
+ except BaseException as cleanup_error:
193
+ if isinstance(primary_error, asyncio.CancelledError):
194
+ raise primary_error from cleanup_error
195
+ if primary_error is not None:
196
+ raise cleanup_error from primary_error
197
+ raise
@@ -208,10 +208,10 @@ class HarborTask(Task[HarborData, State, HarborTaskConfig]):
208
208
 
209
209
  @classmethod
210
210
  def toolsets(cls, config: HarborTaskConfig):
211
- from .toolset import HarborMCPConfig, HarborMCPToolset
211
+ from .toolset import HarborMCPAdapter, HarborMCPConfig
212
212
 
213
213
  return super().toolsets(config) + [
214
- HarborMCPToolset(HarborMCPConfig(colocated=True, server=server))
214
+ HarborMCPAdapter(HarborMCPConfig(server=server))
215
215
  for server in config.mcp_servers
216
216
  ]
217
217
 
@@ -1,6 +1,8 @@
1
- """Task-declared Harbor MCP tools served through the standard VF toolset lifecycle."""
1
+ """Adapt Harbor's task-declared MCP servers to the harness's HTTP transport."""
2
2
 
3
3
  import os
4
+ from collections.abc import AsyncIterator
5
+ from contextlib import asynccontextmanager
4
6
  from typing import Any, cast
5
7
 
6
8
  from mcp import Client
@@ -10,20 +12,30 @@ from mcp.client.streamable_http import streamable_http_client
10
12
  from mcp.server.mcpserver import Context, MCPServer
11
13
  from mcp.server.mcpserver.exceptions import ToolError
12
14
  from mcp.types import CallToolResult, Tool
15
+ from pydantic_config import BaseConfig
13
16
 
14
- from verifiers.v1.mcp import Toolset, ToolsetConfig
17
+ from verifiers.v1.mcp import Toolset
18
+ from verifiers.v1.mcp.launch import serve_in_runtime
19
+ from verifiers.v1.runtimes import Runtime
15
20
 
16
21
 
17
- class HarborMCPConfig(ToolsetConfig):
22
+ class HarborMCPConfig(BaseConfig):
18
23
  server: dict[str, Any]
19
24
  """One declaration already validated by Harbor's task parser."""
20
25
 
21
26
 
22
- class HarborMCPToolset(Toolset[HarborMCPConfig]):
27
+ class HarborMCPAdapter(Toolset[HarborMCPConfig]):
23
28
  @property
24
29
  def server_name(self) -> str:
25
30
  return self.config.server["name"]
26
31
 
32
+ @asynccontextmanager
33
+ async def serve(self, runtime: Runtime, **kwargs) -> AsyncIterator[str]:
34
+ # Harbor commands and task-local URLs belong to the task environment.
35
+ port = await serve_in_runtime(self, runtime, exposed=False)
36
+ host = "localhost" if runtime.network_restricted else "127.0.0.1"
37
+ yield f"http://{host}:{port}/mcp"
38
+
27
39
  async def setup(self) -> None:
28
40
  spec = self.config.server
29
41
  match spec["transport"]:
@@ -88,4 +100,4 @@ class HarborMCPToolset(Toolset[HarborMCPConfig]):
88
100
 
89
101
 
90
102
  if __name__ == "__main__":
91
- HarborMCPToolset.run()
103
+ HarborMCPAdapter.run()
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: verifiers
3
- Version: 0.4.2.dev54
3
+ Version: 0.4.2.dev56
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
@@ -1,5 +1,5 @@
1
1
  verifiers/__init__.py,sha256=F5IVMw6mhGaPBMCw7QKk0la_r5mMwydP2hdTTdQucik,352
2
- verifiers/v1/__init__.py,sha256=TB8TzPRiMc5kUlyWJNknoQ1GC-BpANsIyaeDk41ajUo,18542
2
+ verifiers/v1/__init__.py,sha256=NxxlvKpqOINcPuT1KJrYIBYn1dfjmFVmt-WSqa7uwOo,18668
3
3
  verifiers/v1/agent.py,sha256=bhZsET00xkaEWS6vwLjnqZcvImWZ0Cq1_A6Bzo1_PYU,48987
4
4
  verifiers/v1/delta.py,sha256=23USfU7G5L3TBnV3apyuOa0M_uQAgvTo6a4Ke4msRV0,12205
5
5
  verifiers/v1/env.py,sha256=UA1FdNd64XywIevJliNyL54afa2StN1ND6ro9HrjlVo,20566
@@ -13,6 +13,7 @@ verifiers/v1/rollout.py,sha256=zSKxyz7dvosNBYy7hOQ9Tj7k1aPNRyvpiJJZQcbW-qg,49982
13
13
  verifiers/v1/semantic.py,sha256=nqKPPUoPL5Oh8Es_XjtcbDiQiIMKTYayXEm-EPB-jAE,5129
14
14
  verifiers/v1/session.py,sha256=Vu7YPopaiTEdmDup-aXaUIFVtPAojl5XXdcOHjrcrdI,30157
15
15
  verifiers/v1/state.py,sha256=EckF2bWp-vV4b1jYJ9sLI5xrfGuI5spIgYYwW926toI,595
16
+ verifiers/v1/submission.py,sha256=zgSRbGVz82Efwz4nX4tlJ-i02AmjtKyu_vHfwfLaByw,7989
16
17
  verifiers/v1/task.py,sha256=zcWjBjhJrkGIL29JTnxxw6v2pbJoiek_tF5RVAVV2ZY,15919
17
18
  verifiers/v1/taskset.py,sha256=PRwMfPtUL0Sg9pwKzJYnpLBDqJCmQ4skQPhF1oocyyw,9504
18
19
  verifiers/v1/trace.py,sha256=o7vnIt3pXRbn5JT_gYO05YaL4NlP0k8T_UlpJK3oqnA,40595
@@ -119,7 +120,7 @@ verifiers/v1/harnesses/utils/install.py,sha256=EESYSh_e9L4gj6N4GvAbQY2kb4ckven7t
119
120
  verifiers/v1/harnesses/utils/launch.py,sha256=2KuLnNruUqH6vcW2Ru661P86ffRzaqslNs-kDMn7B6U,5670
120
121
  verifiers/v1/harnesses/utils/mcp.py,sha256=EtDraHEqgsOB6xKvcF2z9C6HlQyKoST0ZDvmy47NWgM,7450
121
122
  verifiers/v1/harnesses/utils/replay.py,sha256=RJMzD-3K0oz_Q0zhjSH4nhwxn95R8e9Q_CCN5sZp9RA,1720
122
- verifiers/v1/interception/__init__.py,sha256=PMysLlBer-tRpMO2J_ffetK6H77T_lmhJuRwYZb8y3I,4018
123
+ verifiers/v1/interception/__init__.py,sha256=jQ9ZbUr4Nx9JFhdcx0rNcR_jkMFcdzBrTpeSFK84YF0,4020
123
124
  verifiers/v1/interception/base.py,sha256=KlXpWgcpAs_vzJxXRTVArZ9ilSV_vNfsX6vlZ35Y7kc,2249
124
125
  verifiers/v1/interception/pool.py,sha256=Ao3iFTOcPZDfTfPH_sApVzA23u-FIaX6-FPIKOWo3c8,6701
125
126
  verifiers/v1/interception/server.py,sha256=IUG55-27qahz1mrZiFyvJZnBCK444St7ULURMEIhBIQ,53236
@@ -134,27 +135,27 @@ verifiers/v1/judges/reference.txt,sha256=Ej35kGXiT2uJ0LcHIeez49rCS_9uHmCQKoVdn93
134
135
  verifiers/v1/judges/rubric.py,sha256=yRaOnc6S6cqrLuySkMsgxsBFCRUA2bBjYSa5qOT-inQ,16158
135
136
  verifiers/v1/judges/rubric.txt,sha256=3KA2ZeYYdcDweJhUGopxu9EFgARhu2aWft5S5cj8Bc8,323
136
137
  verifiers/v1/mcp/__init__.py,sha256=zJw_R6n-rDqB80_Zs1VGCrYVCZGi8nS7qGaSUKFsB50,479
137
- verifiers/v1/mcp/launch.py,sha256=sKUP43FG3RpRX7yVkO2RgJ3PvsVOdqOEnBpAXW-2rv0,32294
138
+ verifiers/v1/mcp/launch.py,sha256=tI4MGpqWVJxALD9RxajBPcQrIhQvxA5r1slU8nwCjNw,29151
138
139
  verifiers/v1/mcp/server.py,sha256=9hH7rJm8yPYVitcKYMZmSt6_JQyysKAr3e6Xav6IsIk,14154
139
- verifiers/v1/mcp/toolset.py,sha256=GMLjCb2A8OhQZhRU9i8RXcLc68mXC5Niqhwz1UT-dGQ,2615
140
+ verifiers/v1/mcp/toolset.py,sha256=52h0tyCk_Eiu54JZ5hlQMfOlu5Dou7PHKmFr09pYFJg,3129
140
141
  verifiers/v1/runtimes/__init__.py,sha256=JrBktZBcRLSnnZh_Er9IuGOVBGYUybJSPHi1q_b-UrI,3386
141
- verifiers/v1/runtimes/base.py,sha256=d8ntehDL1dQfu-9zbtwlvXF5-QBsYDWKfJupOY_f8CY,16431
142
+ verifiers/v1/runtimes/base.py,sha256=Xl5jxNGnNhuWnrgh3h-nDOeMA9UX9MysYLmSuJPZQL4,17215
142
143
  verifiers/v1/runtimes/compose.py,sha256=Q_0auxhXaGhIOrlisFXI8QRYV9DmewVuXG4ZZtfnrKA,15974
143
144
  verifiers/v1/runtimes/deployment.py,sha256=De6N15Vfe7JKn5VOqFwG22SU_lh0f09bJ57hqBi8D6I,7525
144
145
  verifiers/v1/runtimes/egress.py,sha256=4zsNS3Z2A2HyoCcbgaLizA30uJabYrbgYAYUfvyzeBk,23703
145
146
  verifiers/v1/runtimes/limiters.py,sha256=RWR4HdYoa72yeWF_lM7YRLflm10euE3_gPfNG0BuaOc,2742
146
147
  verifiers/v1/runtimes/native_compose.py,sha256=8WBqWqyYWtohcrE_iq8SuuxsDFgK4Ncos8DxQS7FL_A,42335
147
- verifiers/v1/runtimes/private_network.py,sha256=GlPT50guIBhPoriV9RgGGthIXdIPviYgaUYmM-KmPsQ,6648
148
+ verifiers/v1/runtimes/private_network.py,sha256=69ad7-FuGOK9irTO0Iut4JQ23YQMiVzQVYbCVRmF1IM,6717
148
149
  verifiers/v1/runtimes/runtime.py,sha256=U_0G8DkeTPoyxQRN6Qmjll6FZ0bDwlijW4cC11wMbw4,10669
149
150
  verifiers/v1/runtimes/strategies.py,sha256=WtIrIpKmvjvqpUfwLUwDNJcgRLE8d-2sx7reks2S2PA,8765
150
151
  verifiers/v1/runtimes/backends/custom.py,sha256=Iz1Brd4dBTpO1zYVc2KA0u5sxz5ZUROY_Cdme5W33hM,2875
151
- verifiers/v1/runtimes/backends/docker.py,sha256=i5U0WGwn-bmL1cThdW-d8R7F9C4rsLhEhxneGmJVW9w,31617
152
- verifiers/v1/runtimes/backends/prime.py,sha256=CkRz1qxqV4OF-tHIgSrxOABtGHJCx4CEG-NiqaS8WTU,23889
152
+ verifiers/v1/runtimes/backends/docker.py,sha256=k-xjN6m72LH_FUeQ0rCySpYSxtk__3ZwHhOHA5HQ5Zk,32362
153
+ verifiers/v1/runtimes/backends/prime.py,sha256=-AAPG0aUvyK8G-7Y6xII5Uwwod537HfL_0isdxs3Oxw,25188
153
154
  verifiers/v1/runtimes/backends/subprocess.py,sha256=naOWJGmcaOlu2ZdRbUwhJicJdxASDRAUhDT0jzDff3w,8591
154
155
  verifiers/v1/tasksets/__init__.py,sha256=2ijE3qIlLoUA02g6iysOwWQylyBBQL1GhSpjv8_bp0w,521
155
156
  verifiers/v1/tasksets/harbor/__init__.py,sha256=FjW4tM3rgGALMK-8p7ux26G4-d4ZFVmaAmO6Fni6e_g,214
156
- verifiers/v1/tasksets/harbor/taskset.py,sha256=g9uLfSclESw5XV56T9h0TXD9dm9W2FrkpVgegbokctU,43686
157
- verifiers/v1/tasksets/harbor/toolset.py,sha256=bt-hdWJ26OVy5pEifHZc9XxukYFaIY6JFbjCl3VLxDU,3410
157
+ verifiers/v1/tasksets/harbor/taskset.py,sha256=ddUoeAPFDMg5injOeSYTVIE0lStUyjV6KauxEFIiTXQ,43670
158
+ verifiers/v1/tasksets/harbor/toolset.py,sha256=l-h1GATE9HLnEjb844CzBAiVLkPmE-XarjBlQ2ec5gM,3969
158
159
  verifiers/v1/tasksets/nemo_gym/__init__.py,sha256=654gAvG3Wd_Z_nh6mypeKn4s_IIQ0Ge6vcZvxTHC2_E,306
159
160
  verifiers/v1/tasksets/nemo_gym/response.py,sha256=EhrsquEP8g0bjzAThGfE6Ypgy86_nVX235NiFYtVDVM,4463
160
161
  verifiers/v1/tasksets/nemo_gym/server.py,sha256=33C-VDZxPtMV2TFxJVIKijmtBLNlVeRs92ctPE3qAsM,2036
@@ -187,8 +188,8 @@ verifiers/v1/utils/scope.py,sha256=zbs4pj6AVk4jywlAJ3AX0Q0_kzB9dBB02nY-9H4ELdQ,8
187
188
  verifiers/v1/utils/score.py,sha256=493yJVMw8teCu9JxapxMFPFzI0hNUqdo0Y2nGW4kckk,6200
188
189
  verifiers/v1/utils/trace_store.py,sha256=Qo9qvsJAl8PoRUavjQAfUB2VNxmUtYQtU2ejLKPzY9c,3382
189
190
  verifiers/v1/utils/version.py,sha256=-obEo_-l9-D8FLef4hYxncOe-uJpxrM1g2Hig_37Sgs,1607
190
- verifiers-0.4.2.dev54.dist-info/METADATA,sha256=4bqdnNg9HQAyBNkWhi9fLULYGho85zvwMiVjwuww0Tc,5116
191
- verifiers-0.4.2.dev54.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
192
- verifiers-0.4.2.dev54.dist-info/entry_points.txt,sha256=qdMg7ajiFpDsHf7tuPMRclJXizu1J6LTWawS5YS0B0I,137
193
- verifiers-0.4.2.dev54.dist-info/licenses/LICENSE,sha256=v0RrUsdV3IDoZhrRce297IXS3xMHNJ-_LdLpFAUWb9k,1072
194
- verifiers-0.4.2.dev54.dist-info/RECORD,,
191
+ verifiers-0.4.2.dev56.dist-info/METADATA,sha256=QJ-uFafM_SKKgmgMFvYtHHxg1ZhfAxPIRyO9fsF2UTM,5116
192
+ verifiers-0.4.2.dev56.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
193
+ verifiers-0.4.2.dev56.dist-info/entry_points.txt,sha256=qdMg7ajiFpDsHf7tuPMRclJXizu1J6LTWawS5YS0B0I,137
194
+ verifiers-0.4.2.dev56.dist-info/licenses/LICENSE,sha256=v0RrUsdV3IDoZhrRce297IXS3xMHNJ-_LdLpFAUWb9k,1072
195
+ verifiers-0.4.2.dev56.dist-info/RECORD,,