diff --git a/Dockerfile b/Dockerfile index b68f5d441506842220999d449e25099c5dc7be1b..2e2326f112cc50bee41e2538e2f17a9761fd71c4 100644 --- a/Dockerfile +++ b/Dockerfile @@ -90,7 +90,7 @@ RUN pip install --upgrade pip \ && pip install --no-cache-dir cffi cryptography # Install OpenEnv core from GitHub -RUN pip install --no-cache-dir git+https://github.com/huggingface/OpenEnv.git@v0.10.0 +RUN pip install --no-cache-dir git+https://github.com/openenv/OpenEnv.git@v0.15.0 # Copy and install environment dependencies COPY server/requirements.txt /tmp/requirements.txt diff --git a/README.md b/README.md index 2d7afadc678cd6e83b70c04d0cea5fcedc9001b8..dcc966d2a57d745b3ce52453360f3df63b263875 100644 --- a/README.md +++ b/README.md @@ -8,7 +8,7 @@ pinned: false app_port: 8000 base_path: /web tags: - - openenv-0.10.0 + - openenv-0.15.0 - openenv - carla - embodied-ai @@ -31,6 +31,8 @@ Embodied evaluation environment for testing LLM decision-making in a full 3D dri - Free-roam and maze navigation with configurable traffic - Rubric-based reward system for RL training +The [`openenv/carla_env`](https://huggingface.co/spaces/openenv/carla_env) Space is paused because CARLA needs a GPU. Duplicate it and pick an A10G in the Space settings to run your own copy. + ## What Makes This Different Traditional text benchmarks ask models "what would you do?" This environment shows **what models actually do** when: @@ -65,7 +67,7 @@ with CarlaEnv(base_url="http://localhost:8000").sync() as env: ```bash uv run python examples/carla_env/trolley_problems.py \ --model qwen3-235b --scenario classic-3v1 \ - --base-url https://sergiopaniego-carla-env.hf.space + --base-url https://.hf.space ``` ## Scenarios @@ -173,7 +175,7 @@ result = await env.reset(scenario_config={ ## Examples -The [`examples/carla_env/`](../../examples/carla_env/) directory contains inference scripts. All connect to `http://localhost:8000` by default — pass `--base-url https://sergiopaniego-carla-env.hf.space` for the live Space. +The [`examples/carla_env/`](../../examples/carla_env/) directory contains inference scripts. All connect to `http://localhost:8000` by default — pass `--base-url https://.hf.space` for your running copy of the Space. ### Trolley Problems @@ -294,7 +296,7 @@ docker build -t carla-env:latest -f server/Dockerfile . docker run --gpus all -p 8000:8000 carla-env:latest ``` -**Live Space**: [sergiopaniego/carla-env](https://huggingface.co/spaces/sergiopaniego/carla-env) +**Space**: [openenv/carla_env](https://huggingface.co/spaces/openenv/carla_env) (paused, duplicate it with an A10G) ### Specifications @@ -353,7 +355,7 @@ Default is **RenderOffScreen** (supports `capture_image`). For text-only evaluat ## Resources -- **OpenEnv Framework**: [github.com/huggingface/OpenEnv](https://github.com/huggingface/OpenEnv) +- **OpenEnv Framework**: [github.com/openenv/OpenEnv](https://github.com/openenv/OpenEnv) - **Original carla-env**: [sinatras/carla-env](https://github.com/SinatrasC/carla-env) - **Blog Post**: [Carla-Env: Giving Models Access to World Simulation](https://blog.sinatras.dev/Carla-Env) - **CARLA Simulator**: [carla.org](https://carla.org/) @@ -377,20 +379,20 @@ Scenarios and navigation agents adapted from [sinatras/carla-env](https://github title = {CARLA Environment for OpenEnv}, author = {OpenEnv Contributors}, year = {2026}, - url = {https://github.com/huggingface/OpenEnv} + url = {https://github.com/openenv/OpenEnv} } ``` ## License -BSD-3-Clause License (see [LICENSE](https://github.com/huggingface/OpenEnv/blob/main/LICENSE)) +BSD-3-Clause License (see [LICENSE](https://github.com/openenv/OpenEnv/blob/main/LICENSE)) ## Hugging Face Space Deployment This Space is built from OpenEnv environment `carla_env`. - Space URL: `https://huggingface.co/spaces/openenv/carla_env` -- OpenEnv pinned ref: `0.10.0` +- OpenEnv pinned ref: `0.15.0` - Hub tag: `openenv` ### Connecting from Code diff --git a/envs/carla_env/README.md b/envs/carla_env/README.md index e16a57e1a363ffe44abdb8c0b4e0171dd013c09e..cf3917d79d79169bf60370eb5b96b8ea79ca3aa6 100644 --- a/envs/carla_env/README.md +++ b/envs/carla_env/README.md @@ -30,6 +30,8 @@ Embodied evaluation environment for testing LLM decision-making in a full 3D dri - Free-roam and maze navigation with configurable traffic - Rubric-based reward system for RL training +The [`openenv/carla_env`](https://huggingface.co/spaces/openenv/carla_env) Space is paused because CARLA needs a GPU. Duplicate it and pick an A10G in the Space settings to run your own copy. + ## What Makes This Different Traditional text benchmarks ask models "what would you do?" This environment shows **what models actually do** when: @@ -64,7 +66,7 @@ with CarlaEnv(base_url="http://localhost:8000").sync() as env: ```bash uv run python examples/carla_env/trolley_problems.py \ --model qwen3-235b --scenario classic-3v1 \ - --base-url https://sergiopaniego-carla-env.hf.space + --base-url https://.hf.space ``` ## Scenarios @@ -172,7 +174,7 @@ result = await env.reset(scenario_config={ ## Examples -The [`examples/carla_env/`](../../examples/carla_env/) directory contains inference scripts. All connect to `http://localhost:8000` by default — pass `--base-url https://sergiopaniego-carla-env.hf.space` for the live Space. +The [`examples/carla_env/`](../../examples/carla_env/) directory contains inference scripts. All connect to `http://localhost:8000` by default — pass `--base-url https://.hf.space` for your running copy of the Space. ### Trolley Problems @@ -293,7 +295,7 @@ docker build -t carla-env:latest -f server/Dockerfile . docker run --gpus all -p 8000:8000 carla-env:latest ``` -**Live Space**: [sergiopaniego/carla-env](https://huggingface.co/spaces/sergiopaniego/carla-env) +**Space**: [openenv/carla_env](https://huggingface.co/spaces/openenv/carla_env) (paused, duplicate it with an A10G) ### Specifications @@ -352,7 +354,7 @@ Default is **RenderOffScreen** (supports `capture_image`). For text-only evaluat ## Resources -- **OpenEnv Framework**: [github.com/huggingface/OpenEnv](https://github.com/huggingface/OpenEnv) +- **OpenEnv Framework**: [github.com/openenv/OpenEnv](https://github.com/openenv/OpenEnv) - **Original carla-env**: [sinatras/carla-env](https://github.com/SinatrasC/carla-env) - **Blog Post**: [Carla-Env: Giving Models Access to World Simulation](https://blog.sinatras.dev/Carla-Env) - **CARLA Simulator**: [carla.org](https://carla.org/) @@ -376,10 +378,10 @@ Scenarios and navigation agents adapted from [sinatras/carla-env](https://github title = {CARLA Environment for OpenEnv}, author = {OpenEnv Contributors}, year = {2026}, - url = {https://github.com/huggingface/OpenEnv} + url = {https://github.com/openenv/OpenEnv} } ``` ## License -BSD-3-Clause License (see [LICENSE](https://github.com/huggingface/OpenEnv/blob/main/LICENSE)) +BSD-3-Clause License (see [LICENSE](https://github.com/openenv/OpenEnv/blob/main/LICENSE)) diff --git a/envs/carla_env/pyproject.toml b/envs/carla_env/pyproject.toml index 0dcfc82deef9f9efb159840819e094553d5ef4e1..73426407597bc3d7af78db9ad1cdaa1b88a6f834 100644 --- a/envs/carla_env/pyproject.toml +++ b/envs/carla_env/pyproject.toml @@ -15,7 +15,7 @@ description = "CARLA environment for OpenEnv - embodied evaluation with temporal requires-python = ">=3.11" dependencies = [ # Core OpenEnv dependencies (required for server functionality) - "openenv @ git+https://github.com/huggingface/OpenEnv.git@v0.10.0", + "openenv @ git+https://github.com/openenv/OpenEnv.git@v0.15.0", "fastapi>=0.115.0", "pydantic>=2.0.0", "uvicorn>=0.24.0", diff --git a/envs/carla_env/server/Dockerfile b/envs/carla_env/server/Dockerfile index 057a31d079e2ae4921cf1cc1de5a4884ffd26884..f513ab5249315d7d65796b77b775a2f42862b8bc 100644 --- a/envs/carla_env/server/Dockerfile +++ b/envs/carla_env/server/Dockerfile @@ -90,7 +90,7 @@ RUN pip install --upgrade pip \ && pip install --no-cache-dir cffi cryptography # Install OpenEnv core from GitHub -RUN pip install --no-cache-dir git+https://github.com/huggingface/OpenEnv.git +RUN pip install --no-cache-dir git+https://github.com/openenv/OpenEnv.git # Copy and install environment dependencies COPY server/requirements.txt /tmp/requirements.txt diff --git a/envs/carla_env/server/Dockerfile.real b/envs/carla_env/server/Dockerfile.real index e3deb5abbed4b0e78f20493c295e5db0e67e1433..fad911042c55185cfe70a24329ec0beef8a686a3 100644 --- a/envs/carla_env/server/Dockerfile.real +++ b/envs/carla_env/server/Dockerfile.real @@ -25,7 +25,7 @@ RUN apt-get update && apt-get install -y --no-install-recommends \ WORKDIR /app # Install OpenEnv core from GitHub -RUN pip install --no-cache-dir git+https://github.com/huggingface/OpenEnv.git +RUN pip install --no-cache-dir git+https://github.com/openenv/OpenEnv.git # Copy and install environment dependencies COPY server/requirements.txt /tmp/requirements.txt diff --git a/pyproject.toml b/pyproject.toml index 0dcfc82deef9f9efb159840819e094553d5ef4e1..73426407597bc3d7af78db9ad1cdaa1b88a6f834 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -15,7 +15,7 @@ description = "CARLA environment for OpenEnv - embodied evaluation with temporal requires-python = ">=3.11" dependencies = [ # Core OpenEnv dependencies (required for server functionality) - "openenv @ git+https://github.com/huggingface/OpenEnv.git@v0.10.0", + "openenv @ git+https://github.com/openenv/OpenEnv.git@v0.15.0", "fastapi>=0.115.0", "pydantic>=2.0.0", "uvicorn>=0.24.0", diff --git a/server/Dockerfile b/server/Dockerfile index 057a31d079e2ae4921cf1cc1de5a4884ffd26884..f513ab5249315d7d65796b77b775a2f42862b8bc 100644 --- a/server/Dockerfile +++ b/server/Dockerfile @@ -90,7 +90,7 @@ RUN pip install --upgrade pip \ && pip install --no-cache-dir cffi cryptography # Install OpenEnv core from GitHub -RUN pip install --no-cache-dir git+https://github.com/huggingface/OpenEnv.git +RUN pip install --no-cache-dir git+https://github.com/openenv/OpenEnv.git # Copy and install environment dependencies COPY server/requirements.txt /tmp/requirements.txt diff --git a/server/Dockerfile.real b/server/Dockerfile.real index e3deb5abbed4b0e78f20493c295e5db0e67e1433..fad911042c55185cfe70a24329ec0beef8a686a3 100644 --- a/server/Dockerfile.real +++ b/server/Dockerfile.real @@ -25,7 +25,7 @@ RUN apt-get update && apt-get install -y --no-install-recommends \ WORKDIR /app # Install OpenEnv core from GitHub -RUN pip install --no-cache-dir git+https://github.com/huggingface/OpenEnv.git +RUN pip install --no-cache-dir git+https://github.com/openenv/OpenEnv.git # Copy and install environment dependencies COPY server/requirements.txt /tmp/requirements.txt diff --git a/src/core/README.md b/src/core/README.md index 0caa1bed7a0684b2eb822b05d18df1f48209c930..d5e098767963de732725e46784ef36ef71ad2e0f 100644 --- a/src/core/README.md +++ b/src/core/README.md @@ -165,14 +165,14 @@ provider.wait_for_ready(base_url) provider.stop_container() ``` -### Kubernetes Provider (Coming Soon) +### Kubernetes Provider ```python -from openenv.core.containers.runtime import KubernetesProvider +from openenv.core.containers.runtime.kubernetes_provider import KubernetesProvider provider = KubernetesProvider(namespace="envs") base_url = provider.start_container("my-env:latest") -# Use environment... +provider.wait_for_ready(base_url) provider.stop_container() ``` @@ -232,6 +232,6 @@ Contributions are welcome! Please see the main OpenEnv repository for contributi ## Links -- **Homepage**: https://github.com/huggingface/OpenEnv -- **Documentation**: https://github.com/huggingface/OpenEnv/blob/main/README.md -- **Bug Tracker**: https://github.com/huggingface/OpenEnv/issues +- **Homepage**: https://github.com/openenv/OpenEnv +- **Documentation**: https://github.com/openenv/OpenEnv/blob/main/README.md +- **Bug Tracker**: https://github.com/openenv/OpenEnv/issues diff --git a/src/core/__init__.py b/src/core/__init__.py index b365f5ff730e07d626068c3c6ac1053c3811a2f0..1f62b60f6f3b9de01af8463c6fa153229c8ec789 100644 --- a/src/core/__init__.py +++ b/src/core/__init__.py @@ -11,7 +11,7 @@ from . import env_server from .env_server import * # noqa: F403 if TYPE_CHECKING: - from .env_client import EnvClient + from .env_client import EnvClient, SessionLostError from .generic_client import GenericAction, GenericEnvClient from .llm_client import ( AnthropicClient, @@ -26,6 +26,7 @@ if TYPE_CHECKING: __all__ = [ "EnvClient", + "SessionLostError", "SyncEnvClient", "GenericEnvClient", "GenericAction", @@ -42,6 +43,7 @@ __all__ = [ _LAZY_ATTRS = { "EnvClient": (".env_client", "EnvClient"), + "SessionLostError": (".env_client", "SessionLostError"), "SyncEnvClient": (".sync_client", "SyncEnvClient"), "GenericEnvClient": (".generic_client", "GenericEnvClient"), "GenericAction": (".generic_client", "GenericAction"), diff --git a/src/core/containers/runtime/__init__.py b/src/core/containers/runtime/__init__.py index 9a3ce762257cb409cbccece4bb08465d43d438da..16caec4c81a593e3579337edc78226db25f1e828 100644 --- a/src/core/containers/runtime/__init__.py +++ b/src/core/containers/runtime/__init__.py @@ -5,7 +5,6 @@ from .providers import ( ContainerProvider, DockerSwarmProvider, - KubernetesProvider, LocalDockerProvider, RuntimeProvider, ) @@ -20,7 +19,6 @@ __all__ = [ "ContainerProvider", "DockerSwarmProvider", "LocalDockerProvider", - "KubernetesProvider", "RuntimeProvider", "UVProvider", ] diff --git a/src/core/containers/runtime/_server_config.py b/src/core/containers/runtime/_server_config.py index 8eb3f96d60b57b16057946ef80186454bda26224..aff5fff74ec948fd272014e3c5d12176a92752ad 100644 --- a/src/core/containers/runtime/_server_config.py +++ b/src/core/containers/runtime/_server_config.py @@ -30,11 +30,48 @@ def parse_openenv_app_field(yaml_content: str) -> str | None: def parse_dockerfile_cmd(dockerfile_content: str) -> str | None: """Extract the server command from the last Dockerfile ``CMD``.""" last_cmd: str | None = None + instruction = "" + escape = "\\" + directives = True for line in dockerfile_content.splitlines(): - stripped = line.strip() + stripped = line.lstrip() if stripped.startswith("#"): + if directives: + directive = re.fullmatch( + r"#\s*(syntax|check|escape)\s*=\s*(.+)", + stripped, + flags=re.IGNORECASE, + ) + if directive is None: + directives = False + elif directive[1].lower() == "escape" and directive[2].strip() in ( + "\\", + "`", + ): + escape = directive[2].strip() continue - match = re.match(r"CMD\s+(.+)", stripped, flags=re.IGNORECASE) + if not stripped.strip(): + directives = False + continue + directives = False + if not instruction: + match = re.match(r"\s*CMD\s+(.+)", line, flags=re.IGNORECASE) + if match: + last_cmd = match.group(1).strip() + continuation = re.search( + rf"(?=0.10`` +Requires the ``daytona`` SDK: ``pip install 'daytona>=0.10,<1'`` """ from __future__ import annotations diff --git a/src/core/containers/runtime/hf_sandbox_provider.py b/src/core/containers/runtime/hf_sandbox_provider.py index 05d6ce250f69b3e271ca9852a475546bfa174c90..112e0297c81d1492def0fa04aace5fb0d9adda2f 100644 --- a/src/core/containers/runtime/hf_sandbox_provider.py +++ b/src/core/containers/runtime/hf_sandbox_provider.py @@ -10,6 +10,7 @@ from __future__ import annotations import asyncio import hashlib +import logging import socket import threading import time @@ -24,6 +25,8 @@ from websockets.exceptions import ConnectionClosed from .providers import ContainerProvider +logger = logging.getLogger(__name__) + _DEFAULT_PORT = 8000 _SERVER_COMMAND = ( 'export SBX_PROXY_DIR="${SBX_PROXY_DIR:-$HOME/.sbx/proxy}"; ' @@ -95,6 +98,17 @@ def _get_pool(image: str, flavor: str) -> Any: class _LocalAuthProxy: + """Loopback proxy that adds the HF auth headers to every request. + + Copied into agent_sandbox_provider._LocalAuthProxy; keep the copies + aligned. + + Limitations: bodies are buffered (a streamed upstream response such as + SSE is withheld until it ends), only JSON text frames are relayed + upstream (binary client frames and close codes are not forwarded), and + upstream redirects are rejected. EnvClient uses none of these. + """ + def __init__(self, *, target_url: str, headers: dict[str, str]): self.target_url = target_url.rstrip("/") self.headers = headers @@ -131,13 +145,20 @@ class _LocalAuthProxy: data=body, headers=headers, timeout=60.0, - allow_redirects=True, + allow_redirects=False, ) except requests.RequestException: return Response( content=b"upstream HF job unreachable", status_code=502, ) + if 300 <= upstream.status_code < 400: + # Following a redirect would replay the body and the injected + # headers to another origin and could downgrade https to http. + return Response( + content=b"upstream HF job redirected; rejected", + status_code=502, + ) response_headers = { key: value for key, value in upstream.headers.items() @@ -156,7 +177,16 @@ class _LocalAuthProxy: if query: target = f"{target}?{query}" headers = {**self.headers, "accept": "*/*"} - upstream = await self._connect_upstream_websocket(target, headers) + try: + upstream = await self._connect_upstream_websocket(target, headers) + except Exception: + # Never propagate the upstream exception: its message can embed + # the target URL, which may carry credentials. Deny generically + # instead. + logger.warning("HF sandbox WebSocket upstream handshake failed") + with suppress(Exception): + await websocket.close(code=1011) + return await websocket.accept() try: to_upstream = asyncio.create_task( @@ -201,13 +231,18 @@ class _LocalAuthProxy: ) -> Any: last_error: Exception | None = None for _ in range(5): + connector = ws_connect( + target, + additional_headers=headers, + max_size=_MAX_WS_MESSAGE_SIZE, + compression=None, + ) + # Never follow handshake redirects: websockets replays + # additional_headers to the redirect target, which would leak the + # auth headers to another origin. + connector.process_redirect = lambda exc: exc try: - return await ws_connect( - target, - additional_headers=headers, - max_size=_MAX_WS_MESSAGE_SIZE, - compression=None, - ) + return await connector except Exception as exc: last_error = exc await asyncio.sleep(0.5) @@ -227,10 +262,18 @@ class _LocalAuthProxy: await websocket.send_text(message) def stop(self) -> None: + """Shut the proxy down. Raises `RuntimeError` if the thread will not + exit; the handles are then retained so a later call can retry, instead + of silently leaking a thread that keeps the loopback port bound.""" if self._server is None or self._thread is None: return self._server.should_exit = True + # Bound the graceful drain: do not wait out long-lived upstream + # responses that would outlive the 5s join below. + self._server.force_exit = True self._thread.join(timeout=5.0) + if self._thread.is_alive(): + raise RuntimeError("HF sandbox auth proxy did not stop") self._server = None self._thread = None @@ -272,8 +315,11 @@ class HFSandboxProvider(ContainerProvider): env_vars: dict[str, str] | None = None, **kwargs: Any, ) -> str: - if self._sandbox is not None: - raise RuntimeError("HFSandboxProvider already has an active service") + if self._sandbox is not None or self._proxy is not None: + raise RuntimeError( + "HFSandboxProvider already has an active service, or a proxy " + "still awaits cleanup. Call stop_container() first." + ) if kwargs: unsupported = ", ".join(sorted(kwargs)) raise ValueError( @@ -311,14 +357,20 @@ class HFSandboxProvider(ContainerProvider): raise def stop_container(self) -> None: + proxy_error: RuntimeError | None = None if self._proxy is not None: - self._proxy.stop() - self._proxy = None + try: + self._proxy.stop() + self._proxy = None + except RuntimeError as exc: + proxy_error = exc if self._sandbox is not None: sandbox = self._sandbox self._sandbox = None with suppress(Exception): sandbox.kill() + if proxy_error is not None: + raise proxy_error def wait_for_ready(self, base_url: str, timeout_s: float = 120.0) -> None: deadline = time.time() + timeout_s diff --git a/src/core/containers/runtime/kubernetes_provider.py b/src/core/containers/runtime/kubernetes_provider.py new file mode 100644 index 0000000000000000000000000000000000000000..94652b1b53404ea79a0eec99c89f2c9bf60e2f36 --- /dev/null +++ b/src/core/containers/runtime/kubernetes_provider.py @@ -0,0 +1,985 @@ +# SPDX-License-Identifier: BSD-3-Clause + +""" +Kubernetes container provider for running OpenEnv environments in-cluster. + +Requires the ``kubernetes`` client: ``pip install openenv[kubernetes]`` + +One provider instance owns one Pod and one Service, matching +``LocalDockerProvider`` owning one container. The returned ``base_url`` is the +short in-cluster Service address ``http://{name}.{namespace}:{port}``. Pod DNS +search completes that to the cluster domain, so the provider does not hardcode +``.svc.cluster.local``. That plaintext URL is the in-cluster exception +confirmed for this provider: ``ModalProvider`` and ``ACASandboxProvider`` still +refuse non-HTTPS tunnel URLs. This provider never returns a URL it did not +construct from a validated name, namespace, and port, and it does not copy +that URL or raw API bodies into errors. +""" + +from __future__ import annotations + +import re +import secrets +import time +from typing import Any, Mapping, Optional + +from .providers import ContainerProvider + +_CONTAINER_PORT = 8000 +_CONTAINER_NAME = "env" +_DEFAULT_NAMESPACE = "default" +_NAME_PREFIX = "openenv-" + +# ``openenv-`` + slug + ``-`` + millisecond timestamp + ``-`` + 4 hex chars. +_SLUG_MAX = 32 + +_DNS_LABEL = re.compile(r"^[a-z0-9]([-a-z0-9]*[a-z0-9])?$") +_LABEL_NAME = re.compile(r"^[A-Za-z0-9]([A-Za-z0-9_.-]{0,61}[A-Za-z0-9])?$") +_LABEL_VALUE = re.compile(r"^([A-Za-z0-9]([A-Za-z0-9_.-]{0,61}[A-Za-z0-9])?)?$") +_SAFE_REASON = re.compile(r"^[A-Za-z][A-Za-z0-9]{0,63}$") + +# Applied last so a caller-supplied label cannot drop ownership or retarget +# the Service selector. +_SELECTOR_KEY = "app.kubernetes.io/instance" + +_START_KWARGS = { + "resources", + "runtime_class_name", + "image_pull_secrets", + "labels", + "service_account_name", + "automount_service_account_token", +} + + +def _raise_install_error(exc: ImportError) -> None: + raise RuntimeError( + "KubernetesProvider requires the kubernetes client. " + "Install it with `pip install openenv[kubernetes]`." + ) from exc + + +def _dns_label(value: str, *, max_length: int, what: str) -> str: + """Return *value* as a DNS-1123 label, or raise ``ValueError``. + + Namespace and runtime class names are validated, not rewritten: rewriting + them would target a different object than the one the caller named. + """ + if not isinstance(value, str) or not _DNS_LABEL.fullmatch(value): + raise ValueError( + f"{what} must be a DNS-1123 label: lowercase alphanumeric " + "characters or '-', starting and ending with an alphanumeric." + ) + if not 1 <= len(value) <= max_length: + raise ValueError(f"{what} must be 1 to {max_length} characters.") + return value + + +def _slug(image: str) -> str: + """DNS-1123 slug from an image reference. Raises if nothing usable remains.""" + raw = image.split("/")[-1].split("@")[0].split(":")[0] + cleaned = re.sub(r"[^a-z0-9]+", "-", raw.lower()).strip("-") + cleaned = re.sub(r"-{2,}", "-", cleaned)[:_SLUG_MAX].strip("-") + if not cleaned or not _DNS_LABEL.fullmatch(cleaned): + raise ValueError( + "image does not yield a valid Kubernetes name. " + "Use an image reference with an alphanumeric name." + ) + return cleaned + + +def _resource_name(image: str) -> str: + suffix = f"{int(time.time() * 1000)}-{secrets.token_hex(2)}" + name = f"{_NAME_PREFIX}{_slug(image)}-{suffix}" + if len(name) > 63 or not _DNS_LABEL.fullmatch(name): + raise ValueError("generated Kubernetes name is not a valid DNS-1123 label.") + return name + + +def _label_key(key: str) -> str: + if not isinstance(key, str) or len(key) > 253: + raise ValueError( + "Kubernetes label keys must be strings of at most 253 characters." + ) + prefix, sep, name = key.rpartition("/") + if not _LABEL_NAME.fullmatch(name): + raise ValueError(f"Invalid Kubernetes label key {key!r}.") + if sep and (len(prefix) > 253 or not _dns_subdomain(prefix)): + raise ValueError(f"Invalid Kubernetes label key prefix {prefix!r}.") + return key + + +def _dns_subdomain(value: str) -> bool: + if not value or len(value) > 253: + return False + return all(_DNS_LABEL.fullmatch(part) for part in value.split(".")) + + +def _label_value(value: str) -> str: + if not isinstance(value, str) or not _LABEL_VALUE.fullmatch(value): + raise ValueError( + "Kubernetes label values must be 63 characters or fewer and contain " + "only alphanumeric characters, '-', '_' or '.'." + ) + return value + + +def _ownership_labels(name: str) -> dict[str, str]: + return { + "app.kubernetes.io/name": "openenv", + "app.kubernetes.io/instance": name, + "app.kubernetes.io/managed-by": "openenv", + "app.kubernetes.io/part-of": "openenv", + "app.kubernetes.io/component": "environment", + } + + +def _merged_labels(name: str, extra: Optional[Mapping[str, str]]) -> dict[str, str]: + labels: dict[str, str] = {} + if extra: + if not isinstance(extra, Mapping): + raise ValueError("labels must be a mapping of strings.") + for key, value in extra.items(): + labels[_label_key(key)] = _label_value(value) + labels.update(_ownership_labels(name)) + return labels + + +def _safe_reason(reason: Optional[str]) -> Optional[str]: + """Keep kubelet reason codes. Drop anything else so API text cannot leak.""" + if isinstance(reason, str) and _SAFE_REASON.fullmatch(reason): + return reason + return None + + +class _NamespaceMissing(RuntimeError): + """Creating a namespaced object returned 404: the namespace is absent.""" + + +class _CreateConflict(RuntimeError): + """Creating a namespaced object returned 409: the name is already taken.""" + + +class _TransientStatusError(RuntimeError): + """A Pod status read can be retried within the readiness deadline.""" + + +def _incluster_base_url(name: str, namespace: str, port: int) -> str: + # *name* and *namespace* are already DNS-1123 labels and *port* is an int, + # so this cannot be steered by a status field from the API server. + # ``name.namespace`` is completed by the Pod DNS search list + # (``svc.``), which works when the cluster domain is not + # ``cluster.local``. + return f"http://{name}.{namespace}:{port}" + + +def _owned_by_provider(labels: Any, name: str) -> bool: + if not isinstance(labels, Mapping): + return False + return ( + labels.get("app.kubernetes.io/managed-by") == "openenv" + and labels.get("app.kubernetes.io/instance") == name + ) + + +class _DefaultKubernetesAdapter: + """Thin adapter over the official ``kubernetes`` client. + + The provider talks to this private adapter instead of spreading SDK details + through its own logic; tests inject a duck-typed fake in its place. + """ + + def __init__( + self, + *, + namespace: str, + kubeconfig: Optional[str], + context: Optional[str], + ): + try: + from kubernetes import client, config + from kubernetes.client.exceptions import ApiException + except ImportError as exc: + _raise_install_error(exc) + + self._client = client + self._ApiException = ApiException + self._namespace = namespace + self._load_config(config, kubeconfig=kubeconfig, context=context) + configuration = client.Configuration.get_default_copy() + # Readiness owns the retry deadline; SDK retries would multiply it. + configuration.retries = 0 + self._api = client.CoreV1Api(client.ApiClient(configuration=configuration)) + + def _load_config( + self, config: Any, *, kubeconfig: Optional[str], context: Optional[str] + ) -> None: + if kubeconfig is not None or context is not None: + config.load_kube_config(config_file=kubeconfig, context=context) + return + try: + config.load_incluster_config() + except config.ConfigException: + config.load_kube_config() + + def _api_error(self, exc: Exception, action: str, *, missing_ok: bool) -> None: + status = getattr(exc, "status", None) + if missing_ok and status == 404: + return + if status == 409: + raise _CreateConflict( + f"Kubernetes {action} name is already in use" + ) from None + if status == 404 and action.startswith("create "): + raise _NamespaceMissing( + "Kubernetes namespace does not exist. " + "KubernetesProvider does not create namespaces." + ) from None + # The API body can echo object contents. Do not chain it into the error. + raise RuntimeError(f"Failed to {action} Kubernetes resource") from None + + def create_pod(self, manifest: Mapping[str, Any]) -> None: + try: + self._api.create_namespaced_pod(self._namespace, self._pod(manifest)) + except self._ApiException as exc: + self._api_error(exc, "create Pod", missing_ok=False) + + def create_service(self, manifest: Mapping[str, Any]) -> None: + try: + self._api.create_namespaced_service( + self._namespace, self._service(manifest) + ) + except self._ApiException as exc: + self._api_error(exc, "create Service", missing_ok=False) + + def pod_labels(self, name: str) -> Optional[dict[str, str]]: + """Return Pod labels, or ``None`` when the Pod does not exist.""" + return self._resource_labels(name, self._api.read_namespaced_pod, "read Pod") + + def service_labels(self, name: str) -> Optional[dict[str, str]]: + """Return Service labels, or ``None`` when the Service does not exist.""" + return self._resource_labels( + name, self._api.read_namespaced_service, "read Service" + ) + + def _resource_labels( + self, name: str, read: Any, action: str + ) -> Optional[dict[str, str]]: + try: + obj = read(name, self._namespace) + except self._ApiException as exc: + if getattr(exc, "status", None) == 404: + return None + self._api_error(exc, action, missing_ok=False) + raise RuntimeError(f"Failed to {action} Kubernetes resource") from None + metadata = getattr(obj, "metadata", None) + labels = getattr(metadata, "labels", None) if metadata is not None else None + if not isinstance(labels, Mapping): + return {} + return {str(key): str(value) for key, value in labels.items()} + + def delete_pod(self, name: str) -> None: + try: + self._api.delete_namespaced_pod(name, self._namespace) + except self._ApiException as exc: + self._api_error(exc, "delete Pod", missing_ok=True) + + def delete_service(self, name: str) -> None: + try: + self._api.delete_namespaced_service(name, self._namespace) + except self._ApiException as exc: + self._api_error(exc, "delete Service", missing_ok=True) + + def pod_status( + self, name: str, timeout_s: float = 30.0 + ) -> dict[str, Optional[str]]: + from urllib3.exceptions import HTTPError + + try: + # Older supported SDKs ignore a float timeout. Split the budget + # between connect and read using their supported tuple form. + pod = self._api.read_namespaced_pod( + name, + self._namespace, + _request_timeout=(timeout_s / 2, timeout_s / 2), + ) + except Exception as exc: + status = getattr(exc, "status", None) + if ( + isinstance(exc, (TimeoutError, HTTPError)) + or status == 429 + or (isinstance(status, int) and 500 <= status < 600) + ): + raise _TransientStatusError( + "Kubernetes Pod status read failed" + ) from None + self._api_error(exc, "read Pod", missing_ok=False) + raise RuntimeError("Failed to read Kubernetes Pod") from None + status = getattr(pod, "status", None) + phase = getattr(status, "phase", None) if status is not None else None + reason = None + if status is not None: + for container in status.container_statuses or []: + state = getattr(container, "state", None) + waiting = getattr(state, "waiting", None) if state is not None else None + terminated = ( + getattr(state, "terminated", None) if state is not None else None + ) + if waiting is not None and getattr(waiting, "reason", None): + reason = waiting.reason + elif terminated is not None and getattr(terminated, "reason", None): + reason = terminated.reason + return {"phase": phase or "Unknown", "reason": reason} + + def _metadata(self, meta: Mapping[str, Any]) -> Any: + return self._client.V1ObjectMeta( + name=meta["name"], + namespace=meta["namespace"], + labels=dict(meta["labels"]), + ) + + def _pod(self, manifest: Mapping[str, Any]) -> Any: + spec = manifest["spec"] + container = spec["containers"][0] + container_kwargs: dict[str, Any] = { + "name": container["name"], + "image": container["image"], + "ports": [ + self._client.V1ContainerPort( + name=port["name"], container_port=port["container_port"] + ) + for port in container["ports"] + ], + } + if container.get("env"): + container_kwargs["env"] = [ + self._client.V1EnvVar(name=item["name"], value=item["value"]) + for item in container["env"] + ] + resources = container.get("resources") + if resources: + container_kwargs["resources"] = self._client.V1ResourceRequirements( + requests=resources.get("requests"), + limits=resources.get("limits"), + ) + pod_kwargs: dict[str, Any] = { + "restart_policy": spec["restart_policy"], + "automount_service_account_token": spec["automount_service_account_token"], + "containers": [self._client.V1Container(**container_kwargs)], + } + if spec.get("runtime_class_name"): + pod_kwargs["runtime_class_name"] = spec["runtime_class_name"] + if spec.get("service_account_name"): + pod_kwargs["service_account_name"] = spec["service_account_name"] + if spec.get("image_pull_secrets"): + pod_kwargs["image_pull_secrets"] = [ + self._client.V1LocalObjectReference(name=secret) + for secret in spec["image_pull_secrets"] + ] + return self._client.V1Pod( + metadata=self._metadata(manifest["metadata"]), + spec=self._client.V1PodSpec(**pod_kwargs), + ) + + def _service(self, manifest: Mapping[str, Any]) -> Any: + spec = manifest["spec"] + port = spec["ports"][0] + return self._client.V1Service( + metadata=self._metadata(manifest["metadata"]), + spec=self._client.V1ServiceSpec( + selector=dict(spec["selector"]), + ports=[ + self._client.V1ServicePort( + name=port["name"], + port=port["port"], + target_port=port["target_port"], + protocol=port["protocol"], + ) + ], + ), + ) + + +class KubernetesProvider(ContainerProvider): + """ + Container provider that runs one environment as one Pod and one Service. + + ``start_container`` returns ``http://{name}.{namespace}:{port}``. That + address is reachable only from inside the cluster: Pod DNS search expands + it under ``svc.``. It is plaintext on purpose: in-cluster + HTTP is the connectivity decision for this provider. Cloud sandbox + providers keep their own HTTPS requirement. + + The namespace must already exist. This provider does not create namespaces, + Deployments, Ingress objects, or port-forwards. + + Only one Pod is active per provider. Calling ``start_container`` again + before ``stop_container()`` / ``close()`` raises ``RuntimeError`` rather + than orphaning the running Pod. A failed start deletes a resource only + after its OpenEnv ownership labels match. When a create response is lost + and that read fails, the resource stays unconfirmed: ``stop_container`` + reads the labels again and deletes only on a match. ``stop_container`` is + safe to call more than once. + + The Pod does not mount a service-account token unless + ``automount_service_account_token=True`` is passed to ``start_container``. + + Example: + ```python + from openenv.core.containers.runtime.kubernetes_provider import ( + KubernetesProvider, + ) + + provider = KubernetesProvider(namespace="openenv") + base_url = provider.start_container("echo-env:latest") + provider.wait_for_ready(base_url) + provider.stop_container() + ``` + """ + + def __init__( + self, + *, + image: str | None = None, + env_vars: dict[str, str] | None = None, + namespace: str = _DEFAULT_NAMESPACE, + kubeconfig: str | None = None, + context: str | None = None, + _adapter: Any = None, + ): + """ + Args: + image (`str`, *optional*): + Registry image used when ``start_container()`` is called + without an image. + env_vars (`dict`, *optional*): + Environment variables used when ``start_container()`` is called + without ``env_vars``. + namespace (`str`, *optional*, defaults to ``"default"``): + Existing namespace for the Pod and Service. Not created. + kubeconfig (`str`, *optional*): + Kubeconfig path. When omitted, in-cluster config is tried and + then the default kubeconfig. + context (`str`, *optional*): + Kubeconfig context. Implies kubeconfig loading rather than + in-cluster config. + """ + self._image = image + self._env_vars = env_vars + self._namespace = _dns_label(namespace, max_length=63, what="namespace") + self._name: str | None = None + self._base_url: str | None = None + self._service_port: int | None = None + self._pod_created = False + self._service_created = False + self._pod_unconfirmed = False + self._service_unconfirmed = False + + if _adapter is None: + self._adapter: Any = _DefaultKubernetesAdapter( + namespace=self._namespace, + kubeconfig=kubeconfig, + context=context, + ) + else: + self._adapter = _adapter + + @property + def base_url(self) -> str: + """URL returned by the last successful ``start_container``.""" + if self._base_url is None: + raise RuntimeError( + "KubernetesProvider has no active base_url. Start the provider " + "before reading base_url." + ) + return self._base_url + + def start_container( + self, + image: str | None = None, + port: int | None = None, + env_vars: dict[str, str] | None = None, + **kwargs: Any, + ) -> str: + """ + Create one Pod and one Service and return the in-cluster base URL. + + Args: + image (`str`, *optional*): + Registry image. May be omitted when supplied to the constructor. + port (`int`, *optional*): + Service port. Defaults to 8000. The container always listens + on 8000, matching ``LocalDockerProvider``. + env_vars (`dict`, *optional*): + Environment variables for the container. Replaces constructor + ``env_vars`` when passed, including an empty dict. + **kwargs: + ``resources``, ``runtime_class_name``, ``image_pull_secrets``, + ``labels``, ``service_account_name``, and + ``automount_service_account_token``. Unknown keys raise + ``ValueError``. + + Returns: + `str`: ``http://{name}.{namespace}:{port}``. + """ + if self._has_tracked_resources() or self._base_url is not None: + raise RuntimeError( + "KubernetesProvider already has an active Pod. Call " + "stop_container() (or close()) before starting another — a " + "second start would orphan the running Pod." + ) + + unknown = set(kwargs) - _START_KWARGS + if unknown: + raise ValueError( + f"Unsupported kwargs for KubernetesProvider: {sorted(unknown)}" + ) + + effective_image = image if image is not None else self._image + if not isinstance(effective_image, str) or not effective_image: + raise ValueError( + "KubernetesProvider requires an image. Pass it to the " + "constructor or start_container()." + ) + service_port = _CONTAINER_PORT if port is None else port + if isinstance(service_port, bool) or not isinstance(service_port, int): + raise ValueError("port must be an integer.") + if not 1 <= service_port <= 65535: + raise ValueError("port must be between 1 and 65535.") + + effective_env = self._env_vars if env_vars is None else env_vars + env_list = _env_list(effective_env) + resources = _resources(kwargs.get("resources")) + runtime_class_name = _optional_dns_subdomain( + kwargs.get("runtime_class_name"), what="runtime_class_name" + ) + service_account_name = _optional_dns_subdomain( + kwargs.get("service_account_name"), what="service_account_name" + ) + image_pull_secrets = _secret_names(kwargs.get("image_pull_secrets")) + automount = kwargs.get("automount_service_account_token", False) + if not isinstance(automount, bool): + raise ValueError("automount_service_account_token must be a bool.") + + name = _resource_name(effective_image) + labels = _merged_labels(name, kwargs.get("labels")) + self._name = name + self._service_port = service_port + try: + self._adapter.create_pod( + _pod_manifest( + name=name, + namespace=self._namespace, + labels=labels, + image=effective_image, + env_list=env_list, + resources=resources, + runtime_class_name=runtime_class_name, + service_account_name=service_account_name, + image_pull_secrets=image_pull_secrets, + automount_service_account_token=automount, + ) + ) + self._pod_created = True + self._adapter.create_service( + _service_manifest( + name=name, + namespace=self._namespace, + labels=labels, + service_port=service_port, + ) + ) + self._service_created = True + except BaseException as exc: + # Interrupts can also arrive after the API created a resource. + # A cleanup failure must not mask the original error. + try: + self._cleanup_after_failed_start(exc) + except Exception: + pass + raise + + self._base_url = _incluster_base_url(name, self._namespace, service_port) + return self._base_url + + def _cleanup_after_failed_start(self, exc: BaseException) -> None: + """Delete objects this start may have created. + + A 409 is someone else's name, and a 404 means the namespace is + missing, so those do not probe. Any other create error may mean the + API server applied the object and the client lost the response. Only + the resource whose create was attempted is checked. It is deleted only + when the OpenEnv ownership labels match. A failed read is recorded as + unconfirmed, which is not the same as a successful create: a later + ``stop_container()`` reads the labels again before deleting. + """ + uncertain = not isinstance(exc, (_CreateConflict, _NamespaceMissing)) + # Service create runs only after Pod create has succeeded. + service_was_attempted = self._pod_created + self._release("pod", uncertain=uncertain) + self._release("service", uncertain=uncertain and service_was_attempted) + if not self._has_tracked_resources(): + self._name = None + self._base_url = None + self._service_port = None + + def _release(self, kind: str, *, uncertain: bool) -> None: + if self._created(kind): + self._delete_tracked(kind) + return + if not uncertain: + return + owned = self._lookup_owned(kind) + if owned is None: + self._set_unconfirmed(kind, True) + return + if not owned: + return + self._set_created(kind, True) + self._delete_tracked(kind) + + def _lookup_owned(self, kind: str) -> Optional[bool]: + """Return whether *kind* at ``_name`` is ours. + + ``None`` means the read itself failed. Callers record that as + unconfirmed. They do not treat it as a confirmed create. + """ + if self._name is None: + return False + try: + if kind == "pod": + labels = self._adapter.pod_labels(self._name) + else: + labels = self._adapter.service_labels(self._name) + except Exception: + return None + if labels is None: + return False + return _owned_by_provider(labels, self._name) + + def _delete_tracked(self, kind: str) -> None: + """Delete a resource already known to be ours. + + A failed delete stays confirmed so ``stop_container()`` can retry it. + """ + if self._name is None: + return + try: + if kind == "pod": + self._adapter.delete_pod(self._name) + else: + self._adapter.delete_service(self._name) + except Exception: + self._set_created(kind, True) + return + self._set_created(kind, False) + + def _created(self, kind: str) -> bool: + if kind == "pod": + return self._pod_created + return self._service_created + + def _set_created(self, kind: str, created: bool) -> None: + if kind == "pod": + self._pod_created = created + else: + self._service_created = created + + def _unconfirmed(self, kind: str) -> bool: + if kind == "pod": + return self._pod_unconfirmed + return self._service_unconfirmed + + def _set_unconfirmed(self, kind: str, unconfirmed: bool) -> None: + if kind == "pod": + self._pod_unconfirmed = unconfirmed + else: + self._service_unconfirmed = unconfirmed + + def _has_tracked_resources(self) -> bool: + return ( + self._pod_created + or self._service_created + or self._pod_unconfirmed + or self._service_unconfirmed + ) + + def stop_container(self) -> None: + """Delete the Pod and Service this provider created. + + Safe when nothing was started and safe to call twice. A 404 from the + API is treated as already deleted. A confirmed resource is deleted by + name. An unconfirmed one is deleted only after a fresh ownership-label + match. If that read fails, the unconfirmed state is kept for another + retry. Objects this instance does not own are left in place, including + a name that was already taken. + """ + if self._name is None and not self._has_tracked_resources(): + self._base_url = None + self._service_port = None + return + + errors: list[str] = [] + self._stop_kind("pod", errors) + self._stop_kind("service", errors) + if errors: + raise RuntimeError( + "Failed to delete Kubernetes resources created by this provider. " + "Call stop_container() again to retry." + ) + self._name = None + self._base_url = None + self._service_port = None + + def _stop_kind(self, kind: str, errors: list[str]) -> None: + if self._name is None: + return + if self._unconfirmed(kind): + owned = self._lookup_owned(kind) + if owned is None: + errors.append(kind) + return + self._set_unconfirmed(kind, False) + if not owned: + return + self._set_created(kind, True) + if not self._created(kind): + return + try: + if kind == "pod": + self._adapter.delete_pod(self._name) + else: + self._adapter.delete_service(self._name) + except Exception: + errors.append(kind) + return + self._set_created(kind, False) + + def close(self) -> None: + """Stop the active Pod and Service. + + Overrides the base no-op so a caller holding a bare ``ContainerProvider`` + reference can release the Pod polymorphically (also invoked on + context-manager exit). Equivalent to ``stop_container()``. + """ + self.stop_container() + + def __exit__(self, exc_type, exc, tb) -> None: + try: + self.close() + except Exception: + if exc_type is None: + raise + + def wait_for_ready(self, base_url: str, timeout_s: float = 120.0) -> None: + """ + Wait until the Pod is Running and ``GET /health`` returns 200. + + A Failed or Succeeded Pod raises immediately instead of consuming the + timeout. The URL is not included in errors: this method only polls the + Service URL returned by ``start_container``. + + Args: + base_url (`str`): + URL returned by ``start_container()``. + timeout_s (`float`, *optional*, defaults to `120.0`): + Maximum seconds to wait. Image pulls are slower than local Docker. + + Raises: + TimeoutError: If the Pod does not become ready in time. + RuntimeError: If the Pod has already ended. + ValueError: If ``base_url`` is not the URL this provider returned. + """ + import requests + + expected = self._base_url + if expected is None or not isinstance(base_url, str): + raise ValueError( + "base_url does not match the in-cluster Service URL for this provider." + ) + if base_url.rstrip("/") != expected: + raise ValueError( + "base_url does not match the in-cluster Service URL for this provider." + ) + if isinstance(timeout_s, bool) or not isinstance(timeout_s, (int, float)): + raise ValueError("timeout_s must be a number.") + if timeout_s < 0: + raise ValueError("timeout_s must be non-negative.") + + health_url = f"{expected}/health" + proxies = {"http": "", "https": "", "all": ""} + deadline = time.monotonic() + timeout_s + while (remaining := deadline - time.monotonic()) > 0: + try: + phase, reason = self._phase(remaining) + except _TransientStatusError: + phase, reason = "Unknown", None + if phase in ("Failed", "Succeeded"): + raise RuntimeError(self._ended_message(phase, reason)) + remaining = deadline - time.monotonic() + if remaining <= 0: + break + if phase == "Running": + try: + response = requests.get( + health_url, timeout=min(2.0, remaining), proxies=proxies + ) + if response.status_code == 200: + return + except requests.RequestException: + pass + time.sleep(min(0.5, max(0.0, deadline - time.monotonic()))) + + raise TimeoutError(f"Kubernetes Pod did not become ready within {timeout_s}s.") + + def _phase(self, timeout_s: float) -> tuple[str, Optional[str]]: + if self._name is None: + raise RuntimeError( + "KubernetesProvider has no active Pod. Start the provider " + "before waiting for readiness." + ) + status = self._adapter.pod_status(self._name, timeout_s=timeout_s) + phase = status.get("phase") if isinstance(status, Mapping) else None + reason = status.get("reason") if isinstance(status, Mapping) else None + if not isinstance(phase, str) or not _SAFE_REASON.fullmatch(phase): + phase = "Unknown" + return phase, _safe_reason(reason if isinstance(reason, str) else None) + + def _ended_message(self, phase: str, reason: Optional[str]) -> str: + if reason is None: + return ( + f"Kubernetes Pod entered phase {phase} before it became ready. " + "The Service URL and Pod status message are omitted." + ) + return ( + f"Kubernetes Pod entered phase {phase} ({reason}) before it became " + "ready. The Service URL and Pod status message are omitted." + ) + + +def _env_list(env_vars: Optional[Mapping[str, str]]) -> list[dict[str, str]]: + if env_vars is None: + return [] + if not isinstance(env_vars, Mapping): + raise ValueError("env_vars must be a mapping of strings.") + items: list[dict[str, str]] = [] + for key, value in env_vars.items(): + if not isinstance(key, str) or not isinstance(value, str): + raise ValueError("env_vars keys and values must be strings.") + items.append({"name": key, "value": value}) + return items + + +def _resources(resources: Any) -> Optional[dict[str, dict[str, str]]]: + if resources is None: + return None + if not isinstance(resources, Mapping): + raise ValueError("resources must be a mapping of requests and limits.") + unknown = set(resources) - {"requests", "limits"} + if unknown: + raise ValueError( + f"Unsupported resources keys for KubernetesProvider: {sorted(unknown)}" + ) + parsed: dict[str, dict[str, str]] = {} + for section in ("requests", "limits"): + values = resources.get(section) + if values is None: + continue + if not isinstance(values, Mapping) or not values: + raise ValueError(f"resources.{section} must be a non-empty mapping.") + parsed[section] = {} + for key, value in values.items(): + if not isinstance(key, str) or not isinstance(value, str) or not value: + raise ValueError( + f"resources.{section} keys and values must be non-empty strings." + ) + parsed[section][key] = value + return parsed or None + + +def _optional_dns_subdomain(value: Any, *, what: str) -> Optional[str]: + if value is None: + return None + if not isinstance(value, str) or not _dns_subdomain(value): + raise ValueError( + f"{what} must be a DNS-1123 subdomain: lowercase labels separated by '.'." + ) + return value + + +def _secret_names(value: Any) -> list[str]: + if value is None: + return [] + if isinstance(value, str) or not isinstance(value, (list, tuple)): + raise ValueError("image_pull_secrets must be a list of secret names.") + names: list[str] = [] + for item in value: + if not isinstance(item, str) or not _dns_subdomain(item): + raise ValueError("image_pull_secrets entries must be DNS-1123 subdomains.") + names.append(item) + return names + + +def _pod_manifest( + *, + name: str, + namespace: str, + labels: dict[str, str], + image: str, + env_list: list[dict[str, str]], + resources: Optional[dict[str, dict[str, str]]], + runtime_class_name: Optional[str], + service_account_name: Optional[str], + image_pull_secrets: list[str], + automount_service_account_token: bool, +) -> dict[str, Any]: + container: dict[str, Any] = { + "name": _CONTAINER_NAME, + "image": image, + "ports": [{"name": "http", "container_port": _CONTAINER_PORT}], + } + if env_list: + container["env"] = env_list + if resources: + container["resources"] = resources + spec: dict[str, Any] = { + "restart_policy": "Never", + "automount_service_account_token": automount_service_account_token, + "containers": [container], + } + if runtime_class_name: + spec["runtime_class_name"] = runtime_class_name + if service_account_name: + spec["service_account_name"] = service_account_name + if image_pull_secrets: + spec["image_pull_secrets"] = image_pull_secrets + return { + "metadata": {"name": name, "namespace": namespace, "labels": labels}, + "spec": spec, + } + + +def _service_manifest( + *, + name: str, + namespace: str, + labels: dict[str, str], + service_port: int, +) -> dict[str, Any]: + return { + "metadata": {"name": name, "namespace": namespace, "labels": labels}, + "spec": { + "selector": {_SELECTOR_KEY: name}, + "ports": [ + { + "name": "http", + "port": service_port, + "target_port": _CONTAINER_PORT, + "protocol": "TCP", + } + ], + }, + } + + +__all__ = ["KubernetesProvider"] diff --git a/src/core/containers/runtime/modal_provider.py b/src/core/containers/runtime/modal_provider.py index e504ad266c3ffae97a26b8337a46d2d121068335..5db4e605beb1049eee66710f9086097afbb850cb 100644 --- a/src/core/containers/runtime/modal_provider.py +++ b/src/core/containers/runtime/modal_provider.py @@ -3,30 +3,23 @@ """ Modal container provider for running OpenEnv environments in Modal sandboxes. -Requires the ``modal`` SDK: ``pip install modal>=1.4`` +Requires the ``modal`` SDK: ``pip install modal>=1.6.3`` The provider boots an OpenEnv server inside a Modal sandbox, exposes it on an encrypted tunnel, and returns an ``https://`` URL that ``EnvClient`` connects to over ``wss://``. - -Supports both the stable Sandbox API (``modal.Sandbox.create``) and the beta -Sandbox v2 API (``modal.Sandbox._experimental_create``). Sandbox v2 is opt-in -via ``use_sandbox_v2=True`` because it is an experimental, private SDK feature; -see https://modal.com/docs/guide/sandbox-v2 . """ from __future__ import annotations -import logging import shlex import time +import warnings from typing import Any, Dict, Optional from ._server_config import parse_dockerfile_cmd, parse_openenv_app_field from .providers import ContainerProvider -logger = logging.getLogger(__name__) - _DEFAULT_MODAL_PORT = 8000 # Modal's default per-container resource requests. We pass configured cpu/memory @@ -58,28 +51,14 @@ class _DefaultModalAdapter: """Thin adapter over the ``modal`` SDK. The provider talks to this private adapter instead of spreading SDK details - through its own logic; tests inject a duck-typed fake in its place. Keeping - the SDK surface here also localizes the feature check for the private - Sandbox v2 (``_experimental_create``) API. + through its own logic; tests inject a duck-typed fake in its place. """ - def __init__(self, *, app_name: str, use_sandbox_v2: bool): + def __init__(self, *, app_name: str): import modal self._modal = modal self._app_name = app_name - self._use_sandbox_v2 = use_sandbox_v2 - - # Sandbox v2 rides on a private SDK entry point that is not present in - # every modal release. Fail fast at construction with clear guidance - # rather than at start_container time with an AttributeError. - if use_sandbox_v2 and not hasattr(modal.Sandbox, "_experimental_create"): - raise RuntimeError( - "use_sandbox_v2=True requires modal.Sandbox._experimental_create, " - "which is not available in the installed modal SDK. Upgrade modal, " - "or use the stable Sandbox API (use_sandbox_v2=False). Sandbox v2 " - "is an experimental feature; contact support@modal.com for access." - ) def image_from_registry(self, tag: str) -> Any: return self._modal.Image.from_registry(tag) @@ -111,10 +90,6 @@ class _DefaultModalAdapter: # The sandbox is started with a keep-alive entrypoint; the server # command is launched via exec afterwards (see ModalProvider). - if self._use_sandbox_v2: - return self._modal.Sandbox._experimental_create( - "sleep", "infinity", **kwargs - ) return self._modal.Sandbox.create("sleep", "infinity", **kwargs) def exec(self, sandbox: Any, command: str, *, timeout: int = 10) -> str: @@ -164,11 +139,6 @@ class ModalProvider(ContainerProvider): provider.wait_for_ready(base_url) # sandbox terminated on exit ``` - - Sandbox v2 (beta) is opt-in: - ```python - provider = ModalProvider(app_name="openenv", use_sandbox_v2=True) - ``` """ _dockerfile_registry: Dict[str, Dict[str, Any]] = {} @@ -179,7 +149,7 @@ class ModalProvider(ContainerProvider): image: str | None = None, env_vars: dict[str, str] | None = None, app_name: str = "openenv", - use_sandbox_v2: bool = False, + use_sandbox_v2: bool | None = None, timeout: int = 300, cmd: str | None = None, cpu: float | None = None, @@ -198,12 +168,11 @@ class ModalProvider(ContainerProvider): app_name (`str`, *optional*, defaults to `"openenv"`): Modal app name the sandbox is created under. Looked up (and created if missing) via ``modal.App.lookup``. - use_sandbox_v2 (`bool`, *optional*, defaults to `False`): - When `True`, sandboxes are created via the beta - ``modal.Sandbox._experimental_create`` API (Sandbox v2). This is - an experimental, private SDK feature and is therefore off by - default; a feature check fails fast at construction if the - installed SDK lacks it. See https://modal.com/docs/guide/sandbox-v2 . + use_sandbox_v2 (`bool`, *optional*): + Deprecated and ignored; will be removed in OpenEnv 0.15.0. + Modal 1.6+ creates Sandbox v2 sandboxes through + ``modal.Sandbox.create`` by default. Set ``MODAL_SANDBOX_V2=0`` + to use Sandbox v1. timeout (`int`, *optional*, defaults to `300`): Maximum sandbox lifetime in seconds. cmd (`str`, *optional*): @@ -225,10 +194,18 @@ class ModalProvider(ContainerProvider): orchestrator/CI logs. When `True`, a best-effort redacted, length-bounded excerpt is included in startup-crash errors. """ + if use_sandbox_v2 is not None: + warnings.warn( + "`use_sandbox_v2` is deprecated, has no effect, and will be removed " + "in OpenEnv 0.15.0. Remove the argument: Modal 1.6+ creates Sandbox " + "v2 sandboxes through `modal.Sandbox.create` by default. Set " + "`MODAL_SANDBOX_V2=0` to use Sandbox v1.", + FutureWarning, + stacklevel=2, + ) self._image = image self._env_vars = env_vars self._app_name = app_name - self._use_sandbox_v2 = use_sandbox_v2 self._timeout = timeout self._cmd = cmd self._cpu = cpu @@ -241,20 +218,12 @@ class ModalProvider(ContainerProvider): self._redact_values: set[str] = set() if _adapter is None: - # Import eagerly (inside the adapter) so SDK/configuration errors — - # including the Sandbox v2 feature check — surface at construction. - self._adapter: Any = _DefaultModalAdapter( - app_name=app_name, use_sandbox_v2=use_sandbox_v2 - ) + # Import eagerly (inside the adapter) so SDK/configuration errors + # surface at construction. + self._adapter: Any = _DefaultModalAdapter(app_name=app_name) else: self._adapter = _adapter - if use_sandbox_v2: - logger.info( - "Using Modal Sandbox v2 (experimental). This feature must be " - "explicitly enabled. Contact support@modal.com to get access." - ) - def _discover_server_cmd(self, port: int = _DEFAULT_MODAL_PORT) -> str: """Discover the server command from ``openenv.yaml`` inside the sandbox. diff --git a/src/core/containers/runtime/providers.py b/src/core/containers/runtime/providers.py index 3b7575f70173262b5b534d060c7584f4d9607b1c..95e5ff44836a2f96a4c02cd73debc035f6db1207 100644 --- a/src/core/containers/runtime/providers.py +++ b/src/core/containers/runtime/providers.py @@ -9,19 +9,76 @@ This module provides a pluggable architecture for different container providers from __future__ import annotations +import os +import tempfile from abc import ABC, abstractmethod -from typing import Any, Dict, Optional, Sequence, TypeVar +from contextlib import contextmanager +from typing import ( + Any, + Dict, + Iterator, + List, + Mapping, + Optional, + Sequence, + Tuple, + TypeVar, +) _ContainerProviderT = TypeVar("_ContainerProviderT", bound="ContainerProvider") +@contextmanager +def _env_file_args( + env_vars: Optional[Mapping[str, str]], +) -> Iterator[Tuple[List[str], Optional[str]]]: + """ + Yield `--env-file` arguments for the container's environment variables, + and the text to send to docker's stdin. + + The values (often tokens) stay out of the command line, which other + processes can read and errors include, and out of the docker CLI's own + environment, where names like `DOCKER_HOST` or `PATH` would change how + the CLI runs. Docker reads them from its stdin (`/dev/stdin`), so no file + is written and a CLI with a private `/tmp` (snap) still gets them. Windows + has no `/dev/stdin`: there they go in a temporary file only this user can + read, removed once docker returns. + """ + if not env_vars: + yield [], None + return + lines = [] + for key, value in env_vars.items(): + key, value = str(key), str(value) + if not key or key.startswith("#") or any(c in key for c in "= \t\r\n\0"): + raise ValueError(f"Invalid environment variable name: {key!r}") + if any(c in value for c in "\r\n\0"): + raise ValueError( + f"Environment variable {key!r}: values can't contain line breaks " + "or NUL characters" + ) + lines.append(f"{key}={value}\n") + if os.name != "nt": + yield ["--env-file", "/dev/stdin"], "".join(lines) + return + fd, path = tempfile.mkstemp(prefix="openenv-env-") + try: + with os.fdopen(fd, "w") as env_file: + env_file.writelines(lines) + yield ["--env-file", path], None + finally: + os.unlink(path) + + class ContainerProvider(ABC): """ Abstract base class for container providers. Providers implement this interface to support different container platforms: - LocalDockerProvider: Runs containers on local Docker daemon - - KubernetesProvider: Runs containers in Kubernetes cluster + - DockerSwarmProvider: Runs containers as a Docker Swarm service + - KubernetesProvider: optional ``openenv[kubernetes]`` extra + (``kubernetes_provider.py``) - FargateProvider: Runs containers on AWS Fargate - CloudRunProvider: Runs containers on Google Cloud Run @@ -175,8 +232,10 @@ class LocalDockerProvider(ContainerProvider): Port to expose. If `None`, finds an available port. env_vars (`dict`, *optional*): Environment variables for the container. - **kwargs: - Additional Docker run options. + volumes (`dict`, *optional*): + Mapping of host paths or volume names to mount configuration. + Each configuration must contain a `bind` container path and may + contain a `mode` such as `"ro"` or `"rw"`. Returns: `str`: Base URL to connect to the container. @@ -184,6 +243,8 @@ class LocalDockerProvider(ContainerProvider): import subprocess import time + volumes: Optional[Mapping[str, Mapping[str, str]]] = kwargs.get("volumes") + # Find available port if not specified if port is None: port = self._find_available_port() @@ -202,17 +263,33 @@ class LocalDockerProvider(ContainerProvider): f"{port}:8000", # Map port ] - # Add environment variables - if env_vars: - for key, value in env_vars.items(): - cmd.extend(["-e", f"{key}={value}"]) + # Add volume mounts before the image name. + if volumes: + for source, config in volumes.items(): + bind = config.get("bind") + if not bind: + raise ValueError( + f"Volume config for {source!r} must include a non-empty 'bind'" + ) + mode = config.get("mode") + volume_spec = f"{source}:{bind}" + if mode: + volume_spec = f"{volume_spec}:{mode}" + cmd.extend(["--volume", volume_spec]) # Add image cmd.append(image) # Run container try: - result = subprocess.run(cmd, capture_output=True, text=True, check=True) + with _env_file_args(env_vars) as (env_args, env_input): + result = subprocess.run( + cmd[:2] + env_args + cmd[2:], + input=env_input, + capture_output=True, + text=True, + check=True, + ) self._container_id = result.stdout.strip() except subprocess.CalledProcessError as e: error_msg = f"Failed to start Docker container.\nCommand: {' '.join(cmd)}\nExit code: {e.returncode}\nStderr: {e.stderr}\nStdout: {e.stdout}" @@ -441,10 +518,6 @@ class DockerSwarmProvider(ContainerProvider): if self._overlay_network: cmd.extend(["--network", self._overlay_network]) - if env_vars: - for key, value in env_vars.items(): - cmd.extend(["--env", f"{key}={value}"]) - if cpu_limit is not None: cmd.extend(["--limit-cpu", str(cpu_limit)]) @@ -468,12 +541,14 @@ class DockerSwarmProvider(ContainerProvider): cmd.extend(command_override) try: - result = subprocess.run( - cmd, - capture_output=True, - text=True, - check=True, - ) + with _env_file_args(env_vars) as (env_args, env_input): + result = subprocess.run( + cmd[:3] + env_args + cmd[3:], + input=env_input, + capture_output=True, + text=True, + check=True, + ) self._service_id = result.stdout.strip() except subprocess.CalledProcessError as e: error_msg = ( @@ -644,19 +719,6 @@ class DockerSwarmProvider(ContainerProvider): return f"{clean_image}-swarm-{timestamp}" -class KubernetesProvider(ContainerProvider): - """ - Planned container provider for Kubernetes clusters. - - Not yet implemented: this is a placeholder for the planned Kubernetes - backend and does not implement the abstract `ContainerProvider` methods, so - it cannot be instantiated. Use `LocalDockerProvider`, `DockerSwarmProvider`, - `DaytonaProvider`, or `ACASandboxProvider` instead. - """ - - pass - - class RuntimeProvider(ABC): """ Abstract base class for runtime providers that are not container providers. diff --git a/src/core/containers/runtime/uv_provider.py b/src/core/containers/runtime/uv_provider.py index 3dc3f5e72a4299639440b32d2a0c198e36eb1d87..f1f17012ee3476686ad20fb438e4ed5beb94181d 100644 --- a/src/core/containers/runtime/uv_provider.py +++ b/src/core/containers/runtime/uv_provider.py @@ -2,6 +2,7 @@ from __future__ import annotations +import logging import os import shutil import socket @@ -12,6 +13,9 @@ from typing import Dict, Optional import requests +from ...utils import _SECRET_ENV_NAME + +logger = logging.getLogger(__name__) from .providers import RuntimeProvider GIT_URL_PREFIX = "git+" @@ -137,7 +141,11 @@ class UVProvider(RuntimeProvider): reload (`bool`, *optional*, defaults to `False`): Whether to enable uvicorn's reload mode. env_vars (`dict`, *optional*): - Environment variables to pass through to the spawned process. + Environment variables to pass through to the spawned process. The + server inherits this process's environment except variables named + like credentials (`TOKEN`, `KEY`, `SECRET` or `PASSWORD` as a part + of the name, such as `HF_TOKEN`), so a credential the server needs + has to be passed here. context_timeout_s (`float`, *optional*, defaults to `60.0`): How long to wait for the environment to become ready. @@ -195,7 +203,8 @@ class UVProvider(RuntimeProvider): port (`int`, *optional*): The port to bind the environment to. env_vars (`dict`, *optional*): - Environment variables to pass to the environment. + Environment variables to pass to the environment, on top of + the constructor's. Credentials reach the server only this way. workers (`int`, *optional*, defaults to `1`): The number of workers to use. @@ -232,13 +241,23 @@ class UVProvider(RuntimeProvider): project_path=project_path, ) - env = os.environ.copy() + # Environment servers can run code a model wrote: they don't inherit + # this process's credentials, only the ones passed in env_vars. + env = {k: v for k, v in os.environ.items() if not _SECRET_ENV_NAME.search(k)} if self.env_vars: env.update(self.env_vars) if env_vars: env.update(env_vars) + dropped = sorted(k for k in os.environ if k not in env) + if dropped: + logger.warning( + "Not passing %s to the environment server. Pass the ones it " + "needs with env_vars.", + ", ".join(dropped), + ) + try: self._process = subprocess.Popen(command, env=env) except OSError as exc: diff --git a/src/core/env_client.py b/src/core/env_client.py index 01abe1aeb9df4f8bc7e7ba3327464d751198288b..01b72643fe80ccb3531e6db278b0b966f36b00a4 100644 --- a/src/core/env_client.py +++ b/src/core/env_client.py @@ -275,6 +275,15 @@ async def _best_effort_graceful_close(ws: ClientConnection) -> None: await _best_effort_close(ws) +class SessionLostError(ConnectionError): + """The connection to the server was lost in the middle of an episode. + + The server keeps one environment per WebSocket connection, so reconnecting + opens a new session with an environment this client never reset. Call + `reset()` to start a new episode. + """ + + class EnvClient(ABC, Generic[ActT, ObsT, StateT]): """ Async environment client for persistent sessions. @@ -386,6 +395,8 @@ class EnvClient(ABC, Generic[ActT, ObsT, StateT]): # Strong references for fire-and-forget socket closes (see _receive), # so the task isn't garbage-collected mid-close. Discarded on done. self._pending_close_tasks: set[asyncio.Task] = set() + # The socket that carries the episode started by `reset()`, if one is open. + self._episode_ws: Optional[ClientConnection] = None if base_url is not None: self._set_base_url(base_url) @@ -517,6 +528,7 @@ class EnvClient(ABC, Generic[ActT, ObsT, StateT]): coro_factory: Callable[[], Any], *, allow_async_handoff: bool = False, + stop_loop: bool = False, ) -> Any: """Run an async operation through the sync wrapper.""" if allow_async_handoff and self._execution_mode == "async": @@ -525,9 +537,15 @@ class EnvClient(ABC, Generic[ActT, ObsT, StateT]): self._claim_execution_mode("sync") if self._sync_client is None: self._sync_client = self.sync() - return self._sync_client._run(coro_factory()) + try: + return self._sync_client._run(coro_factory()) + finally: + if stop_loop: + self._sync_client._stop_loop() - def _dispatch(self, coro_factory: Callable[[], Any]) -> Any: + def _dispatch( + self, coro_factory: Callable[[], Any], *, stop_loop: bool = False + ) -> Any: """Return an awaitable in async code and a concrete result in sync code.""" try: running_loop = asyncio.get_running_loop() @@ -538,15 +556,17 @@ class EnvClient(ABC, Generic[ActT, ObsT, StateT]): sync_loop = ( self._sync_client._loop if self._sync_client is not None else None ) - if running_loop is sync_loop: + if running_loop is not None and running_loop is sync_loop: return coro_factory() - return self._run_sync(coro_factory) + return self._run_sync(coro_factory, stop_loop=stop_loop) if running_loop is not None: if self._execution_mode == "async": return coro_factory() return _AutoAsyncResult(self, coro_factory) - return self._run_sync(coro_factory, allow_async_handoff=True) + return self._run_sync( + coro_factory, allow_async_handoff=True, stop_loop=stop_loop + ) def connect(self) -> Any: return self._dispatch(self._connect_async) @@ -653,6 +673,7 @@ class EnvClient(ABC, Generic[ActT, ObsT, StateT]): # leave a stale socket cached for a later operation. self._ws = None self._ws_loop = None + self._episode_ws = None same_loop = ws_loop is asyncio.get_running_loop() if same_loop: # Keep ownership of the handshake if this caller is cancelled. @@ -929,6 +950,8 @@ class EnvClient(ABC, Generic[ActT, ObsT, StateT]): `start_container` (docker) or to the `UVProvider` constructor/start (uv). When `use_docker=False`, the `project_path` argument can be used to override the default git URL (`git+https://huggingface.co/spaces/{repo_id}`). + With `use_docker=False` the server doesn't inherit variables named like + credentials (such as `HF_TOKEN`): pass the ones it needs in `env_vars`. Returns: `_BootstrapResult`: `await` for a connected async client, or call @@ -996,8 +1019,12 @@ class EnvClient(ABC, Generic[ActT, ObsT, StateT]): "type": "reset", "data": kwargs, } + # A reset may reconnect: it starts a new episode on whatever session it lands on. + self._episode_ws = None response = await self._send_and_receive(message) - return self._parse_result(response.get("data", {})) + result = self._parse_result(response.get("data", {})) + self._episode_ws = None if result.done else self._ws + return result def step(self, action: ActT, **kwargs: Any) -> Any: return self._dispatch(lambda: self._step_async(action, **kwargs)) @@ -1019,8 +1046,12 @@ class EnvClient(ABC, Generic[ActT, ObsT, StateT]): "type": "step", "data": self._step_payload(action), } + self._raise_if_session_lost() response = await self._send_and_receive(message) - return self._parse_result(response.get("data", {})) + result = self._parse_result(response.get("data", {})) + if result.done: + self._episode_ws = None + return result def state(self) -> Any: return self._dispatch(self._state_async) @@ -1033,11 +1064,33 @@ class EnvClient(ABC, Generic[ActT, ObsT, StateT]): State object with environment state information """ message = {"type": "state"} + self._raise_if_session_lost() response = await self._send_and_receive(message) return self._parse_state(response.get("data", {})) + def _raise_if_session_lost(self) -> None: + """Raise `SessionLostError` if the socket that carried the episode is gone. + + `_connect_async()` would replace it with a new socket, which the server + treats as a new session, and the call would run on an environment this + client never reset. It keeps raising until `reset()`, so a retried call + does not land on the new session either. + """ + ws = self._episode_ws + if ws is None: + return + if ( + self._ws is not ws + or ws.state in (State.CLOSING, State.CLOSED) + or self._ws_loop is not asyncio.get_running_loop() + ): + raise SessionLostError( + f"Lost the connection to {self._ws_url} in the middle of an episode. " + "Call reset() to start a new one." + ) + def close(self) -> Any: - return self._dispatch(self._close_async) + return self._dispatch(self._close_async, stop_loop=True) async def _close_child_clients(self) -> asyncio.CancelledError | None: """Close every captured child while deferring caller cancellation.""" @@ -1164,7 +1217,7 @@ class EnvClient(ABC, Generic[ActT, ObsT, StateT]): def __exit__(self, exc_type, exc_val, exc_tb) -> None: """Exit sync context manager, closing connection.""" - self._run_sync(self._close_async) + self._run_sync(self._close_async, stop_loop=True) def sync(self) -> "SyncEnvClient": """ diff --git a/src/core/env_server/exceptions.py b/src/core/env_server/exceptions.py index bc2261654e18a7c390ac1bd593e3ff9d59e86929..437b0e15add1cc1f601bf06ac91c2f9ae892cac2 100644 --- a/src/core/env_server/exceptions.py +++ b/src/core/env_server/exceptions.py @@ -44,7 +44,10 @@ class SessionCapacityError(OpenEnvError): Raised when the server cannot accept new sessions due to capacity limits. This error is raised when a new WebSocket connection is attempted but - the server has already reached max_concurrent_envs active sessions. + the server has already reached max_concurrent_envs active sessions. The + default message tells the caller which server setting limits the number of + sessions, since the client (e.g. a trainer opening one session per + concurrent episode) usually cannot see the server configuration. """ def __init__( @@ -59,7 +62,13 @@ class SessionCapacityError(OpenEnvError): if message is None: message = ( f"Server at capacity: {active_sessions}/{max_sessions} sessions active. " - f"Cannot accept new connections." + f"Cannot accept new connections. To serve more concurrent sessions, " + f"start the server with a higher max_concurrent_envs (most " + f"environment servers read it from the MAX_CONCURRENT_ENVS " + f"environment variable). Values above 1 also require an environment " + f"that isolates per-session state and declares " + f"SUPPORTS_CONCURRENT_SESSIONS=True. Otherwise, open fewer " + f"sessions at once or close idle ones." ) super().__init__(message) diff --git a/src/core/env_server/http_server.py b/src/core/env_server/http_server.py index 92b40d642a2e20350f8c0150354e5d30f6d83751..640905b386692a8fda782fde2ae149b8fc75332d 100644 --- a/src/core/env_server/http_server.py +++ b/src/core/env_server/http_server.py @@ -14,9 +14,10 @@ import inspect import json import logging import os +import secrets import time import uuid -from concurrent.futures import ThreadPoolExecutor +from concurrent.futures import Future, ThreadPoolExecutor from contextlib import AsyncExitStack from typing import ( Any, @@ -56,11 +57,23 @@ from .mcp_types import ( ListToolsAction, ListToolsObservation, McpMethod, + ToolErrorType, WSMCPMessage, WSMCPResponse, ) from .route_config import GetEndpointConfig, register_get_endpoints from .serialization import deserialize_action, serialize_observation +from .session_telemetry import ( + rubric_counts, + rubric_snapshot, + SeedAcceptance, + SessionTelemetry, + ValidationOpenedData, + ValidationOpenedResponse, + ValidationOpenMessage, + ValidationReadMessage, + ValidationResponse, +) from .types import ( Action, ConcurrencyConfig, @@ -181,6 +194,7 @@ class HTTPEnvServer: state_cls: Type[State] = State, *, reset_observation_cls: Optional[Type[Observation]] = None, + reset_cls: Type[ResetRequest] = ResetRequest, ): """ Initialize HTTP server wrapper. @@ -208,6 +222,10 @@ class HTTPEnvServer: The `State` subclass this environment reports. Used for the `/state` response model and the `state` entry of `/schema`, so that fields declared by the subclass are published and serialized. + reset_cls (`Type[ResetRequest]`, *optional*, defaults to `ResetRequest`): + The `ResetRequest` subclass describing this environment's reset parameters. + Published as the `reset` entry of `/schema`. It is not used to validate + reset requests. Raises: `ValueError`: If both `max_concurrent_envs` and `concurrency_config` are provided. @@ -253,6 +271,7 @@ class HTTPEnvServer: self.observation_cls = observation_cls self.reset_observation_cls = reset_observation_cls or observation_cls self.state_cls = state_cls + self.reset_cls = reset_cls self.env_name = env_name or self._default_env_name() # Session management for WebSocket connections @@ -260,8 +279,12 @@ class HTTPEnvServer: self._session_executors: Dict[str, ThreadPoolExecutor] = {} self._session_stacks: Dict[str, AsyncExitStack] = {} self._session_info: Dict[str, SessionInfo] = {} + self._session_modes: Dict[str, Optional[str]] = {} self._session_websocket_attachments: set[str] = set() self._session_pending_closes: set[str] = set() + # WebSocket messages being handled, per session; such sessions are never + # idle-reaped. A count, since an attached socket can share the session. + self._session_operations_in_flight: Dict[str, int] = {} self._session_lock = asyncio.Lock() # Create thread pool for running sync code in async context @@ -270,8 +293,10 @@ class HTTPEnvServer: self._requires_single_thread_executor = self._detect_single_thread_requirement() self._shared_session_executor: Optional[ThreadPoolExecutor] = None + self._shared_session_creation_lock: Optional[asyncio.Lock] = None if self._requires_single_thread_executor: self._shared_session_executor = ThreadPoolExecutor(max_workers=1) + self._shared_session_creation_lock = asyncio.Lock() # Idle session reaper configuration. # Timeout is taken from ConcurrencyConfig.session_timeout; @@ -280,6 +305,7 @@ class HTTPEnvServer: self._concurrency_config.session_timeout ) self._reaper_task: Optional[asyncio.Task[None]] = None + self._reaper_stop_event = asyncio.Event() def _default_env_name(self) -> str: factory = self._env_factory @@ -370,7 +396,9 @@ class HTTPEnvServer: return valid_kwargs - async def _create_session(self) -> tuple[str, Environment]: + async def _create_session( + self, mode: Optional[str | ServerMode] = None + ) -> tuple[str, Environment]: """ Create a new WebSocket session with its own environment instance. @@ -400,58 +428,220 @@ class HTTPEnvServer: self._session_executors[session_id] = executor self._sessions[session_id] = None # placeholder until env is ready + # Every await from here to registration runs with the slot reserved, so + # cancellation has to release it. CancelledError is not an Exception, so + # the handlers below never see it, and a surviving reservation is + # permanent: capacity counts _sessions, while the idle reaper only scans + # sessions that reached _session_info. + env: Optional[Environment] = None + stack: Optional[AsyncExitStack] = None + factory_future: Optional[Future[Environment]] = None + mcp_entry_task: Optional[asyncio.Task[Any]] = None + cleanup_task: Optional[asyncio.Task[None]] = None + creation_lock_acquired = False + + def start_cleanup() -> asyncio.Task[None]: + # Startup failure and cancellation share one cleanup owner. Whoever + # gets here first starts the task; a later caller joins the same one + # instead of submitting a second env.close(). + nonlocal cleanup_task + if cleanup_task is None: + cleanup_task = asyncio.create_task( + self._discard_reserved_session( + session_id, + executor, + env, + stack, + factory_future, + mcp_entry_task, + ) + ) + return cleanup_task + + async def drain_cleanup(task: asyncio.Task[None]) -> None: + # ASGI cancel scopes may cancel a request repeatedly. Keep awaiting + # the shielded cleanup task until it reaches a terminal state so + # cancellation cannot escape while the reservation still exists. + try: + await asyncio.shield(task) + except asyncio.CancelledError: + while not task.done(): + try: + await asyncio.shield(task) + except asyncio.CancelledError: + pass + task.result() + raise + try: - # Create environment in the executor thread (outside lock) - loop = asyncio.get_event_loop() - env = await loop.run_in_executor(executor, self._env_factory) - except Exception as e: - async with self._session_lock: - if executor is not self._shared_session_executor: - executor.shutdown(wait=False) - self._session_executors.pop(session_id, None) - self._sessions.pop(session_id, None) - factory_name = getattr( - self._env_factory, "__name__", str(self._env_factory) - ) - raise EnvironmentFactoryError(factory_name) from e - - # Hold the MCP session open for the lifetime of this session, - # matching the WebSocket path's AsyncExitStack pattern. This - # prevents per-request MCP transport teardown/reconnection and - # preserves FastMCP session state (ctx.set_state / ctx.get_state) - # across HTTP calls within the same OpenEnv session. - stack = AsyncExitStack() - try: - mcp_session_factory = getattr(env, "mcp_session", None) - if callable(mcp_session_factory): - mcp_session_cm = cast(AsyncContextManager[Any], mcp_session_factory()) - await stack.enter_async_context(mcp_session_cm) - except Exception: - # MCP transport failed to start — clean up the reserved slot, - # the env, and the executor so they don't leak permanently - # against _max_concurrent_envs. - await stack.aclose() # best-effort + if self._shared_session_creation_lock is not None: + await self._shared_session_creation_lock.acquire() + creation_lock_acquired = True + + try: + # Create environment in the executor thread (outside lock). + # submit() plus wrap_future() is what run_in_executor() does + # internally; spelling it out keeps the thread's future, which is + # the only handle on an environment still being built when the + # await is cancelled. + loop = asyncio.get_event_loop() + factory_future = executor.submit(self._env_factory) + env = await asyncio.wrap_future(factory_future, loop=loop) + mode_val = ( + mode.value + if isinstance(mode, ServerMode) + else (str(mode) if mode is not None else None) + ) + if mode_val is not None and hasattr(env, "set_mode"): + env.set_mode(mode_val) + except Exception as e: + async with self._session_lock: + if executor is not self._shared_session_executor: + executor.shutdown(wait=False) + self._session_executors.pop(session_id, None) + self._sessions.pop(session_id, None) + factory_name = getattr( + self._env_factory, "__name__", str(self._env_factory) + ) + raise EnvironmentFactoryError(factory_name) from e + + # The factory result is delivered, so the shared executor thread is + # free. Release the creation lock before MCP startup: it exists to + # order factory calls (and disposal of a factory cancelled + # mid-flight) on that one thread, and holding it through an MCP + # handshake lets a single stalled connection starve every later + # session's constructor. Cancellation during construction keeps the + # lock instead, so late-factory disposal still precedes the next + # constructor. + if creation_lock_acquired: + assert self._shared_session_creation_lock is not None + self._shared_session_creation_lock.release() + creation_lock_acquired = False + + # Hold the MCP session open for the lifetime of this session, + # matching the WebSocket path's AsyncExitStack pattern. This + # prevents per-request MCP transport teardown/reconnection and + # preserves FastMCP session state (ctx.set_state / ctx.get_state) + # across HTTP calls within the same OpenEnv session. + stack = AsyncExitStack() + try: + mcp_session_factory = getattr(env, "mcp_session", None) + if callable(mcp_session_factory): + mcp_session_cm = cast( + AsyncContextManager[Any], mcp_session_factory() + ) + # Enter in its own task and await it shielded. An entry that + # blocks before yielding may release resources in its own + # finally, and the stack cannot replay that cleanup: it + # registers the exit callback only once __aenter__ returns. + # Shielding keeps repeated cancellation off the entry, so + # the cleanup owner can cancel it exactly once and drain the + # unwind instead of aborting it part-way. + mcp_entry_task = asyncio.create_task( + stack.enter_async_context(mcp_session_cm) + ) + await asyncio.shield(mcp_entry_task) + except Exception: + # MCP transport failed to start — clean up the reserved slot, + # the env, and the executor so they don't leak permanently + # against _max_concurrent_envs. Cancellation arriving mid-close + # joins this same task rather than closing the env twice. + await drain_cleanup(start_cleanup()) + raise + async with self._session_lock: - self._sessions.pop(session_id, None) - self._session_executors.pop(session_id, None) - self._session_info.pop(session_id, None) - await self._cleanup_session_resources(env, executor) + self._sessions[session_id] = env + self._session_stacks[session_id] = stack + if mode is not None: + self._session_modes[session_id] = mode_val + now = time.time() + self._session_info[session_id] = SessionInfo( + session_id=session_id, + created_at=current_time, + last_activity_at=now, + step_count=0, + environment_type=type(env).__name__, + ) + except asyncio.CancelledError: + # Joins the cleanup already under way if startup failure began one, + # so the environment is closed by a single owner. + try: + await drain_cleanup(start_cleanup()) + except asyncio.CancelledError: + pass raise - - async with self._session_lock: - self._sessions[session_id] = env - self._session_stacks[session_id] = stack - now = time.time() - self._session_info[session_id] = SessionInfo( - session_id=session_id, - created_at=current_time, - last_activity_at=now, - step_count=0, - environment_type=type(env).__name__, - ) + finally: + if creation_lock_acquired: + assert self._shared_session_creation_lock is not None + self._shared_session_creation_lock.release() return session_id, env + async def _discard_reserved_session( + self, + session_id: str, + executor: ThreadPoolExecutor, + env: Optional[Environment] = None, + stack: Optional[AsyncExitStack] = None, + factory_future: Optional[Future[Environment]] = None, + mcp_entry_task: Optional[asyncio.Task[Any]] = None, + ) -> None: + """ + Release a session slot reserved by `_create_session` that never opened. + + Drops every mapping the slot may have reached and closes whatever the + interrupted creation built, so the slot stops counting against + `max_concurrent_envs` and no environment outlives it. + + Args: + session_id (`str`): + The reserved session ID to release. + executor (`ThreadPoolExecutor`): + The executor reserved alongside the slot. + env (`Environment`, *optional*): + The environment, if the factory already returned one. + stack (`AsyncExitStack`, *optional*): + The MCP session stack, if one was already entered. + factory_future (`Future`, *optional*): + The factory's thread future, if the factory call was reached. + Used to close an environment the thread is still building. + mcp_entry_task (`asyncio.Task`, *optional*): + The in-flight MCP session entry, if MCP startup was reached. + Cancelled and drained here so an entry interrupted before it + yielded can finish releasing what it had already acquired. + """ + if mcp_entry_task is not None: + # Cancel at most once: a second cancellation would abort the entry's + # own unwind, and the stack holds no exit callback to replay it. + if not mcp_entry_task.done(): + mcp_entry_task.cancel() + try: + await mcp_entry_task + except (asyncio.CancelledError, Exception): + # A cancelled or failed entry has unwound itself. If it did + # finish, `stack` owns the context and closes it below. + pass + + if env is None and factory_future is not None: + # Cancelling the await can cancel a queued future, but cannot stop a + # factory whose executor thread is already running. In that case, + # keep the capacity reservation until its result can be disposed of. + if not factory_future.cancel(): + try: + env = await asyncio.wrap_future(factory_future) + except (asyncio.CancelledError, Exception): + # A cancelled or failed factory produced no environment to + # close. Its capacity reservation still has to be released. + env = None + + await self._cleanup_session_resources(env, executor, stack) + async with self._session_lock: + self._sessions.pop(session_id, None) + self._session_executors.pop(session_id, None) + self._session_stacks.pop(session_id, None) + self._session_info.pop(session_id, None) + self._session_modes.pop(session_id, None) + async def _destroy_session(self, session_id: str) -> None: """ Destroy a WebSocket session and cleanup resources. @@ -465,6 +655,7 @@ class HTTPEnvServer: executor = self._session_executors.pop(session_id, None) stack = self._session_stacks.pop(session_id, None) self._session_info.pop(session_id, None) + self._session_modes.pop(session_id, None) self._session_websocket_attachments.discard(session_id) self._session_pending_closes.discard(session_id) @@ -533,17 +724,26 @@ class HTTPEnvServer: interval = max(timeout / 4, 5.0) # check frequently enough while True: try: - await asyncio.sleep(interval) + try: + await asyncio.wait_for( + self._reaper_stop_event.wait(), timeout=interval + ) + return + except asyncio.TimeoutError: + pass now = time.time() stale_ids: list[str] = [] async with self._session_lock: for sid, info in self._session_info.items(): if ( sid not in self._session_websocket_attachments + and sid not in self._session_operations_in_flight and now - info.last_activity_at > timeout ): stale_ids.append(sid) for sid in stale_ids: + if self._reaper_stop_event.is_set(): + return # Re-check under lock: activity may have arrived since # the snapshot was taken, making this session active again. # Refresh `now` so slow _destroy_session calls don't cause @@ -554,6 +754,7 @@ class HTTPEnvServer: if ( info is None or sid in self._session_websocket_attachments + or sid in self._session_operations_in_flight or (now - info.last_activity_at) <= timeout ): continue @@ -569,12 +770,14 @@ class HTTPEnvServer: def _start_reaper(self) -> None: """Start the idle-session reaper if a timeout is configured.""" if self._session_idle_timeout_s is not None and self._reaper_task is None: + self._reaper_stop_event.clear() self._reaper_task = asyncio.create_task(self._reap_idle_sessions()) - def _stop_reaper(self) -> None: - """Cancel the reaper background task.""" + async def _stop_reaper(self) -> None: + """Stop the reaper after any in-progress session cleanup finishes.""" if self._reaper_task is not None: - self._reaper_task.cancel() + self._reaper_stop_event.set() + await self._reaper_task self._reaper_task = None def get_session_info(self, session_id: str) -> Optional[SessionInfo]: @@ -879,20 +1082,30 @@ class HTTPEnvServer: f"Invalid mode: '{mode}'. Must be one of: {valid_modes}" ) - # Wire up idle-session reaper lifecycle via app events + # Only explicitly provisioned simulation servers accept validation controls. + validation_token = os.environ.get("OPENENV_VALIDATION_TOKEN", "") + validation_enabled = ( + mode == ServerMode.SIMULATION and 32 <= len(validation_token) <= 256 + ) + + # Wire up session lifecycle via app events server_ref = self async def _start_session_reaper() -> None: server_ref._start_reaper() - async def _stop_session_reaper() -> None: - server_ref._stop_reaper() + async def _shutdown_sessions() -> None: + await server_ref._stop_reaper() + async with server_ref._session_lock: + session_ids = list(server_ref._sessions) + for session_id in session_ids: + await server_ref._destroy_session(session_id) if server_ref._shared_session_executor is not None: server_ref._shared_session_executor.shutdown(wait=True) if not getattr(app.router, "_openenv_reaper_registered", False): app.router.on_startup.append(_start_session_reaper) - app.router.on_shutdown.append(_stop_session_reaper) + app.router.on_shutdown.append(_shutdown_sessions) app.router._openenv_reaper_registered = True # type: ignore[attr-defined] # Helper function to handle reset endpoint @@ -993,7 +1206,7 @@ class HTTPEnvServer: request_id=request_id, ) try: - created_session_id, _ = await self._create_session() + created_session_id, _ = await self._create_session(mode=mode) except SessionCapacityError as e: return JsonRpcResponse.error_response( JsonRpcErrorCode.SERVER_ERROR, @@ -1033,6 +1246,21 @@ class HTTPEnvServer: ) async with self._session_lock: + session_mode = self._session_modes.get(target_session_id) + if ( + ( + target_session_id in self._sessions + or target_session_id in self._session_websocket_attachments + ) + and session_mode is not None + and session_mode != mode.value + ): + return JsonRpcResponse.error_response( + JsonRpcErrorCode.INVALID_PARAMS, + f"Session '{target_session_id}' belongs to mode '{session_mode}', not '{mode.value}'", + request_id=request_id, + ) + if target_session_id in self._session_websocket_attachments: env = _MISSING attached = True @@ -1046,6 +1274,7 @@ class HTTPEnvServer: executor = self._session_executors.pop(target_session_id, None) stack = self._session_stacks.pop(target_session_id, None) self._session_info.pop(target_session_id, None) + self._session_modes.pop(target_session_id, None) elif not attached: executor = None stack = None @@ -1099,6 +1328,7 @@ class HTTPEnvServer: elif requested_session_id: async with self._session_lock: _env = self._sessions.get(requested_session_id, _MISSING) + session_mode = self._session_modes.get(requested_session_id) if _env is _MISSING: return JsonRpcResponse.error_response( @@ -1107,6 +1337,13 @@ class HTTPEnvServer: request_id=request_id, ) + if session_mode is not None and session_mode != mode.value: + return JsonRpcResponse.error_response( + JsonRpcErrorCode.INVALID_PARAMS, + f"Session '{requested_session_id}' belongs to mode '{session_mode}', not '{mode.value}'", + request_id=request_id, + ) + if _env is None: return JsonRpcResponse.error_response( JsonRpcErrorCode.INVALID_REQUEST, @@ -1118,6 +1355,8 @@ class HTTPEnvServer: managed_session_id = requested_session_id else: _env = self._env_factory() + if hasattr(_env, "set_mode"): + _env.set_mode(mode.value) should_close = True try: mcp_client = getattr(_env, "mcp_client", None) @@ -1142,6 +1381,27 @@ class HTTPEnvServer: } if method == McpMethod.TOOLS_LIST: + if hasattr(_env, "_async_handle_list_tools"): + obs = await _env._async_handle_list_tools() + if obs.metadata and "error" in obs.metadata: + return JsonRpcResponse.error_response( + JsonRpcErrorCode.INTERNAL_ERROR, + obs.metadata["error"], + request_id=request_id, + ) + tools = [ + { + "name": t.name, + "description": t.description or "", + "inputSchema": t.input_schema, + } + for t in obs.tools + ] + return JsonRpcResponse.success( + result={"tools": tools}, + request_id=request_id, + ) + # Check if environment is MCP-enabled if mcp_client is None and mcp_server is None: if supports_mcp_style_actions: @@ -1164,7 +1424,7 @@ class HTTPEnvServer: request_id=request_id, ) return JsonRpcResponse.error_response( - JsonRpcErrorCode.INTERNAL_ERROR, + JsonRpcErrorCode.METHOD_NOT_FOUND, "Environment does not support MCP", request_id=request_id, ) @@ -1180,7 +1440,7 @@ class HTTPEnvServer: return JsonRpcResponse.success( result={ "tools": [ - t.model_dump() + t.model_dump(by_alias=True) if hasattr(t, "model_dump") else dict(t) for t in tools @@ -1221,6 +1481,32 @@ class HTTPEnvServer: request_id=request_id, ) + if hasattr(_env, "_mode_tools") and any( + m is not None for m in _env._mode_tools.get(tool_name, {}) + ): + obs = await _env._async_handle_call_tool( + CallToolAction(tool_name=tool_name, arguments=arguments) + ) + if obs.error: + err_code = ( + JsonRpcErrorCode.INVALID_PARAMS + if obs.error.error_type + in ( + ToolErrorType.INVALID_ARGS, + ToolErrorType.TOOL_NOT_FOUND, + ) + else JsonRpcErrorCode.INTERNAL_ERROR + ) + return JsonRpcResponse.error_response( + err_code, + obs.error.message, + request_id=request_id, + ) + return JsonRpcResponse.success( + result=_make_json_serializable(obs.result), + request_id=request_id, + ) + if mcp_client is None and mcp_server is None: if supports_mcp_style_actions: observation = await call_mcp_style_step( @@ -1242,7 +1528,7 @@ class HTTPEnvServer: request_id=request_id, ) return JsonRpcResponse.error_response( - JsonRpcErrorCode.INTERNAL_ERROR, + JsonRpcErrorCode.METHOD_NOT_FOUND, "Environment does not support MCP", request_id=request_id, ) @@ -1414,7 +1700,7 @@ class HTTPEnvServer: try: # Create session with dedicated environment - session_id, session_env = await self._create_session() + session_id, session_env = await self._create_session(mode=mode) if session_env is None: raise RuntimeError( "Session environment not initialized for MCP websocket" @@ -1661,13 +1947,14 @@ The structure of the state object is defined by the environment's State model. tags=["Schema"], summary="Get all JSON schemas", description=""" -Get JSON schemas for actions, observations, and state in a single response. +Get JSON schemas for actions, observations, state, and reset parameters in a single response. Returns a combined schema object containing: - **action**: JSON schema for actions accepted by this environment - **observation**: JSON schema for observations returned by step - **reset_observation**: JSON schema for observations returned by reset - **state**: JSON schema for environment state objects +- **reset**: JSON schema for reset parameters accepted by this environment This is more efficient than calling individual schema endpoints and provides all schema information needed to interact with the environment. @@ -1690,6 +1977,10 @@ all schema information needed to interact with the environment. "type": "object", "properties": {"step_count": {"type": "integer"}}, }, + "reset": { + "type": "object", + "properties": {"seed": {"type": "integer"}}, + }, } } }, @@ -1703,6 +1994,7 @@ all schema information needed to interact with the environment. observation=self.observation_cls.model_json_schema(), reset_observation=self.reset_observation_cls.model_json_schema(), state=self.state_cls.model_json_schema(), + reset=self.reset_cls.model_json_schema(), ) # Register MCP endpoint for production mode (direct MCP access) @@ -1753,6 +2045,8 @@ all schema information needed to interact with the environment. session_env = None owns_session = False attached_session = False + telemetry = None + operations_started = False try: requested_session_id = websocket.query_params.get("session_id") @@ -1761,10 +2055,15 @@ all schema information needed to interact with the environment. attached_env = self._sessions.get( requested_session_id, _MISSING ) + session_mode = self._session_modes.get(requested_session_id) if attached_env is _MISSING: raise RuntimeError( f"Unknown session_id: {requested_session_id}" ) + if session_mode is not None and session_mode != mode.value: + raise RuntimeError( + f"Session '{requested_session_id}' belongs to mode '{session_mode}', not '{mode.value}'" + ) if attached_env is None: raise RuntimeError( f"Session {requested_session_id} is still initializing" @@ -1780,7 +2079,7 @@ all schema information needed to interact with the environment. attached_session = True self._update_session_activity(session_id) else: - session_id, session_env = await self._create_session() + session_id, session_env = await self._create_session(mode=mode) owns_session = True if session_env is None: @@ -1803,6 +2102,19 @@ all schema information needed to interact with the environment. # Receive message from client raw_message = await websocket.receive_text() + # The reaper or shutdown may have destroyed this + # session (closing its env and freeing its slot). + if session_id not in self._sessions: + error_resp = WSErrorResponse( + data={ + "message": "Session expired or was closed; " + "open a new connection", + "code": WSErrorCode.SESSION_ERROR, + } + ) + await websocket.send_text(error_resp.model_dump_json()) + break + try: message_dict = json.loads(raw_message) except json.JSONDecodeError as e: @@ -1817,6 +2129,67 @@ all schema information needed to interact with the environment. msg_type = message_dict.get("type", "") + if msg_type in {"validation_open", "validation_read"}: + # Do not return Pydantic input/error details: these messages + # contain credentials and must never echo or log them. + try: + if not validation_enabled or not owns_session: + raise ValueError("Validation unavailable") + if msg_type == "validation_open": + auth = ValidationOpenMessage.model_validate( + message_dict + ) + if telemetry is not None or operations_started: + raise ValueError("Validation already started") + if not secrets.compare_digest( + validation_token.encode(), + auth.data.token.get_secret_value().encode(), + ): + raise ValueError("Unauthorized") + telemetry = SessionTelemetry() + response = ValidationOpenedResponse( + data=ValidationOpenedData( + capability=telemetry.capability + ) + ) + else: + auth = ValidationReadMessage.model_validate( + message_dict + ) + if telemetry is None or not telemetry.authorized( + auth.data.capability.get_secret_value() + ): + raise ValueError("Unauthorized") + response = ValidationResponse( + data=telemetry.snapshot + ) + except Exception: + response = WSErrorResponse( + data={ + "message": "Validation unavailable or unauthorized", + "code": WSErrorCode.VALIDATION_ERROR, + } + ) + await websocket.send_text(response.model_dump_json()) + continue + + seed_acceptance = None + before_scores = None + if msg_type in {"reset", "step", "state"}: + operations_started = True + if telemetry is not None and msg_type == "step": + try: + before_scores = rubric_counts( + getattr(session_env, "rubric", None) + ) + except Exception: + telemetry.snapshot.rubric_error = ( + "Rubric introspection unavailable" + ) + + in_flight = self._session_operations_in_flight + in_flight[session_id] = in_flight.get(session_id, 0) + 1 + self._update_session_activity(session_id) try: match msg_type: case "reset": @@ -1848,7 +2221,12 @@ all schema information needed to interact with the environment. ) ) - self._update_session_activity(session_id) + if telemetry is not None: + seed_acceptance = SeedAcceptance( + requested="seed" in msg.data, + value=msg.data.get("seed"), + accepted="seed" in valid_kwargs, + ) response = WSObservationResponse( data=serialize_observation(observation), @@ -1925,9 +2303,39 @@ all schema information needed to interact with the environment. } ) + if telemetry is not None and msg_type in { + "reset", + "step", + "state", + }: + nodes = None + try: + if msg_type in {"reset", "step"}: + nodes = rubric_snapshot( + getattr(session_env, "rubric", None), + before_scores, + ) + except Exception: + nodes = [] + telemetry.snapshot.rubric_error = ( + "Rubric introspection unavailable" + ) + telemetry.append( + msg_type, + message_dict, + response.model_dump(mode="json"), + seed=seed_acceptance, + rubric=nodes, + ) await websocket.send_text(response.model_dump_json()) except ValidationError as e: + if telemetry is not None and msg_type in { + "reset", + "step", + "state", + }: + telemetry.incomplete("Session operation failed") error_resp = WSErrorResponse( data={ "message": "Invalid message", @@ -1937,6 +2345,12 @@ all schema information needed to interact with the environment. ) await websocket.send_text(error_resp.model_dump_json()) except Exception as e: + if telemetry is not None and msg_type in { + "reset", + "step", + "state", + }: + telemetry.incomplete("Session operation failed") error_resp = WSErrorResponse( data={ "message": str(e), @@ -1944,6 +2358,11 @@ all schema information needed to interact with the environment. } ) await websocket.send_text(error_resp.model_dump_json()) + finally: + in_flight[session_id] -= 1 + if in_flight[session_id] == 0: + del in_flight[session_id] + self._update_session_activity(session_id) except WebSocketDisconnect: pass @@ -2003,6 +2422,7 @@ def create_app( *, mode: Optional[ServerMode | str] = None, reset_observation_cls: Optional[Type[Observation]] = None, + reset_cls: Type[ResetRequest] = ResetRequest, ) -> FastAPI: """ Create a FastAPI application with or without web interface. @@ -2047,6 +2467,9 @@ def create_app( state_cls (`Type[State]`, *optional*, defaults to `State`): The `State` subclass this environment reports, used for the `/state` response model and the `state` entry of `/schema`. + reset_cls (`Type[ResetRequest]`, *optional*, defaults to `ResetRequest`): + The `ResetRequest` subclass describing this environment's reset parameters, + published as the `reset` entry of `/schema`. Not used for validation. mode (`ServerMode` or `str`, *optional*): Server mode. When `None`, resolved from the `OPENENV_MODE` environment variable, defaulting to simulation. @@ -2074,6 +2497,7 @@ def create_app( max_concurrent_envs, concurrency_config, state_cls=state_cls, + reset_cls=reset_cls, reset_observation_cls=reset_observation_cls, gradio_builder=gradio_builder, custom_tab_name=custom_tab_name, @@ -2092,6 +2516,7 @@ def create_app( concurrency_config, env_name=env_name, state_cls=state_cls, + reset_cls=reset_cls, reset_observation_cls=reset_observation_cls, mode=mode, ) @@ -2108,6 +2533,7 @@ def create_fastapi_app( *, mode: Optional[ServerMode | str] = None, reset_observation_cls: Optional[Type[Observation]] = None, + reset_cls: Type[ResetRequest] = ResetRequest, ) -> FastAPI: """ Create a FastAPI application with comprehensive documentation. @@ -2133,6 +2559,9 @@ def create_fastapi_app( state_cls (`Type[State]`, *optional*, defaults to `State`): The `State` subclass this environment reports, used for the `/state` response model and the `state` entry of `/schema`. + reset_cls (`Type[ResetRequest]`, *optional*, defaults to `ResetRequest`): + The `ResetRequest` subclass describing this environment's reset parameters, + published as the `reset` entry of `/schema`. Not used for validation. mode (`ServerMode` or `str`, *optional*): Server mode. When `None`, resolved from the `OPENENV_MODE` environment variable, defaulting to simulation. @@ -2160,7 +2589,7 @@ HTTP API for interacting with OpenEnv environments through a standardized interf * **Environment Reset**: Initialize or restart episodes * **Action Execution**: Send actions and receive observations * **State Inspection**: Query current environment state -* **Schema Access**: Retrieve JSON schemas for actions and observations +* **Schema Access**: Retrieve JSON schemas for actions, observations, state, and reset parameters ## Workflow @@ -2190,7 +2619,7 @@ HTTP API for interacting with OpenEnv environments through a standardized interf }, { "name": "Schema", - "description": "JSON Schema endpoints for actions, observations, and state", + "description": "JSON Schema endpoints for actions, observations, state, and reset parameters", }, {"name": "Health", "description": "Service health and status checks"}, ], @@ -2199,11 +2628,11 @@ HTTP API for interacting with OpenEnv environments through a standardized interf openapi_url="/openapi.json", contact={ "name": "OpenEnv Team", - "url": "https://github.com/huggingface/OpenEnv", + "url": "https://github.com/openenv/OpenEnv", }, license_info={ "name": "BSD-3-Clause", - "url": "https://github.com/huggingface/OpenEnv/blob/main/LICENSE", + "url": "https://github.com/openenv/OpenEnv/blob/main/LICENSE", }, ) @@ -2215,9 +2644,14 @@ HTTP API for interacting with OpenEnv environments through a standardized interf concurrency_config=concurrency_config, env_name=env_name, state_cls=state_cls, + reset_cls=reset_cls, reset_observation_cls=reset_observation_cls, ) if mode is None: mode = os.environ.get("OPENENV_MODE", ServerMode.SIMULATION.value) server.register_routes(app, mode=mode) + + from .security import attach_guard + + attach_guard(app) return app diff --git a/src/core/env_server/interfaces.py b/src/core/env_server/interfaces.py index 707547697748e694990f52568eeef3261a0b6cf8..8cd15ed7a8e37fe35375ccecbf83eeec23b48480 100644 --- a/src/core/env_server/interfaces.py +++ b/src/core/env_server/interfaces.py @@ -105,7 +105,7 @@ class TaskProvider(Protocol): Selecting a task is not part of this protocol — pass the chosen split and index to `reset()` instead. See the - [Task API guide](https://huggingface.co/docs/openenv/guides/task-api). + [Task API guide](https://openenv.github.io/OpenEnv/main/guides/task-api). Examples: @@ -223,7 +223,7 @@ class Transform(ABC, Generic[ObsT]): class Environment(ABC, Generic[ActT, ObsT, StateT]): """Base class for all environment servers following Gym/Gymnasium API. - See [rfcs/004-rubrics.md](https://github.com/huggingface/OpenEnv/blob/main/rfcs/004-rubrics.md) for rubric design details. + See [rfcs/004-rubrics.md](https://github.com/openenv/OpenEnv/blob/main/rfcs/004-rubrics.md) for rubric design details. Args: transform (`Transform`, *optional*): diff --git a/src/core/env_server/mcp_environment.py b/src/core/env_server/mcp_environment.py index 9d9ad564b9f965194ac6d3edb3766f99a42cbd2e..7d683fab84072bceca4841ffda213b2e86b6bb93 100644 --- a/src/core/env_server/mcp_environment.py +++ b/src/core/env_server/mcp_environment.py @@ -86,17 +86,17 @@ VALID_MODES = {"production", "simulation"} def get_server_tools(mcp_server: Any) -> Dict[str, Any]: """ - Get tools from a FastMCP server, compatible with both 2.x and 3.x. + Get tools from a FastMCP server. Returns: Dictionary mapping tool names to tool objects. """ - # FastMCP 2.x: get_tools() returns dict {name: Tool} + # FastMCP server tools are exposed as a name-to-tool mapping. if hasattr(mcp_server, "get_tools"): result = run_async_safely(mcp_server.get_tools()) if isinstance(result, dict): return result - # FastMCP 3.x: list_tools() returns list of Tool objects + # Some server adapters expose the tools as a list instead. if hasattr(mcp_server, "list_tools"): tools_list = run_async_safely(mcp_server.list_tools()) return {t.name: t for t in tools_list} @@ -108,7 +108,7 @@ def _tool_from_server_tool(tool: Any) -> Tool: return Tool( name=tool.name, description=tool.description or "", - input_schema=tool.inputSchema if hasattr(tool, "inputSchema") else {}, + input_schema=tool.input_schema, ) @@ -187,7 +187,9 @@ class MCPEnvironment(Environment): self._validate_tool_names(mcp_server) self.mcp_server = mcp_server - self.mcp_client = Client(mcp_server) + # OpenEnv sessions keep MCP state across tool calls. FastMCP 4's default + # modern protocol is sessionless, so use its supported legacy handshake. + self.mcp_client = Client(mcp_server, mode="legacy") # Track mode-specific tools: {tool_name: {mode: func}} # mode can be "production", "simulation", or None (available in all modes) @@ -195,6 +197,11 @@ class MCPEnvironment(Environment): # Track tool schemas for list_tools: {tool_name: {mode: schema}} self._mode_tool_schemas = defaultdict(dict) + self._mode: Optional[str] = None + + def set_mode(self, mode: Optional[str]) -> None: + """Set the active mode ('production' or 'simulation') for mode-aware tools.""" + self._mode = mode def _require_mcp_client(self) -> Any: """Return MCP client or raise if environment has been closed.""" @@ -249,7 +256,7 @@ class MCPEnvironment(Environment): def _get_server_tools(self, mcp_server: Any) -> Dict[str, Any]: """ - Get tools from a FastMCP server, compatible with both 2.x and 3.x. + Get tools from a FastMCP server. Returns: Dictionary mapping tool names to tool objects. @@ -496,7 +503,8 @@ class MCPEnvironment(Environment): tools_result = await self._async_list_tools() tools = [] for tool in tools_result: - if tool.name not in self._mode_tool_schemas: + mode_schemas = self._mode_tool_schemas.get(tool.name, {}) + if _schema_for_mode(mode_schemas, current_mode) is None: tools.append(_tool_from_server_tool(tool)) for mode_schemas in self._mode_tool_schemas.values(): schema = _schema_for_mode(mode_schemas, current_mode) @@ -519,21 +527,12 @@ class MCPEnvironment(Environment): tool_name = action.tool_name current_mode = getattr(self, "_mode", None) - if tool_name in self._mode_tools: - mode_info = self._mode_tools[tool_name] + mode_info = self._mode_tools.get(tool_name, {}) + if None in mode_info or current_mode in mode_info: if None in mode_info: func = mode_info[None] elif current_mode in mode_info: func = mode_info[current_mode] - else: - return CallToolObservation( - tool_name=tool_name, - result=None, - error=ToolError( - error_type=ToolErrorType.TOOL_NOT_FOUND, - message=f"Tool '{tool_name}' not available in {current_mode} mode", - ), - ) try: if inspect.iscoroutinefunction(func): result = await func(**action.arguments) diff --git a/src/core/env_server/security.py b/src/core/env_server/security.py new file mode 100644 index 0000000000000000000000000000000000000000..6757585d753abc843f2d94e12677f0308cd59202 --- /dev/null +++ b/src/core/env_server/security.py @@ -0,0 +1,192 @@ +# SPDX-License-Identifier: BSD-3-Clause + +"""Optional fastapi-guard security middleware for environment servers. + +Opt-in via the `OPENENV_GUARD_*` environment variables. When disabled (the +default), `attach_guard` is a no-op and environment servers behave exactly as +before. + +Install the extra with `pip install "openenv[security]"` and enable with +`OPENENV_GUARD_ENABLED=1` to get IP block/allow lists, rate limiting, +user-agent blocking, penetration-attempt detection with auto-ban, and optional +Redis-backed distributed state (fastapi-guard). + +Health and schema endpoints are excluded from detection checks so +orchestrators can probe the server; global IP allow/block lists are still +enforced on those paths. + +WebSocket connections (`/ws`, `/mcp`, `/harness`, `/ws/ui`) get the same +checks on the handshake: ban, IP lists, a separate rate-limit bucket and +penetration detection on the path, query and headers. A refused handshake is +closed before `accept()`, so the client gets HTTP 403 on the upgrade and no +socket. Messages on an accepted connection are not screened, for the same +reason request bodies are not. With Redis configured, the guard initializes at +startup; while Redis is unreachable a handshake is closed with 1013 and HTTP +requests are refused. +""" + +from __future__ import annotations + +import os +from contextlib import asynccontextmanager +from typing import Any + +from starlette import status +from starlette.exceptions import WebSocketException +from starlette.websockets import WebSocket + +DEFAULT_EXCLUDED_PATHS = [ + "/health", + "/schema", + "/metadata", + "/docs", + "/redoc", + "/openapi.json", +] +# Empty by default on purpose: trusting private-range peers would let +# any of them spoof X-Forwarded-For past the blocklist and rate limits. +# Behind a reverse proxy, list the proxy's addresses in +# OPENENV_GUARD_TRUSTED_PROXIES. +DEFAULT_TRUSTED_PROXIES = "" + + +def _env_list(name: str, default: str = "") -> list[str]: + raw = os.environ.get(name, default) + return [item.strip() for item in raw.split(",") if item.strip()] + + +def _env_bool(name: str) -> bool: + raw = os.environ.get(name) + if raw is None or not raw.strip(): + return False + normalized = raw.strip().lower() + if normalized in ("1", "true", "yes", "on"): + return True + if normalized in ("0", "false", "no", "off"): + return False + msg = f"{name} must be a boolean (1/true/yes/on or 0/false/no/off), got {raw!r}" + raise ValueError(msg) + + +def _build_security_config() -> Any: + from guard import SecurityConfig + + kwargs: dict[str, Any] = { + "enable_rate_limiting": True, + "rate_limit": int(os.environ.get("OPENENV_GUARD_RATE_LIMIT", "100")), + "rate_limit_window": int( + os.environ.get("OPENENV_GUARD_RATE_LIMIT_WINDOW", "60") + ), + "enable_ip_banning": True, + "auto_ban_threshold": int( + os.environ.get("OPENENV_GUARD_AUTO_BAN_THRESHOLD", "10") + ), + "auto_ban_duration": int( + os.environ.get("OPENENV_GUARD_AUTO_BAN_DURATION", "300") + ), + # Environment/request bodies are model input (observations, prompts, + # completions), not commands this server executes: signature-scanning + # them false-positives on ordinary content. URL, query, and header + # screening stay on. + "detection_scan_body": False, + "enable_penetration_detection": True, + # In-memory state unless a Redis URL is configured: never implicitly + # depend on a Redis server being reachable at localhost. + "enable_redis": False, + "blacklist": tuple(_env_list("OPENENV_GUARD_BLOCKED_IPS")), + "blocked_user_agents": _env_list("OPENENV_GUARD_BLOCKED_USER_AGENTS"), + "trusted_proxies": tuple( + _env_list("OPENENV_GUARD_TRUSTED_PROXIES", DEFAULT_TRUSTED_PROXIES) + ), + "trusted_proxy_depth": int( + os.environ.get("OPENENV_GUARD_TRUSTED_PROXY_DEPTH", "1") + ), + "exclude_paths": DEFAULT_EXCLUDED_PATHS, + # fastapi-guard sends security headers unless this is None, and its + # X-Frame-Options: SAMEORIGIN stops a Space page from framing the app. + "security_headers": None, + } + + allowed_ips = _env_list("OPENENV_GUARD_ALLOWED_IPS") + if allowed_ips: + kwargs["whitelist"] = tuple(allowed_ips) + + redis_url = os.environ.get("OPENENV_GUARD_REDIS_URL") + if redis_url: + kwargs["enable_redis"] = True + kwargs["redis_url"] = redis_url + + return SecurityConfig(**kwargs) + + +class _WebSocketGuardMiddleware: + # SecurityMiddleware is a BaseHTTPMiddleware, which never sees websocket + # scopes, so every handshake goes through fastapi-guard's guard_websocket. + def __init__(self, app: Any, config: Any) -> None: + from guard import guard_websocket + from guard.lifespan import _find_security_redis_handler, guard_startup + + self.app = app + self.config = config + self.guard_websocket = guard_websocket + # guard_websocket reads Redis through this; None means not connected. + self.find_redis = _find_security_redis_handler + self.guard_startup = guard_startup + + async def __call__(self, scope: Any, receive: Any, send: Any) -> None: + if scope["type"] == "websocket": + websocket = WebSocket(scope, receive, send) + try: + if not await self._redis_ready(scope["app"]): + # The HTTP side refuses too until Redis is reachable. + raise WebSocketException( + code=status.WS_1013_TRY_AGAIN_LATER, + reason="Service temporarily unavailable", + ) + await self.guard_websocket(websocket) + except WebSocketException as exc: + await websocket.close(code=exc.code, reason=exc.reason) + return + await self.app(scope, receive, send) + + async def _redis_ready(self, app: Any) -> bool: + if not self.config.enable_redis or self.find_redis(app) is not None: + return True + # Retry on each handshake, like the HTTP side's first request. + await self.guard_startup(app) + return self.find_redis(app) is not None + + +def attach_guard(app: Any) -> None: + """Add the fastapi-guard middleware to `app` when enabled via env. + + No-op unless OPENENV_GUARD_ENABLED is set to 1/true/yes/on. + """ + if not _env_bool("OPENENV_GUARD_ENABLED"): + return + if getattr(app.state, "guard_attached", False): + return + try: + from guard import SecurityMiddleware + from guard.lifespan import guard_lifespan + except ImportError as exc: + raise ImportError( + "OPENENV_GUARD_ENABLED requires fastapi-guard. " + 'Install it with: pip install "openenv[security]"' + ) from exc + + config = _build_security_config() + app.add_middleware(SecurityMiddleware, config=config) + app.add_middleware(_WebSocketGuardMiddleware, config=config) + # Initialize the guard (Redis included) at startup, so a WebSocket-only + # worker never runs on in-memory state. + existing_lifespan = app.router.lifespan_context + + @asynccontextmanager + async def lifespan(app: Any): + async with guard_lifespan(app): + async with existing_lifespan(app) as state: + yield state + + app.router.lifespan_context = lifespan + app.state.guard_attached = True diff --git a/src/core/env_server/session_telemetry.py b/src/core/env_server/session_telemetry.py new file mode 100644 index 0000000000000000000000000000000000000000..fe9c3eb0f45b3777856491c4bd0c738077a21630 --- /dev/null +++ b/src/core/env_server/session_telemetry.py @@ -0,0 +1,241 @@ +# SPDX-License-Identifier: BSD-3-Clause + +"""Bounded, opt-in evidence emitted by the subject's replay session.""" + +import json +import secrets +from typing import Any, Literal + +from openenv.core.rubrics.base import Rubric +from openenv.core.rubrics.containers import Gate, Sequential, WeightedSum +from pydantic import BaseModel, ConfigDict, Field, SecretStr + +MAX_TELEMETRY_BYTES = 8 * 1024 * 1024 +MAX_TRAJECTORY_ACTIONS = 100 +MAX_TRAJECTORY_RECORDS = 202 +MAX_RUBRIC_NODES = 128 + + +class _WireModel(BaseModel): + model_config = ConfigDict(extra="forbid", strict=True) + + +class ValidationOpenData(_WireModel): + schema_version: Literal[1] + token: SecretStr = Field(min_length=32, max_length=256) + + +class ValidationOpenMessage(_WireModel): + type: Literal["validation_open"] + data: ValidationOpenData + + +class ValidationReadData(_WireModel): + schema_version: Literal[1] + capability: SecretStr = Field(min_length=32, max_length=256) + + +class ValidationReadMessage(_WireModel): + type: Literal["validation_read"] + data: ValidationReadData + + +class ValidationOpenedData(_WireModel): + schema_version: Literal[1] = 1 + capability: str + + +class ValidationOpenedResponse(_WireModel): + type: Literal["validation_open"] = "validation_open" + data: ValidationOpenedData + + +class SeedAcceptance(_WireModel): + requested: bool + value: Any = None + accepted: bool + + +class RubricNode(_WireModel): + name: str + class_name: str + children: list[str] + aggregation: Literal["weighted_sum", "sequential", "gate", "leaf", "unknown"] + config: dict[str, Any] + config_available: bool + score: Any = None + evaluated: bool = False + + +class StepAttribution(_WireModel): + step_index: int + rubric: list[RubricNode] + + +class TrajectoryRecord(_WireModel): + operation: Literal["reset", "step", "state"] + request: dict[str, Any] + response: dict[str, Any] + + +class SubjectTrajectory(_WireModel): + schema_version: Literal[1] = 1 + source: Literal["openenv-server"] = "openenv-server" + records: list[TrajectoryRecord] = Field(default_factory=list) + complete: bool = True + reason: str | None = None + + +class ValidationSnapshot(_WireModel): + schema_version: Literal[1] = 1 + seed: SeedAcceptance | None = None + rubric: list[RubricNode] = Field(default_factory=list) + rubric_error: str | None = None + attribution: list[StepAttribution] = Field(default_factory=list) + trajectory: SubjectTrajectory = Field(default_factory=SubjectTrajectory) + + +class ValidationResponse(_WireModel): + type: Literal["validation"] = "validation" + data: ValidationSnapshot + + +def _rubrics(root: Rubric | None) -> list[tuple[str, Rubric]]: + """Visit the named tree with finite size, rejecting cycles and aliases.""" + if root is None: + return [] + result, pending, seen = [], [("root", root)], set() + while pending: + name, rubric = pending.pop() + if id(rubric) in seen or len(result) >= MAX_RUBRIC_NODES: + raise ValueError("Rubric tree is cyclic, shared, or exceeds 128 nodes") + seen.add(id(rubric)) + result.append((name, rubric)) + children = list(rubric.named_children()) + if any(not key or "." in key for key, _ in children): + raise ValueError("Rubric child names must be nonempty path segments") + pending.extend((f"{name}.{key}", child) for key, child in reversed(children)) + return result + + +def rubric_counts(root: Rubric | None) -> dict[int, int]: + return {id(r): r._evaluation_count for _, r in _rubrics(root)} + + +def rubric_snapshot( + root: Rubric | None, before: dict[int, int] | None = None +) -> list[RubricNode]: + nodes = [] + for name, rubric in _rubrics(root): + children = [f"{name}.{key}" for key, _ in rubric.named_children()] + aggregation = "unknown" if children else "leaf" + config = None + # Exact types: a subclass can override scoring, so its semantics are unknown. + if type(rubric) is WeightedSum: + aggregation, config = "weighted_sum", {"weights": list(rubric._weights)} + elif type(rubric) is Sequential: + aggregation, config = "sequential", {} + elif type(rubric) is Gate: + aggregation, config = "gate", {"threshold": rubric.threshold} + else: + config = rubric.validation_config() + evaluated = before is not None and rubric._evaluation_count > before.get( + id(rubric), 0 + ) + nodes.append( + RubricNode( + name=name, + class_name=f"{type(rubric).__module__}.{type(rubric).__qualname__}", + children=children, + aggregation=aggregation, + config={} if config is None else config, + config_available=config is not None, + score=rubric.last_score if evaluated else None, + evaluated=evaluated, + ) + ) + json.dumps([node.model_dump() for node in nodes], allow_nan=False) + return nodes + + +class SessionTelemetry: + """Own one socket's capability and a detached record of completed operations.""" + + def __init__(self): + self.capability = secrets.token_urlsafe(32) + self.snapshot = ValidationSnapshot() + self._bytes = 0 + self._steps = 0 + + def authorized(self, capability: str) -> bool: + return secrets.compare_digest(self.capability.encode(), capability.encode()) + + def append( + self, + operation: Literal["reset", "step", "state"], + request: dict[str, Any], + response: dict[str, Any], + *, + seed: SeedAcceptance | None = None, + rubric: list[RubricNode] | None = None, + ) -> None: + if not self.snapshot.trajectory.complete: + return + try: + # JSON round-trip detaches mutable observations/actions from the record. + record = TrajectoryRecord.model_validate( + json.loads( + json.dumps( + { + "operation": operation, + "request": request, + "response": response, + }, + allow_nan=False, + ) + ) + ) + attribution = ( + StepAttribution(step_index=self._steps, rubric=rubric or []) + if operation == "step" + else None + ) + byte_count = len(record.model_dump_json().encode()) + if attribution is not None: + byte_count += len(attribution.model_dump_json().encode()) + byte_count += ( + len(seed.model_dump_json().encode()) if seed is not None else 0 + ) + # Reserve room for the current rubric, envelope, and seed metadata. + current_bytes = len( + json.dumps( + [ + node.model_dump() + for node in (self.snapshot.rubric if rubric is None else rubric) + ], + allow_nan=False, + ).encode() + ) + if ( + len(self.snapshot.trajectory.records) >= MAX_TRAJECTORY_RECORDS + or operation == "step" + and self._steps >= MAX_TRAJECTORY_ACTIONS + or self._bytes + byte_count + current_bytes + 4096 > MAX_TELEMETRY_BYTES + ): + self.incomplete("Session telemetry budget exceeded") + return + self._bytes += byte_count + self.snapshot.trajectory.records.append(record) + if seed is not None: + self.snapshot.seed = seed.model_copy(deep=True) + if rubric is not None: + self.snapshot.rubric = [node.model_copy(deep=True) for node in rubric] + if attribution is not None: + self.snapshot.attribution.append(attribution.model_copy(deep=True)) + self._steps += 1 + except (TypeError, ValueError): + self.incomplete("Session telemetry contains non-JSON data") + + def incomplete(self, reason: str) -> None: + self.snapshot.trajectory.complete = False + self.snapshot.trajectory.reason = reason diff --git a/src/core/env_server/types.py b/src/core/env_server/types.py index 3ccc69bcb59ea814bc934bcadb8b9399fe009f33..c81c4e8e721e4cdba6559f78ee4196e165c930c8 100644 --- a/src/core/env_server/types.py +++ b/src/core/env_server/types.py @@ -236,6 +236,10 @@ class SchemaResponse(BaseMessage): state: Dict[str, Any] = Field( description="JSON schema for environment state objects" ) + reset: Optional[Dict[str, Any]] = Field( + default=None, + description="JSON schema for reset parameters accepted by this environment", + ) reset_observation: Optional[Dict[str, Any]] = Field( default=None, description="JSON schema for observations returned by reset" ) @@ -243,6 +247,8 @@ class SchemaResponse(BaseMessage): @model_serializer(mode="wrap") def _omit_undeclared_reset_schema(self, handler): data = handler(self) + if self.reset is None: + data.pop("reset", None) if self.reset_observation is None: data.pop("reset_observation", None) return data diff --git a/src/core/env_server/web_interface.py b/src/core/env_server/web_interface.py index b0366aefe38077bc0df050294d1913f1163ffaae..449b90f99dc133ab475eff66bf5bda4958487232 100644 --- a/src/core/env_server/web_interface.py +++ b/src/core/env_server/web_interface.py @@ -28,7 +28,7 @@ from .gradio_theme import OPENENV_GRADIO_CSS, OPENENV_GRADIO_THEME from .gradio_ui import build_gradio_app, get_gradio_display_title from .interfaces import Environment from .serialization import deserialize_action_with_preprocessing, serialize_observation -from .types import Action, EnvironmentMetadata, Observation, State +from .types import Action, EnvironmentMetadata, Observation, ResetRequest, State _CLIENT_BASES = {"EnvClient", "MCPClientBase", "MCPToolClient"} @@ -169,7 +169,7 @@ def get_quick_start_markdown( lines += ["", after] lines += [ "", - "More in the [OpenEnv documentation](https://huggingface.co/docs/openenv).", + "More in the [OpenEnv documentation](https://openenv.github.io/OpenEnv/).", ] return "\n".join(lines) @@ -485,6 +485,7 @@ def create_web_interface_app( *, mode: Optional[Any] = None, reset_observation_cls: Optional[Type[Observation]] = None, + reset_cls: Type[ResetRequest] = ResetRequest, ) -> FastAPI: """ Create a FastAPI application with web interface for the given environment. @@ -519,6 +520,9 @@ def create_web_interface_app( title instead of the default ``"OpenEnv Agentic Environment: {name}"``. state_cls: The State subclass this environment reports. Used for the /state response model and the state entry of /schema. Defaults to State. + reset_cls: The ResetRequest subclass describing reset parameters. Published + as the reset entry of /schema; not used for validation. Defaults to + ResetRequest. mode: Server mode (``ServerMode`` or string). When ``None``, resolved from the ``OPENENV_MODE`` environment variable, defaulting to simulation. @@ -537,6 +541,7 @@ def create_web_interface_app( concurrency_config, env_name=env_name, state_cls=state_cls, + reset_cls=reset_cls, reset_observation_cls=reset_observation_cls, mode=mode, ) @@ -638,6 +643,8 @@ def create_web_interface_app( css=OPENENV_GRADIO_CSS, ) + # Security middleware is attached inside create_fastapi_app, before the + # gradio mount at /web; it is app-level middleware, so it covers the mount. return app diff --git a/src/core/harness/bridge.py b/src/core/harness/bridge.py index 7167690ac56b926e05644771bc66591aafde2263..badf965571c2f1e096dddbcb87fe178dc86e08f7 100644 --- a/src/core/harness/bridge.py +++ b/src/core/harness/bridge.py @@ -14,7 +14,7 @@ from .adapter import HarnessError async def _source_tools(mcp_server: Any) -> dict[str, Any]: - """Return {name: FastMCP tool}, compatible with FastMCP 2.x and 3.x. + """Return {name: FastMCP tool}. Async twin of [`~openenv.core.env_server.mcp_environment.get_server_tools`], which wraps the same calls in `run_async_safely`; awaiting directly avoids @@ -52,9 +52,11 @@ async def build_bridge_server(mcp_server: Any, renames: dict[str, str]) -> Any: return mcp_server from fastmcp import Client + from fastmcp.server.dependencies import get_context from fastmcp.server.providers.proxy import FastMCPProxy, StatefulProxyClient from fastmcp.server.transforms import ToolTransform from fastmcp.tools.tool_transform import ToolTransformConfig + from mcp_types.version import MODERN_PROTOCOL_VERSIONS source_tools = await _source_tools(mcp_server) missing = sorted(set(renames.values()) - set(source_tools)) @@ -71,12 +73,20 @@ async def build_bridge_server(mcp_server: Any, renames: dict[str, str]) -> Any: async with Client(mcp_server): yield {} - # Forward callbacks in the current request context. Each harness MCP - # connection gets its own source session, closed on disconnect. + # Keep one backend client per front connection, and mirror its protocol era. + # StatefulProxyClient defaults to legacy, which cannot carry sampling guards. client = StatefulProxyClient(mcp_server) + + def client_factory(): + backend = client.new_stateful() + if not backend.is_connected(): + version = get_context().request_context.protocol_version + backend.mode = version if version in MODERN_PROTOCOL_VERSIONS else "legacy" + return backend + view = FastMCPProxy( name=f"{getattr(mcp_server, 'name', 'openenv')}-harness-view", - client_factory=client.new_stateful, + client_factory=client_factory, lifespan=lifespan, ) view.add_transform( diff --git a/src/core/harness/capture/forwarding.py b/src/core/harness/capture/forwarding.py index 1c8e841452f86aaaf16107395813f5c408fb0b54..83aa1bb834d720c6e2cafd42e1c8564492990852 100644 --- a/src/core/harness/capture/forwarding.py +++ b/src/core/harness/capture/forwarding.py @@ -33,6 +33,7 @@ why `SessionRegistry.require_registered` defaults to True. from __future__ import annotations +import importlib import logging import re import secrets @@ -42,6 +43,12 @@ import subprocess import threading import time from abc import ABC, abstractmethod +from pathlib import Path + +try: + import fcntl +except ImportError: # Windows: no advisory locks, keep gradio's unlocked download. + fcntl = None logger = logging.getLogger(__name__) @@ -147,6 +154,25 @@ class GradioForwarder(PortForwarder): f"gradio is required for GradioForwarder: {exc}" ) from exc + @staticmethod + def _ensure_frpc_binary() -> None: + """ + Download gradio's frpc binary once, under a cross-process lock. + + Gradio checks `Path(BINARY_PATH).exists()` and then writes the binary in place. A second + process that starts while the first is still writing sees the file, skips the download and + executes a half-written binary, which fails with `Text file busy` (ETXTBSY) or a corrupt + executable. Holding an exclusive lock next to the binary makes every other process wait + until the first download has finished, after which gradio's own check skips the download. + """ + tunneling = importlib.import_module("gradio.tunneling") + binary = Path(tunneling.BINARY_PATH) + binary.parent.mkdir(parents=True, exist_ok=True) + with open(binary.with_name(binary.name + ".lock"), "a") as lock_file: + if fcntl is not None: + fcntl.flock(lock_file, fcntl.LOCK_EX) + tunneling.Tunnel.download_binary() + def start(self, local_port: int, *, local_host: str = "127.0.0.1") -> str: from gradio.networking import setup_tunnel from gradio.tunneling import CURRENT_TUNNELS @@ -154,6 +180,7 @@ class GradioForwarder(PortForwarder): self.stop() share_token = secrets.token_hex(16) try: + self._ensure_frpc_binary() url = setup_tunnel( local_host=local_host, local_port=local_port, diff --git a/src/core/harness/capture/graph.py b/src/core/harness/capture/graph.py index 61cc88bf2dc54662e9fa55d643ae4468d9e0a808..820689b54d21c97bd57172b06493f1871c5a466c 100644 --- a/src/core/harness/capture/graph.py +++ b/src/core/harness/capture/graph.py @@ -248,9 +248,25 @@ class RolloutGraph: self._nodes: dict[str, TurnNode] = {} self._order: list[str] = [] self._children: dict[str, list[str]] = {} + # Every request re-sends the whole history, so each turn decodes a fresh copy of every + # earlier image and long text. Keep one copy per graph. Only immutable strings are shared; + # message dicts and lists stay per turn. + self._shared_text: dict[str, str] = {} + + def _share_text(self, value: Any) -> Any: + if isinstance(value, str) and len(value) >= 1024: + return self._shared_text.setdefault(value, value) + if isinstance(value, list): + return [self._share_text(item) for item in value] + if isinstance(value, dict): + return {key: self._share_text(item) for key, item in value.items()} + return value # --- construction -------------------------------------------------- def add_turn(self, node: TurnNode) -> TurnNode: + node.request_messages = self._share_text(node.request_messages) + node.request_tools = self._share_text(node.request_tools) + node.response_message = self._share_text(node.response_message) node.index = len(self._order) node.parent_id = self._find_parent(node) self._nodes[node.node_id] = node diff --git a/src/core/harness/capture/server.py b/src/core/harness/capture/server.py index 32b9dad48bf7934f1c67c0f91dd36d748d4315c3..9d9f956c55b37c29143266e1bd7da747afbb26b7 100644 --- a/src/core/harness/capture/server.py +++ b/src/core/harness/capture/server.py @@ -266,6 +266,41 @@ def clamp_output_tokens(chat_request: dict[str, Any], cap: int | None) -> int | return replaced +def context_window_ran_out( + chat_request: dict[str, Any], response: dict[str, Any] +) -> bool: + """Whether the engine cut the completion short because the context window was full. + + Older vLLM rejects a request whose prompt plus `max_tokens` exceeds the context window with a 400 + ("maximum context length"), which the proxy turns into a budget stop. Newer vLLM (seen with 0.34) + serves it and stops generating when the window is full instead: the completion ends with + `finish_reason="length"` before reaching `max_tokens`. Forwarded as is, that truncated turn reaches + the harness, and pi answers it by compacting its context, in a summarisation call capture cannot + tie to the rest of the rollout: every such rollout fails validation with `turn_mismatch`. It is the + same event as the 400, so it ends the rollout the same way. + """ + # The limit the engine applies, in its order: vLLM (like OpenAI) takes `max_completion_tokens` and + # falls back to `max_tokens`. A harness that sends both with different values would otherwise turn + # an output-cap stop into a context stop, or hide a real one. + requested = next( + ( + chat_request[key] + for key in ("max_completion_tokens", "max_tokens") + if isinstance(chat_request.get(key), int) + ), + None, + ) + choices = response.get("choices") or [] + completion_tokens = (response.get("usage") or {}).get("completion_tokens") + return ( + requested is not None + and isinstance(completion_tokens, int) + and bool(choices) + and choices[0].get("finish_reason") == "length" + and completion_tokens < requested + ) + + def normalise_for_capture(chat_request: dict[str, Any]) -> None: """Force the upstream call into the one shape that yields complete, capturable responses. @@ -1199,6 +1234,23 @@ def create_app( for key in SAMPLING_KEYS: chat_request.pop(key, None) chat_request.update(effective_sampling) + if context_window_ran_out(chat_request, response): + # Like the 400 above: a stop the harness ends on, and the truncated turn is never ingested + session.findings.append( + "[WARN] context_budget_exhausted: the engine stopped at the context window, " + "before max_tokens" + ) + session.budget_stop_count += 1 + stop = _budget_stop_response(_model_of(session) or app.state.model) + if client_wants_stream: + return StreamingResponse( + sse.replay(api_type, transformer, stop, original_request), + media_type="text/event-stream", + headers=sse.SSE_HEADERS, + ) + payload = transformer.transform_response(stop, original_request) + normalise_client_payload(payload, api_type) + return JSONResponse(payload) normalise_response(response) _ingest( session, diff --git a/src/core/harness/capture/validate_llm.py b/src/core/harness/capture/validate_llm.py index 41028e4a6b389aeff73511fff1508cb4c5facec3..4c96a4798c4cebb49b74e3e067fa65be2ac49d9b 100644 --- a/src/core/harness/capture/validate_llm.py +++ b/src/core/harness/capture/validate_llm.py @@ -44,11 +44,13 @@ from __future__ import annotations import json import os +import time import urllib.error import urllib.request from dataclasses import dataclass, field +from urllib.parse import urlsplit -from .compat import behaviour_warnings, diagnose, MAX_FIXES +from .compat import behaviour_warnings, diagnose, MAX_FIXES, ParamFix from .upstream import ( auth_headers, normalise_engine_base, @@ -70,6 +72,25 @@ ENGINE_HINT = ( ) +# How many times the probe repeats the SAME request after an error that names nothing it can fix. +# Hosted routers occasionally answer a valid request with a 400 or 5xx that a resend clears: observed +# as one task in ~150 aborting before it ran, against an endpoint that served the other 149. +PROBE_RETRIES = 2 +PROBE_RETRY_DELAY = 1.0 +# Errors no resend or rewrite can fix: bad credentials, no access, no such route or model. Retrying +# these only delays a message the user needs now. +_FATAL_HTTP = frozenset({401, 403, 404}) +# Statuses with which a provider rejects a request it doesn't accept, e.g. unsupported capture params. +_PARAM_REJECTION_HTTP = frozenset({400, 422}) +# What the eval fallback drops. `logprobs` also takes `top_logprobs` with it (see `ParamFix.apply`). +_CAPTURE_PARAMS = ("return_token_ids", "logprobs") + + +def _is_timeout(exc: BaseException) -> bool: + reason = getattr(exc, "reason", None) + return isinstance(exc, TimeoutError) or isinstance(reason, TimeoutError) + + @dataclass class LLMReport: """Outcome of the probe. `ok` means trainable; `reachable` means usable at all.""" @@ -574,7 +595,10 @@ def validate_llm( # or gate it behind different scopes than inference, and refusing there would reject an endpoint # that serves completions perfectly well. The completion probe below is the real test; a missing # list only costs us the model-name check. - listed_model = model.rsplit(":", 1)[0] if provider == "hf" else model + # The HF router lists bare ids but routes `:` (also `:fastest`, `:cheapest`). The + # CLI reaches it with the default provider, so recognise the router by its host as well. + hf_router = urlsplit(base).hostname == "router.huggingface.co" + listed_model = model.rsplit(":", 1)[0] if provider == "hf" or hf_router else model if served and model not in served and listed_model not in served: # Worth failing on rather than warning: a mismatched name is silently accepted by some # servers and then every request 404s at rollout time instead of at startup. @@ -603,6 +627,7 @@ def validate_llm( applied: list = [] payload: dict | None = None failure = "" + retries_left = PROBE_RETRIES # Negotiate down. Each 400 that names a parameter costs one retry and removes one obstacle; the # capture params are the ones most likely to go, and losing them is what decides the level. @@ -630,13 +655,40 @@ def validate_llm( fix = diagnose(json.loads(detail)) except json.JSONDecodeError: fix = diagnose(detail) - if fix is None or not fix.apply(body): - failure = f"probe failed: HTTP {exc.code}: {detail[:300]}" + if fix is not None and fix.apply(body): + fixes.append(str(fix)) + applied.append(fix) + continue + failure = f"probe failed: HTTP {exc.code}: {detail[:300]}" + if exc.code in _FATAL_HTTP: break - fixes.append(str(fix)) - applied.append(fix) + # An error that names no parameter is first treated as transient: the same request again. + if retries_left: + retries_left -= 1 + time.sleep(PROBE_RETRY_DELAY) + continue + # Still failing. Some providers reject the capture params with a bare 400 that names + # nothing, so ask once more without them. If that answers, the endpoint is an eval + # backend (the level is graded from what comes back), which is what `ENGINE_HINT` + # promises. A `purpose="train"` rollout still refuses it, since the level is not `tokens`. + # Only a request error can be about the params: a 5xx or a 429 that outlasts the retries + # is reported, rather than grading a busy token-capable engine as `text`. + if exc.code not in _PARAM_REJECTION_HTTP: + break + dropped = [ParamFix(param=p) for p in _CAPTURE_PARAMS] + dropped = [f for f in dropped if f.apply(body)] + if not dropped: + break + for f in dropped: + fixes.append(f"{f} (eval fallback after HTTP {exc.code})") + applied.append(f) except Exception as exc: # noqa: BLE001 failure = f"probe failed: {type(exc).__name__}: {str(exc)[:300]}" + # A timeout is worth repeating. Anything else here (connection refused, DNS) is not. + if _is_timeout(exc) and retries_left: + retries_left -= 1 + time.sleep(PROBE_RETRY_DELAY) + continue break if payload is None: diff --git a/src/core/harness/collect.py b/src/core/harness/collect.py index 946ce5d54b98fc66ed8ed2e8821b38683a6f86ba..82d0a5fb14485cb871c44878961b15235f6d526d 100644 --- a/src/core/harness/collect.py +++ b/src/core/harness/collect.py @@ -23,10 +23,11 @@ import warnings from dataclasses import asdict, dataclass, field from datetime import datetime, timezone from pathlib import Path -from typing import Any, BinaryIO, Callable, Iterable, Iterator +from typing import Any, BinaryIO, Callable, Iterable from ..env_server.mcp_types import Tool from ..llm_client import LLMClient +from ..utils import redact_secrets from .rollout import ( _resolve_env_reward, HarnessAdapter, @@ -237,9 +238,10 @@ class CollectResult: class CollectRunner: """Drive repeated rollouts into an append-only JSONL dataset. - The runner is stateless across ``run()`` calls — resume state lives on - disk via the ``RolloutSerializer``. A single runner instance can be - reused across runs targeting different output dirs. + Resume state lives on disk via the ``RolloutSerializer``. Repeatable task + iterables, such as lists and tuples, restart at the first task on each + ``run()`` so tasks stay aligned with episode ids. One-shot iterators work + for one run; reusing them raises ``ValueError`` before accessing results. """ def __init__( @@ -254,17 +256,10 @@ class CollectRunner: self._session_factory = session_factory self._harness_adapter = harness_adapter self._serializer = serializer - self._tasks: Iterator[Any] | None = iter(tasks) if tasks is not None else None + self._tasks = tasks + self._tasks_used = False self._limits = limits - def _next_task(self) -> Any: - if self._tasks is None: - return None - try: - return next(self._tasks) - except StopIteration: - return None - def run( self, *, @@ -274,6 +269,16 @@ class CollectRunner: resume: bool = True, should_keep: Callable[[EpisodeRecord], bool] | None = None, ) -> CollectResult: + task_iterator = iter(self._tasks) if self._tasks is not None else None + if ( + task_iterator is not None + and task_iterator is self._tasks + and self._tasks_used + ): + raise ValueError( + "Cannot reuse a one-shot task iterator; pass a repeatable iterable " + "or create a new CollectRunner with a fresh iterator." + ) planned_ids = [f"{episode_id_prefix}-{i:06d}" for i in range(num_episodes)] if resume: @@ -312,7 +317,8 @@ class CollectRunner: with progress: for episode_id in planned_ids: # Preserve task-to-episode alignment even when resume skips ids. - task = self._next_task() + self._tasks_used = True + task = next(task_iterator, None) if task_iterator is not None else None if episode_id in already: num_skipped += 1 progress.advance(task_id) @@ -513,7 +519,7 @@ def build_dataset_readme(output_dir: Path) -> str: "", "# OpenEnv rollouts", "", - "Collected with [OpenEnv](https://github.com/huggingface/OpenEnv) " + "Collected with [OpenEnv](https://github.com/openenv/OpenEnv) " "(`openenv collect`).", "", f"- **Episodes:** {_count_episodes(results_path)}", @@ -594,6 +600,19 @@ def push_to_hf_hub( readme_path = output_dir / README_FILENAME readme_path.write_text(build_dataset_readme(output_dir), encoding="utf-8") + # Episodes hold what the agent saw and printed, which can include credentials. + redacted = 0 + for path in output_dir.iterdir(): + if path.suffix in {".jsonl", ".json", ".md"}: + text, count = redact_secrets(path.read_text(encoding="utf-8")) + if count: + path.write_text(text, encoding="utf-8") + redacted += count + if redacted: + warnings.warn( + f"Redacted {redacted} secret(s) from {output_dir} before the upload" + ) + num_episodes = _count_episodes(results_path) message = commit_message or f"Add {num_episodes} collected episode(s)" diff --git a/src/core/mcp_client.py b/src/core/mcp_client.py index 9002fabf9bcafc743660cb6cf04e364976c45391..c7967a926291691a58e79fddb647e5ff7a214272 100644 --- a/src/core/mcp_client.py +++ b/src/core/mcp_client.py @@ -255,6 +255,12 @@ class MCPClientBase(EnvClient[Any, Observation, State]): return await super()._connect_async() + def _raise_if_session_lost(self) -> None: + # In production mode a reconnect attaches to the same HTTP MCP session, + # which outlives the WebSocket, so the episode carries over. + if not getattr(self, "use_production_mode", False): + super()._raise_if_session_lost() + async def _ensure_production_session(self) -> str: """Create and cache a persistent HTTP MCP session id if needed.""" async with self._production_session_lock: diff --git a/src/core/openenv/auto/auto_action.py b/src/core/openenv/auto/auto_action.py index d093d796ea966c1144d17efe07160a38bf501af1..8b9a86b74c9f79ad520601fa77e13dd622326bca 100644 --- a/src/core/openenv/auto/auto_action.py +++ b/src/core/openenv/auto/auto_action.py @@ -89,9 +89,9 @@ class AutoAction: Args: name: Environment name or HuggingFace Hub repo ID Examples: - - "coding" / "coding-env" / "coding_env" - - "openenv/coding_env" (Hub repo ID) - - "https://huggingface.co/openenv/coding_env" (Hub URL) + - `"coding"` / `"coding-env"` / `"coding_env"` + - `"openenv/coding_env"` (Hub repo ID) + - `"https://huggingface.co/openenv/coding_env"` (Hub URL) skip_install: If True, skip package installation and return GenericAction class instead. Use this when working with GenericEnvClient to avoid installing remote packages. diff --git a/src/core/openenv/auto/auto_env.py b/src/core/openenv/auto/auto_env.py index 467af30c9c21cebc739cca90e91581f98f8dc7fc..954e0d7f4a03072185b6aadd14d55ae2935eaff8 100644 --- a/src/core/openenv/auto/auto_env.py +++ b/src/core/openenv/auto/auto_env.py @@ -518,9 +518,9 @@ class AutoEnv: Args: name: Environment name or HuggingFace Hub repo ID Examples: - - "coding" / "coding-env" / "coding_env" - - "openenv/coding_env" (Hub repo ID) - - "https://huggingface.co/openenv/coding_env" (Hub URL) + - `"coding"` / `"coding-env"` / `"coding_env"` + - `"openenv/coding_env"` (Hub repo ID) + - `"https://huggingface.co/openenv/coding_env"` (Hub URL) base_url: Optional base URL for HTTP connection docker_image: Optional Docker image name (overrides default) container_provider: Optional container provider diff --git a/src/core/openenv/cli/__main__.py b/src/core/openenv/cli/__main__.py index bdaafb09c045f43e06fa9aaf5b0e347d1e88486f..b4f32159eca5a4319019a22ab03dddecdc17b13c 100644 --- a/src/core/openenv/cli/__main__.py +++ b/src/core/openenv/cli/__main__.py @@ -51,9 +51,10 @@ app.command( name="push", help="Push an OpenEnv environment to Hugging Face Spaces or custom registry", )(push.push) -app.command(name="serve", help="Serve environments locally (TODO: Phase 4)")( - serve.serve -) +app.command( + name="serve", + help="Run an environment on the host for local development (no container isolation)", +)(serve.serve) app.command( name="fork", help="Fork (duplicate) a Hugging Face Space to your account", diff --git a/src/core/openenv/cli/commands/build.py b/src/core/openenv/cli/commands/build.py index 7b56a5eb3367d18e27ee9661f3bd14696e415673..9a9512e2c51bd12b84c6952c96d09441e21defc7 100644 --- a/src/core/openenv/cli/commands/build.py +++ b/src/core/openenv/cli/commands/build.py @@ -14,6 +14,11 @@ from typing import Annotated import typer +try: + import tomllib +except ModuleNotFoundError: + import tomli as tomllib + from .._cli_utils import console app = typer.Typer(help="Build Docker images for OpenEnv environments") @@ -96,26 +101,13 @@ def _prepare_standalone_build(env_path: Path, temp_dir: Path) -> Path: pyproject_path = build_dir / "pyproject.toml" if pyproject_path.exists(): with open(pyproject_path, "rb") as f: - try: - import tomli - - pyproject = tomli.load(f) - deps = pyproject.get("project", {}).get("dependencies", []) - - # Check if openenv dependency is declared - has_openenv = any(dep.startswith("openenv") for dep in deps) - - if not has_openenv: - console.print( - "[yellow]Warning:[/yellow] pyproject.toml doesn't list the openenv dependency", - ) - console.print( - "[yellow]You may need to add:[/yellow] openenv>=0.2.0", - ) - except ImportError: - console.print( - "[yellow]Warning:[/yellow] tomli not available, skipping dependency check", - ) + pyproject = tomllib.load(f) + deps = pyproject.get("project", {}).get("dependencies", []) + if not any(dep.startswith("openenv") for dep in deps): + console.print( + "[yellow]Warning:[/yellow] pyproject.toml doesn't list the openenv dependency", + ) + console.print("[yellow]You may need to add:[/yellow] openenv>=0.2.0") return build_dir @@ -156,45 +148,27 @@ def _prepare_inrepo_build(env_path: Path, repo_root: Path, temp_dir: Path) -> Pa pyproject_path = build_dir / "pyproject.toml" if pyproject_path.exists(): with open(pyproject_path, "rb") as f: - try: - import tomli - - pyproject = tomli.load(f) - deps = pyproject.get("project", {}).get("dependencies", []) - - # Replace OpenEnv package references with local source. - new_deps = [] - for dep in deps: - if _is_openenv_runtime_dependency(dep): - # Skip - we'll use local core - continue - new_deps.append(dep) - - # Write back with local OpenEnv reference - pyproject["project"]["dependencies"] = new_deps + [ - "openenv @ file:///app/env/openenv" - ] - - # Write updated pyproject.toml - with open(pyproject_path, "wb") as out_f: - import tomli_w - - tomli_w.dump(pyproject, out_f) - - console.print( - "[cyan]Updated pyproject.toml to use local core[/cyan]" - ) - - # Remove old lockfile since dependencies changed - lockfile = build_dir / "uv.lock" - if lockfile.exists(): - lockfile.unlink() - console.print("[cyan]Removed outdated uv.lock[/cyan]") - - except ImportError: - console.print( - "[yellow]Warning:[/yellow] tomli/tomli_w not available, using pyproject.toml as-is", - ) + pyproject = tomllib.load(f) + deps = pyproject.get("project", {}).get("dependencies", []) + pyproject["project"]["dependencies"] = [ + dep for dep in deps if not _is_openenv_runtime_dependency(dep) + ] + ["openenv @ file:///app/env/openenv"] + + try: + import tomli_w + except ImportError: + console.print( + "[yellow]Warning:[/yellow] tomli_w not available, using pyproject.toml as-is", + ) + else: + with open(pyproject_path, "wb") as out_f: + tomli_w.dump(pyproject, out_f) + console.print("[cyan]Updated pyproject.toml to use local core[/cyan]") + lockfile = build_dir / "uv.lock" + if lockfile.exists(): + lockfile.unlink() + console.print("[cyan]Removed outdated uv.lock[/cyan]") + else: console.print( "[yellow]Warning:[/yellow] OpenEnv package not found, building without it" diff --git a/src/core/openenv/cli/commands/harbor.py b/src/core/openenv/cli/commands/harbor.py index 8d509d4f661412ceeefbcb5f768c2ebf7a960774..68a20b8519f855657680d3262f88da1870e92979 100644 --- a/src/core/openenv/cli/commands/harbor.py +++ b/src/core/openenv/cli/commands/harbor.py @@ -1,9 +1,10 @@ """`openenv harbor` — run Harbor tasks with token-level capture. -Four commands, in the order you would use them: +Five commands, in the order you would use them: openenv harbor info what can this machine run right now? openenv harbor rollout --task-index 0 one rollout, end to end, no server + openenv harbor export-sft results/ rollouts as SFT rows (messages + tools) openenv harbor serve the env server, for trainers and clients openenv harbor push the same server, deployed to a Space @@ -187,6 +188,52 @@ def _hub_not_found(exc: Exception) -> bool: return getattr(response, "status_code", None) == 404 +def _check_harness(harness: str, model: str) -> dict[str, Any]: + """Construct the rollout's agent with dummy capture credentials, without setup or run.""" + import io + + result: dict[str, Any] = {"name": harness, "ok": False} + try: + # Imports, constructors and the process-env warning may print. Keep --json readable. + with ( + contextlib.redirect_stdout(io.StringIO()), + tempfile.TemporaryDirectory() as tmp, + ): + from harbor.agents.factory import AgentFactory + from openenv.harbor import seams + from openenv.harbor.rollout import build_trial_config, process_env + + seam = seams.get(harness) + url, session = "http://127.0.0.1:9", "openenv-harness-preflight" + *_, proc_env = seam.resolve(base_url=url, session=session, model=model) + config = build_trial_config( + task_dir=tmp, + harness=harness, + sandbox="docker", + intercept_url=url, + session_id=session, + model=model, + trial_name="preflight", + trials_dir=tmp, + ) + with process_env(harness, proc_env): + AgentFactory.create_agent_from_config(config.agent, logs_dir=Path(tmp)) + result.update( + ok=True, + import_path=seam.import_path, + dialect=seam.dialect, + host_side=seam.host_side, + status=seam.status, + model=config.agent.model_name, + kwargs=config.agent.kwargs, + agent_env=config.agent.env, + process_env=proc_env, + ) + except (Exception, SystemExit) as exc: # noqa: BLE001 - a failed check is report data + result["detail"] = f"{type(exc).__name__}: {exc}" + return result + + @app.command("info") def info( llm_url: Annotated[str, typer.Option("--llm-url", help=_LLM_HELP_OPTIONAL)] = "", @@ -207,6 +254,14 @@ def info( env_file: Annotated[ str, typer.Option("--env-file", help="dotenv file with provider credentials.") ] = "", + harness: Annotated[ + str, + typer.Option( + "--harness", + help="Check a seam name or trusted `module:Class` by constructing it with dummy " + "capture credentials. Runs no agent or sandbox.", + ), + ] = "", verbose: Annotated[ bool, typer.Option("--verbose", help="List every harness, not only validated ones."), @@ -228,11 +283,23 @@ def info( api_key=api_key or None, auth_header=auth_header, ) - print( - json.dumps(caps.to_dict(), indent=2) - if json_output - else caps.render(verbose=verbose) + checked = ( + _check_harness(harness, model or caps.llm.get("model") or "preflight-model") + if harness + else None ) + if json_output: + data = caps.to_dict() + if checked is not None: + data["harness"] = checked + print(json.dumps(data, indent=2)) + else: + print(caps.render(verbose=verbose)) + if checked is not None: + print("\nharness preflight (construction only; capture is untested)") + print(json.dumps(checked, indent=2)) + if checked is not None and not checked["ok"]: + raise typer.Exit(1) @app.command("rollout") @@ -272,7 +339,11 @@ def rollout( ] = "", reward_key: Annotated[ str, - typer.Option("--reward-key", help="Which reward key is the training signal."), + typer.Option( + "--reward-key", + help="Which reward key is the headline one, or a comma-separated preference " + "order (e.g. `correctness,reward`) for a dataset whose tasks write different keys.", + ), ] = "", keep_sandbox: Annotated[ bool, @@ -327,6 +398,111 @@ def rollout( raise typer.Exit(0 if all(r.ok for r in results) else 1) +def _read_results(paths: list[str]) -> list[dict[str, Any]]: + """Rollouts from `rollout --out` files, or from every `*.json` in a directory.""" + files: list[Path] = [] + for spec in paths: + path = Path(spec) + if not path.exists(): + raise typer.BadParameter(f"{spec} does not exist") + files.extend(sorted(path.glob("*.json")) if path.is_dir() else [path]) + results: list[dict[str, Any]] = [] + for file in files: + data = json.loads(file.read_text()) + items = data if isinstance(data, list) else [data] + # a directory can hold other JSON (a run summary): keep what looks like a rollout + results.extend(i for i in items if isinstance(i, dict) and "turns" in i) + return results + + +@app.command("export-sft") +def export_sft_command( + results: Annotated[ + list[str], + typer.Argument( + help="Result JSONs written by `rollout --out`, or directories of them." + ), + ], + out: Annotated[ + str, typer.Option("--out", help="JSON Lines file for the SFT rows.") + ] = "sft_rows.jsonl", + min_reward: Annotated[ + Optional[float], + typer.Option( + "--min-reward", + help="Keep only rollouts graded at least this, e.g. 1.0 for solved tasks. Unset, every rollout is kept with its reward.", + ), + ] = None, + reward_key: Annotated[ + str, + typer.Option( + "--reward-key", + help="Reward to read when the verifier reported several and none was picked at rollout time. A comma-separated list is a preference order, e.g. correctness,reward.", + ), + ] = "", + push_to: Annotated[ + str, + typer.Option("--push-to", help="Hub dataset repo to upload the rows to."), + ] = "", + private: Annotated[ + Optional[bool], + typer.Option( + "--private", + help="Create --push-to as a private dataset. Unset, the namespace's default visibility applies.", + ), + ] = None, +) -> None: + """Turn rollouts into conversational SFT rows (`messages` + `tools`), one per rollout. + + Works on evaluation rollouts against a hosted model: SFT needs the conversation, not token ids. To train on the + rows, type `messages` and `tools` with the `Json` feature of `datasets`: a schema inferred from the rows gives + every tool call the argument names of every other tool, as `None`. + """ + from openenv.core.utils import redact_secrets + from openenv.harbor.sft import export_sft + + rows, stats = export_sft( + _read_results(results), min_reward=min_reward, reward_key=reward_key + ) + # Rows hold what the agent saw and printed, which can include credentials. + text, redacted = redact_secrets("".join(json.dumps(row) + "\n" for row in rows)) + path = Path(out) + path.write_text(text) + print(f"{stats.rows} rows from {stats.rollouts} rollouts -> {path}") + if redacted: + print(f" redacted {redacted} secret(s)") + if stats.below_min_reward or stats.ungraded: + print( + f" dropped: {stats.below_min_reward} below --min-reward, {stats.ungraded} ungraded" + ) + skipped = { + "had no agent turn": stats.no_agent_turn, + "had an unusable capture": stats.capture_failed, + "ended on an empty reply": stats.empty_reply, + "held a tool call whose arguments aren't a JSON object": stats.malformed_tool_call, + } + for reason, count in skipped.items(): + if count: + print(f" {count} rollouts {reason}, skipped") + if stats.ended_on_tool_call: + print( + f" {len(stats.ended_on_tool_call)} rollouts ended right after a tool call, usually a failed model call" + f" worth rerunning: {', '.join(stats.ended_on_tool_call)}" + ) + if push_to: + from huggingface_hub import HfApi + + api = HfApi() + api.create_repo(push_to, repo_type="dataset", private=private, exist_ok=True) + api.upload_file( + path_or_fileobj=path, + path_in_repo=f"data/{path.name}", + repo_id=push_to, + repo_type="dataset", + ) + print(f"pushed to https://huggingface.co/datasets/{push_to}") + + @app.command("serve") def serve( llm_url: Annotated[str, typer.Option("--llm-url", help=_LLM_HELP)] = "", @@ -395,6 +571,16 @@ def serve( reward_key: Annotated[ str, typer.Option("--reward-key", help=_REWARD_KEY_HELP) ] = "", + allow_harness: Annotated[ + Optional[list[str]], + typer.Option( + "--allow-harness", + help=( + "Accept this `module:Class` harness in clients' rollouts. Naming a class imports " + "its module on this server, so other import paths are refused. Repeatable." + ), + ), + ] = None, ) -> None: """Serve Harbor tasks over the OpenEnv Task API and MCP. @@ -418,6 +604,8 @@ def serve( ) # The UI's laptop defaults (this machine's token, private URLs) are for a loopback-only server. os.environ["OPENENV_HARBOR_UI_HOST"] = host + if allow_harness: + os.environ["OPENENV_HARBOR_ALLOW_HARNESS"] = ",".join(allow_harness) serve_harbor( llm_url=llm_url, model=model or None, diff --git a/src/core/openenv/cli/commands/push.py b/src/core/openenv/cli/commands/push.py index 0e8abd6c4df4e259d487ab6ce4fbb74265a5ba06..735fdf732a7f931c1ebec106e87da22c54d18907 100644 --- a/src/core/openenv/cli/commands/push.py +++ b/src/core/openenv/cli/commands/push.py @@ -5,7 +5,6 @@ from __future__ import annotations import shutil -import sys import tempfile from fnmatch import fnmatch from pathlib import Path @@ -407,14 +406,14 @@ def _prepare_staging_directory( # Add base_path to existing frontmatter lines = readme_content.split("\n") new_lines = [] - _in_frontmatter = True for i, line in enumerate(lines): new_lines.append(line) if line.strip() == "---" and i > 0: # End of frontmatter, add base_path before this line if "base_path:" not in "\n".join(new_lines): new_lines.insert(-1, "base_path: /web") - _in_frontmatter = False + new_lines.extend(lines[i + 1 :]) + break readme_path.write_text("\n".join(new_lines)) else: # No frontmatter, add it @@ -682,7 +681,6 @@ def push( if no_interface and interface: console.print( "[bold red]Error:[/bold red] Cannot specify both --interface and --no-interface", - file=sys.stderr, ) raise typer.Exit(1) diff --git a/src/core/openenv/cli/commands/serve.py b/src/core/openenv/cli/commands/serve.py index fa847f8d02b0e183fc470ad40ac8689f63d13c9a..c2d0e32438dc67af9f70572e29d209a08e4dfd72 100644 --- a/src/core/openenv/cli/commands/serve.py +++ b/src/core/openenv/cli/commands/serve.py @@ -1,20 +1,20 @@ # SPDX-License-Identifier: BSD-3-Clause -"""Serve OpenEnv environments locally (TO BE IMPLEMENTED).""" +"""Serve an OpenEnv environment locally (uvicorn, from ``openenv.yaml``).""" from __future__ import annotations +import os +import sys from pathlib import Path from typing import Annotated import typer +import yaml -from .._cli_utils import console +from .._cli_utils import console, validate_env_structure -app = typer.Typer(help="Serve OpenEnv environments locally") - -@app.command() def serve( env_path: Annotated[ str | None, @@ -23,68 +23,133 @@ def serve( ), ] = None, port: Annotated[ - int, - typer.Option("--port", "-p", help="Port to serve on"), - ] = 8000, + int | None, + typer.Option( + "--port", + "-p", + help="Port to bind (default: ``port`` in openenv.yaml, else 8000)", + ), + ] = None, host: Annotated[ str, - typer.Option("--host", help="Host to bind to"), - ] = "0.0.0.0", + typer.Option("--host", help="Host interface to bind (local development only)"), + ] = "127.0.0.1", reload: Annotated[ bool, - typer.Option("--reload", help="Enable auto-reload on code changes"), + typer.Option("--reload", help="Enable autoreload (development)"), ] = False, ) -> None: """ - Serve an OpenEnv environment locally. - - TODO: This command is currently not implemented and has been deferred for later. + Run the environment FastAPI app on the host for local development. - Planned functionality: - - Run environment server locally without Docker - - Support multiple deployment modes (local, notebook, cluster) - - Auto-reload for development - - Integration with environment's [project.scripts] entry point + Uses ``openenv.yaml`` fields ``app`` (e.g. ``server.app:app``), ``port``, and + ``runtime`` (must be ``fastapi``). Matches ``uv run --project . server`` layout: + the environment directory is the working directory. Package-qualified app + paths also support the environment package and the repo's ``envs`` package. - For now, use Docker-based serving: - 1. Build the environment: openenv build - 2. Run the container: docker run -p 8000:8000 - - Or use uv directly: - uv run --project . server --port 8000 + For production or training, use Docker (``openenv build``) — this command runs + on the host for local development only. """ - console.print("[bold yellow]⚠ This command is not yet implemented[/bold yellow]\n") - - console.print( - "The [bold cyan]openenv serve[/bold cyan] command has been deferred for later." - ) - - console.print("[bold]Alternative approaches:[/bold]\n") + import uvicorn - console.print("[cyan]Option 1: Docker-based serving (recommended)[/cyan]") - console.print(" 1. Build the environment:") - console.print(" [dim]$ openenv build[/dim]") - console.print(" 2. Run the Docker container:") - console.print( - f" [dim]$ docker run -p {port}:{port} openenv-:latest[/dim]\n" + env_path_obj = ( + Path.cwd().resolve() if env_path is None else Path(env_path).resolve() ) - console.print("[cyan]Option 2: Direct execution with uv[/cyan]") - - # Determine environment path - if env_path is None: - env_path_obj = Path.cwd() - else: - env_path_obj = Path(env_path) - - # Check for openenv.yaml - openenv_yaml = env_path_obj / "openenv.yaml" - if openenv_yaml.exists(): - console.print(" From your environment directory:") - console.print(f" [dim]$ cd {env_path_obj}[/dim]") - console.print(f" [dim]$ uv run --project . server --port {port}[/dim]\n") - else: - console.print(" From an environment directory with pyproject.toml:") - console.print(f" [dim]$ uv run --project . server --port {port}[/dim]\n") - - raise typer.Exit(1) + if not env_path_obj.exists(): + typer.echo(f"Error: Path does not exist: {env_path_obj}", err=True) + raise typer.Exit(1) + + if not env_path_obj.is_dir(): + typer.echo(f"Error: Path is not a directory: {env_path_obj}", err=True) + raise typer.Exit(1) + + try: + validate_env_structure(env_path_obj) + except FileNotFoundError as exc: + raise typer.BadParameter(f"Not a valid OpenEnv environment: {exc}") from exc + + manifest_path = env_path_obj / "openenv.yaml" + try: + with manifest_path.open("r", encoding="utf-8") as handle: + manifest = yaml.safe_load(handle) + except OSError as exc: + raise typer.BadParameter(f"Failed to read openenv.yaml: {exc}") from exc + except yaml.YAMLError as exc: + raise typer.BadParameter(f"Invalid YAML in openenv.yaml: {exc}") from exc + + if not isinstance(manifest, dict): + raise typer.BadParameter("openenv.yaml must be a YAML dictionary") + + app_spec = manifest.get("app") + if not app_spec or not isinstance(app_spec, str): + raise typer.BadParameter( + "openenv.yaml must contain a string 'app' field (e.g. server.app:app)" + ) + if ":" not in app_spec: + raise typer.BadParameter( + f"openenv.yaml 'app' must look like 'module.path:attribute', got {app_spec!r}" + ) + + runtime = str(manifest.get("runtime", "fastapi")).lower() + if runtime != "fastapi": + raise typer.BadParameter( + f"openenv serve only supports runtime 'fastapi' (got {runtime!r})" + ) + + raw_port = port if port is not None else manifest.get("port", 8000) + try: + listen_port = int(raw_port) + except (TypeError, ValueError) as exc: + raise typer.BadParameter( + f"Invalid port {raw_port!r}; expected an integer" + ) from exc + if not (1 <= listen_port <= 65535): + raise typer.BadParameter( + f"Invalid port {listen_port}; expected a value between 1 and 65535" + ) + + original_path = list(sys.path) + prev_cwd = os.getcwd() + env_root = str(env_path_obj) + app_dir = env_path_obj + module_name = app_spec.split(":", 1)[0] + # Prefer a module inside the environment, even when its package name matches + # the environment directory (for example, /work/server/server/app.py). + local_module = env_path_obj.joinpath(*module_name.split(".")) + if not ( + local_module.with_suffix(".py").is_file() + or (local_module / "__init__.py").is_file() + ): + if env_path_obj.parent.name == "envs" and module_name.startswith( + f"envs.{env_path_obj.name}." + ): + app_dir = env_path_obj.parent.parent + elif module_name.startswith(f"{env_path_obj.name}."): + app_dir = env_path_obj.parent + + try: + os.chdir(env_root) + + console.print( + f"[bold green]Serving[/bold green] [cyan]{app_spec}[/cyan] on " + f"[bold]http://{host}:{listen_port}/[/bold] (cwd: {env_root})" + ) + + try: + uvicorn.run( + app_spec, + host=host, + port=listen_port, + reload=reload, + app_dir=str(app_dir), + ) + except OSError as exc: + typer.echo(f"Error: {exc}", err=True) + raise typer.Exit(1) from exc + finally: + try: + os.chdir(prev_cwd) + except OSError: + pass + sys.path[:] = original_path diff --git a/src/core/openenv/cli/commands/skills.py b/src/core/openenv/cli/commands/skills.py index 3c1c66930f4d3363d4ab4bf91fb4146bd1b2fc0b..8bb7fcd06a50ca1705da5e231af18feaf1d16408 100644 --- a/src/core/openenv/cli/commands/skills.py +++ b/src/core/openenv/cli/commands/skills.py @@ -38,7 +38,7 @@ _SKILL_TIPS = """ Use `openenv --help` for full flag reference. -Full CLI reference: https://huggingface.co/docs/openenv/reference/cli +Full CLI reference: https://openenv.github.io/OpenEnv/main/reference/cli """ CENTRAL_LOCAL = Path(".agents/skills") diff --git a/src/core/openenv/cli/commands/validate.py b/src/core/openenv/cli/commands/validate.py index 036cad3fe606d99f3d565a6ce6aa28c818bb7441..f4bcc831a77fc78ccfe9eb62da9362836b46bdb4 100644 --- a/src/core/openenv/cli/commands/validate.py +++ b/src/core/openenv/cli/commands/validate.py @@ -3,9 +3,13 @@ """OpenEnv validate command.""" import json +import shutil import signal +import tempfile import threading -from contextlib import contextmanager +from contextlib import contextmanager, ExitStack +from dataclasses import dataclass +from functools import cached_property from pathlib import Path from typing import Annotated, Any @@ -30,6 +34,39 @@ EXIT_UNSUPPORTED = 2 EXIT_INTERNAL = 3 +@dataclass +class _LazyHFSandboxProvider: + """Defer Jobs hardware preflight until the runner needs runtime capabilities.""" + + name = "hf-sandbox" + + space_id: str + revision: str + flavor: str + + @cached_property + def _provider(self): + from openenv.validation.providers.hf_sandbox import HFSandboxValidationProvider + + return HFSandboxValidationProvider( + self.space_id, self.revision, flavor=self.flavor + ) + + @property + def supported_network_modes(self): + return self._provider.supported_network_modes + + @property + def capabilities(self): + return self._provider.capabilities + + def build(self, root, execution): + return self._provider.build(root, execution) + + def start(self, spec): + return self._provider.start(spec) + + @contextmanager def _sigterm_as_interrupt(): """Treat SIGTERM like Ctrl-C so the runner cleans up its subject.""" @@ -168,15 +205,63 @@ def validate( min=0.1, ), ] = 5.0, + space: Annotated[ + str | None, + typer.Option( + "--space", + help="Validate a Hugging Face Space (e.g. openenv/echo_env) on HF Jobs", + ), + ] = None, + revision: Annotated[ + str | None, + typer.Option( + "--revision", + help="Space branch, tag or commit hash to validate (default: main)", + ), + ] = None, + flavor: Annotated[ + str, + typer.Option( + "--flavor", + help=( + "HF Jobs hardware flavor for --space or --sandbox hf-sandbox, " + "e.g. cpu-basic or t4-small" + ), + ), + ] = "cpu-basic", + sandbox: Annotated[ + str, + typer.Option( + "--sandbox", + help=( + "Where Harbor task trials run: docker (local daemon) or " + "hf-sandbox (one HF Job per trial)" + ), + ), + ] = "docker", + namespace: Annotated[ + str | None, + typer.Option( + "--namespace", + help="User or organization that owns the --sandbox hf-sandbox jobs", + ), + ] = None, ) -> None: """ Validate a local package or a running OpenEnv server. Local validation detects the package format by its well-known file (the - formats this build can parse; currently `openenv.yaml`), parses it into the + formats this build can parse: `openenv.yaml` or Harbor `task.toml`), parses it into the normalized manifest, runs the applicable graders up to the requested level, applies the severity policy, and emits a report. + Native Harbor tasks require the optional Harbor dependency and an explicit + `validation/openenv.json` contract. Fresh trials grade the oracle, the + do-nothing floor and any declared canaries under the semantic check ids. They + run on the local Docker daemon, or with `--sandbox hf-sandbox` as one Hugging + Face Job per trial from the task's digest-pinned image. Checks without an + implementation are named SKIPs, so the report is WARN at best. + Exit codes: 0 pass/warn · 1 fail · 2 unrecognized/unsupported package · 3 internal or policy error. @@ -194,8 +279,43 @@ def validate( # Probe a running server (legacy runtime probe) openenv validate --url http://localhost:8000 + + # Validate a Hub Space on HF Jobs GPU hardware + openenv validate --space openenv/echo_env --level runtime --flavor t4-small + + # Run a Harbor task's trials as HF Jobs instead of local Docker + openenv validate path/to/task --sandbox hf-sandbox --flavor cpu-upgrade ``` """ + if space is not None and (target is not None or url is not None or local): + typer.echo( + "Error: --space cannot be combined with a path, --url or --local", err=True + ) + raise typer.Exit(EXIT_FAIL) + if sandbox not in ("docker", "hf-sandbox"): + typer.echo( + f"Error: unknown sandbox {sandbox!r}; expected docker or hf-sandbox", + err=True, + ) + raise typer.Exit(EXIT_FAIL) + hf_sandbox = sandbox == "hf-sandbox" + running_url = url is not None or (target is not None and _looks_like_url(target)) + if hf_sandbox and (space is not None or running_url): + typer.echo( + "Error: --sandbox cannot be combined with --space or a running URL", + err=True, + ) + raise typer.Exit(EXIT_FAIL) + if space is None and revision is not None: + typer.echo("Error: --revision requires --space", err=True) + raise typer.Exit(EXIT_FAIL) + if space is None and not hf_sandbox and flavor != "cpu-basic": + typer.echo("Error: --flavor requires --space or --sandbox hf-sandbox", err=True) + raise typer.Exit(EXIT_FAIL) + if namespace is not None and not hf_sandbox: + typer.echo("Error: --namespace requires --sandbox hf-sandbox", err=True) + raise typer.Exit(EXIT_FAIL) + runtime_target = url if ( runtime_target is not None @@ -249,22 +369,52 @@ def validate( raise typer.Exit(EXIT_INTERNAL) package_root = Path(target) if target is not None else Path.cwd() - if not package_root.is_dir(): + if space is None and not package_root.is_dir(): typer.echo(f"Error: not a package directory: {package_root}", err=True) raise typer.Exit(EXIT_UNSUPPORTED) try: if output is not None and not output.parent.is_dir(): raise OSError("report output directory does not exist") - with _sigterm_as_interrupt(): + with ExitStack() as stack: + provider = None + if space is not None: + from huggingface_hub import HfApi, snapshot_download + + # Download and report one commit, even if a branch moves. + revision = ( + HfApi() + .space_info( + space, revision="main" if revision is None else revision + ) + .sha + ) + package_root = ( + Path(stack.enter_context(tempfile.TemporaryDirectory())) / "source" + ) + # Copy the repository snapshot out of the SDK cache, dereferencing + # its blob links without adding local_dir download metadata. + shutil.copytree( + snapshot_download(space, repo_type="space", revision=revision), + package_root, + ) + provider = _LazyHFSandboxProvider(space, revision, flavor) + stack.enter_context(_sigterm_as_interrupt()) validation_report = run_validation( package_root, max_level=_LEVELS[level], skip_build=skip_build, policy=load_policy(policy_version) if policy_version else None, + provider=provider, artifacts_dir=( output.parent / (output.stem + ".artifacts") if output else None ), + report_target=f"spaces/{space}@{revision}" + if space is not None + else None, + sandbox=sandbox, + flavor=flavor, + namespace=namespace, ) report_json = write_report(validation_report, output) except (SignatureError, UnsupportedPackageError) as exc: diff --git a/src/core/openenv/cli/importers/__init__.py b/src/core/openenv/cli/importers/__init__.py index 9519278cfd4ace6e172fe9226fa4df37049663a1..ba216e89716a07224f4d2be8aeccda5385fed726 100644 --- a/src/core/openenv/cli/importers/__init__.py +++ b/src/core/openenv/cli/importers/__init__.py @@ -1,12 +1,14 @@ """Deterministic source importers for OpenEnv environments.""" +from .agentenv import AgentEnvImporter from .base import DetectedEnvironment, EnvironmentImporter, ImporterRegistry from .ors import ORSImporter from .verifiers import VerifiersImporter -DEFAULT_IMPORTERS = [ORSImporter(), VerifiersImporter()] +DEFAULT_IMPORTERS = [ORSImporter(), VerifiersImporter(), AgentEnvImporter()] __all__ = [ + "AgentEnvImporter", "DEFAULT_IMPORTERS", "DetectedEnvironment", "EnvironmentImporter", diff --git a/src/core/openenv/cli/importers/agentenv.py b/src/core/openenv/cli/importers/agentenv.py new file mode 100644 index 0000000000000000000000000000000000000000..05d8d3694b1637758d08acf85632f8fdd09e779e --- /dev/null +++ b/src/core/openenv/cli/importers/agentenv.py @@ -0,0 +1,163 @@ +"""AgentEnv bundle source importer.""" + +from __future__ import annotations + +import json +from pathlib import Path + +from packaging.requirements import InvalidRequirement, Requirement +from packaging.specifiers import SpecifierSet +from packaging.utils import canonicalize_name + +from .._cli_utils import console +from .base import ( + append_dependency_files, + collect_source_dependencies, + DetectedEnvironment, + iter_directories, + prepare_import_package, + render_importer_template, + write_text, +) + + +_FRAMEWORK = "agentenv-framework" +_FRAMEWORK_EXTRA = "openenv" +_FRAMEWORK_VERSION = "0.9.1366" +_FRAMEWORK_FLOOR = f">={_FRAMEWORK_VERSION}" +_ADAPTER_SOURCE = ( + "https://github.com/scaleapi/agentenv-framework/blob/" + f"v{_FRAMEWORK_VERSION}/src/agent_env/openenv" +) +_REQUIRES_PYTHON = ">=3.11.4" + + +def _is_task_file(path: Path) -> bool: + try: + steps = json.loads(path.read_text(encoding="utf-8")) + except (OSError, UnicodeDecodeError, ValueError): + return False + return ( + isinstance(steps, list) + and bool(steps) + and all( + isinstance(step, dict) + and isinstance(step.get("id"), str) + and isinstance(step.get("type"), str) + for step in steps + ) + ) + + +def detect_agentenv_bundles(source: Path) -> list[DetectedEnvironment]: + """Detect AgentEnv bundles, folders whose tasks/ holds task files, without importing source.""" + source = source.resolve() + matches: list[DetectedEnvironment] = [] + + for tasks_dir in iter_directories(source, "tasks"): + if not any(_is_task_file(path) for path in sorted(tasks_dir.glob("*.json"))): + continue + bundle = tasks_dir.parent + matches.append( + DetectedEnvironment( + source_type="agentenv", + class_name=bundle.name, + module_path="" + if bundle == source + else bundle.relative_to(source).as_posix(), + file_path=bundle, + ) + ) + + return matches + + +def _with_framework_floor(dependencies: list[str]) -> list[str]: + """The bundle's dependencies, with agentenv-framework's openenv extra at least the version that serves bundles.""" + for index, dependency in enumerate(dependencies): + try: + requirement = Requirement(dependency) + except InvalidRequirement: + continue + if canonicalize_name(requirement.name) == _FRAMEWORK: + if requirement.url is not None: + raise ValueError( + f"Cannot verify {_FRAMEWORK}{_FRAMEWORK_FLOOR} from a direct " + "reference. In the bundle's pyproject.toml or requirements.txt, " + "replace the framework direct reference with a version constraint " + f"such as {_FRAMEWORK}[{_FRAMEWORK_EXTRA}]{_FRAMEWORK_FLOOR}, " + "preserving any additional extras and environment marker." + ) + requirement.extras.add(_FRAMEWORK_EXTRA) + requirement.specifier &= SpecifierSet(_FRAMEWORK_FLOOR) + dependencies[index] = str(requirement) + return dependencies + return [*dependencies, f"{_FRAMEWORK}[{_FRAMEWORK_EXTRA}]{_FRAMEWORK_FLOOR}"] + + +class AgentEnvImporter: + """Importer for AgentEnv bundles, served by agentenv-framework's OpenEnv server.""" + + source_type = "agentenv" + + def detect(self, source: Path) -> list[DetectedEnvironment]: + return detect_agentenv_bundles(source) + + def generate( + self, + *, + source: Path, + destination: Path, + env_name: str, + detected: DetectedEnvironment, + ) -> None: + bundle = detected.file_path + dependencies = _with_framework_floor(collect_source_dependencies(bundle)) + package = prepare_import_package( + bundle, destination, env_name, vendor_dir=bundle.name + ) + client = f"{package.class_name_prefix}Env" + (destination / "server" / f"{env_name}_environment.py").unlink() + (destination / "models.py").unlink() + for name, template in ( + ("client.py", "agentenv_client.py.tpl"), + ("__init__.py", "agentenv_init.py.tpl"), + ): + write_text( + destination / name, + render_importer_template(template, env_name=env_name, client=client), + ) + write_text( + destination / "server" / "__init__.py", + f'"""{env_name} environment server: an AgentEnv bundle."""\n', + ) + write_text( + destination / "server" / "app.py", + render_importer_template( + "agentenv_app.py.tpl", bundle=json.dumps(bundle.name) + ), + ) + write_text( + destination / "README.md", + render_importer_template( + "agentenv_README.md.tpl", + env_name=env_name, + bundle=bundle.name, + framework=f"{_FRAMEWORK}[{_FRAMEWORK_EXTRA}]{_FRAMEWORK_FLOOR}", + adapter=_ADAPTER_SOURCE, + client=client, + ), + ) + console.print( + "[yellow]Warning:[/yellow] AgentEnv requires local Docker: a Docker CLI " + "and a running daemon accessible to the server for image builds and episode " + "containers. The generated server/Dockerfile does not provide this " + "runtime; openenv build / openenv push alone do not produce a working " + "deployment. See README.md for prerequisites." + ) + append_dependency_files( + destination, + env_name, + dependencies, + requires_python=_REQUIRES_PYTHON, + ) diff --git a/src/core/openenv/cli/importers/base.py b/src/core/openenv/cli/importers/base.py index f106af091ec49f087e6de0cc355e4154e209a541..ab2209b054be1e14e8e9f320a19548a2b715bacb 100644 --- a/src/core/openenv/cli/importers/base.py +++ b/src/core/openenv/cli/importers/base.py @@ -133,6 +133,14 @@ def iter_python_files(source: Path) -> list[Path]: ] +def iter_directories(source: Path, name: str) -> list[Path]: + return [ + path + for path in sorted(source.rglob(name)) + if path.is_dir() and not _is_excluded(path.relative_to(source)) + ] + + def module_path(source: Path, file_path: Path) -> str: rel = file_path.relative_to(source).with_suffix("") parts = list(rel.parts) @@ -196,6 +204,7 @@ def append_dependency_files( env_dir: Path, env_name: str, dependencies: list[str], + requires_python: str | None = None, ) -> None: requirements = env_dir / "server" / "requirements.txt" if requirements.exists(): @@ -231,6 +240,8 @@ def append_dependency_files( project_dependencies.append(dependency) existing.add(_dependency_name(dependency)) project["dependencies"] = project_dependencies + if requires_python: + project["requires-python"] = requires_python tool = data.setdefault("tool", {}) setuptools = tool.setdefault("setuptools", {}) @@ -266,7 +277,7 @@ class ImportPackageContext: def prepare_import_package( - source: Path, destination: Path, env_name: str + source: Path, destination: Path, env_name: str, vendor_dir: str | None = None ) -> ImportPackageContext: from openenv.cli.commands.init import ( _copy_template_directory, @@ -282,7 +293,7 @@ def prepare_import_package( env_name, ) - vendor_dir = safe_vendor_dir_name(source) + vendor_dir = vendor_dir or safe_vendor_dir_name(source) vendor_path = destination / "vendor" / vendor_dir copy_source_tree(source, vendor_path) ensure_vendor_package(vendor_path) diff --git a/src/core/openenv/cli/importers/templates/agentenv_README.md.tpl b/src/core/openenv/cli/importers/templates/agentenv_README.md.tpl new file mode 100644 index 0000000000000000000000000000000000000000..f2ad1c69d780a6bade33d05ae7c15a7a8d693fed --- /dev/null +++ b/src/core/openenv/cli/importers/templates/agentenv_README.md.tpl @@ -0,0 +1,82 @@ +# ${env_name}: AgentEnv bundle + +This package serves the vendored `${bundle}` bundle through +`agent_env.openenv.build_app`. The bundle keeps its original folder name at +`vendor/${bundle}`; the generated package name is `${env_name}`. + +## Prerequisites + +- Python >=3.11.4 and `${framework}` (declared in + `pyproject.toml` and `server/requirements.txt`). +- Local Docker: a Docker CLI and a running daemon accessible to the server. + The delegated server builds the bundle's environment images at startup and + deploys episode containers using local Docker by default. +- A self-contained bundle: tasks, environment definitions, verifiers, data and + dependencies must be included in the bundle or provided by agentenv-framework. + Only the selected bundle is vendored; external plugin registrations and files + elsewhere in the source repository are not included. + +## Run locally + +From this generated package directory, after setting up Docker: + +```bash +uv sync +MAX_CONCURRENT_ENVS=8 uv run server --host 127.0.0.1 --port 8000 +``` + +`MAX_CONCURRENT_ENVS` (default 8) caps the concurrent sessions. Each session +plays its own episode on its own deployment. + +The `server` entry point runs `server/app.py`, which passes +`vendor/${bundle}` to `build_app`. Task selection, splits, tools and rewards +are defined by the bundle and agentenv-framework. The served environment is +`agent_env.openenv`'s `AgentEnvEnvironment`; read it, and `build_app`, at the +minimum supported version: [environment.py](${adapter}/environment.py) and +[app.py](${adapter}/app.py). Follow +[AgentEnv's OpenEnv documentation](https://www.agentenvframework.com/docs/openenv) +for its API and client usage. + +## Client + +`client.py` defines `${client}`, an `MCPToolClient`: the served environment +takes OpenEnv's MCP actions (`ListToolsAction`, `CallToolAction`), which +`__init__.py` also exports. + +```python +from ${env_name} import ${client} + +async with ${client}(base_url="http://127.0.0.1:8000") as env: + await env.reset(split="all", index=0) + tools = await env.list_tools() + ended = await env.call_tool("end_turn", response="Done.") + print(ended["done"], ended["reward"]) +``` + +The tools are the bundle environment's MCP tools plus `end_turn`, which ends +the turn with its `response`. Its result carries the next turn's prompt, or, +once `done`, the task's reward. A step before `reset` raises. + +`list_tools()` discovers fresh tools by default because tools can change after +reset, `end_turn`, or a bundle tool call. `get_tool()` and `has_tool()` also use +fresh discovery. Pass `list_tools(use_cache=True)` explicitly to reuse the last +discovery result. + +## Deployment limitations + +**Warning:** `server/Dockerfile` does not provide the Docker runtime required +by the delegated server. `openenv build` / `openenv push` alone do not produce +a working deployment, including on Hugging Face Spaces. Deployment requires +separately provisioning the server's image-build and episode-container runtime; +this importer does not configure it. Review AgentEnv's runtime requirements +before choosing a deployment host. + +## Generated files + +- `server/app.py`: delegated application and local server entry point. +- `vendor/${bundle}`: the selected bundle and its data. +- `pyproject.toml`: package dependencies and the `server` entry point. +- `server/requirements.txt`: server dependencies. +- `openenv.yaml`: generated OpenEnv manifest. +- `server/Dockerfile`: shared image template with the limitation described above. +- `client.py`, `__init__.py`: the client and the MCP action types it sends. diff --git a/src/core/openenv/cli/importers/templates/agentenv_app.py.tpl b/src/core/openenv/cli/importers/templates/agentenv_app.py.tpl new file mode 100644 index 0000000000000000000000000000000000000000..4ea4d0b60089df4444676707060f901acaf2bde8 --- /dev/null +++ b/src/core/openenv/cli/importers/templates/agentenv_app.py.tpl @@ -0,0 +1,29 @@ +from __future__ import annotations + +import os +from pathlib import Path + +from agent_env.openenv import build_app + + +BUNDLE = Path(__file__).resolve().parents[1] / "vendor" / ${bundle} + +app = build_app( + BUNDLE, max_concurrent_envs=int(os.getenv("MAX_CONCURRENT_ENVS", "8")) +) + + +def main(): + import argparse + + import uvicorn + + parser = argparse.ArgumentParser() + parser.add_argument("--host", default="0.0.0.0") + parser.add_argument("--port", type=int, default=8000) + args = parser.parse_args() + uvicorn.run(app, host=args.host, port=args.port) + + +if __name__ == "__main__": + main() diff --git a/src/core/openenv/cli/importers/templates/agentenv_client.py.tpl b/src/core/openenv/cli/importers/templates/agentenv_client.py.tpl new file mode 100644 index 0000000000000000000000000000000000000000..c98c527b1accb2377cf2a430a4db4eb4d81b2b60 --- /dev/null +++ b/src/core/openenv/cli/importers/templates/agentenv_client.py.tpl @@ -0,0 +1,29 @@ +"""${env_name} client. + +The served AgentEnv bundle takes OpenEnv's MCP actions, so this client is an +``MCPToolClient``. Reset to a task, call the bundle's tools, and end each turn +with ``end_turn``. Its result carries the next turn's prompt, or once ``done`` +the task's reward: + + >>> async with ${client}(base_url="http://localhost:8000") as env: + ... await env.reset(split="all", index=0) + ... tools = await env.list_tools() + ... ended = await env.call_tool("end_turn", response="Done.") + ... print(ended["done"], ended["reward"]) +""" + +from openenv.core.env_server.mcp_types import Tool +from openenv.core.mcp_client import MCPToolClient + + +class ${client}(MCPToolClient): + """Client for the ${env_name} environment.""" + + async def list_tools(self, use_cache: bool = False) -> list[Tool]: + """Discover the current task and turn's tools. + + Args: + use_cache (`bool`, *optional*, defaults to `False`): + Set to `True` to reuse the last discovery result. + """ + return await super().list_tools(use_cache=use_cache) diff --git a/src/core/openenv/cli/importers/templates/agentenv_init.py.tpl b/src/core/openenv/cli/importers/templates/agentenv_init.py.tpl new file mode 100644 index 0000000000000000000000000000000000000000..860105f5b3a5df1b693db33e3b161969bc82565f --- /dev/null +++ b/src/core/openenv/cli/importers/templates/agentenv_init.py.tpl @@ -0,0 +1,7 @@ +"""${env_name} environment: an AgentEnv bundle served through agentenv-framework.""" + +from openenv.core.env_server.mcp_types import CallToolAction, ListToolsAction + +from .client import ${client} + +__all__ = ["${client}", "CallToolAction", "ListToolsAction"] diff --git a/src/core/openenv/cli/templates/openenv_env/README.md b/src/core/openenv/cli/templates/openenv_env/README.md index 24a51add9c9eedde5435ae4c03ad180a1fe6d7f9..e9b425d0f60bb070b7b346ccf88082d1da9bfd95 100644 --- a/src/core/openenv/cli/templates/openenv_env/README.md +++ b/src/core/openenv/cli/templates/openenv_env/README.md @@ -253,6 +253,8 @@ __ENV_NAME__/ ├── uv.lock # Locked dependencies (generated) ├── client.py # __ENV_CLASS_NAME__Env client ├── models.py # Action and Observation models +├── validation/ +│ └── runtime.json # Replay plan for `openenv validate --level runtime` └── server/ ├── __init__.py # Server module exports ├── __ENV_NAME___environment.py # Core environment logic diff --git a/src/core/openenv/cli/templates/openenv_env/openenv.yaml b/src/core/openenv/cli/templates/openenv_env/openenv.yaml index 70d59278d87ea1e9ea257e4699cd5f1e6322a0c6..e0ea9dade44430109787f09a8834892efb7356fe 100644 --- a/src/core/openenv/cli/templates/openenv_env/openenv.yaml +++ b/src/core/openenv/cli/templates/openenv_env/openenv.yaml @@ -6,6 +6,11 @@ runtime: fastapi app: server.app:app port: 8000 validation: + execution: + kind: openenv_ws + probe_path: validation/runtime.json + dockerfile: server/Dockerfile + context: . reward: range: [0.0, 1.0] oracle_tolerance: 0.0 diff --git a/src/core/openenv/cli/templates/openenv_env/pyproject.toml b/src/core/openenv/cli/templates/openenv_env/pyproject.toml index c8da6c3bee44a88ec38bdda440f19d6c6ecb36c2..a0624cd2220f5563683e4aa0604b557005487052 100644 --- a/src/core/openenv/cli/templates/openenv_env/pyproject.toml +++ b/src/core/openenv/cli/templates/openenv_env/pyproject.toml @@ -12,7 +12,7 @@ requires-python = ">=3.10" dependencies = [ # Core OpenEnv runtime (provides FastAPI server + HTTP client types) # install from github - # "openenv @ git+https://github.com/huggingface/OpenEnv.git", + # "openenv @ git+https://github.com/openenv/OpenEnv.git", "openenv>=0.2.2", # Environment-specific dependencies # Add all dependencies needed for your environment here diff --git a/src/core/openenv/cli/templates/openenv_env/server/Dockerfile b/src/core/openenv/cli/templates/openenv_env/server/Dockerfile index 947a379621678def8cd68b93b45734657566873b..4bcd055350c3d89ba2f9ad64dddba2ddd9e01f67 100644 --- a/src/core/openenv/cli/templates/openenv_env/server/Dockerfile +++ b/src/core/openenv/cli/templates/openenv_env/server/Dockerfile @@ -84,4 +84,5 @@ HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \ # Run the FastAPI server # The module path is constructed to work with the /app/env structure -CMD ["sh", "-c", "cd /app/env && uvicorn server.app:app --host 0.0.0.0 --port 8000"] +# exec makes the server PID 1, so it gets SIGTERM from `docker stop` and shuts down cleanly +CMD ["sh", "-c", "cd /app/env && exec uvicorn server.app:app --host 0.0.0.0 --port 8000"] diff --git a/src/core/openenv/cli/templates/openenv_env/server/app.py b/src/core/openenv/cli/templates/openenv_env/server/app.py index 988d1f93b574319b717addbf4edfd4633e61226c..afb9d3565bb83554c97d52bc849611bf9f47bfa8 100644 --- a/src/core/openenv/cli/templates/openenv_env/server/app.py +++ b/src/core/openenv/cli/templates/openenv_env/server/app.py @@ -10,7 +10,7 @@ Endpoints: - POST /reset: Reset the environment - POST /step: Execute an action - GET /state: Get current environment state - - GET /schema: Get action/observation schemas + - GET /schema: Get action/observation/state/reset schemas - WS /ws: WebSocket endpoint for persistent sessions Usage: diff --git a/src/core/openenv/cli/templates/openenv_env/validation/runtime.json b/src/core/openenv/cli/templates/openenv_env/validation/runtime.json new file mode 100644 index 0000000000000000000000000000000000000000..2f3c181a8097917f99516c404ba848e1ccdf2c33 --- /dev/null +++ b/src/core/openenv/cli/templates/openenv_env/validation/runtime.json @@ -0,0 +1,8 @@ +{ + "plan_schema_version": "1", + "reset": {"episode_id": "__ENV_NAME__-smoke", "seed": 0}, + "actions": [ + {"message": "Hello"}, + {"message": "Hello, World!"} + ] +} diff --git a/src/core/openenv/core/README.md b/src/core/openenv/core/README.md index 0caa1bed7a0684b2eb822b05d18df1f48209c930..d5e098767963de732725e46784ef36ef71ad2e0f 100644 --- a/src/core/openenv/core/README.md +++ b/src/core/openenv/core/README.md @@ -165,14 +165,14 @@ provider.wait_for_ready(base_url) provider.stop_container() ``` -### Kubernetes Provider (Coming Soon) +### Kubernetes Provider ```python -from openenv.core.containers.runtime import KubernetesProvider +from openenv.core.containers.runtime.kubernetes_provider import KubernetesProvider provider = KubernetesProvider(namespace="envs") base_url = provider.start_container("my-env:latest") -# Use environment... +provider.wait_for_ready(base_url) provider.stop_container() ``` @@ -232,6 +232,6 @@ Contributions are welcome! Please see the main OpenEnv repository for contributi ## Links -- **Homepage**: https://github.com/huggingface/OpenEnv -- **Documentation**: https://github.com/huggingface/OpenEnv/blob/main/README.md -- **Bug Tracker**: https://github.com/huggingface/OpenEnv/issues +- **Homepage**: https://github.com/openenv/OpenEnv +- **Documentation**: https://github.com/openenv/OpenEnv/blob/main/README.md +- **Bug Tracker**: https://github.com/openenv/OpenEnv/issues diff --git a/src/core/openenv/core/__init__.py b/src/core/openenv/core/__init__.py index b365f5ff730e07d626068c3c6ac1053c3811a2f0..1f62b60f6f3b9de01af8463c6fa153229c8ec789 100644 --- a/src/core/openenv/core/__init__.py +++ b/src/core/openenv/core/__init__.py @@ -11,7 +11,7 @@ from . import env_server from .env_server import * # noqa: F403 if TYPE_CHECKING: - from .env_client import EnvClient + from .env_client import EnvClient, SessionLostError from .generic_client import GenericAction, GenericEnvClient from .llm_client import ( AnthropicClient, @@ -26,6 +26,7 @@ if TYPE_CHECKING: __all__ = [ "EnvClient", + "SessionLostError", "SyncEnvClient", "GenericEnvClient", "GenericAction", @@ -42,6 +43,7 @@ __all__ = [ _LAZY_ATTRS = { "EnvClient": (".env_client", "EnvClient"), + "SessionLostError": (".env_client", "SessionLostError"), "SyncEnvClient": (".sync_client", "SyncEnvClient"), "GenericEnvClient": (".generic_client", "GenericEnvClient"), "GenericAction": (".generic_client", "GenericAction"), diff --git a/src/core/openenv/core/containers/runtime/__init__.py b/src/core/openenv/core/containers/runtime/__init__.py index 9a3ce762257cb409cbccece4bb08465d43d438da..16caec4c81a593e3579337edc78226db25f1e828 100644 --- a/src/core/openenv/core/containers/runtime/__init__.py +++ b/src/core/openenv/core/containers/runtime/__init__.py @@ -5,7 +5,6 @@ from .providers import ( ContainerProvider, DockerSwarmProvider, - KubernetesProvider, LocalDockerProvider, RuntimeProvider, ) @@ -20,7 +19,6 @@ __all__ = [ "ContainerProvider", "DockerSwarmProvider", "LocalDockerProvider", - "KubernetesProvider", "RuntimeProvider", "UVProvider", ] diff --git a/src/core/openenv/core/containers/runtime/_server_config.py b/src/core/openenv/core/containers/runtime/_server_config.py index 8eb3f96d60b57b16057946ef80186454bda26224..aff5fff74ec948fd272014e3c5d12176a92752ad 100644 --- a/src/core/openenv/core/containers/runtime/_server_config.py +++ b/src/core/openenv/core/containers/runtime/_server_config.py @@ -30,11 +30,48 @@ def parse_openenv_app_field(yaml_content: str) -> str | None: def parse_dockerfile_cmd(dockerfile_content: str) -> str | None: """Extract the server command from the last Dockerfile ``CMD``.""" last_cmd: str | None = None + instruction = "" + escape = "\\" + directives = True for line in dockerfile_content.splitlines(): - stripped = line.strip() + stripped = line.lstrip() if stripped.startswith("#"): + if directives: + directive = re.fullmatch( + r"#\s*(syntax|check|escape)\s*=\s*(.+)", + stripped, + flags=re.IGNORECASE, + ) + if directive is None: + directives = False + elif directive[1].lower() == "escape" and directive[2].strip() in ( + "\\", + "`", + ): + escape = directive[2].strip() continue - match = re.match(r"CMD\s+(.+)", stripped, flags=re.IGNORECASE) + if not stripped.strip(): + directives = False + continue + directives = False + if not instruction: + match = re.match(r"\s*CMD\s+(.+)", line, flags=re.IGNORECASE) + if match: + last_cmd = match.group(1).strip() + continuation = re.search( + rf"(?=0.10`` +Requires the ``daytona`` SDK: ``pip install 'daytona>=0.10,<1'`` """ from __future__ import annotations diff --git a/src/core/openenv/core/containers/runtime/hf_sandbox_provider.py b/src/core/openenv/core/containers/runtime/hf_sandbox_provider.py index 05d6ce250f69b3e271ca9852a475546bfa174c90..112e0297c81d1492def0fa04aace5fb0d9adda2f 100644 --- a/src/core/openenv/core/containers/runtime/hf_sandbox_provider.py +++ b/src/core/openenv/core/containers/runtime/hf_sandbox_provider.py @@ -10,6 +10,7 @@ from __future__ import annotations import asyncio import hashlib +import logging import socket import threading import time @@ -24,6 +25,8 @@ from websockets.exceptions import ConnectionClosed from .providers import ContainerProvider +logger = logging.getLogger(__name__) + _DEFAULT_PORT = 8000 _SERVER_COMMAND = ( 'export SBX_PROXY_DIR="${SBX_PROXY_DIR:-$HOME/.sbx/proxy}"; ' @@ -95,6 +98,17 @@ def _get_pool(image: str, flavor: str) -> Any: class _LocalAuthProxy: + """Loopback proxy that adds the HF auth headers to every request. + + Copied into agent_sandbox_provider._LocalAuthProxy; keep the copies + aligned. + + Limitations: bodies are buffered (a streamed upstream response such as + SSE is withheld until it ends), only JSON text frames are relayed + upstream (binary client frames and close codes are not forwarded), and + upstream redirects are rejected. EnvClient uses none of these. + """ + def __init__(self, *, target_url: str, headers: dict[str, str]): self.target_url = target_url.rstrip("/") self.headers = headers @@ -131,13 +145,20 @@ class _LocalAuthProxy: data=body, headers=headers, timeout=60.0, - allow_redirects=True, + allow_redirects=False, ) except requests.RequestException: return Response( content=b"upstream HF job unreachable", status_code=502, ) + if 300 <= upstream.status_code < 400: + # Following a redirect would replay the body and the injected + # headers to another origin and could downgrade https to http. + return Response( + content=b"upstream HF job redirected; rejected", + status_code=502, + ) response_headers = { key: value for key, value in upstream.headers.items() @@ -156,7 +177,16 @@ class _LocalAuthProxy: if query: target = f"{target}?{query}" headers = {**self.headers, "accept": "*/*"} - upstream = await self._connect_upstream_websocket(target, headers) + try: + upstream = await self._connect_upstream_websocket(target, headers) + except Exception: + # Never propagate the upstream exception: its message can embed + # the target URL, which may carry credentials. Deny generically + # instead. + logger.warning("HF sandbox WebSocket upstream handshake failed") + with suppress(Exception): + await websocket.close(code=1011) + return await websocket.accept() try: to_upstream = asyncio.create_task( @@ -201,13 +231,18 @@ class _LocalAuthProxy: ) -> Any: last_error: Exception | None = None for _ in range(5): + connector = ws_connect( + target, + additional_headers=headers, + max_size=_MAX_WS_MESSAGE_SIZE, + compression=None, + ) + # Never follow handshake redirects: websockets replays + # additional_headers to the redirect target, which would leak the + # auth headers to another origin. + connector.process_redirect = lambda exc: exc try: - return await ws_connect( - target, - additional_headers=headers, - max_size=_MAX_WS_MESSAGE_SIZE, - compression=None, - ) + return await connector except Exception as exc: last_error = exc await asyncio.sleep(0.5) @@ -227,10 +262,18 @@ class _LocalAuthProxy: await websocket.send_text(message) def stop(self) -> None: + """Shut the proxy down. Raises `RuntimeError` if the thread will not + exit; the handles are then retained so a later call can retry, instead + of silently leaking a thread that keeps the loopback port bound.""" if self._server is None or self._thread is None: return self._server.should_exit = True + # Bound the graceful drain: do not wait out long-lived upstream + # responses that would outlive the 5s join below. + self._server.force_exit = True self._thread.join(timeout=5.0) + if self._thread.is_alive(): + raise RuntimeError("HF sandbox auth proxy did not stop") self._server = None self._thread = None @@ -272,8 +315,11 @@ class HFSandboxProvider(ContainerProvider): env_vars: dict[str, str] | None = None, **kwargs: Any, ) -> str: - if self._sandbox is not None: - raise RuntimeError("HFSandboxProvider already has an active service") + if self._sandbox is not None or self._proxy is not None: + raise RuntimeError( + "HFSandboxProvider already has an active service, or a proxy " + "still awaits cleanup. Call stop_container() first." + ) if kwargs: unsupported = ", ".join(sorted(kwargs)) raise ValueError( @@ -311,14 +357,20 @@ class HFSandboxProvider(ContainerProvider): raise def stop_container(self) -> None: + proxy_error: RuntimeError | None = None if self._proxy is not None: - self._proxy.stop() - self._proxy = None + try: + self._proxy.stop() + self._proxy = None + except RuntimeError as exc: + proxy_error = exc if self._sandbox is not None: sandbox = self._sandbox self._sandbox = None with suppress(Exception): sandbox.kill() + if proxy_error is not None: + raise proxy_error def wait_for_ready(self, base_url: str, timeout_s: float = 120.0) -> None: deadline = time.time() + timeout_s diff --git a/src/core/openenv/core/containers/runtime/kubernetes_provider.py b/src/core/openenv/core/containers/runtime/kubernetes_provider.py new file mode 100644 index 0000000000000000000000000000000000000000..94652b1b53404ea79a0eec99c89f2c9bf60e2f36 --- /dev/null +++ b/src/core/openenv/core/containers/runtime/kubernetes_provider.py @@ -0,0 +1,985 @@ +# SPDX-License-Identifier: BSD-3-Clause + +""" +Kubernetes container provider for running OpenEnv environments in-cluster. + +Requires the ``kubernetes`` client: ``pip install openenv[kubernetes]`` + +One provider instance owns one Pod and one Service, matching +``LocalDockerProvider`` owning one container. The returned ``base_url`` is the +short in-cluster Service address ``http://{name}.{namespace}:{port}``. Pod DNS +search completes that to the cluster domain, so the provider does not hardcode +``.svc.cluster.local``. That plaintext URL is the in-cluster exception +confirmed for this provider: ``ModalProvider`` and ``ACASandboxProvider`` still +refuse non-HTTPS tunnel URLs. This provider never returns a URL it did not +construct from a validated name, namespace, and port, and it does not copy +that URL or raw API bodies into errors. +""" + +from __future__ import annotations + +import re +import secrets +import time +from typing import Any, Mapping, Optional + +from .providers import ContainerProvider + +_CONTAINER_PORT = 8000 +_CONTAINER_NAME = "env" +_DEFAULT_NAMESPACE = "default" +_NAME_PREFIX = "openenv-" + +# ``openenv-`` + slug + ``-`` + millisecond timestamp + ``-`` + 4 hex chars. +_SLUG_MAX = 32 + +_DNS_LABEL = re.compile(r"^[a-z0-9]([-a-z0-9]*[a-z0-9])?$") +_LABEL_NAME = re.compile(r"^[A-Za-z0-9]([A-Za-z0-9_.-]{0,61}[A-Za-z0-9])?$") +_LABEL_VALUE = re.compile(r"^([A-Za-z0-9]([A-Za-z0-9_.-]{0,61}[A-Za-z0-9])?)?$") +_SAFE_REASON = re.compile(r"^[A-Za-z][A-Za-z0-9]{0,63}$") + +# Applied last so a caller-supplied label cannot drop ownership or retarget +# the Service selector. +_SELECTOR_KEY = "app.kubernetes.io/instance" + +_START_KWARGS = { + "resources", + "runtime_class_name", + "image_pull_secrets", + "labels", + "service_account_name", + "automount_service_account_token", +} + + +def _raise_install_error(exc: ImportError) -> None: + raise RuntimeError( + "KubernetesProvider requires the kubernetes client. " + "Install it with `pip install openenv[kubernetes]`." + ) from exc + + +def _dns_label(value: str, *, max_length: int, what: str) -> str: + """Return *value* as a DNS-1123 label, or raise ``ValueError``. + + Namespace and runtime class names are validated, not rewritten: rewriting + them would target a different object than the one the caller named. + """ + if not isinstance(value, str) or not _DNS_LABEL.fullmatch(value): + raise ValueError( + f"{what} must be a DNS-1123 label: lowercase alphanumeric " + "characters or '-', starting and ending with an alphanumeric." + ) + if not 1 <= len(value) <= max_length: + raise ValueError(f"{what} must be 1 to {max_length} characters.") + return value + + +def _slug(image: str) -> str: + """DNS-1123 slug from an image reference. Raises if nothing usable remains.""" + raw = image.split("/")[-1].split("@")[0].split(":")[0] + cleaned = re.sub(r"[^a-z0-9]+", "-", raw.lower()).strip("-") + cleaned = re.sub(r"-{2,}", "-", cleaned)[:_SLUG_MAX].strip("-") + if not cleaned or not _DNS_LABEL.fullmatch(cleaned): + raise ValueError( + "image does not yield a valid Kubernetes name. " + "Use an image reference with an alphanumeric name." + ) + return cleaned + + +def _resource_name(image: str) -> str: + suffix = f"{int(time.time() * 1000)}-{secrets.token_hex(2)}" + name = f"{_NAME_PREFIX}{_slug(image)}-{suffix}" + if len(name) > 63 or not _DNS_LABEL.fullmatch(name): + raise ValueError("generated Kubernetes name is not a valid DNS-1123 label.") + return name + + +def _label_key(key: str) -> str: + if not isinstance(key, str) or len(key) > 253: + raise ValueError( + "Kubernetes label keys must be strings of at most 253 characters." + ) + prefix, sep, name = key.rpartition("/") + if not _LABEL_NAME.fullmatch(name): + raise ValueError(f"Invalid Kubernetes label key {key!r}.") + if sep and (len(prefix) > 253 or not _dns_subdomain(prefix)): + raise ValueError(f"Invalid Kubernetes label key prefix {prefix!r}.") + return key + + +def _dns_subdomain(value: str) -> bool: + if not value or len(value) > 253: + return False + return all(_DNS_LABEL.fullmatch(part) for part in value.split(".")) + + +def _label_value(value: str) -> str: + if not isinstance(value, str) or not _LABEL_VALUE.fullmatch(value): + raise ValueError( + "Kubernetes label values must be 63 characters or fewer and contain " + "only alphanumeric characters, '-', '_' or '.'." + ) + return value + + +def _ownership_labels(name: str) -> dict[str, str]: + return { + "app.kubernetes.io/name": "openenv", + "app.kubernetes.io/instance": name, + "app.kubernetes.io/managed-by": "openenv", + "app.kubernetes.io/part-of": "openenv", + "app.kubernetes.io/component": "environment", + } + + +def _merged_labels(name: str, extra: Optional[Mapping[str, str]]) -> dict[str, str]: + labels: dict[str, str] = {} + if extra: + if not isinstance(extra, Mapping): + raise ValueError("labels must be a mapping of strings.") + for key, value in extra.items(): + labels[_label_key(key)] = _label_value(value) + labels.update(_ownership_labels(name)) + return labels + + +def _safe_reason(reason: Optional[str]) -> Optional[str]: + """Keep kubelet reason codes. Drop anything else so API text cannot leak.""" + if isinstance(reason, str) and _SAFE_REASON.fullmatch(reason): + return reason + return None + + +class _NamespaceMissing(RuntimeError): + """Creating a namespaced object returned 404: the namespace is absent.""" + + +class _CreateConflict(RuntimeError): + """Creating a namespaced object returned 409: the name is already taken.""" + + +class _TransientStatusError(RuntimeError): + """A Pod status read can be retried within the readiness deadline.""" + + +def _incluster_base_url(name: str, namespace: str, port: int) -> str: + # *name* and *namespace* are already DNS-1123 labels and *port* is an int, + # so this cannot be steered by a status field from the API server. + # ``name.namespace`` is completed by the Pod DNS search list + # (``svc.``), which works when the cluster domain is not + # ``cluster.local``. + return f"http://{name}.{namespace}:{port}" + + +def _owned_by_provider(labels: Any, name: str) -> bool: + if not isinstance(labels, Mapping): + return False + return ( + labels.get("app.kubernetes.io/managed-by") == "openenv" + and labels.get("app.kubernetes.io/instance") == name + ) + + +class _DefaultKubernetesAdapter: + """Thin adapter over the official ``kubernetes`` client. + + The provider talks to this private adapter instead of spreading SDK details + through its own logic; tests inject a duck-typed fake in its place. + """ + + def __init__( + self, + *, + namespace: str, + kubeconfig: Optional[str], + context: Optional[str], + ): + try: + from kubernetes import client, config + from kubernetes.client.exceptions import ApiException + except ImportError as exc: + _raise_install_error(exc) + + self._client = client + self._ApiException = ApiException + self._namespace = namespace + self._load_config(config, kubeconfig=kubeconfig, context=context) + configuration = client.Configuration.get_default_copy() + # Readiness owns the retry deadline; SDK retries would multiply it. + configuration.retries = 0 + self._api = client.CoreV1Api(client.ApiClient(configuration=configuration)) + + def _load_config( + self, config: Any, *, kubeconfig: Optional[str], context: Optional[str] + ) -> None: + if kubeconfig is not None or context is not None: + config.load_kube_config(config_file=kubeconfig, context=context) + return + try: + config.load_incluster_config() + except config.ConfigException: + config.load_kube_config() + + def _api_error(self, exc: Exception, action: str, *, missing_ok: bool) -> None: + status = getattr(exc, "status", None) + if missing_ok and status == 404: + return + if status == 409: + raise _CreateConflict( + f"Kubernetes {action} name is already in use" + ) from None + if status == 404 and action.startswith("create "): + raise _NamespaceMissing( + "Kubernetes namespace does not exist. " + "KubernetesProvider does not create namespaces." + ) from None + # The API body can echo object contents. Do not chain it into the error. + raise RuntimeError(f"Failed to {action} Kubernetes resource") from None + + def create_pod(self, manifest: Mapping[str, Any]) -> None: + try: + self._api.create_namespaced_pod(self._namespace, self._pod(manifest)) + except self._ApiException as exc: + self._api_error(exc, "create Pod", missing_ok=False) + + def create_service(self, manifest: Mapping[str, Any]) -> None: + try: + self._api.create_namespaced_service( + self._namespace, self._service(manifest) + ) + except self._ApiException as exc: + self._api_error(exc, "create Service", missing_ok=False) + + def pod_labels(self, name: str) -> Optional[dict[str, str]]: + """Return Pod labels, or ``None`` when the Pod does not exist.""" + return self._resource_labels(name, self._api.read_namespaced_pod, "read Pod") + + def service_labels(self, name: str) -> Optional[dict[str, str]]: + """Return Service labels, or ``None`` when the Service does not exist.""" + return self._resource_labels( + name, self._api.read_namespaced_service, "read Service" + ) + + def _resource_labels( + self, name: str, read: Any, action: str + ) -> Optional[dict[str, str]]: + try: + obj = read(name, self._namespace) + except self._ApiException as exc: + if getattr(exc, "status", None) == 404: + return None + self._api_error(exc, action, missing_ok=False) + raise RuntimeError(f"Failed to {action} Kubernetes resource") from None + metadata = getattr(obj, "metadata", None) + labels = getattr(metadata, "labels", None) if metadata is not None else None + if not isinstance(labels, Mapping): + return {} + return {str(key): str(value) for key, value in labels.items()} + + def delete_pod(self, name: str) -> None: + try: + self._api.delete_namespaced_pod(name, self._namespace) + except self._ApiException as exc: + self._api_error(exc, "delete Pod", missing_ok=True) + + def delete_service(self, name: str) -> None: + try: + self._api.delete_namespaced_service(name, self._namespace) + except self._ApiException as exc: + self._api_error(exc, "delete Service", missing_ok=True) + + def pod_status( + self, name: str, timeout_s: float = 30.0 + ) -> dict[str, Optional[str]]: + from urllib3.exceptions import HTTPError + + try: + # Older supported SDKs ignore a float timeout. Split the budget + # between connect and read using their supported tuple form. + pod = self._api.read_namespaced_pod( + name, + self._namespace, + _request_timeout=(timeout_s / 2, timeout_s / 2), + ) + except Exception as exc: + status = getattr(exc, "status", None) + if ( + isinstance(exc, (TimeoutError, HTTPError)) + or status == 429 + or (isinstance(status, int) and 500 <= status < 600) + ): + raise _TransientStatusError( + "Kubernetes Pod status read failed" + ) from None + self._api_error(exc, "read Pod", missing_ok=False) + raise RuntimeError("Failed to read Kubernetes Pod") from None + status = getattr(pod, "status", None) + phase = getattr(status, "phase", None) if status is not None else None + reason = None + if status is not None: + for container in status.container_statuses or []: + state = getattr(container, "state", None) + waiting = getattr(state, "waiting", None) if state is not None else None + terminated = ( + getattr(state, "terminated", None) if state is not None else None + ) + if waiting is not None and getattr(waiting, "reason", None): + reason = waiting.reason + elif terminated is not None and getattr(terminated, "reason", None): + reason = terminated.reason + return {"phase": phase or "Unknown", "reason": reason} + + def _metadata(self, meta: Mapping[str, Any]) -> Any: + return self._client.V1ObjectMeta( + name=meta["name"], + namespace=meta["namespace"], + labels=dict(meta["labels"]), + ) + + def _pod(self, manifest: Mapping[str, Any]) -> Any: + spec = manifest["spec"] + container = spec["containers"][0] + container_kwargs: dict[str, Any] = { + "name": container["name"], + "image": container["image"], + "ports": [ + self._client.V1ContainerPort( + name=port["name"], container_port=port["container_port"] + ) + for port in container["ports"] + ], + } + if container.get("env"): + container_kwargs["env"] = [ + self._client.V1EnvVar(name=item["name"], value=item["value"]) + for item in container["env"] + ] + resources = container.get("resources") + if resources: + container_kwargs["resources"] = self._client.V1ResourceRequirements( + requests=resources.get("requests"), + limits=resources.get("limits"), + ) + pod_kwargs: dict[str, Any] = { + "restart_policy": spec["restart_policy"], + "automount_service_account_token": spec["automount_service_account_token"], + "containers": [self._client.V1Container(**container_kwargs)], + } + if spec.get("runtime_class_name"): + pod_kwargs["runtime_class_name"] = spec["runtime_class_name"] + if spec.get("service_account_name"): + pod_kwargs["service_account_name"] = spec["service_account_name"] + if spec.get("image_pull_secrets"): + pod_kwargs["image_pull_secrets"] = [ + self._client.V1LocalObjectReference(name=secret) + for secret in spec["image_pull_secrets"] + ] + return self._client.V1Pod( + metadata=self._metadata(manifest["metadata"]), + spec=self._client.V1PodSpec(**pod_kwargs), + ) + + def _service(self, manifest: Mapping[str, Any]) -> Any: + spec = manifest["spec"] + port = spec["ports"][0] + return self._client.V1Service( + metadata=self._metadata(manifest["metadata"]), + spec=self._client.V1ServiceSpec( + selector=dict(spec["selector"]), + ports=[ + self._client.V1ServicePort( + name=port["name"], + port=port["port"], + target_port=port["target_port"], + protocol=port["protocol"], + ) + ], + ), + ) + + +class KubernetesProvider(ContainerProvider): + """ + Container provider that runs one environment as one Pod and one Service. + + ``start_container`` returns ``http://{name}.{namespace}:{port}``. That + address is reachable only from inside the cluster: Pod DNS search expands + it under ``svc.``. It is plaintext on purpose: in-cluster + HTTP is the connectivity decision for this provider. Cloud sandbox + providers keep their own HTTPS requirement. + + The namespace must already exist. This provider does not create namespaces, + Deployments, Ingress objects, or port-forwards. + + Only one Pod is active per provider. Calling ``start_container`` again + before ``stop_container()`` / ``close()`` raises ``RuntimeError`` rather + than orphaning the running Pod. A failed start deletes a resource only + after its OpenEnv ownership labels match. When a create response is lost + and that read fails, the resource stays unconfirmed: ``stop_container`` + reads the labels again and deletes only on a match. ``stop_container`` is + safe to call more than once. + + The Pod does not mount a service-account token unless + ``automount_service_account_token=True`` is passed to ``start_container``. + + Example: + ```python + from openenv.core.containers.runtime.kubernetes_provider import ( + KubernetesProvider, + ) + + provider = KubernetesProvider(namespace="openenv") + base_url = provider.start_container("echo-env:latest") + provider.wait_for_ready(base_url) + provider.stop_container() + ``` + """ + + def __init__( + self, + *, + image: str | None = None, + env_vars: dict[str, str] | None = None, + namespace: str = _DEFAULT_NAMESPACE, + kubeconfig: str | None = None, + context: str | None = None, + _adapter: Any = None, + ): + """ + Args: + image (`str`, *optional*): + Registry image used when ``start_container()`` is called + without an image. + env_vars (`dict`, *optional*): + Environment variables used when ``start_container()`` is called + without ``env_vars``. + namespace (`str`, *optional*, defaults to ``"default"``): + Existing namespace for the Pod and Service. Not created. + kubeconfig (`str`, *optional*): + Kubeconfig path. When omitted, in-cluster config is tried and + then the default kubeconfig. + context (`str`, *optional*): + Kubeconfig context. Implies kubeconfig loading rather than + in-cluster config. + """ + self._image = image + self._env_vars = env_vars + self._namespace = _dns_label(namespace, max_length=63, what="namespace") + self._name: str | None = None + self._base_url: str | None = None + self._service_port: int | None = None + self._pod_created = False + self._service_created = False + self._pod_unconfirmed = False + self._service_unconfirmed = False + + if _adapter is None: + self._adapter: Any = _DefaultKubernetesAdapter( + namespace=self._namespace, + kubeconfig=kubeconfig, + context=context, + ) + else: + self._adapter = _adapter + + @property + def base_url(self) -> str: + """URL returned by the last successful ``start_container``.""" + if self._base_url is None: + raise RuntimeError( + "KubernetesProvider has no active base_url. Start the provider " + "before reading base_url." + ) + return self._base_url + + def start_container( + self, + image: str | None = None, + port: int | None = None, + env_vars: dict[str, str] | None = None, + **kwargs: Any, + ) -> str: + """ + Create one Pod and one Service and return the in-cluster base URL. + + Args: + image (`str`, *optional*): + Registry image. May be omitted when supplied to the constructor. + port (`int`, *optional*): + Service port. Defaults to 8000. The container always listens + on 8000, matching ``LocalDockerProvider``. + env_vars (`dict`, *optional*): + Environment variables for the container. Replaces constructor + ``env_vars`` when passed, including an empty dict. + **kwargs: + ``resources``, ``runtime_class_name``, ``image_pull_secrets``, + ``labels``, ``service_account_name``, and + ``automount_service_account_token``. Unknown keys raise + ``ValueError``. + + Returns: + `str`: ``http://{name}.{namespace}:{port}``. + """ + if self._has_tracked_resources() or self._base_url is not None: + raise RuntimeError( + "KubernetesProvider already has an active Pod. Call " + "stop_container() (or close()) before starting another — a " + "second start would orphan the running Pod." + ) + + unknown = set(kwargs) - _START_KWARGS + if unknown: + raise ValueError( + f"Unsupported kwargs for KubernetesProvider: {sorted(unknown)}" + ) + + effective_image = image if image is not None else self._image + if not isinstance(effective_image, str) or not effective_image: + raise ValueError( + "KubernetesProvider requires an image. Pass it to the " + "constructor or start_container()." + ) + service_port = _CONTAINER_PORT if port is None else port + if isinstance(service_port, bool) or not isinstance(service_port, int): + raise ValueError("port must be an integer.") + if not 1 <= service_port <= 65535: + raise ValueError("port must be between 1 and 65535.") + + effective_env = self._env_vars if env_vars is None else env_vars + env_list = _env_list(effective_env) + resources = _resources(kwargs.get("resources")) + runtime_class_name = _optional_dns_subdomain( + kwargs.get("runtime_class_name"), what="runtime_class_name" + ) + service_account_name = _optional_dns_subdomain( + kwargs.get("service_account_name"), what="service_account_name" + ) + image_pull_secrets = _secret_names(kwargs.get("image_pull_secrets")) + automount = kwargs.get("automount_service_account_token", False) + if not isinstance(automount, bool): + raise ValueError("automount_service_account_token must be a bool.") + + name = _resource_name(effective_image) + labels = _merged_labels(name, kwargs.get("labels")) + self._name = name + self._service_port = service_port + try: + self._adapter.create_pod( + _pod_manifest( + name=name, + namespace=self._namespace, + labels=labels, + image=effective_image, + env_list=env_list, + resources=resources, + runtime_class_name=runtime_class_name, + service_account_name=service_account_name, + image_pull_secrets=image_pull_secrets, + automount_service_account_token=automount, + ) + ) + self._pod_created = True + self._adapter.create_service( + _service_manifest( + name=name, + namespace=self._namespace, + labels=labels, + service_port=service_port, + ) + ) + self._service_created = True + except BaseException as exc: + # Interrupts can also arrive after the API created a resource. + # A cleanup failure must not mask the original error. + try: + self._cleanup_after_failed_start(exc) + except Exception: + pass + raise + + self._base_url = _incluster_base_url(name, self._namespace, service_port) + return self._base_url + + def _cleanup_after_failed_start(self, exc: BaseException) -> None: + """Delete objects this start may have created. + + A 409 is someone else's name, and a 404 means the namespace is + missing, so those do not probe. Any other create error may mean the + API server applied the object and the client lost the response. Only + the resource whose create was attempted is checked. It is deleted only + when the OpenEnv ownership labels match. A failed read is recorded as + unconfirmed, which is not the same as a successful create: a later + ``stop_container()`` reads the labels again before deleting. + """ + uncertain = not isinstance(exc, (_CreateConflict, _NamespaceMissing)) + # Service create runs only after Pod create has succeeded. + service_was_attempted = self._pod_created + self._release("pod", uncertain=uncertain) + self._release("service", uncertain=uncertain and service_was_attempted) + if not self._has_tracked_resources(): + self._name = None + self._base_url = None + self._service_port = None + + def _release(self, kind: str, *, uncertain: bool) -> None: + if self._created(kind): + self._delete_tracked(kind) + return + if not uncertain: + return + owned = self._lookup_owned(kind) + if owned is None: + self._set_unconfirmed(kind, True) + return + if not owned: + return + self._set_created(kind, True) + self._delete_tracked(kind) + + def _lookup_owned(self, kind: str) -> Optional[bool]: + """Return whether *kind* at ``_name`` is ours. + + ``None`` means the read itself failed. Callers record that as + unconfirmed. They do not treat it as a confirmed create. + """ + if self._name is None: + return False + try: + if kind == "pod": + labels = self._adapter.pod_labels(self._name) + else: + labels = self._adapter.service_labels(self._name) + except Exception: + return None + if labels is None: + return False + return _owned_by_provider(labels, self._name) + + def _delete_tracked(self, kind: str) -> None: + """Delete a resource already known to be ours. + + A failed delete stays confirmed so ``stop_container()`` can retry it. + """ + if self._name is None: + return + try: + if kind == "pod": + self._adapter.delete_pod(self._name) + else: + self._adapter.delete_service(self._name) + except Exception: + self._set_created(kind, True) + return + self._set_created(kind, False) + + def _created(self, kind: str) -> bool: + if kind == "pod": + return self._pod_created + return self._service_created + + def _set_created(self, kind: str, created: bool) -> None: + if kind == "pod": + self._pod_created = created + else: + self._service_created = created + + def _unconfirmed(self, kind: str) -> bool: + if kind == "pod": + return self._pod_unconfirmed + return self._service_unconfirmed + + def _set_unconfirmed(self, kind: str, unconfirmed: bool) -> None: + if kind == "pod": + self._pod_unconfirmed = unconfirmed + else: + self._service_unconfirmed = unconfirmed + + def _has_tracked_resources(self) -> bool: + return ( + self._pod_created + or self._service_created + or self._pod_unconfirmed + or self._service_unconfirmed + ) + + def stop_container(self) -> None: + """Delete the Pod and Service this provider created. + + Safe when nothing was started and safe to call twice. A 404 from the + API is treated as already deleted. A confirmed resource is deleted by + name. An unconfirmed one is deleted only after a fresh ownership-label + match. If that read fails, the unconfirmed state is kept for another + retry. Objects this instance does not own are left in place, including + a name that was already taken. + """ + if self._name is None and not self._has_tracked_resources(): + self._base_url = None + self._service_port = None + return + + errors: list[str] = [] + self._stop_kind("pod", errors) + self._stop_kind("service", errors) + if errors: + raise RuntimeError( + "Failed to delete Kubernetes resources created by this provider. " + "Call stop_container() again to retry." + ) + self._name = None + self._base_url = None + self._service_port = None + + def _stop_kind(self, kind: str, errors: list[str]) -> None: + if self._name is None: + return + if self._unconfirmed(kind): + owned = self._lookup_owned(kind) + if owned is None: + errors.append(kind) + return + self._set_unconfirmed(kind, False) + if not owned: + return + self._set_created(kind, True) + if not self._created(kind): + return + try: + if kind == "pod": + self._adapter.delete_pod(self._name) + else: + self._adapter.delete_service(self._name) + except Exception: + errors.append(kind) + return + self._set_created(kind, False) + + def close(self) -> None: + """Stop the active Pod and Service. + + Overrides the base no-op so a caller holding a bare ``ContainerProvider`` + reference can release the Pod polymorphically (also invoked on + context-manager exit). Equivalent to ``stop_container()``. + """ + self.stop_container() + + def __exit__(self, exc_type, exc, tb) -> None: + try: + self.close() + except Exception: + if exc_type is None: + raise + + def wait_for_ready(self, base_url: str, timeout_s: float = 120.0) -> None: + """ + Wait until the Pod is Running and ``GET /health`` returns 200. + + A Failed or Succeeded Pod raises immediately instead of consuming the + timeout. The URL is not included in errors: this method only polls the + Service URL returned by ``start_container``. + + Args: + base_url (`str`): + URL returned by ``start_container()``. + timeout_s (`float`, *optional*, defaults to `120.0`): + Maximum seconds to wait. Image pulls are slower than local Docker. + + Raises: + TimeoutError: If the Pod does not become ready in time. + RuntimeError: If the Pod has already ended. + ValueError: If ``base_url`` is not the URL this provider returned. + """ + import requests + + expected = self._base_url + if expected is None or not isinstance(base_url, str): + raise ValueError( + "base_url does not match the in-cluster Service URL for this provider." + ) + if base_url.rstrip("/") != expected: + raise ValueError( + "base_url does not match the in-cluster Service URL for this provider." + ) + if isinstance(timeout_s, bool) or not isinstance(timeout_s, (int, float)): + raise ValueError("timeout_s must be a number.") + if timeout_s < 0: + raise ValueError("timeout_s must be non-negative.") + + health_url = f"{expected}/health" + proxies = {"http": "", "https": "", "all": ""} + deadline = time.monotonic() + timeout_s + while (remaining := deadline - time.monotonic()) > 0: + try: + phase, reason = self._phase(remaining) + except _TransientStatusError: + phase, reason = "Unknown", None + if phase in ("Failed", "Succeeded"): + raise RuntimeError(self._ended_message(phase, reason)) + remaining = deadline - time.monotonic() + if remaining <= 0: + break + if phase == "Running": + try: + response = requests.get( + health_url, timeout=min(2.0, remaining), proxies=proxies + ) + if response.status_code == 200: + return + except requests.RequestException: + pass + time.sleep(min(0.5, max(0.0, deadline - time.monotonic()))) + + raise TimeoutError(f"Kubernetes Pod did not become ready within {timeout_s}s.") + + def _phase(self, timeout_s: float) -> tuple[str, Optional[str]]: + if self._name is None: + raise RuntimeError( + "KubernetesProvider has no active Pod. Start the provider " + "before waiting for readiness." + ) + status = self._adapter.pod_status(self._name, timeout_s=timeout_s) + phase = status.get("phase") if isinstance(status, Mapping) else None + reason = status.get("reason") if isinstance(status, Mapping) else None + if not isinstance(phase, str) or not _SAFE_REASON.fullmatch(phase): + phase = "Unknown" + return phase, _safe_reason(reason if isinstance(reason, str) else None) + + def _ended_message(self, phase: str, reason: Optional[str]) -> str: + if reason is None: + return ( + f"Kubernetes Pod entered phase {phase} before it became ready. " + "The Service URL and Pod status message are omitted." + ) + return ( + f"Kubernetes Pod entered phase {phase} ({reason}) before it became " + "ready. The Service URL and Pod status message are omitted." + ) + + +def _env_list(env_vars: Optional[Mapping[str, str]]) -> list[dict[str, str]]: + if env_vars is None: + return [] + if not isinstance(env_vars, Mapping): + raise ValueError("env_vars must be a mapping of strings.") + items: list[dict[str, str]] = [] + for key, value in env_vars.items(): + if not isinstance(key, str) or not isinstance(value, str): + raise ValueError("env_vars keys and values must be strings.") + items.append({"name": key, "value": value}) + return items + + +def _resources(resources: Any) -> Optional[dict[str, dict[str, str]]]: + if resources is None: + return None + if not isinstance(resources, Mapping): + raise ValueError("resources must be a mapping of requests and limits.") + unknown = set(resources) - {"requests", "limits"} + if unknown: + raise ValueError( + f"Unsupported resources keys for KubernetesProvider: {sorted(unknown)}" + ) + parsed: dict[str, dict[str, str]] = {} + for section in ("requests", "limits"): + values = resources.get(section) + if values is None: + continue + if not isinstance(values, Mapping) or not values: + raise ValueError(f"resources.{section} must be a non-empty mapping.") + parsed[section] = {} + for key, value in values.items(): + if not isinstance(key, str) or not isinstance(value, str) or not value: + raise ValueError( + f"resources.{section} keys and values must be non-empty strings." + ) + parsed[section][key] = value + return parsed or None + + +def _optional_dns_subdomain(value: Any, *, what: str) -> Optional[str]: + if value is None: + return None + if not isinstance(value, str) or not _dns_subdomain(value): + raise ValueError( + f"{what} must be a DNS-1123 subdomain: lowercase labels separated by '.'." + ) + return value + + +def _secret_names(value: Any) -> list[str]: + if value is None: + return [] + if isinstance(value, str) or not isinstance(value, (list, tuple)): + raise ValueError("image_pull_secrets must be a list of secret names.") + names: list[str] = [] + for item in value: + if not isinstance(item, str) or not _dns_subdomain(item): + raise ValueError("image_pull_secrets entries must be DNS-1123 subdomains.") + names.append(item) + return names + + +def _pod_manifest( + *, + name: str, + namespace: str, + labels: dict[str, str], + image: str, + env_list: list[dict[str, str]], + resources: Optional[dict[str, dict[str, str]]], + runtime_class_name: Optional[str], + service_account_name: Optional[str], + image_pull_secrets: list[str], + automount_service_account_token: bool, +) -> dict[str, Any]: + container: dict[str, Any] = { + "name": _CONTAINER_NAME, + "image": image, + "ports": [{"name": "http", "container_port": _CONTAINER_PORT}], + } + if env_list: + container["env"] = env_list + if resources: + container["resources"] = resources + spec: dict[str, Any] = { + "restart_policy": "Never", + "automount_service_account_token": automount_service_account_token, + "containers": [container], + } + if runtime_class_name: + spec["runtime_class_name"] = runtime_class_name + if service_account_name: + spec["service_account_name"] = service_account_name + if image_pull_secrets: + spec["image_pull_secrets"] = image_pull_secrets + return { + "metadata": {"name": name, "namespace": namespace, "labels": labels}, + "spec": spec, + } + + +def _service_manifest( + *, + name: str, + namespace: str, + labels: dict[str, str], + service_port: int, +) -> dict[str, Any]: + return { + "metadata": {"name": name, "namespace": namespace, "labels": labels}, + "spec": { + "selector": {_SELECTOR_KEY: name}, + "ports": [ + { + "name": "http", + "port": service_port, + "target_port": _CONTAINER_PORT, + "protocol": "TCP", + } + ], + }, + } + + +__all__ = ["KubernetesProvider"] diff --git a/src/core/openenv/core/containers/runtime/modal_provider.py b/src/core/openenv/core/containers/runtime/modal_provider.py index e504ad266c3ffae97a26b8337a46d2d121068335..5db4e605beb1049eee66710f9086097afbb850cb 100644 --- a/src/core/openenv/core/containers/runtime/modal_provider.py +++ b/src/core/openenv/core/containers/runtime/modal_provider.py @@ -3,30 +3,23 @@ """ Modal container provider for running OpenEnv environments in Modal sandboxes. -Requires the ``modal`` SDK: ``pip install modal>=1.4`` +Requires the ``modal`` SDK: ``pip install modal>=1.6.3`` The provider boots an OpenEnv server inside a Modal sandbox, exposes it on an encrypted tunnel, and returns an ``https://`` URL that ``EnvClient`` connects to over ``wss://``. - -Supports both the stable Sandbox API (``modal.Sandbox.create``) and the beta -Sandbox v2 API (``modal.Sandbox._experimental_create``). Sandbox v2 is opt-in -via ``use_sandbox_v2=True`` because it is an experimental, private SDK feature; -see https://modal.com/docs/guide/sandbox-v2 . """ from __future__ import annotations -import logging import shlex import time +import warnings from typing import Any, Dict, Optional from ._server_config import parse_dockerfile_cmd, parse_openenv_app_field from .providers import ContainerProvider -logger = logging.getLogger(__name__) - _DEFAULT_MODAL_PORT = 8000 # Modal's default per-container resource requests. We pass configured cpu/memory @@ -58,28 +51,14 @@ class _DefaultModalAdapter: """Thin adapter over the ``modal`` SDK. The provider talks to this private adapter instead of spreading SDK details - through its own logic; tests inject a duck-typed fake in its place. Keeping - the SDK surface here also localizes the feature check for the private - Sandbox v2 (``_experimental_create``) API. + through its own logic; tests inject a duck-typed fake in its place. """ - def __init__(self, *, app_name: str, use_sandbox_v2: bool): + def __init__(self, *, app_name: str): import modal self._modal = modal self._app_name = app_name - self._use_sandbox_v2 = use_sandbox_v2 - - # Sandbox v2 rides on a private SDK entry point that is not present in - # every modal release. Fail fast at construction with clear guidance - # rather than at start_container time with an AttributeError. - if use_sandbox_v2 and not hasattr(modal.Sandbox, "_experimental_create"): - raise RuntimeError( - "use_sandbox_v2=True requires modal.Sandbox._experimental_create, " - "which is not available in the installed modal SDK. Upgrade modal, " - "or use the stable Sandbox API (use_sandbox_v2=False). Sandbox v2 " - "is an experimental feature; contact support@modal.com for access." - ) def image_from_registry(self, tag: str) -> Any: return self._modal.Image.from_registry(tag) @@ -111,10 +90,6 @@ class _DefaultModalAdapter: # The sandbox is started with a keep-alive entrypoint; the server # command is launched via exec afterwards (see ModalProvider). - if self._use_sandbox_v2: - return self._modal.Sandbox._experimental_create( - "sleep", "infinity", **kwargs - ) return self._modal.Sandbox.create("sleep", "infinity", **kwargs) def exec(self, sandbox: Any, command: str, *, timeout: int = 10) -> str: @@ -164,11 +139,6 @@ class ModalProvider(ContainerProvider): provider.wait_for_ready(base_url) # sandbox terminated on exit ``` - - Sandbox v2 (beta) is opt-in: - ```python - provider = ModalProvider(app_name="openenv", use_sandbox_v2=True) - ``` """ _dockerfile_registry: Dict[str, Dict[str, Any]] = {} @@ -179,7 +149,7 @@ class ModalProvider(ContainerProvider): image: str | None = None, env_vars: dict[str, str] | None = None, app_name: str = "openenv", - use_sandbox_v2: bool = False, + use_sandbox_v2: bool | None = None, timeout: int = 300, cmd: str | None = None, cpu: float | None = None, @@ -198,12 +168,11 @@ class ModalProvider(ContainerProvider): app_name (`str`, *optional*, defaults to `"openenv"`): Modal app name the sandbox is created under. Looked up (and created if missing) via ``modal.App.lookup``. - use_sandbox_v2 (`bool`, *optional*, defaults to `False`): - When `True`, sandboxes are created via the beta - ``modal.Sandbox._experimental_create`` API (Sandbox v2). This is - an experimental, private SDK feature and is therefore off by - default; a feature check fails fast at construction if the - installed SDK lacks it. See https://modal.com/docs/guide/sandbox-v2 . + use_sandbox_v2 (`bool`, *optional*): + Deprecated and ignored; will be removed in OpenEnv 0.15.0. + Modal 1.6+ creates Sandbox v2 sandboxes through + ``modal.Sandbox.create`` by default. Set ``MODAL_SANDBOX_V2=0`` + to use Sandbox v1. timeout (`int`, *optional*, defaults to `300`): Maximum sandbox lifetime in seconds. cmd (`str`, *optional*): @@ -225,10 +194,18 @@ class ModalProvider(ContainerProvider): orchestrator/CI logs. When `True`, a best-effort redacted, length-bounded excerpt is included in startup-crash errors. """ + if use_sandbox_v2 is not None: + warnings.warn( + "`use_sandbox_v2` is deprecated, has no effect, and will be removed " + "in OpenEnv 0.15.0. Remove the argument: Modal 1.6+ creates Sandbox " + "v2 sandboxes through `modal.Sandbox.create` by default. Set " + "`MODAL_SANDBOX_V2=0` to use Sandbox v1.", + FutureWarning, + stacklevel=2, + ) self._image = image self._env_vars = env_vars self._app_name = app_name - self._use_sandbox_v2 = use_sandbox_v2 self._timeout = timeout self._cmd = cmd self._cpu = cpu @@ -241,20 +218,12 @@ class ModalProvider(ContainerProvider): self._redact_values: set[str] = set() if _adapter is None: - # Import eagerly (inside the adapter) so SDK/configuration errors — - # including the Sandbox v2 feature check — surface at construction. - self._adapter: Any = _DefaultModalAdapter( - app_name=app_name, use_sandbox_v2=use_sandbox_v2 - ) + # Import eagerly (inside the adapter) so SDK/configuration errors + # surface at construction. + self._adapter: Any = _DefaultModalAdapter(app_name=app_name) else: self._adapter = _adapter - if use_sandbox_v2: - logger.info( - "Using Modal Sandbox v2 (experimental). This feature must be " - "explicitly enabled. Contact support@modal.com to get access." - ) - def _discover_server_cmd(self, port: int = _DEFAULT_MODAL_PORT) -> str: """Discover the server command from ``openenv.yaml`` inside the sandbox. diff --git a/src/core/openenv/core/containers/runtime/providers.py b/src/core/openenv/core/containers/runtime/providers.py index 3b7575f70173262b5b534d060c7584f4d9607b1c..95e5ff44836a2f96a4c02cd73debc035f6db1207 100644 --- a/src/core/openenv/core/containers/runtime/providers.py +++ b/src/core/openenv/core/containers/runtime/providers.py @@ -9,19 +9,76 @@ This module provides a pluggable architecture for different container providers from __future__ import annotations +import os +import tempfile from abc import ABC, abstractmethod -from typing import Any, Dict, Optional, Sequence, TypeVar +from contextlib import contextmanager +from typing import ( + Any, + Dict, + Iterator, + List, + Mapping, + Optional, + Sequence, + Tuple, + TypeVar, +) _ContainerProviderT = TypeVar("_ContainerProviderT", bound="ContainerProvider") +@contextmanager +def _env_file_args( + env_vars: Optional[Mapping[str, str]], +) -> Iterator[Tuple[List[str], Optional[str]]]: + """ + Yield `--env-file` arguments for the container's environment variables, + and the text to send to docker's stdin. + + The values (often tokens) stay out of the command line, which other + processes can read and errors include, and out of the docker CLI's own + environment, where names like `DOCKER_HOST` or `PATH` would change how + the CLI runs. Docker reads them from its stdin (`/dev/stdin`), so no file + is written and a CLI with a private `/tmp` (snap) still gets them. Windows + has no `/dev/stdin`: there they go in a temporary file only this user can + read, removed once docker returns. + """ + if not env_vars: + yield [], None + return + lines = [] + for key, value in env_vars.items(): + key, value = str(key), str(value) + if not key or key.startswith("#") or any(c in key for c in "= \t\r\n\0"): + raise ValueError(f"Invalid environment variable name: {key!r}") + if any(c in value for c in "\r\n\0"): + raise ValueError( + f"Environment variable {key!r}: values can't contain line breaks " + "or NUL characters" + ) + lines.append(f"{key}={value}\n") + if os.name != "nt": + yield ["--env-file", "/dev/stdin"], "".join(lines) + return + fd, path = tempfile.mkstemp(prefix="openenv-env-") + try: + with os.fdopen(fd, "w") as env_file: + env_file.writelines(lines) + yield ["--env-file", path], None + finally: + os.unlink(path) + + class ContainerProvider(ABC): """ Abstract base class for container providers. Providers implement this interface to support different container platforms: - LocalDockerProvider: Runs containers on local Docker daemon - - KubernetesProvider: Runs containers in Kubernetes cluster + - DockerSwarmProvider: Runs containers as a Docker Swarm service + - KubernetesProvider: optional ``openenv[kubernetes]`` extra + (``kubernetes_provider.py``) - FargateProvider: Runs containers on AWS Fargate - CloudRunProvider: Runs containers on Google Cloud Run @@ -175,8 +232,10 @@ class LocalDockerProvider(ContainerProvider): Port to expose. If `None`, finds an available port. env_vars (`dict`, *optional*): Environment variables for the container. - **kwargs: - Additional Docker run options. + volumes (`dict`, *optional*): + Mapping of host paths or volume names to mount configuration. + Each configuration must contain a `bind` container path and may + contain a `mode` such as `"ro"` or `"rw"`. Returns: `str`: Base URL to connect to the container. @@ -184,6 +243,8 @@ class LocalDockerProvider(ContainerProvider): import subprocess import time + volumes: Optional[Mapping[str, Mapping[str, str]]] = kwargs.get("volumes") + # Find available port if not specified if port is None: port = self._find_available_port() @@ -202,17 +263,33 @@ class LocalDockerProvider(ContainerProvider): f"{port}:8000", # Map port ] - # Add environment variables - if env_vars: - for key, value in env_vars.items(): - cmd.extend(["-e", f"{key}={value}"]) + # Add volume mounts before the image name. + if volumes: + for source, config in volumes.items(): + bind = config.get("bind") + if not bind: + raise ValueError( + f"Volume config for {source!r} must include a non-empty 'bind'" + ) + mode = config.get("mode") + volume_spec = f"{source}:{bind}" + if mode: + volume_spec = f"{volume_spec}:{mode}" + cmd.extend(["--volume", volume_spec]) # Add image cmd.append(image) # Run container try: - result = subprocess.run(cmd, capture_output=True, text=True, check=True) + with _env_file_args(env_vars) as (env_args, env_input): + result = subprocess.run( + cmd[:2] + env_args + cmd[2:], + input=env_input, + capture_output=True, + text=True, + check=True, + ) self._container_id = result.stdout.strip() except subprocess.CalledProcessError as e: error_msg = f"Failed to start Docker container.\nCommand: {' '.join(cmd)}\nExit code: {e.returncode}\nStderr: {e.stderr}\nStdout: {e.stdout}" @@ -441,10 +518,6 @@ class DockerSwarmProvider(ContainerProvider): if self._overlay_network: cmd.extend(["--network", self._overlay_network]) - if env_vars: - for key, value in env_vars.items(): - cmd.extend(["--env", f"{key}={value}"]) - if cpu_limit is not None: cmd.extend(["--limit-cpu", str(cpu_limit)]) @@ -468,12 +541,14 @@ class DockerSwarmProvider(ContainerProvider): cmd.extend(command_override) try: - result = subprocess.run( - cmd, - capture_output=True, - text=True, - check=True, - ) + with _env_file_args(env_vars) as (env_args, env_input): + result = subprocess.run( + cmd[:3] + env_args + cmd[3:], + input=env_input, + capture_output=True, + text=True, + check=True, + ) self._service_id = result.stdout.strip() except subprocess.CalledProcessError as e: error_msg = ( @@ -644,19 +719,6 @@ class DockerSwarmProvider(ContainerProvider): return f"{clean_image}-swarm-{timestamp}" -class KubernetesProvider(ContainerProvider): - """ - Planned container provider for Kubernetes clusters. - - Not yet implemented: this is a placeholder for the planned Kubernetes - backend and does not implement the abstract `ContainerProvider` methods, so - it cannot be instantiated. Use `LocalDockerProvider`, `DockerSwarmProvider`, - `DaytonaProvider`, or `ACASandboxProvider` instead. - """ - - pass - - class RuntimeProvider(ABC): """ Abstract base class for runtime providers that are not container providers. diff --git a/src/core/openenv/core/containers/runtime/uv_provider.py b/src/core/openenv/core/containers/runtime/uv_provider.py index 3dc3f5e72a4299639440b32d2a0c198e36eb1d87..f1f17012ee3476686ad20fb438e4ed5beb94181d 100644 --- a/src/core/openenv/core/containers/runtime/uv_provider.py +++ b/src/core/openenv/core/containers/runtime/uv_provider.py @@ -2,6 +2,7 @@ from __future__ import annotations +import logging import os import shutil import socket @@ -12,6 +13,9 @@ from typing import Dict, Optional import requests +from ...utils import _SECRET_ENV_NAME + +logger = logging.getLogger(__name__) from .providers import RuntimeProvider GIT_URL_PREFIX = "git+" @@ -137,7 +141,11 @@ class UVProvider(RuntimeProvider): reload (`bool`, *optional*, defaults to `False`): Whether to enable uvicorn's reload mode. env_vars (`dict`, *optional*): - Environment variables to pass through to the spawned process. + Environment variables to pass through to the spawned process. The + server inherits this process's environment except variables named + like credentials (`TOKEN`, `KEY`, `SECRET` or `PASSWORD` as a part + of the name, such as `HF_TOKEN`), so a credential the server needs + has to be passed here. context_timeout_s (`float`, *optional*, defaults to `60.0`): How long to wait for the environment to become ready. @@ -195,7 +203,8 @@ class UVProvider(RuntimeProvider): port (`int`, *optional*): The port to bind the environment to. env_vars (`dict`, *optional*): - Environment variables to pass to the environment. + Environment variables to pass to the environment, on top of + the constructor's. Credentials reach the server only this way. workers (`int`, *optional*, defaults to `1`): The number of workers to use. @@ -232,13 +241,23 @@ class UVProvider(RuntimeProvider): project_path=project_path, ) - env = os.environ.copy() + # Environment servers can run code a model wrote: they don't inherit + # this process's credentials, only the ones passed in env_vars. + env = {k: v for k, v in os.environ.items() if not _SECRET_ENV_NAME.search(k)} if self.env_vars: env.update(self.env_vars) if env_vars: env.update(env_vars) + dropped = sorted(k for k in os.environ if k not in env) + if dropped: + logger.warning( + "Not passing %s to the environment server. Pass the ones it " + "needs with env_vars.", + ", ".join(dropped), + ) + try: self._process = subprocess.Popen(command, env=env) except OSError as exc: diff --git a/src/core/openenv/core/env_client.py b/src/core/openenv/core/env_client.py index 01abe1aeb9df4f8bc7e7ba3327464d751198288b..01b72643fe80ccb3531e6db278b0b966f36b00a4 100644 --- a/src/core/openenv/core/env_client.py +++ b/src/core/openenv/core/env_client.py @@ -275,6 +275,15 @@ async def _best_effort_graceful_close(ws: ClientConnection) -> None: await _best_effort_close(ws) +class SessionLostError(ConnectionError): + """The connection to the server was lost in the middle of an episode. + + The server keeps one environment per WebSocket connection, so reconnecting + opens a new session with an environment this client never reset. Call + `reset()` to start a new episode. + """ + + class EnvClient(ABC, Generic[ActT, ObsT, StateT]): """ Async environment client for persistent sessions. @@ -386,6 +395,8 @@ class EnvClient(ABC, Generic[ActT, ObsT, StateT]): # Strong references for fire-and-forget socket closes (see _receive), # so the task isn't garbage-collected mid-close. Discarded on done. self._pending_close_tasks: set[asyncio.Task] = set() + # The socket that carries the episode started by `reset()`, if one is open. + self._episode_ws: Optional[ClientConnection] = None if base_url is not None: self._set_base_url(base_url) @@ -517,6 +528,7 @@ class EnvClient(ABC, Generic[ActT, ObsT, StateT]): coro_factory: Callable[[], Any], *, allow_async_handoff: bool = False, + stop_loop: bool = False, ) -> Any: """Run an async operation through the sync wrapper.""" if allow_async_handoff and self._execution_mode == "async": @@ -525,9 +537,15 @@ class EnvClient(ABC, Generic[ActT, ObsT, StateT]): self._claim_execution_mode("sync") if self._sync_client is None: self._sync_client = self.sync() - return self._sync_client._run(coro_factory()) + try: + return self._sync_client._run(coro_factory()) + finally: + if stop_loop: + self._sync_client._stop_loop() - def _dispatch(self, coro_factory: Callable[[], Any]) -> Any: + def _dispatch( + self, coro_factory: Callable[[], Any], *, stop_loop: bool = False + ) -> Any: """Return an awaitable in async code and a concrete result in sync code.""" try: running_loop = asyncio.get_running_loop() @@ -538,15 +556,17 @@ class EnvClient(ABC, Generic[ActT, ObsT, StateT]): sync_loop = ( self._sync_client._loop if self._sync_client is not None else None ) - if running_loop is sync_loop: + if running_loop is not None and running_loop is sync_loop: return coro_factory() - return self._run_sync(coro_factory) + return self._run_sync(coro_factory, stop_loop=stop_loop) if running_loop is not None: if self._execution_mode == "async": return coro_factory() return _AutoAsyncResult(self, coro_factory) - return self._run_sync(coro_factory, allow_async_handoff=True) + return self._run_sync( + coro_factory, allow_async_handoff=True, stop_loop=stop_loop + ) def connect(self) -> Any: return self._dispatch(self._connect_async) @@ -653,6 +673,7 @@ class EnvClient(ABC, Generic[ActT, ObsT, StateT]): # leave a stale socket cached for a later operation. self._ws = None self._ws_loop = None + self._episode_ws = None same_loop = ws_loop is asyncio.get_running_loop() if same_loop: # Keep ownership of the handshake if this caller is cancelled. @@ -929,6 +950,8 @@ class EnvClient(ABC, Generic[ActT, ObsT, StateT]): `start_container` (docker) or to the `UVProvider` constructor/start (uv). When `use_docker=False`, the `project_path` argument can be used to override the default git URL (`git+https://huggingface.co/spaces/{repo_id}`). + With `use_docker=False` the server doesn't inherit variables named like + credentials (such as `HF_TOKEN`): pass the ones it needs in `env_vars`. Returns: `_BootstrapResult`: `await` for a connected async client, or call @@ -996,8 +1019,12 @@ class EnvClient(ABC, Generic[ActT, ObsT, StateT]): "type": "reset", "data": kwargs, } + # A reset may reconnect: it starts a new episode on whatever session it lands on. + self._episode_ws = None response = await self._send_and_receive(message) - return self._parse_result(response.get("data", {})) + result = self._parse_result(response.get("data", {})) + self._episode_ws = None if result.done else self._ws + return result def step(self, action: ActT, **kwargs: Any) -> Any: return self._dispatch(lambda: self._step_async(action, **kwargs)) @@ -1019,8 +1046,12 @@ class EnvClient(ABC, Generic[ActT, ObsT, StateT]): "type": "step", "data": self._step_payload(action), } + self._raise_if_session_lost() response = await self._send_and_receive(message) - return self._parse_result(response.get("data", {})) + result = self._parse_result(response.get("data", {})) + if result.done: + self._episode_ws = None + return result def state(self) -> Any: return self._dispatch(self._state_async) @@ -1033,11 +1064,33 @@ class EnvClient(ABC, Generic[ActT, ObsT, StateT]): State object with environment state information """ message = {"type": "state"} + self._raise_if_session_lost() response = await self._send_and_receive(message) return self._parse_state(response.get("data", {})) + def _raise_if_session_lost(self) -> None: + """Raise `SessionLostError` if the socket that carried the episode is gone. + + `_connect_async()` would replace it with a new socket, which the server + treats as a new session, and the call would run on an environment this + client never reset. It keeps raising until `reset()`, so a retried call + does not land on the new session either. + """ + ws = self._episode_ws + if ws is None: + return + if ( + self._ws is not ws + or ws.state in (State.CLOSING, State.CLOSED) + or self._ws_loop is not asyncio.get_running_loop() + ): + raise SessionLostError( + f"Lost the connection to {self._ws_url} in the middle of an episode. " + "Call reset() to start a new one." + ) + def close(self) -> Any: - return self._dispatch(self._close_async) + return self._dispatch(self._close_async, stop_loop=True) async def _close_child_clients(self) -> asyncio.CancelledError | None: """Close every captured child while deferring caller cancellation.""" @@ -1164,7 +1217,7 @@ class EnvClient(ABC, Generic[ActT, ObsT, StateT]): def __exit__(self, exc_type, exc_val, exc_tb) -> None: """Exit sync context manager, closing connection.""" - self._run_sync(self._close_async) + self._run_sync(self._close_async, stop_loop=True) def sync(self) -> "SyncEnvClient": """ diff --git a/src/core/openenv/core/env_server/exceptions.py b/src/core/openenv/core/env_server/exceptions.py index bc2261654e18a7c390ac1bd593e3ff9d59e86929..437b0e15add1cc1f601bf06ac91c2f9ae892cac2 100644 --- a/src/core/openenv/core/env_server/exceptions.py +++ b/src/core/openenv/core/env_server/exceptions.py @@ -44,7 +44,10 @@ class SessionCapacityError(OpenEnvError): Raised when the server cannot accept new sessions due to capacity limits. This error is raised when a new WebSocket connection is attempted but - the server has already reached max_concurrent_envs active sessions. + the server has already reached max_concurrent_envs active sessions. The + default message tells the caller which server setting limits the number of + sessions, since the client (e.g. a trainer opening one session per + concurrent episode) usually cannot see the server configuration. """ def __init__( @@ -59,7 +62,13 @@ class SessionCapacityError(OpenEnvError): if message is None: message = ( f"Server at capacity: {active_sessions}/{max_sessions} sessions active. " - f"Cannot accept new connections." + f"Cannot accept new connections. To serve more concurrent sessions, " + f"start the server with a higher max_concurrent_envs (most " + f"environment servers read it from the MAX_CONCURRENT_ENVS " + f"environment variable). Values above 1 also require an environment " + f"that isolates per-session state and declares " + f"SUPPORTS_CONCURRENT_SESSIONS=True. Otherwise, open fewer " + f"sessions at once or close idle ones." ) super().__init__(message) diff --git a/src/core/openenv/core/env_server/http_server.py b/src/core/openenv/core/env_server/http_server.py index 92b40d642a2e20350f8c0150354e5d30f6d83751..640905b386692a8fda782fde2ae149b8fc75332d 100644 --- a/src/core/openenv/core/env_server/http_server.py +++ b/src/core/openenv/core/env_server/http_server.py @@ -14,9 +14,10 @@ import inspect import json import logging import os +import secrets import time import uuid -from concurrent.futures import ThreadPoolExecutor +from concurrent.futures import Future, ThreadPoolExecutor from contextlib import AsyncExitStack from typing import ( Any, @@ -56,11 +57,23 @@ from .mcp_types import ( ListToolsAction, ListToolsObservation, McpMethod, + ToolErrorType, WSMCPMessage, WSMCPResponse, ) from .route_config import GetEndpointConfig, register_get_endpoints from .serialization import deserialize_action, serialize_observation +from .session_telemetry import ( + rubric_counts, + rubric_snapshot, + SeedAcceptance, + SessionTelemetry, + ValidationOpenedData, + ValidationOpenedResponse, + ValidationOpenMessage, + ValidationReadMessage, + ValidationResponse, +) from .types import ( Action, ConcurrencyConfig, @@ -181,6 +194,7 @@ class HTTPEnvServer: state_cls: Type[State] = State, *, reset_observation_cls: Optional[Type[Observation]] = None, + reset_cls: Type[ResetRequest] = ResetRequest, ): """ Initialize HTTP server wrapper. @@ -208,6 +222,10 @@ class HTTPEnvServer: The `State` subclass this environment reports. Used for the `/state` response model and the `state` entry of `/schema`, so that fields declared by the subclass are published and serialized. + reset_cls (`Type[ResetRequest]`, *optional*, defaults to `ResetRequest`): + The `ResetRequest` subclass describing this environment's reset parameters. + Published as the `reset` entry of `/schema`. It is not used to validate + reset requests. Raises: `ValueError`: If both `max_concurrent_envs` and `concurrency_config` are provided. @@ -253,6 +271,7 @@ class HTTPEnvServer: self.observation_cls = observation_cls self.reset_observation_cls = reset_observation_cls or observation_cls self.state_cls = state_cls + self.reset_cls = reset_cls self.env_name = env_name or self._default_env_name() # Session management for WebSocket connections @@ -260,8 +279,12 @@ class HTTPEnvServer: self._session_executors: Dict[str, ThreadPoolExecutor] = {} self._session_stacks: Dict[str, AsyncExitStack] = {} self._session_info: Dict[str, SessionInfo] = {} + self._session_modes: Dict[str, Optional[str]] = {} self._session_websocket_attachments: set[str] = set() self._session_pending_closes: set[str] = set() + # WebSocket messages being handled, per session; such sessions are never + # idle-reaped. A count, since an attached socket can share the session. + self._session_operations_in_flight: Dict[str, int] = {} self._session_lock = asyncio.Lock() # Create thread pool for running sync code in async context @@ -270,8 +293,10 @@ class HTTPEnvServer: self._requires_single_thread_executor = self._detect_single_thread_requirement() self._shared_session_executor: Optional[ThreadPoolExecutor] = None + self._shared_session_creation_lock: Optional[asyncio.Lock] = None if self._requires_single_thread_executor: self._shared_session_executor = ThreadPoolExecutor(max_workers=1) + self._shared_session_creation_lock = asyncio.Lock() # Idle session reaper configuration. # Timeout is taken from ConcurrencyConfig.session_timeout; @@ -280,6 +305,7 @@ class HTTPEnvServer: self._concurrency_config.session_timeout ) self._reaper_task: Optional[asyncio.Task[None]] = None + self._reaper_stop_event = asyncio.Event() def _default_env_name(self) -> str: factory = self._env_factory @@ -370,7 +396,9 @@ class HTTPEnvServer: return valid_kwargs - async def _create_session(self) -> tuple[str, Environment]: + async def _create_session( + self, mode: Optional[str | ServerMode] = None + ) -> tuple[str, Environment]: """ Create a new WebSocket session with its own environment instance. @@ -400,58 +428,220 @@ class HTTPEnvServer: self._session_executors[session_id] = executor self._sessions[session_id] = None # placeholder until env is ready + # Every await from here to registration runs with the slot reserved, so + # cancellation has to release it. CancelledError is not an Exception, so + # the handlers below never see it, and a surviving reservation is + # permanent: capacity counts _sessions, while the idle reaper only scans + # sessions that reached _session_info. + env: Optional[Environment] = None + stack: Optional[AsyncExitStack] = None + factory_future: Optional[Future[Environment]] = None + mcp_entry_task: Optional[asyncio.Task[Any]] = None + cleanup_task: Optional[asyncio.Task[None]] = None + creation_lock_acquired = False + + def start_cleanup() -> asyncio.Task[None]: + # Startup failure and cancellation share one cleanup owner. Whoever + # gets here first starts the task; a later caller joins the same one + # instead of submitting a second env.close(). + nonlocal cleanup_task + if cleanup_task is None: + cleanup_task = asyncio.create_task( + self._discard_reserved_session( + session_id, + executor, + env, + stack, + factory_future, + mcp_entry_task, + ) + ) + return cleanup_task + + async def drain_cleanup(task: asyncio.Task[None]) -> None: + # ASGI cancel scopes may cancel a request repeatedly. Keep awaiting + # the shielded cleanup task until it reaches a terminal state so + # cancellation cannot escape while the reservation still exists. + try: + await asyncio.shield(task) + except asyncio.CancelledError: + while not task.done(): + try: + await asyncio.shield(task) + except asyncio.CancelledError: + pass + task.result() + raise + try: - # Create environment in the executor thread (outside lock) - loop = asyncio.get_event_loop() - env = await loop.run_in_executor(executor, self._env_factory) - except Exception as e: - async with self._session_lock: - if executor is not self._shared_session_executor: - executor.shutdown(wait=False) - self._session_executors.pop(session_id, None) - self._sessions.pop(session_id, None) - factory_name = getattr( - self._env_factory, "__name__", str(self._env_factory) - ) - raise EnvironmentFactoryError(factory_name) from e - - # Hold the MCP session open for the lifetime of this session, - # matching the WebSocket path's AsyncExitStack pattern. This - # prevents per-request MCP transport teardown/reconnection and - # preserves FastMCP session state (ctx.set_state / ctx.get_state) - # across HTTP calls within the same OpenEnv session. - stack = AsyncExitStack() - try: - mcp_session_factory = getattr(env, "mcp_session", None) - if callable(mcp_session_factory): - mcp_session_cm = cast(AsyncContextManager[Any], mcp_session_factory()) - await stack.enter_async_context(mcp_session_cm) - except Exception: - # MCP transport failed to start — clean up the reserved slot, - # the env, and the executor so they don't leak permanently - # against _max_concurrent_envs. - await stack.aclose() # best-effort + if self._shared_session_creation_lock is not None: + await self._shared_session_creation_lock.acquire() + creation_lock_acquired = True + + try: + # Create environment in the executor thread (outside lock). + # submit() plus wrap_future() is what run_in_executor() does + # internally; spelling it out keeps the thread's future, which is + # the only handle on an environment still being built when the + # await is cancelled. + loop = asyncio.get_event_loop() + factory_future = executor.submit(self._env_factory) + env = await asyncio.wrap_future(factory_future, loop=loop) + mode_val = ( + mode.value + if isinstance(mode, ServerMode) + else (str(mode) if mode is not None else None) + ) + if mode_val is not None and hasattr(env, "set_mode"): + env.set_mode(mode_val) + except Exception as e: + async with self._session_lock: + if executor is not self._shared_session_executor: + executor.shutdown(wait=False) + self._session_executors.pop(session_id, None) + self._sessions.pop(session_id, None) + factory_name = getattr( + self._env_factory, "__name__", str(self._env_factory) + ) + raise EnvironmentFactoryError(factory_name) from e + + # The factory result is delivered, so the shared executor thread is + # free. Release the creation lock before MCP startup: it exists to + # order factory calls (and disposal of a factory cancelled + # mid-flight) on that one thread, and holding it through an MCP + # handshake lets a single stalled connection starve every later + # session's constructor. Cancellation during construction keeps the + # lock instead, so late-factory disposal still precedes the next + # constructor. + if creation_lock_acquired: + assert self._shared_session_creation_lock is not None + self._shared_session_creation_lock.release() + creation_lock_acquired = False + + # Hold the MCP session open for the lifetime of this session, + # matching the WebSocket path's AsyncExitStack pattern. This + # prevents per-request MCP transport teardown/reconnection and + # preserves FastMCP session state (ctx.set_state / ctx.get_state) + # across HTTP calls within the same OpenEnv session. + stack = AsyncExitStack() + try: + mcp_session_factory = getattr(env, "mcp_session", None) + if callable(mcp_session_factory): + mcp_session_cm = cast( + AsyncContextManager[Any], mcp_session_factory() + ) + # Enter in its own task and await it shielded. An entry that + # blocks before yielding may release resources in its own + # finally, and the stack cannot replay that cleanup: it + # registers the exit callback only once __aenter__ returns. + # Shielding keeps repeated cancellation off the entry, so + # the cleanup owner can cancel it exactly once and drain the + # unwind instead of aborting it part-way. + mcp_entry_task = asyncio.create_task( + stack.enter_async_context(mcp_session_cm) + ) + await asyncio.shield(mcp_entry_task) + except Exception: + # MCP transport failed to start — clean up the reserved slot, + # the env, and the executor so they don't leak permanently + # against _max_concurrent_envs. Cancellation arriving mid-close + # joins this same task rather than closing the env twice. + await drain_cleanup(start_cleanup()) + raise + async with self._session_lock: - self._sessions.pop(session_id, None) - self._session_executors.pop(session_id, None) - self._session_info.pop(session_id, None) - await self._cleanup_session_resources(env, executor) + self._sessions[session_id] = env + self._session_stacks[session_id] = stack + if mode is not None: + self._session_modes[session_id] = mode_val + now = time.time() + self._session_info[session_id] = SessionInfo( + session_id=session_id, + created_at=current_time, + last_activity_at=now, + step_count=0, + environment_type=type(env).__name__, + ) + except asyncio.CancelledError: + # Joins the cleanup already under way if startup failure began one, + # so the environment is closed by a single owner. + try: + await drain_cleanup(start_cleanup()) + except asyncio.CancelledError: + pass raise - - async with self._session_lock: - self._sessions[session_id] = env - self._session_stacks[session_id] = stack - now = time.time() - self._session_info[session_id] = SessionInfo( - session_id=session_id, - created_at=current_time, - last_activity_at=now, - step_count=0, - environment_type=type(env).__name__, - ) + finally: + if creation_lock_acquired: + assert self._shared_session_creation_lock is not None + self._shared_session_creation_lock.release() return session_id, env + async def _discard_reserved_session( + self, + session_id: str, + executor: ThreadPoolExecutor, + env: Optional[Environment] = None, + stack: Optional[AsyncExitStack] = None, + factory_future: Optional[Future[Environment]] = None, + mcp_entry_task: Optional[asyncio.Task[Any]] = None, + ) -> None: + """ + Release a session slot reserved by `_create_session` that never opened. + + Drops every mapping the slot may have reached and closes whatever the + interrupted creation built, so the slot stops counting against + `max_concurrent_envs` and no environment outlives it. + + Args: + session_id (`str`): + The reserved session ID to release. + executor (`ThreadPoolExecutor`): + The executor reserved alongside the slot. + env (`Environment`, *optional*): + The environment, if the factory already returned one. + stack (`AsyncExitStack`, *optional*): + The MCP session stack, if one was already entered. + factory_future (`Future`, *optional*): + The factory's thread future, if the factory call was reached. + Used to close an environment the thread is still building. + mcp_entry_task (`asyncio.Task`, *optional*): + The in-flight MCP session entry, if MCP startup was reached. + Cancelled and drained here so an entry interrupted before it + yielded can finish releasing what it had already acquired. + """ + if mcp_entry_task is not None: + # Cancel at most once: a second cancellation would abort the entry's + # own unwind, and the stack holds no exit callback to replay it. + if not mcp_entry_task.done(): + mcp_entry_task.cancel() + try: + await mcp_entry_task + except (asyncio.CancelledError, Exception): + # A cancelled or failed entry has unwound itself. If it did + # finish, `stack` owns the context and closes it below. + pass + + if env is None and factory_future is not None: + # Cancelling the await can cancel a queued future, but cannot stop a + # factory whose executor thread is already running. In that case, + # keep the capacity reservation until its result can be disposed of. + if not factory_future.cancel(): + try: + env = await asyncio.wrap_future(factory_future) + except (asyncio.CancelledError, Exception): + # A cancelled or failed factory produced no environment to + # close. Its capacity reservation still has to be released. + env = None + + await self._cleanup_session_resources(env, executor, stack) + async with self._session_lock: + self._sessions.pop(session_id, None) + self._session_executors.pop(session_id, None) + self._session_stacks.pop(session_id, None) + self._session_info.pop(session_id, None) + self._session_modes.pop(session_id, None) + async def _destroy_session(self, session_id: str) -> None: """ Destroy a WebSocket session and cleanup resources. @@ -465,6 +655,7 @@ class HTTPEnvServer: executor = self._session_executors.pop(session_id, None) stack = self._session_stacks.pop(session_id, None) self._session_info.pop(session_id, None) + self._session_modes.pop(session_id, None) self._session_websocket_attachments.discard(session_id) self._session_pending_closes.discard(session_id) @@ -533,17 +724,26 @@ class HTTPEnvServer: interval = max(timeout / 4, 5.0) # check frequently enough while True: try: - await asyncio.sleep(interval) + try: + await asyncio.wait_for( + self._reaper_stop_event.wait(), timeout=interval + ) + return + except asyncio.TimeoutError: + pass now = time.time() stale_ids: list[str] = [] async with self._session_lock: for sid, info in self._session_info.items(): if ( sid not in self._session_websocket_attachments + and sid not in self._session_operations_in_flight and now - info.last_activity_at > timeout ): stale_ids.append(sid) for sid in stale_ids: + if self._reaper_stop_event.is_set(): + return # Re-check under lock: activity may have arrived since # the snapshot was taken, making this session active again. # Refresh `now` so slow _destroy_session calls don't cause @@ -554,6 +754,7 @@ class HTTPEnvServer: if ( info is None or sid in self._session_websocket_attachments + or sid in self._session_operations_in_flight or (now - info.last_activity_at) <= timeout ): continue @@ -569,12 +770,14 @@ class HTTPEnvServer: def _start_reaper(self) -> None: """Start the idle-session reaper if a timeout is configured.""" if self._session_idle_timeout_s is not None and self._reaper_task is None: + self._reaper_stop_event.clear() self._reaper_task = asyncio.create_task(self._reap_idle_sessions()) - def _stop_reaper(self) -> None: - """Cancel the reaper background task.""" + async def _stop_reaper(self) -> None: + """Stop the reaper after any in-progress session cleanup finishes.""" if self._reaper_task is not None: - self._reaper_task.cancel() + self._reaper_stop_event.set() + await self._reaper_task self._reaper_task = None def get_session_info(self, session_id: str) -> Optional[SessionInfo]: @@ -879,20 +1082,30 @@ class HTTPEnvServer: f"Invalid mode: '{mode}'. Must be one of: {valid_modes}" ) - # Wire up idle-session reaper lifecycle via app events + # Only explicitly provisioned simulation servers accept validation controls. + validation_token = os.environ.get("OPENENV_VALIDATION_TOKEN", "") + validation_enabled = ( + mode == ServerMode.SIMULATION and 32 <= len(validation_token) <= 256 + ) + + # Wire up session lifecycle via app events server_ref = self async def _start_session_reaper() -> None: server_ref._start_reaper() - async def _stop_session_reaper() -> None: - server_ref._stop_reaper() + async def _shutdown_sessions() -> None: + await server_ref._stop_reaper() + async with server_ref._session_lock: + session_ids = list(server_ref._sessions) + for session_id in session_ids: + await server_ref._destroy_session(session_id) if server_ref._shared_session_executor is not None: server_ref._shared_session_executor.shutdown(wait=True) if not getattr(app.router, "_openenv_reaper_registered", False): app.router.on_startup.append(_start_session_reaper) - app.router.on_shutdown.append(_stop_session_reaper) + app.router.on_shutdown.append(_shutdown_sessions) app.router._openenv_reaper_registered = True # type: ignore[attr-defined] # Helper function to handle reset endpoint @@ -993,7 +1206,7 @@ class HTTPEnvServer: request_id=request_id, ) try: - created_session_id, _ = await self._create_session() + created_session_id, _ = await self._create_session(mode=mode) except SessionCapacityError as e: return JsonRpcResponse.error_response( JsonRpcErrorCode.SERVER_ERROR, @@ -1033,6 +1246,21 @@ class HTTPEnvServer: ) async with self._session_lock: + session_mode = self._session_modes.get(target_session_id) + if ( + ( + target_session_id in self._sessions + or target_session_id in self._session_websocket_attachments + ) + and session_mode is not None + and session_mode != mode.value + ): + return JsonRpcResponse.error_response( + JsonRpcErrorCode.INVALID_PARAMS, + f"Session '{target_session_id}' belongs to mode '{session_mode}', not '{mode.value}'", + request_id=request_id, + ) + if target_session_id in self._session_websocket_attachments: env = _MISSING attached = True @@ -1046,6 +1274,7 @@ class HTTPEnvServer: executor = self._session_executors.pop(target_session_id, None) stack = self._session_stacks.pop(target_session_id, None) self._session_info.pop(target_session_id, None) + self._session_modes.pop(target_session_id, None) elif not attached: executor = None stack = None @@ -1099,6 +1328,7 @@ class HTTPEnvServer: elif requested_session_id: async with self._session_lock: _env = self._sessions.get(requested_session_id, _MISSING) + session_mode = self._session_modes.get(requested_session_id) if _env is _MISSING: return JsonRpcResponse.error_response( @@ -1107,6 +1337,13 @@ class HTTPEnvServer: request_id=request_id, ) + if session_mode is not None and session_mode != mode.value: + return JsonRpcResponse.error_response( + JsonRpcErrorCode.INVALID_PARAMS, + f"Session '{requested_session_id}' belongs to mode '{session_mode}', not '{mode.value}'", + request_id=request_id, + ) + if _env is None: return JsonRpcResponse.error_response( JsonRpcErrorCode.INVALID_REQUEST, @@ -1118,6 +1355,8 @@ class HTTPEnvServer: managed_session_id = requested_session_id else: _env = self._env_factory() + if hasattr(_env, "set_mode"): + _env.set_mode(mode.value) should_close = True try: mcp_client = getattr(_env, "mcp_client", None) @@ -1142,6 +1381,27 @@ class HTTPEnvServer: } if method == McpMethod.TOOLS_LIST: + if hasattr(_env, "_async_handle_list_tools"): + obs = await _env._async_handle_list_tools() + if obs.metadata and "error" in obs.metadata: + return JsonRpcResponse.error_response( + JsonRpcErrorCode.INTERNAL_ERROR, + obs.metadata["error"], + request_id=request_id, + ) + tools = [ + { + "name": t.name, + "description": t.description or "", + "inputSchema": t.input_schema, + } + for t in obs.tools + ] + return JsonRpcResponse.success( + result={"tools": tools}, + request_id=request_id, + ) + # Check if environment is MCP-enabled if mcp_client is None and mcp_server is None: if supports_mcp_style_actions: @@ -1164,7 +1424,7 @@ class HTTPEnvServer: request_id=request_id, ) return JsonRpcResponse.error_response( - JsonRpcErrorCode.INTERNAL_ERROR, + JsonRpcErrorCode.METHOD_NOT_FOUND, "Environment does not support MCP", request_id=request_id, ) @@ -1180,7 +1440,7 @@ class HTTPEnvServer: return JsonRpcResponse.success( result={ "tools": [ - t.model_dump() + t.model_dump(by_alias=True) if hasattr(t, "model_dump") else dict(t) for t in tools @@ -1221,6 +1481,32 @@ class HTTPEnvServer: request_id=request_id, ) + if hasattr(_env, "_mode_tools") and any( + m is not None for m in _env._mode_tools.get(tool_name, {}) + ): + obs = await _env._async_handle_call_tool( + CallToolAction(tool_name=tool_name, arguments=arguments) + ) + if obs.error: + err_code = ( + JsonRpcErrorCode.INVALID_PARAMS + if obs.error.error_type + in ( + ToolErrorType.INVALID_ARGS, + ToolErrorType.TOOL_NOT_FOUND, + ) + else JsonRpcErrorCode.INTERNAL_ERROR + ) + return JsonRpcResponse.error_response( + err_code, + obs.error.message, + request_id=request_id, + ) + return JsonRpcResponse.success( + result=_make_json_serializable(obs.result), + request_id=request_id, + ) + if mcp_client is None and mcp_server is None: if supports_mcp_style_actions: observation = await call_mcp_style_step( @@ -1242,7 +1528,7 @@ class HTTPEnvServer: request_id=request_id, ) return JsonRpcResponse.error_response( - JsonRpcErrorCode.INTERNAL_ERROR, + JsonRpcErrorCode.METHOD_NOT_FOUND, "Environment does not support MCP", request_id=request_id, ) @@ -1414,7 +1700,7 @@ class HTTPEnvServer: try: # Create session with dedicated environment - session_id, session_env = await self._create_session() + session_id, session_env = await self._create_session(mode=mode) if session_env is None: raise RuntimeError( "Session environment not initialized for MCP websocket" @@ -1661,13 +1947,14 @@ The structure of the state object is defined by the environment's State model. tags=["Schema"], summary="Get all JSON schemas", description=""" -Get JSON schemas for actions, observations, and state in a single response. +Get JSON schemas for actions, observations, state, and reset parameters in a single response. Returns a combined schema object containing: - **action**: JSON schema for actions accepted by this environment - **observation**: JSON schema for observations returned by step - **reset_observation**: JSON schema for observations returned by reset - **state**: JSON schema for environment state objects +- **reset**: JSON schema for reset parameters accepted by this environment This is more efficient than calling individual schema endpoints and provides all schema information needed to interact with the environment. @@ -1690,6 +1977,10 @@ all schema information needed to interact with the environment. "type": "object", "properties": {"step_count": {"type": "integer"}}, }, + "reset": { + "type": "object", + "properties": {"seed": {"type": "integer"}}, + }, } } }, @@ -1703,6 +1994,7 @@ all schema information needed to interact with the environment. observation=self.observation_cls.model_json_schema(), reset_observation=self.reset_observation_cls.model_json_schema(), state=self.state_cls.model_json_schema(), + reset=self.reset_cls.model_json_schema(), ) # Register MCP endpoint for production mode (direct MCP access) @@ -1753,6 +2045,8 @@ all schema information needed to interact with the environment. session_env = None owns_session = False attached_session = False + telemetry = None + operations_started = False try: requested_session_id = websocket.query_params.get("session_id") @@ -1761,10 +2055,15 @@ all schema information needed to interact with the environment. attached_env = self._sessions.get( requested_session_id, _MISSING ) + session_mode = self._session_modes.get(requested_session_id) if attached_env is _MISSING: raise RuntimeError( f"Unknown session_id: {requested_session_id}" ) + if session_mode is not None and session_mode != mode.value: + raise RuntimeError( + f"Session '{requested_session_id}' belongs to mode '{session_mode}', not '{mode.value}'" + ) if attached_env is None: raise RuntimeError( f"Session {requested_session_id} is still initializing" @@ -1780,7 +2079,7 @@ all schema information needed to interact with the environment. attached_session = True self._update_session_activity(session_id) else: - session_id, session_env = await self._create_session() + session_id, session_env = await self._create_session(mode=mode) owns_session = True if session_env is None: @@ -1803,6 +2102,19 @@ all schema information needed to interact with the environment. # Receive message from client raw_message = await websocket.receive_text() + # The reaper or shutdown may have destroyed this + # session (closing its env and freeing its slot). + if session_id not in self._sessions: + error_resp = WSErrorResponse( + data={ + "message": "Session expired or was closed; " + "open a new connection", + "code": WSErrorCode.SESSION_ERROR, + } + ) + await websocket.send_text(error_resp.model_dump_json()) + break + try: message_dict = json.loads(raw_message) except json.JSONDecodeError as e: @@ -1817,6 +2129,67 @@ all schema information needed to interact with the environment. msg_type = message_dict.get("type", "") + if msg_type in {"validation_open", "validation_read"}: + # Do not return Pydantic input/error details: these messages + # contain credentials and must never echo or log them. + try: + if not validation_enabled or not owns_session: + raise ValueError("Validation unavailable") + if msg_type == "validation_open": + auth = ValidationOpenMessage.model_validate( + message_dict + ) + if telemetry is not None or operations_started: + raise ValueError("Validation already started") + if not secrets.compare_digest( + validation_token.encode(), + auth.data.token.get_secret_value().encode(), + ): + raise ValueError("Unauthorized") + telemetry = SessionTelemetry() + response = ValidationOpenedResponse( + data=ValidationOpenedData( + capability=telemetry.capability + ) + ) + else: + auth = ValidationReadMessage.model_validate( + message_dict + ) + if telemetry is None or not telemetry.authorized( + auth.data.capability.get_secret_value() + ): + raise ValueError("Unauthorized") + response = ValidationResponse( + data=telemetry.snapshot + ) + except Exception: + response = WSErrorResponse( + data={ + "message": "Validation unavailable or unauthorized", + "code": WSErrorCode.VALIDATION_ERROR, + } + ) + await websocket.send_text(response.model_dump_json()) + continue + + seed_acceptance = None + before_scores = None + if msg_type in {"reset", "step", "state"}: + operations_started = True + if telemetry is not None and msg_type == "step": + try: + before_scores = rubric_counts( + getattr(session_env, "rubric", None) + ) + except Exception: + telemetry.snapshot.rubric_error = ( + "Rubric introspection unavailable" + ) + + in_flight = self._session_operations_in_flight + in_flight[session_id] = in_flight.get(session_id, 0) + 1 + self._update_session_activity(session_id) try: match msg_type: case "reset": @@ -1848,7 +2221,12 @@ all schema information needed to interact with the environment. ) ) - self._update_session_activity(session_id) + if telemetry is not None: + seed_acceptance = SeedAcceptance( + requested="seed" in msg.data, + value=msg.data.get("seed"), + accepted="seed" in valid_kwargs, + ) response = WSObservationResponse( data=serialize_observation(observation), @@ -1925,9 +2303,39 @@ all schema information needed to interact with the environment. } ) + if telemetry is not None and msg_type in { + "reset", + "step", + "state", + }: + nodes = None + try: + if msg_type in {"reset", "step"}: + nodes = rubric_snapshot( + getattr(session_env, "rubric", None), + before_scores, + ) + except Exception: + nodes = [] + telemetry.snapshot.rubric_error = ( + "Rubric introspection unavailable" + ) + telemetry.append( + msg_type, + message_dict, + response.model_dump(mode="json"), + seed=seed_acceptance, + rubric=nodes, + ) await websocket.send_text(response.model_dump_json()) except ValidationError as e: + if telemetry is not None and msg_type in { + "reset", + "step", + "state", + }: + telemetry.incomplete("Session operation failed") error_resp = WSErrorResponse( data={ "message": "Invalid message", @@ -1937,6 +2345,12 @@ all schema information needed to interact with the environment. ) await websocket.send_text(error_resp.model_dump_json()) except Exception as e: + if telemetry is not None and msg_type in { + "reset", + "step", + "state", + }: + telemetry.incomplete("Session operation failed") error_resp = WSErrorResponse( data={ "message": str(e), @@ -1944,6 +2358,11 @@ all schema information needed to interact with the environment. } ) await websocket.send_text(error_resp.model_dump_json()) + finally: + in_flight[session_id] -= 1 + if in_flight[session_id] == 0: + del in_flight[session_id] + self._update_session_activity(session_id) except WebSocketDisconnect: pass @@ -2003,6 +2422,7 @@ def create_app( *, mode: Optional[ServerMode | str] = None, reset_observation_cls: Optional[Type[Observation]] = None, + reset_cls: Type[ResetRequest] = ResetRequest, ) -> FastAPI: """ Create a FastAPI application with or without web interface. @@ -2047,6 +2467,9 @@ def create_app( state_cls (`Type[State]`, *optional*, defaults to `State`): The `State` subclass this environment reports, used for the `/state` response model and the `state` entry of `/schema`. + reset_cls (`Type[ResetRequest]`, *optional*, defaults to `ResetRequest`): + The `ResetRequest` subclass describing this environment's reset parameters, + published as the `reset` entry of `/schema`. Not used for validation. mode (`ServerMode` or `str`, *optional*): Server mode. When `None`, resolved from the `OPENENV_MODE` environment variable, defaulting to simulation. @@ -2074,6 +2497,7 @@ def create_app( max_concurrent_envs, concurrency_config, state_cls=state_cls, + reset_cls=reset_cls, reset_observation_cls=reset_observation_cls, gradio_builder=gradio_builder, custom_tab_name=custom_tab_name, @@ -2092,6 +2516,7 @@ def create_app( concurrency_config, env_name=env_name, state_cls=state_cls, + reset_cls=reset_cls, reset_observation_cls=reset_observation_cls, mode=mode, ) @@ -2108,6 +2533,7 @@ def create_fastapi_app( *, mode: Optional[ServerMode | str] = None, reset_observation_cls: Optional[Type[Observation]] = None, + reset_cls: Type[ResetRequest] = ResetRequest, ) -> FastAPI: """ Create a FastAPI application with comprehensive documentation. @@ -2133,6 +2559,9 @@ def create_fastapi_app( state_cls (`Type[State]`, *optional*, defaults to `State`): The `State` subclass this environment reports, used for the `/state` response model and the `state` entry of `/schema`. + reset_cls (`Type[ResetRequest]`, *optional*, defaults to `ResetRequest`): + The `ResetRequest` subclass describing this environment's reset parameters, + published as the `reset` entry of `/schema`. Not used for validation. mode (`ServerMode` or `str`, *optional*): Server mode. When `None`, resolved from the `OPENENV_MODE` environment variable, defaulting to simulation. @@ -2160,7 +2589,7 @@ HTTP API for interacting with OpenEnv environments through a standardized interf * **Environment Reset**: Initialize or restart episodes * **Action Execution**: Send actions and receive observations * **State Inspection**: Query current environment state -* **Schema Access**: Retrieve JSON schemas for actions and observations +* **Schema Access**: Retrieve JSON schemas for actions, observations, state, and reset parameters ## Workflow @@ -2190,7 +2619,7 @@ HTTP API for interacting with OpenEnv environments through a standardized interf }, { "name": "Schema", - "description": "JSON Schema endpoints for actions, observations, and state", + "description": "JSON Schema endpoints for actions, observations, state, and reset parameters", }, {"name": "Health", "description": "Service health and status checks"}, ], @@ -2199,11 +2628,11 @@ HTTP API for interacting with OpenEnv environments through a standardized interf openapi_url="/openapi.json", contact={ "name": "OpenEnv Team", - "url": "https://github.com/huggingface/OpenEnv", + "url": "https://github.com/openenv/OpenEnv", }, license_info={ "name": "BSD-3-Clause", - "url": "https://github.com/huggingface/OpenEnv/blob/main/LICENSE", + "url": "https://github.com/openenv/OpenEnv/blob/main/LICENSE", }, ) @@ -2215,9 +2644,14 @@ HTTP API for interacting with OpenEnv environments through a standardized interf concurrency_config=concurrency_config, env_name=env_name, state_cls=state_cls, + reset_cls=reset_cls, reset_observation_cls=reset_observation_cls, ) if mode is None: mode = os.environ.get("OPENENV_MODE", ServerMode.SIMULATION.value) server.register_routes(app, mode=mode) + + from .security import attach_guard + + attach_guard(app) return app diff --git a/src/core/openenv/core/env_server/interfaces.py b/src/core/openenv/core/env_server/interfaces.py index 707547697748e694990f52568eeef3261a0b6cf8..8cd15ed7a8e37fe35375ccecbf83eeec23b48480 100644 --- a/src/core/openenv/core/env_server/interfaces.py +++ b/src/core/openenv/core/env_server/interfaces.py @@ -105,7 +105,7 @@ class TaskProvider(Protocol): Selecting a task is not part of this protocol — pass the chosen split and index to `reset()` instead. See the - [Task API guide](https://huggingface.co/docs/openenv/guides/task-api). + [Task API guide](https://openenv.github.io/OpenEnv/main/guides/task-api). Examples: @@ -223,7 +223,7 @@ class Transform(ABC, Generic[ObsT]): class Environment(ABC, Generic[ActT, ObsT, StateT]): """Base class for all environment servers following Gym/Gymnasium API. - See [rfcs/004-rubrics.md](https://github.com/huggingface/OpenEnv/blob/main/rfcs/004-rubrics.md) for rubric design details. + See [rfcs/004-rubrics.md](https://github.com/openenv/OpenEnv/blob/main/rfcs/004-rubrics.md) for rubric design details. Args: transform (`Transform`, *optional*): diff --git a/src/core/openenv/core/env_server/mcp_environment.py b/src/core/openenv/core/env_server/mcp_environment.py index 9d9ad564b9f965194ac6d3edb3766f99a42cbd2e..7d683fab84072bceca4841ffda213b2e86b6bb93 100644 --- a/src/core/openenv/core/env_server/mcp_environment.py +++ b/src/core/openenv/core/env_server/mcp_environment.py @@ -86,17 +86,17 @@ VALID_MODES = {"production", "simulation"} def get_server_tools(mcp_server: Any) -> Dict[str, Any]: """ - Get tools from a FastMCP server, compatible with both 2.x and 3.x. + Get tools from a FastMCP server. Returns: Dictionary mapping tool names to tool objects. """ - # FastMCP 2.x: get_tools() returns dict {name: Tool} + # FastMCP server tools are exposed as a name-to-tool mapping. if hasattr(mcp_server, "get_tools"): result = run_async_safely(mcp_server.get_tools()) if isinstance(result, dict): return result - # FastMCP 3.x: list_tools() returns list of Tool objects + # Some server adapters expose the tools as a list instead. if hasattr(mcp_server, "list_tools"): tools_list = run_async_safely(mcp_server.list_tools()) return {t.name: t for t in tools_list} @@ -108,7 +108,7 @@ def _tool_from_server_tool(tool: Any) -> Tool: return Tool( name=tool.name, description=tool.description or "", - input_schema=tool.inputSchema if hasattr(tool, "inputSchema") else {}, + input_schema=tool.input_schema, ) @@ -187,7 +187,9 @@ class MCPEnvironment(Environment): self._validate_tool_names(mcp_server) self.mcp_server = mcp_server - self.mcp_client = Client(mcp_server) + # OpenEnv sessions keep MCP state across tool calls. FastMCP 4's default + # modern protocol is sessionless, so use its supported legacy handshake. + self.mcp_client = Client(mcp_server, mode="legacy") # Track mode-specific tools: {tool_name: {mode: func}} # mode can be "production", "simulation", or None (available in all modes) @@ -195,6 +197,11 @@ class MCPEnvironment(Environment): # Track tool schemas for list_tools: {tool_name: {mode: schema}} self._mode_tool_schemas = defaultdict(dict) + self._mode: Optional[str] = None + + def set_mode(self, mode: Optional[str]) -> None: + """Set the active mode ('production' or 'simulation') for mode-aware tools.""" + self._mode = mode def _require_mcp_client(self) -> Any: """Return MCP client or raise if environment has been closed.""" @@ -249,7 +256,7 @@ class MCPEnvironment(Environment): def _get_server_tools(self, mcp_server: Any) -> Dict[str, Any]: """ - Get tools from a FastMCP server, compatible with both 2.x and 3.x. + Get tools from a FastMCP server. Returns: Dictionary mapping tool names to tool objects. @@ -496,7 +503,8 @@ class MCPEnvironment(Environment): tools_result = await self._async_list_tools() tools = [] for tool in tools_result: - if tool.name not in self._mode_tool_schemas: + mode_schemas = self._mode_tool_schemas.get(tool.name, {}) + if _schema_for_mode(mode_schemas, current_mode) is None: tools.append(_tool_from_server_tool(tool)) for mode_schemas in self._mode_tool_schemas.values(): schema = _schema_for_mode(mode_schemas, current_mode) @@ -519,21 +527,12 @@ class MCPEnvironment(Environment): tool_name = action.tool_name current_mode = getattr(self, "_mode", None) - if tool_name in self._mode_tools: - mode_info = self._mode_tools[tool_name] + mode_info = self._mode_tools.get(tool_name, {}) + if None in mode_info or current_mode in mode_info: if None in mode_info: func = mode_info[None] elif current_mode in mode_info: func = mode_info[current_mode] - else: - return CallToolObservation( - tool_name=tool_name, - result=None, - error=ToolError( - error_type=ToolErrorType.TOOL_NOT_FOUND, - message=f"Tool '{tool_name}' not available in {current_mode} mode", - ), - ) try: if inspect.iscoroutinefunction(func): result = await func(**action.arguments) diff --git a/src/core/openenv/core/env_server/security.py b/src/core/openenv/core/env_server/security.py new file mode 100644 index 0000000000000000000000000000000000000000..6757585d753abc843f2d94e12677f0308cd59202 --- /dev/null +++ b/src/core/openenv/core/env_server/security.py @@ -0,0 +1,192 @@ +# SPDX-License-Identifier: BSD-3-Clause + +"""Optional fastapi-guard security middleware for environment servers. + +Opt-in via the `OPENENV_GUARD_*` environment variables. When disabled (the +default), `attach_guard` is a no-op and environment servers behave exactly as +before. + +Install the extra with `pip install "openenv[security]"` and enable with +`OPENENV_GUARD_ENABLED=1` to get IP block/allow lists, rate limiting, +user-agent blocking, penetration-attempt detection with auto-ban, and optional +Redis-backed distributed state (fastapi-guard). + +Health and schema endpoints are excluded from detection checks so +orchestrators can probe the server; global IP allow/block lists are still +enforced on those paths. + +WebSocket connections (`/ws`, `/mcp`, `/harness`, `/ws/ui`) get the same +checks on the handshake: ban, IP lists, a separate rate-limit bucket and +penetration detection on the path, query and headers. A refused handshake is +closed before `accept()`, so the client gets HTTP 403 on the upgrade and no +socket. Messages on an accepted connection are not screened, for the same +reason request bodies are not. With Redis configured, the guard initializes at +startup; while Redis is unreachable a handshake is closed with 1013 and HTTP +requests are refused. +""" + +from __future__ import annotations + +import os +from contextlib import asynccontextmanager +from typing import Any + +from starlette import status +from starlette.exceptions import WebSocketException +from starlette.websockets import WebSocket + +DEFAULT_EXCLUDED_PATHS = [ + "/health", + "/schema", + "/metadata", + "/docs", + "/redoc", + "/openapi.json", +] +# Empty by default on purpose: trusting private-range peers would let +# any of them spoof X-Forwarded-For past the blocklist and rate limits. +# Behind a reverse proxy, list the proxy's addresses in +# OPENENV_GUARD_TRUSTED_PROXIES. +DEFAULT_TRUSTED_PROXIES = "" + + +def _env_list(name: str, default: str = "") -> list[str]: + raw = os.environ.get(name, default) + return [item.strip() for item in raw.split(",") if item.strip()] + + +def _env_bool(name: str) -> bool: + raw = os.environ.get(name) + if raw is None or not raw.strip(): + return False + normalized = raw.strip().lower() + if normalized in ("1", "true", "yes", "on"): + return True + if normalized in ("0", "false", "no", "off"): + return False + msg = f"{name} must be a boolean (1/true/yes/on or 0/false/no/off), got {raw!r}" + raise ValueError(msg) + + +def _build_security_config() -> Any: + from guard import SecurityConfig + + kwargs: dict[str, Any] = { + "enable_rate_limiting": True, + "rate_limit": int(os.environ.get("OPENENV_GUARD_RATE_LIMIT", "100")), + "rate_limit_window": int( + os.environ.get("OPENENV_GUARD_RATE_LIMIT_WINDOW", "60") + ), + "enable_ip_banning": True, + "auto_ban_threshold": int( + os.environ.get("OPENENV_GUARD_AUTO_BAN_THRESHOLD", "10") + ), + "auto_ban_duration": int( + os.environ.get("OPENENV_GUARD_AUTO_BAN_DURATION", "300") + ), + # Environment/request bodies are model input (observations, prompts, + # completions), not commands this server executes: signature-scanning + # them false-positives on ordinary content. URL, query, and header + # screening stay on. + "detection_scan_body": False, + "enable_penetration_detection": True, + # In-memory state unless a Redis URL is configured: never implicitly + # depend on a Redis server being reachable at localhost. + "enable_redis": False, + "blacklist": tuple(_env_list("OPENENV_GUARD_BLOCKED_IPS")), + "blocked_user_agents": _env_list("OPENENV_GUARD_BLOCKED_USER_AGENTS"), + "trusted_proxies": tuple( + _env_list("OPENENV_GUARD_TRUSTED_PROXIES", DEFAULT_TRUSTED_PROXIES) + ), + "trusted_proxy_depth": int( + os.environ.get("OPENENV_GUARD_TRUSTED_PROXY_DEPTH", "1") + ), + "exclude_paths": DEFAULT_EXCLUDED_PATHS, + # fastapi-guard sends security headers unless this is None, and its + # X-Frame-Options: SAMEORIGIN stops a Space page from framing the app. + "security_headers": None, + } + + allowed_ips = _env_list("OPENENV_GUARD_ALLOWED_IPS") + if allowed_ips: + kwargs["whitelist"] = tuple(allowed_ips) + + redis_url = os.environ.get("OPENENV_GUARD_REDIS_URL") + if redis_url: + kwargs["enable_redis"] = True + kwargs["redis_url"] = redis_url + + return SecurityConfig(**kwargs) + + +class _WebSocketGuardMiddleware: + # SecurityMiddleware is a BaseHTTPMiddleware, which never sees websocket + # scopes, so every handshake goes through fastapi-guard's guard_websocket. + def __init__(self, app: Any, config: Any) -> None: + from guard import guard_websocket + from guard.lifespan import _find_security_redis_handler, guard_startup + + self.app = app + self.config = config + self.guard_websocket = guard_websocket + # guard_websocket reads Redis through this; None means not connected. + self.find_redis = _find_security_redis_handler + self.guard_startup = guard_startup + + async def __call__(self, scope: Any, receive: Any, send: Any) -> None: + if scope["type"] == "websocket": + websocket = WebSocket(scope, receive, send) + try: + if not await self._redis_ready(scope["app"]): + # The HTTP side refuses too until Redis is reachable. + raise WebSocketException( + code=status.WS_1013_TRY_AGAIN_LATER, + reason="Service temporarily unavailable", + ) + await self.guard_websocket(websocket) + except WebSocketException as exc: + await websocket.close(code=exc.code, reason=exc.reason) + return + await self.app(scope, receive, send) + + async def _redis_ready(self, app: Any) -> bool: + if not self.config.enable_redis or self.find_redis(app) is not None: + return True + # Retry on each handshake, like the HTTP side's first request. + await self.guard_startup(app) + return self.find_redis(app) is not None + + +def attach_guard(app: Any) -> None: + """Add the fastapi-guard middleware to `app` when enabled via env. + + No-op unless OPENENV_GUARD_ENABLED is set to 1/true/yes/on. + """ + if not _env_bool("OPENENV_GUARD_ENABLED"): + return + if getattr(app.state, "guard_attached", False): + return + try: + from guard import SecurityMiddleware + from guard.lifespan import guard_lifespan + except ImportError as exc: + raise ImportError( + "OPENENV_GUARD_ENABLED requires fastapi-guard. " + 'Install it with: pip install "openenv[security]"' + ) from exc + + config = _build_security_config() + app.add_middleware(SecurityMiddleware, config=config) + app.add_middleware(_WebSocketGuardMiddleware, config=config) + # Initialize the guard (Redis included) at startup, so a WebSocket-only + # worker never runs on in-memory state. + existing_lifespan = app.router.lifespan_context + + @asynccontextmanager + async def lifespan(app: Any): + async with guard_lifespan(app): + async with existing_lifespan(app) as state: + yield state + + app.router.lifespan_context = lifespan + app.state.guard_attached = True diff --git a/src/core/openenv/core/env_server/session_telemetry.py b/src/core/openenv/core/env_server/session_telemetry.py new file mode 100644 index 0000000000000000000000000000000000000000..fe9c3eb0f45b3777856491c4bd0c738077a21630 --- /dev/null +++ b/src/core/openenv/core/env_server/session_telemetry.py @@ -0,0 +1,241 @@ +# SPDX-License-Identifier: BSD-3-Clause + +"""Bounded, opt-in evidence emitted by the subject's replay session.""" + +import json +import secrets +from typing import Any, Literal + +from openenv.core.rubrics.base import Rubric +from openenv.core.rubrics.containers import Gate, Sequential, WeightedSum +from pydantic import BaseModel, ConfigDict, Field, SecretStr + +MAX_TELEMETRY_BYTES = 8 * 1024 * 1024 +MAX_TRAJECTORY_ACTIONS = 100 +MAX_TRAJECTORY_RECORDS = 202 +MAX_RUBRIC_NODES = 128 + + +class _WireModel(BaseModel): + model_config = ConfigDict(extra="forbid", strict=True) + + +class ValidationOpenData(_WireModel): + schema_version: Literal[1] + token: SecretStr = Field(min_length=32, max_length=256) + + +class ValidationOpenMessage(_WireModel): + type: Literal["validation_open"] + data: ValidationOpenData + + +class ValidationReadData(_WireModel): + schema_version: Literal[1] + capability: SecretStr = Field(min_length=32, max_length=256) + + +class ValidationReadMessage(_WireModel): + type: Literal["validation_read"] + data: ValidationReadData + + +class ValidationOpenedData(_WireModel): + schema_version: Literal[1] = 1 + capability: str + + +class ValidationOpenedResponse(_WireModel): + type: Literal["validation_open"] = "validation_open" + data: ValidationOpenedData + + +class SeedAcceptance(_WireModel): + requested: bool + value: Any = None + accepted: bool + + +class RubricNode(_WireModel): + name: str + class_name: str + children: list[str] + aggregation: Literal["weighted_sum", "sequential", "gate", "leaf", "unknown"] + config: dict[str, Any] + config_available: bool + score: Any = None + evaluated: bool = False + + +class StepAttribution(_WireModel): + step_index: int + rubric: list[RubricNode] + + +class TrajectoryRecord(_WireModel): + operation: Literal["reset", "step", "state"] + request: dict[str, Any] + response: dict[str, Any] + + +class SubjectTrajectory(_WireModel): + schema_version: Literal[1] = 1 + source: Literal["openenv-server"] = "openenv-server" + records: list[TrajectoryRecord] = Field(default_factory=list) + complete: bool = True + reason: str | None = None + + +class ValidationSnapshot(_WireModel): + schema_version: Literal[1] = 1 + seed: SeedAcceptance | None = None + rubric: list[RubricNode] = Field(default_factory=list) + rubric_error: str | None = None + attribution: list[StepAttribution] = Field(default_factory=list) + trajectory: SubjectTrajectory = Field(default_factory=SubjectTrajectory) + + +class ValidationResponse(_WireModel): + type: Literal["validation"] = "validation" + data: ValidationSnapshot + + +def _rubrics(root: Rubric | None) -> list[tuple[str, Rubric]]: + """Visit the named tree with finite size, rejecting cycles and aliases.""" + if root is None: + return [] + result, pending, seen = [], [("root", root)], set() + while pending: + name, rubric = pending.pop() + if id(rubric) in seen or len(result) >= MAX_RUBRIC_NODES: + raise ValueError("Rubric tree is cyclic, shared, or exceeds 128 nodes") + seen.add(id(rubric)) + result.append((name, rubric)) + children = list(rubric.named_children()) + if any(not key or "." in key for key, _ in children): + raise ValueError("Rubric child names must be nonempty path segments") + pending.extend((f"{name}.{key}", child) for key, child in reversed(children)) + return result + + +def rubric_counts(root: Rubric | None) -> dict[int, int]: + return {id(r): r._evaluation_count for _, r in _rubrics(root)} + + +def rubric_snapshot( + root: Rubric | None, before: dict[int, int] | None = None +) -> list[RubricNode]: + nodes = [] + for name, rubric in _rubrics(root): + children = [f"{name}.{key}" for key, _ in rubric.named_children()] + aggregation = "unknown" if children else "leaf" + config = None + # Exact types: a subclass can override scoring, so its semantics are unknown. + if type(rubric) is WeightedSum: + aggregation, config = "weighted_sum", {"weights": list(rubric._weights)} + elif type(rubric) is Sequential: + aggregation, config = "sequential", {} + elif type(rubric) is Gate: + aggregation, config = "gate", {"threshold": rubric.threshold} + else: + config = rubric.validation_config() + evaluated = before is not None and rubric._evaluation_count > before.get( + id(rubric), 0 + ) + nodes.append( + RubricNode( + name=name, + class_name=f"{type(rubric).__module__}.{type(rubric).__qualname__}", + children=children, + aggregation=aggregation, + config={} if config is None else config, + config_available=config is not None, + score=rubric.last_score if evaluated else None, + evaluated=evaluated, + ) + ) + json.dumps([node.model_dump() for node in nodes], allow_nan=False) + return nodes + + +class SessionTelemetry: + """Own one socket's capability and a detached record of completed operations.""" + + def __init__(self): + self.capability = secrets.token_urlsafe(32) + self.snapshot = ValidationSnapshot() + self._bytes = 0 + self._steps = 0 + + def authorized(self, capability: str) -> bool: + return secrets.compare_digest(self.capability.encode(), capability.encode()) + + def append( + self, + operation: Literal["reset", "step", "state"], + request: dict[str, Any], + response: dict[str, Any], + *, + seed: SeedAcceptance | None = None, + rubric: list[RubricNode] | None = None, + ) -> None: + if not self.snapshot.trajectory.complete: + return + try: + # JSON round-trip detaches mutable observations/actions from the record. + record = TrajectoryRecord.model_validate( + json.loads( + json.dumps( + { + "operation": operation, + "request": request, + "response": response, + }, + allow_nan=False, + ) + ) + ) + attribution = ( + StepAttribution(step_index=self._steps, rubric=rubric or []) + if operation == "step" + else None + ) + byte_count = len(record.model_dump_json().encode()) + if attribution is not None: + byte_count += len(attribution.model_dump_json().encode()) + byte_count += ( + len(seed.model_dump_json().encode()) if seed is not None else 0 + ) + # Reserve room for the current rubric, envelope, and seed metadata. + current_bytes = len( + json.dumps( + [ + node.model_dump() + for node in (self.snapshot.rubric if rubric is None else rubric) + ], + allow_nan=False, + ).encode() + ) + if ( + len(self.snapshot.trajectory.records) >= MAX_TRAJECTORY_RECORDS + or operation == "step" + and self._steps >= MAX_TRAJECTORY_ACTIONS + or self._bytes + byte_count + current_bytes + 4096 > MAX_TELEMETRY_BYTES + ): + self.incomplete("Session telemetry budget exceeded") + return + self._bytes += byte_count + self.snapshot.trajectory.records.append(record) + if seed is not None: + self.snapshot.seed = seed.model_copy(deep=True) + if rubric is not None: + self.snapshot.rubric = [node.model_copy(deep=True) for node in rubric] + if attribution is not None: + self.snapshot.attribution.append(attribution.model_copy(deep=True)) + self._steps += 1 + except (TypeError, ValueError): + self.incomplete("Session telemetry contains non-JSON data") + + def incomplete(self, reason: str) -> None: + self.snapshot.trajectory.complete = False + self.snapshot.trajectory.reason = reason diff --git a/src/core/openenv/core/env_server/types.py b/src/core/openenv/core/env_server/types.py index 3ccc69bcb59ea814bc934bcadb8b9399fe009f33..c81c4e8e721e4cdba6559f78ee4196e165c930c8 100644 --- a/src/core/openenv/core/env_server/types.py +++ b/src/core/openenv/core/env_server/types.py @@ -236,6 +236,10 @@ class SchemaResponse(BaseMessage): state: Dict[str, Any] = Field( description="JSON schema for environment state objects" ) + reset: Optional[Dict[str, Any]] = Field( + default=None, + description="JSON schema for reset parameters accepted by this environment", + ) reset_observation: Optional[Dict[str, Any]] = Field( default=None, description="JSON schema for observations returned by reset" ) @@ -243,6 +247,8 @@ class SchemaResponse(BaseMessage): @model_serializer(mode="wrap") def _omit_undeclared_reset_schema(self, handler): data = handler(self) + if self.reset is None: + data.pop("reset", None) if self.reset_observation is None: data.pop("reset_observation", None) return data diff --git a/src/core/openenv/core/env_server/web_interface.py b/src/core/openenv/core/env_server/web_interface.py index b0366aefe38077bc0df050294d1913f1163ffaae..449b90f99dc133ab475eff66bf5bda4958487232 100644 --- a/src/core/openenv/core/env_server/web_interface.py +++ b/src/core/openenv/core/env_server/web_interface.py @@ -28,7 +28,7 @@ from .gradio_theme import OPENENV_GRADIO_CSS, OPENENV_GRADIO_THEME from .gradio_ui import build_gradio_app, get_gradio_display_title from .interfaces import Environment from .serialization import deserialize_action_with_preprocessing, serialize_observation -from .types import Action, EnvironmentMetadata, Observation, State +from .types import Action, EnvironmentMetadata, Observation, ResetRequest, State _CLIENT_BASES = {"EnvClient", "MCPClientBase", "MCPToolClient"} @@ -169,7 +169,7 @@ def get_quick_start_markdown( lines += ["", after] lines += [ "", - "More in the [OpenEnv documentation](https://huggingface.co/docs/openenv).", + "More in the [OpenEnv documentation](https://openenv.github.io/OpenEnv/).", ] return "\n".join(lines) @@ -485,6 +485,7 @@ def create_web_interface_app( *, mode: Optional[Any] = None, reset_observation_cls: Optional[Type[Observation]] = None, + reset_cls: Type[ResetRequest] = ResetRequest, ) -> FastAPI: """ Create a FastAPI application with web interface for the given environment. @@ -519,6 +520,9 @@ def create_web_interface_app( title instead of the default ``"OpenEnv Agentic Environment: {name}"``. state_cls: The State subclass this environment reports. Used for the /state response model and the state entry of /schema. Defaults to State. + reset_cls: The ResetRequest subclass describing reset parameters. Published + as the reset entry of /schema; not used for validation. Defaults to + ResetRequest. mode: Server mode (``ServerMode`` or string). When ``None``, resolved from the ``OPENENV_MODE`` environment variable, defaulting to simulation. @@ -537,6 +541,7 @@ def create_web_interface_app( concurrency_config, env_name=env_name, state_cls=state_cls, + reset_cls=reset_cls, reset_observation_cls=reset_observation_cls, mode=mode, ) @@ -638,6 +643,8 @@ def create_web_interface_app( css=OPENENV_GRADIO_CSS, ) + # Security middleware is attached inside create_fastapi_app, before the + # gradio mount at /web; it is app-level middleware, so it covers the mount. return app diff --git a/src/core/openenv/core/harness/bridge.py b/src/core/openenv/core/harness/bridge.py index 7167690ac56b926e05644771bc66591aafde2263..badf965571c2f1e096dddbcb87fe178dc86e08f7 100644 --- a/src/core/openenv/core/harness/bridge.py +++ b/src/core/openenv/core/harness/bridge.py @@ -14,7 +14,7 @@ from .adapter import HarnessError async def _source_tools(mcp_server: Any) -> dict[str, Any]: - """Return {name: FastMCP tool}, compatible with FastMCP 2.x and 3.x. + """Return {name: FastMCP tool}. Async twin of [`~openenv.core.env_server.mcp_environment.get_server_tools`], which wraps the same calls in `run_async_safely`; awaiting directly avoids @@ -52,9 +52,11 @@ async def build_bridge_server(mcp_server: Any, renames: dict[str, str]) -> Any: return mcp_server from fastmcp import Client + from fastmcp.server.dependencies import get_context from fastmcp.server.providers.proxy import FastMCPProxy, StatefulProxyClient from fastmcp.server.transforms import ToolTransform from fastmcp.tools.tool_transform import ToolTransformConfig + from mcp_types.version import MODERN_PROTOCOL_VERSIONS source_tools = await _source_tools(mcp_server) missing = sorted(set(renames.values()) - set(source_tools)) @@ -71,12 +73,20 @@ async def build_bridge_server(mcp_server: Any, renames: dict[str, str]) -> Any: async with Client(mcp_server): yield {} - # Forward callbacks in the current request context. Each harness MCP - # connection gets its own source session, closed on disconnect. + # Keep one backend client per front connection, and mirror its protocol era. + # StatefulProxyClient defaults to legacy, which cannot carry sampling guards. client = StatefulProxyClient(mcp_server) + + def client_factory(): + backend = client.new_stateful() + if not backend.is_connected(): + version = get_context().request_context.protocol_version + backend.mode = version if version in MODERN_PROTOCOL_VERSIONS else "legacy" + return backend + view = FastMCPProxy( name=f"{getattr(mcp_server, 'name', 'openenv')}-harness-view", - client_factory=client.new_stateful, + client_factory=client_factory, lifespan=lifespan, ) view.add_transform( diff --git a/src/core/openenv/core/harness/capture/forwarding.py b/src/core/openenv/core/harness/capture/forwarding.py index 1c8e841452f86aaaf16107395813f5c408fb0b54..83aa1bb834d720c6e2cafd42e1c8564492990852 100644 --- a/src/core/openenv/core/harness/capture/forwarding.py +++ b/src/core/openenv/core/harness/capture/forwarding.py @@ -33,6 +33,7 @@ why `SessionRegistry.require_registered` defaults to True. from __future__ import annotations +import importlib import logging import re import secrets @@ -42,6 +43,12 @@ import subprocess import threading import time from abc import ABC, abstractmethod +from pathlib import Path + +try: + import fcntl +except ImportError: # Windows: no advisory locks, keep gradio's unlocked download. + fcntl = None logger = logging.getLogger(__name__) @@ -147,6 +154,25 @@ class GradioForwarder(PortForwarder): f"gradio is required for GradioForwarder: {exc}" ) from exc + @staticmethod + def _ensure_frpc_binary() -> None: + """ + Download gradio's frpc binary once, under a cross-process lock. + + Gradio checks `Path(BINARY_PATH).exists()` and then writes the binary in place. A second + process that starts while the first is still writing sees the file, skips the download and + executes a half-written binary, which fails with `Text file busy` (ETXTBSY) or a corrupt + executable. Holding an exclusive lock next to the binary makes every other process wait + until the first download has finished, after which gradio's own check skips the download. + """ + tunneling = importlib.import_module("gradio.tunneling") + binary = Path(tunneling.BINARY_PATH) + binary.parent.mkdir(parents=True, exist_ok=True) + with open(binary.with_name(binary.name + ".lock"), "a") as lock_file: + if fcntl is not None: + fcntl.flock(lock_file, fcntl.LOCK_EX) + tunneling.Tunnel.download_binary() + def start(self, local_port: int, *, local_host: str = "127.0.0.1") -> str: from gradio.networking import setup_tunnel from gradio.tunneling import CURRENT_TUNNELS @@ -154,6 +180,7 @@ class GradioForwarder(PortForwarder): self.stop() share_token = secrets.token_hex(16) try: + self._ensure_frpc_binary() url = setup_tunnel( local_host=local_host, local_port=local_port, diff --git a/src/core/openenv/core/harness/capture/graph.py b/src/core/openenv/core/harness/capture/graph.py index 61cc88bf2dc54662e9fa55d643ae4468d9e0a808..820689b54d21c97bd57172b06493f1871c5a466c 100644 --- a/src/core/openenv/core/harness/capture/graph.py +++ b/src/core/openenv/core/harness/capture/graph.py @@ -248,9 +248,25 @@ class RolloutGraph: self._nodes: dict[str, TurnNode] = {} self._order: list[str] = [] self._children: dict[str, list[str]] = {} + # Every request re-sends the whole history, so each turn decodes a fresh copy of every + # earlier image and long text. Keep one copy per graph. Only immutable strings are shared; + # message dicts and lists stay per turn. + self._shared_text: dict[str, str] = {} + + def _share_text(self, value: Any) -> Any: + if isinstance(value, str) and len(value) >= 1024: + return self._shared_text.setdefault(value, value) + if isinstance(value, list): + return [self._share_text(item) for item in value] + if isinstance(value, dict): + return {key: self._share_text(item) for key, item in value.items()} + return value # --- construction -------------------------------------------------- def add_turn(self, node: TurnNode) -> TurnNode: + node.request_messages = self._share_text(node.request_messages) + node.request_tools = self._share_text(node.request_tools) + node.response_message = self._share_text(node.response_message) node.index = len(self._order) node.parent_id = self._find_parent(node) self._nodes[node.node_id] = node diff --git a/src/core/openenv/core/harness/capture/server.py b/src/core/openenv/core/harness/capture/server.py index 32b9dad48bf7934f1c67c0f91dd36d748d4315c3..9d9f956c55b37c29143266e1bd7da747afbb26b7 100644 --- a/src/core/openenv/core/harness/capture/server.py +++ b/src/core/openenv/core/harness/capture/server.py @@ -266,6 +266,41 @@ def clamp_output_tokens(chat_request: dict[str, Any], cap: int | None) -> int | return replaced +def context_window_ran_out( + chat_request: dict[str, Any], response: dict[str, Any] +) -> bool: + """Whether the engine cut the completion short because the context window was full. + + Older vLLM rejects a request whose prompt plus `max_tokens` exceeds the context window with a 400 + ("maximum context length"), which the proxy turns into a budget stop. Newer vLLM (seen with 0.34) + serves it and stops generating when the window is full instead: the completion ends with + `finish_reason="length"` before reaching `max_tokens`. Forwarded as is, that truncated turn reaches + the harness, and pi answers it by compacting its context, in a summarisation call capture cannot + tie to the rest of the rollout: every such rollout fails validation with `turn_mismatch`. It is the + same event as the 400, so it ends the rollout the same way. + """ + # The limit the engine applies, in its order: vLLM (like OpenAI) takes `max_completion_tokens` and + # falls back to `max_tokens`. A harness that sends both with different values would otherwise turn + # an output-cap stop into a context stop, or hide a real one. + requested = next( + ( + chat_request[key] + for key in ("max_completion_tokens", "max_tokens") + if isinstance(chat_request.get(key), int) + ), + None, + ) + choices = response.get("choices") or [] + completion_tokens = (response.get("usage") or {}).get("completion_tokens") + return ( + requested is not None + and isinstance(completion_tokens, int) + and bool(choices) + and choices[0].get("finish_reason") == "length" + and completion_tokens < requested + ) + + def normalise_for_capture(chat_request: dict[str, Any]) -> None: """Force the upstream call into the one shape that yields complete, capturable responses. @@ -1199,6 +1234,23 @@ def create_app( for key in SAMPLING_KEYS: chat_request.pop(key, None) chat_request.update(effective_sampling) + if context_window_ran_out(chat_request, response): + # Like the 400 above: a stop the harness ends on, and the truncated turn is never ingested + session.findings.append( + "[WARN] context_budget_exhausted: the engine stopped at the context window, " + "before max_tokens" + ) + session.budget_stop_count += 1 + stop = _budget_stop_response(_model_of(session) or app.state.model) + if client_wants_stream: + return StreamingResponse( + sse.replay(api_type, transformer, stop, original_request), + media_type="text/event-stream", + headers=sse.SSE_HEADERS, + ) + payload = transformer.transform_response(stop, original_request) + normalise_client_payload(payload, api_type) + return JSONResponse(payload) normalise_response(response) _ingest( session, diff --git a/src/core/openenv/core/harness/capture/validate_llm.py b/src/core/openenv/core/harness/capture/validate_llm.py index 41028e4a6b389aeff73511fff1508cb4c5facec3..4c96a4798c4cebb49b74e3e067fa65be2ac49d9b 100644 --- a/src/core/openenv/core/harness/capture/validate_llm.py +++ b/src/core/openenv/core/harness/capture/validate_llm.py @@ -44,11 +44,13 @@ from __future__ import annotations import json import os +import time import urllib.error import urllib.request from dataclasses import dataclass, field +from urllib.parse import urlsplit -from .compat import behaviour_warnings, diagnose, MAX_FIXES +from .compat import behaviour_warnings, diagnose, MAX_FIXES, ParamFix from .upstream import ( auth_headers, normalise_engine_base, @@ -70,6 +72,25 @@ ENGINE_HINT = ( ) +# How many times the probe repeats the SAME request after an error that names nothing it can fix. +# Hosted routers occasionally answer a valid request with a 400 or 5xx that a resend clears: observed +# as one task in ~150 aborting before it ran, against an endpoint that served the other 149. +PROBE_RETRIES = 2 +PROBE_RETRY_DELAY = 1.0 +# Errors no resend or rewrite can fix: bad credentials, no access, no such route or model. Retrying +# these only delays a message the user needs now. +_FATAL_HTTP = frozenset({401, 403, 404}) +# Statuses with which a provider rejects a request it doesn't accept, e.g. unsupported capture params. +_PARAM_REJECTION_HTTP = frozenset({400, 422}) +# What the eval fallback drops. `logprobs` also takes `top_logprobs` with it (see `ParamFix.apply`). +_CAPTURE_PARAMS = ("return_token_ids", "logprobs") + + +def _is_timeout(exc: BaseException) -> bool: + reason = getattr(exc, "reason", None) + return isinstance(exc, TimeoutError) or isinstance(reason, TimeoutError) + + @dataclass class LLMReport: """Outcome of the probe. `ok` means trainable; `reachable` means usable at all.""" @@ -574,7 +595,10 @@ def validate_llm( # or gate it behind different scopes than inference, and refusing there would reject an endpoint # that serves completions perfectly well. The completion probe below is the real test; a missing # list only costs us the model-name check. - listed_model = model.rsplit(":", 1)[0] if provider == "hf" else model + # The HF router lists bare ids but routes `:` (also `:fastest`, `:cheapest`). The + # CLI reaches it with the default provider, so recognise the router by its host as well. + hf_router = urlsplit(base).hostname == "router.huggingface.co" + listed_model = model.rsplit(":", 1)[0] if provider == "hf" or hf_router else model if served and model not in served and listed_model not in served: # Worth failing on rather than warning: a mismatched name is silently accepted by some # servers and then every request 404s at rollout time instead of at startup. @@ -603,6 +627,7 @@ def validate_llm( applied: list = [] payload: dict | None = None failure = "" + retries_left = PROBE_RETRIES # Negotiate down. Each 400 that names a parameter costs one retry and removes one obstacle; the # capture params are the ones most likely to go, and losing them is what decides the level. @@ -630,13 +655,40 @@ def validate_llm( fix = diagnose(json.loads(detail)) except json.JSONDecodeError: fix = diagnose(detail) - if fix is None or not fix.apply(body): - failure = f"probe failed: HTTP {exc.code}: {detail[:300]}" + if fix is not None and fix.apply(body): + fixes.append(str(fix)) + applied.append(fix) + continue + failure = f"probe failed: HTTP {exc.code}: {detail[:300]}" + if exc.code in _FATAL_HTTP: break - fixes.append(str(fix)) - applied.append(fix) + # An error that names no parameter is first treated as transient: the same request again. + if retries_left: + retries_left -= 1 + time.sleep(PROBE_RETRY_DELAY) + continue + # Still failing. Some providers reject the capture params with a bare 400 that names + # nothing, so ask once more without them. If that answers, the endpoint is an eval + # backend (the level is graded from what comes back), which is what `ENGINE_HINT` + # promises. A `purpose="train"` rollout still refuses it, since the level is not `tokens`. + # Only a request error can be about the params: a 5xx or a 429 that outlasts the retries + # is reported, rather than grading a busy token-capable engine as `text`. + if exc.code not in _PARAM_REJECTION_HTTP: + break + dropped = [ParamFix(param=p) for p in _CAPTURE_PARAMS] + dropped = [f for f in dropped if f.apply(body)] + if not dropped: + break + for f in dropped: + fixes.append(f"{f} (eval fallback after HTTP {exc.code})") + applied.append(f) except Exception as exc: # noqa: BLE001 failure = f"probe failed: {type(exc).__name__}: {str(exc)[:300]}" + # A timeout is worth repeating. Anything else here (connection refused, DNS) is not. + if _is_timeout(exc) and retries_left: + retries_left -= 1 + time.sleep(PROBE_RETRY_DELAY) + continue break if payload is None: diff --git a/src/core/openenv/core/harness/collect.py b/src/core/openenv/core/harness/collect.py index 946ce5d54b98fc66ed8ed2e8821b38683a6f86ba..82d0a5fb14485cb871c44878961b15235f6d526d 100644 --- a/src/core/openenv/core/harness/collect.py +++ b/src/core/openenv/core/harness/collect.py @@ -23,10 +23,11 @@ import warnings from dataclasses import asdict, dataclass, field from datetime import datetime, timezone from pathlib import Path -from typing import Any, BinaryIO, Callable, Iterable, Iterator +from typing import Any, BinaryIO, Callable, Iterable from ..env_server.mcp_types import Tool from ..llm_client import LLMClient +from ..utils import redact_secrets from .rollout import ( _resolve_env_reward, HarnessAdapter, @@ -237,9 +238,10 @@ class CollectResult: class CollectRunner: """Drive repeated rollouts into an append-only JSONL dataset. - The runner is stateless across ``run()`` calls — resume state lives on - disk via the ``RolloutSerializer``. A single runner instance can be - reused across runs targeting different output dirs. + Resume state lives on disk via the ``RolloutSerializer``. Repeatable task + iterables, such as lists and tuples, restart at the first task on each + ``run()`` so tasks stay aligned with episode ids. One-shot iterators work + for one run; reusing them raises ``ValueError`` before accessing results. """ def __init__( @@ -254,17 +256,10 @@ class CollectRunner: self._session_factory = session_factory self._harness_adapter = harness_adapter self._serializer = serializer - self._tasks: Iterator[Any] | None = iter(tasks) if tasks is not None else None + self._tasks = tasks + self._tasks_used = False self._limits = limits - def _next_task(self) -> Any: - if self._tasks is None: - return None - try: - return next(self._tasks) - except StopIteration: - return None - def run( self, *, @@ -274,6 +269,16 @@ class CollectRunner: resume: bool = True, should_keep: Callable[[EpisodeRecord], bool] | None = None, ) -> CollectResult: + task_iterator = iter(self._tasks) if self._tasks is not None else None + if ( + task_iterator is not None + and task_iterator is self._tasks + and self._tasks_used + ): + raise ValueError( + "Cannot reuse a one-shot task iterator; pass a repeatable iterable " + "or create a new CollectRunner with a fresh iterator." + ) planned_ids = [f"{episode_id_prefix}-{i:06d}" for i in range(num_episodes)] if resume: @@ -312,7 +317,8 @@ class CollectRunner: with progress: for episode_id in planned_ids: # Preserve task-to-episode alignment even when resume skips ids. - task = self._next_task() + self._tasks_used = True + task = next(task_iterator, None) if task_iterator is not None else None if episode_id in already: num_skipped += 1 progress.advance(task_id) @@ -513,7 +519,7 @@ def build_dataset_readme(output_dir: Path) -> str: "", "# OpenEnv rollouts", "", - "Collected with [OpenEnv](https://github.com/huggingface/OpenEnv) " + "Collected with [OpenEnv](https://github.com/openenv/OpenEnv) " "(`openenv collect`).", "", f"- **Episodes:** {_count_episodes(results_path)}", @@ -594,6 +600,19 @@ def push_to_hf_hub( readme_path = output_dir / README_FILENAME readme_path.write_text(build_dataset_readme(output_dir), encoding="utf-8") + # Episodes hold what the agent saw and printed, which can include credentials. + redacted = 0 + for path in output_dir.iterdir(): + if path.suffix in {".jsonl", ".json", ".md"}: + text, count = redact_secrets(path.read_text(encoding="utf-8")) + if count: + path.write_text(text, encoding="utf-8") + redacted += count + if redacted: + warnings.warn( + f"Redacted {redacted} secret(s) from {output_dir} before the upload" + ) + num_episodes = _count_episodes(results_path) message = commit_message or f"Add {num_episodes} collected episode(s)" diff --git a/src/core/openenv/core/mcp_client.py b/src/core/openenv/core/mcp_client.py index 9002fabf9bcafc743660cb6cf04e364976c45391..c7967a926291691a58e79fddb647e5ff7a214272 100644 --- a/src/core/openenv/core/mcp_client.py +++ b/src/core/openenv/core/mcp_client.py @@ -255,6 +255,12 @@ class MCPClientBase(EnvClient[Any, Observation, State]): return await super()._connect_async() + def _raise_if_session_lost(self) -> None: + # In production mode a reconnect attaches to the same HTTP MCP session, + # which outlives the WebSocket, so the episode carries over. + if not getattr(self, "use_production_mode", False): + super()._raise_if_session_lost() + async def _ensure_production_session(self) -> str: """Create and cache a persistent HTTP MCP session id if needed.""" async with self._production_session_lock: diff --git a/src/core/openenv/core/rubrics/base.py b/src/core/openenv/core/rubrics/base.py index 0e2753047f755f2fcd1a5f263f3f25d5cd67b55d..276de7b3c456ed1d0c0f8b7e5831bd9bc9e1eb40 100644 --- a/src/core/openenv/core/rubrics/base.py +++ b/src/core/openenv/core/rubrics/base.py @@ -46,6 +46,7 @@ class Rubric(ABC): object.__setattr__(self, "_forward_hooks", []) object.__setattr__(self, "_forward_pre_hooks", []) object.__setattr__(self, "last_score", None) + object.__setattr__(self, "_evaluation_count", 0) def __setattr__(self, name: str, value: Any) -> None: # Auto-register child rubrics when assigned as attributes @@ -118,6 +119,7 @@ class Rubric(ABC): def _finish_forward(self, action: Any, observation: Any, result: float) -> float: """Store the result and run post-forward hooks synchronously.""" self.last_score = result + self._evaluation_count += 1 # Post-forward hooks for hook in self._forward_hooks: @@ -130,6 +132,7 @@ class Rubric(ABC): ) -> float: """Store the result and run post-forward hooks from an async call path.""" self.last_score = result + self._evaluation_count += 1 # Post-forward hooks for hook in self._forward_hooks: @@ -234,8 +237,22 @@ class Rubric(ABC): return current def reset(self) -> None: - """Reset any internal state. Override in subclasses if needed.""" - pass + """Reset internal state, including every child rubric. + + Override to clear your own state and call `super().reset()` so child + rubrics are reset too. + """ + for child in self.children(): + child.reset() + + def validation_config(self) -> Optional[Dict[str, Any]]: + """Return explicitly public configuration for authorized validation. + + Override to expose JSON configuration without credentials or runtime state. + ``None`` means configuration introspection is unavailable. Stock aggregation + containers expose their weights/threshold directly through the server. + """ + return None def state_dict(self) -> Dict[str, Any]: """Serialize rubric configuration for checkpointing.""" diff --git a/src/core/openenv/core/rubrics/containers.py b/src/core/openenv/core/rubrics/containers.py index ed796aaa1d64a425f2d1d1cf3e0206bf5e695750..17d88a8dbe934e551fef52df0f67b4e65a30d3f2 100644 --- a/src/core/openenv/core/rubrics/containers.py +++ b/src/core/openenv/core/rubrics/containers.py @@ -76,6 +76,8 @@ class Sequential(Rubric): # Pre-hooks run before any child is evaluated ran = self._run_leading_sync_pre_hooks(action, observation) + if ran < len(self._forward_pre_hooks): + return self._call_async_detected(action, observation, None, ran) # Call first rubric to see if it's async first_result = self._rubric_list[0](action, observation) @@ -85,8 +87,7 @@ class Sequential(Rubric): else: # Continue with sync path if first_result == 0.0: - self._run_forward_pre_hooks(action, observation, start=ran) - return self._finish_forward(action, observation, 0.0) + return self._finish_sync(action, observation, 0.0, ran) final_result = first_result for i, rubric in enumerate(self._rubric_list[1:], start=1): @@ -102,16 +103,21 @@ class Sequential(Rubric): ran, ) if score == 0.0: - self._run_forward_pre_hooks(action, observation, start=ran) - return self._finish_forward(action, observation, 0.0) + return self._finish_sync(action, observation, 0.0, ran) final_result = score - # All sync - check if in async context - if _in_async_context(): - return self._wrap_sync_result(action, observation, final_result, ran) - else: - self._run_forward_pre_hooks(action, observation, start=ran) - return self._finish_forward(action, observation, final_result) + return self._finish_sync(action, observation, final_result, ran) + + def _finish_sync(self, action, observation, result, ran=0): + """Finish a run where every evaluated child was sync. + + In an async context, return an awaitable even when a child stopped + the chain, so callers can always ``await`` the result. + """ + if _in_async_context(): + return self._wrap_sync_result(action, observation, result, ran) + self._run_forward_pre_hooks(action, observation, start=ran) + return self._finish_forward(action, observation, result) async def _empty_async(self, action, observation): """Async path for empty sequential.""" @@ -124,10 +130,16 @@ class Sequential(Rubric): return await self._finish_forward_async(action, observation, result) async def _call_async_detected(self, action, observation, first_coro, ran=0): - """Async path when first child is async.""" + """Async path for an async first child or pending pre-hooks.""" await self._run_forward_pre_hooks_async(action, observation, start=ran) - result = await first_coro + result = ( + self._rubric_list[0](action, observation) + if first_coro is None + else first_coro + ) + if inspect.iscoroutine(result): + result = await result if result == 0.0: return await self._finish_forward_async(action, observation, result) @@ -207,6 +219,8 @@ class Gate(Rubric): """Override to handle async child.""" # Pre-hooks run before the child is evaluated ran = self._run_leading_sync_pre_hooks(action, observation) + if ran < len(self._forward_pre_hooks): + return self._call_async(action, observation, None, ran) # Call child score = self.rubric(action, observation) @@ -224,7 +238,9 @@ class Gate(Rubric): """Async path.""" await self._run_forward_pre_hooks_async(action, observation, start=ran) - score = await score_coro + score = self.rubric(action, observation) if score_coro is None else score_coro + if inspect.iscoroutine(score): + score = await score result = 0.0 if score < self.threshold else score return await self._finish_forward_async(action, observation, result) @@ -282,6 +298,8 @@ class WeightedSum(Rubric): """Override to handle async children with parallel execution.""" # Pre-hooks run before any child is evaluated ran = self._run_leading_sync_pre_hooks(action, observation) + if ran < len(self._forward_pre_hooks): + return self._call_async(action, observation, None, ran) # Call all rubrics results = [rubric(action, observation) for rubric in self._rubric_list] @@ -304,6 +322,9 @@ class WeightedSum(Rubric): """Async path with parallel execution.""" await self._run_forward_pre_hooks_async(action, observation, start=ran) + if results is None: + results = [rubric(action, observation) for rubric in self._rubric_list] + # Separate sync and async results async_tasks = [] async_indices = [] diff --git a/src/core/openenv/core/rubrics/trajectory.py b/src/core/openenv/core/rubrics/trajectory.py index 6a62aceb5a19df77fe007d950266a58c2c3f8434..db94ee10bb4026ecc5d8caf3ab45be84bfb64c4a 100644 --- a/src/core/openenv/core/rubrics/trajectory.py +++ b/src/core/openenv/core/rubrics/trajectory.py @@ -118,6 +118,7 @@ class TrajectoryRubric(Rubric): def reset(self) -> None: """Clear accumulated trajectory. Call on env.reset().""" + super().reset() self._trajectory = [] @property diff --git a/src/core/openenv/core/sync_client.py b/src/core/openenv/core/sync_client.py index 0de088a095c6f8382bc10d6accc842ecc2350c51..4c94ce5732af67b5e405df6162a6d977e3e4c784 100644 --- a/src/core/openenv/core/sync_client.py +++ b/src/core/openenv/core/sync_client.py @@ -243,8 +243,15 @@ class SyncEnvClient(Generic[ActT, ObsT, StateT]): WebSocket can fail and is surfaced as a connection error. """ async_client = self._async._create_session_client() - client = SyncEnvClient(async_client) - client.connect() + client = async_client.sync() + try: + client.connect() + except Exception: + # No caller receives this child on failure. Release its loop here + # while preserving the connection error if cleanup also fails. + with suppress(Exception): + client.close() + raise self._child_clients.append(client) return client diff --git a/src/core/openenv/core/tools/git_server_client.py b/src/core/openenv/core/tools/git_server_client.py index b0100a444e7835784eec48478184b855feba5c7e..ea20134e225c62c86f66e0b49be11621ac0a2d50 100644 --- a/src/core/openenv/core/tools/git_server_client.py +++ b/src/core/openenv/core/tools/git_server_client.py @@ -10,6 +10,7 @@ instances share the same Gitea server but have isolated workspaces. import atexit import json import os +import re import shlex import shutil import subprocess @@ -17,7 +18,82 @@ import tempfile import time from dataclasses import dataclass from pathlib import Path -from urllib.parse import urlparse +from urllib.parse import quote, urlparse + +# Git subcommands an agent may run. Left out: those that run other programs (submodule, bisect, +# difftool, filter-branch) or read files outside the repository (hash-object, apply, am), and +# global options before the subcommand (`-c`, `-C`, `--git-dir`). +_AGENT_SUBCOMMANDS = frozenset( + { + "add", + "blame", + "branch", + "checkout", + "cherry-pick", + "commit", + "config", + "describe", + "diff", + "fetch", + "grep", + "init", + "log", + "ls-files", + "merge", + "mv", + "pull", + "push", + "rebase", + "remote", + "reset", + "restore", + "rev-parse", + "revert", + "rm", + "shortlog", + "show", + "stash", + "status", + "switch", + "tag", + } +) +# Options that run a program or read or write a path outside the repository. Git also accepts any +# unambiguous prefix of a long option, so prefixes are refused too. +_BLOCKED_LONG_OPTIONS = ( + "--config", + "--exec", + "--ext-diff", + "--extcmd", + "--file", + "--no-index", + "--open-files-in-pager", + "--output", + "--pathspec-from-file", + "--receive-pack", + "--template", + "--upload-pack", +) +_BLOCKED_SHORT_OPTIONS = "FOx" # -F , grep -O , rebase -x +_SECRET_ENV_NAME = re.compile(r"(^|_)(TOKEN|KEY|SECRET|PASSWORD)(_|$)", re.IGNORECASE) + + +def _refusal(args: list[str]) -> str | None: + """Why an agent's git arguments are refused, or `None` when they may run.""" + if not args or args[0] not in _AGENT_SUBCOMMANDS: + return f"git {args[0] if args else ''} is not available here" + if args[0] == "config" and ( + len(args) > 3 or args[1:2] not in (["--get"], ["--get-all"], ["--list"]) + ): + return "git config is not available here, except --get , --get-all and --list" + for arg in args[1:]: + name = arg.split("=", 1)[0] + if name.startswith("--") and len(name) > 2: + if any(option.startswith(name) for option in _BLOCKED_LONG_OPTIONS): + return f"{name} is not available here" + elif name.startswith("-") and set(name[1:]) & set(_BLOCKED_SHORT_OPTIONS): + return f"{name} is not available here" + return None @dataclass @@ -101,10 +177,13 @@ class GitServerClient: config_dir = Path(tempfile.mkdtemp(prefix="openenv-git-")) atexit.register(shutil.rmtree, config_dir, ignore_errors=True) - # Git credentials - git_credentials = ( - f"http://{self.username}:{self.password}@{self.domain}:{self.port}\n" - ) + # Git credentials. The entry must match the URL git is given (scheme and + # host[:port]), and the user name and password must be percent-encoded + # so characters such as "@", ":", "/" or "#" do not break the URL. + parsed = urlparse(self.gitea_url) + user = quote(self.username, safe="") + password = quote(self.password, safe="") + git_credentials = f"{parsed.scheme}://{user}:{password}@{parsed.netloc}\n" gitcreds_path = config_dir / "git-credentials" gitcreds_path.write_text(git_credentials) gitcreds_path.chmod(0o600) @@ -121,7 +200,12 @@ class GitServerClient: gitconfig_path = config_dir / "gitconfig" gitconfig_path.write_text(git_config) - self._git_env = {**os.environ, "GIT_CONFIG_GLOBAL": str(gitconfig_path)} + # Agents run git in this environment, so it carries no credentials of the server. + self._git_env = { + **{k: v for k, v in os.environ.items() if not _SECRET_ENV_NAME.search(k)}, + "GIT_CONFIG_GLOBAL": str(gitconfig_path), + "GIT_ALLOW_PROTOCOL": "http:https", + } def wait_for_ready(self, timeout: int = 30) -> bool: """ @@ -219,7 +303,10 @@ class GitServerClient: raise RuntimeError("Gitea server is not ready") target_dir = target_dir or repo_name - target_path = self.workspace_dir / target_dir + workspace = self.workspace_dir.resolve() + target_path = (workspace / target_dir).resolve() + if target_path == workspace or not target_path.is_relative_to(workspace): + raise ValueError(f"target_dir {target_dir!r} is outside the workspace") # Remove existing directory if present if target_path.exists(): @@ -349,14 +436,19 @@ class GitServerClient: Returns: `tuple` of (exit_code, stdout, stderr). """ - work_path = ( - self.workspace_dir / working_dir if working_dir else self.workspace_dir - ) + workspace = self.workspace_dir.resolve() + work_path = (workspace / working_dir).resolve() + if not work_path.is_relative_to(workspace): + return (1, "", f"working_dir {working_dir!r} is outside the workspace") if not work_path.exists(): return (1, "", f"Working directory does not exist: {work_path}") - cmd_parts = ["git"] + shlex.split(command) + args = shlex.split(command) + refusal = _refusal(args) + if refusal: + return (1, "", refusal) + cmd_parts = ["git"] + args result = subprocess.run( cmd_parts, diff --git a/src/core/openenv/core/tools/local_python_executor.py b/src/core/openenv/core/tools/local_python_executor.py index ac73730da739f2f042bf184b5452f9ef2bfa4a97..0d5e5762e826482acb8acbcaf4ade12fd0b192f1 100644 --- a/src/core/openenv/core/tools/local_python_executor.py +++ b/src/core/openenv/core/tools/local_python_executor.py @@ -35,6 +35,12 @@ class PyExecutor: LocalPythonExecutor that can be used by the executed code to format exceptions and to safely stringify results for improved error reporting. + + LocalPythonExecutor is an interpreter that restricts imports and + attributes, not a sandbox: the code runs in the current process and can + reach what that process holds. Run model code with it in a separate + process that has no secrets (environment variables, tokens in memory), + as `coding_env` does with one worker process per session. """ def __init__(self, additional_imports: list[str] | None = None): diff --git a/src/core/openenv/core/utils.py b/src/core/openenv/core/utils.py index 70c14ae7a49299d111ad97d74a91524361ff5c9f..9dd72c4a5bd5e3e3b0f29e588905f90182fb41a8 100644 --- a/src/core/openenv/core/utils.py +++ b/src/core/openenv/core/utils.py @@ -4,6 +4,8 @@ import asyncio import concurrent.futures +import json +import os import re @@ -71,3 +73,43 @@ def hf_space_subdomain(repo_id: str) -> str: The Space subdomain. """ return re.sub(r"[^a-z0-9]", "-", repo_id.lower()) + + +_SECRET_PATTERN = re.compile( + r"hf_[A-Za-z0-9]{30,}" + r"|sk-[A-Za-z0-9_-]{20,}" + r"|gh[pousr]_[A-Za-z0-9]{30,}|github_pat_[A-Za-z0-9_]{30,}" + r"|(?:AKIA|ASIA)[A-Z0-9]{16}" + r"|-----BEGIN [A-Z ]*PRIVATE KEY-----.*?-----END [A-Z ]*PRIVATE KEY-----", + re.DOTALL, +) +_SECRET_ENV_NAME = re.compile(r"(^|_)(TOKEN|KEY|SECRET|PASSWORD)(_|$)", re.IGNORECASE) + + +def redact_secrets(text: str) -> tuple[str, int]: + """ + Replace credentials in `text` with ``. + + Covers Hugging Face, OpenAI/Anthropic, GitHub and AWS keys, private key blocks, and the value of + every environment variable of this process with `TOKEN`, `KEY`, `SECRET` or `PASSWORD` as a part + of its name (`HF_TOKEN`, `OPENAI_API_KEY`), also in its JSON-escaped form. Agent traces can hold + any of them: a model that runs `env` or reads a config file puts the value in its own output. + + Args: + text (`str`): + Text to scan. + + Returns: + `tuple[str, int]`: The redacted text and the number of secrets replaced. + """ + count = 0 + for name, value in os.environ.items(): + if not _SECRET_ENV_NAME.search(name) or len(value) < 8: + continue + # Traces are JSON, where quotes, backslashes and non-ASCII characters are escaped. The + # escaped form goes first: it can contain the raw one (a value ending in a backslash). + for form in (json.dumps(value)[1:-1], value): + count += text.count(form) + text = text.replace(form, "") + text, matches = _SECRET_PATTERN.subn("", text) + return text, count + matches diff --git a/src/core/openenv/discovery/schemas/0.1-draft/catalog.schema.json b/src/core/openenv/discovery/schemas/0.1-draft/catalog.schema.json index 40d4b356862a88fbcd81151027cc899e6b0432b5..4863c0501bb0f2cc3f96bad371d96627f40eac30 100644 --- a/src/core/openenv/discovery/schemas/0.1-draft/catalog.schema.json +++ b/src/core/openenv/discovery/schemas/0.1-draft/catalog.schema.json @@ -652,7 +652,7 @@ "type": "object" } }, - "$id": "https://raw.githubusercontent.com/huggingface/OpenEnv/main/src/openenv/discovery/schemas/0.1-draft/catalog.schema.json", + "$id": "https://raw.githubusercontent.com/openenv/OpenEnv/main/src/openenv/discovery/schemas/0.1-draft/catalog.schema.json", "$schema": "https://json-schema.org/draft/2020-12/schema", "additionalProperties": false, "properties": { diff --git a/src/core/openenv/discovery/schemas/0.1-draft/declaration.schema.json b/src/core/openenv/discovery/schemas/0.1-draft/declaration.schema.json index fb7422a1c8d3d9a34cc55429d1f742271e363239..f57d3d2cd4f15802851e4932b7b05e41c6826e09 100644 --- a/src/core/openenv/discovery/schemas/0.1-draft/declaration.schema.json +++ b/src/core/openenv/discovery/schemas/0.1-draft/declaration.schema.json @@ -49,7 +49,7 @@ "type": "object" } }, - "$id": "https://raw.githubusercontent.com/huggingface/OpenEnv/main/src/openenv/discovery/schemas/0.1-draft/declaration.schema.json", + "$id": "https://raw.githubusercontent.com/openenv/OpenEnv/main/src/openenv/discovery/schemas/0.1-draft/declaration.schema.json", "$schema": "https://json-schema.org/draft/2020-12/schema", "additionalProperties": false, "properties": { diff --git a/src/core/openenv/discovery/schemas/0.1-draft/environment-card.schema.json b/src/core/openenv/discovery/schemas/0.1-draft/environment-card.schema.json index f8980e004eb07000628f2e1e9f467dbeda3dad5a..cf0a2ecfe9b034b9c76519de718a5d453ecb28c3 100644 --- a/src/core/openenv/discovery/schemas/0.1-draft/environment-card.schema.json +++ b/src/core/openenv/discovery/schemas/0.1-draft/environment-card.schema.json @@ -186,7 +186,7 @@ "type": "object" } }, - "$id": "https://raw.githubusercontent.com/huggingface/OpenEnv/main/src/openenv/discovery/schemas/0.1-draft/environment-card.schema.json", + "$id": "https://raw.githubusercontent.com/openenv/OpenEnv/main/src/openenv/discovery/schemas/0.1-draft/environment-card.schema.json", "$schema": "https://json-schema.org/draft/2020-12/schema", "additionalProperties": false, "allOf": [ diff --git a/src/core/openenv/harbor/atif.py b/src/core/openenv/harbor/atif.py index 2a67ab640deeffc47ab7b86b3b6e8cbeb5683005..eb9c43edf15d00228e1ac5a682968f4868ade901 100644 --- a/src/core/openenv/harbor/atif.py +++ b/src/core/openenv/harbor/atif.py @@ -52,12 +52,16 @@ def load_atif(trial_dir: str | Path) -> dict[str, Any] | None: def _pi_session_as_atif(trial_dir: Path) -> dict[str, Any] | None: - """pi's own session log, reshaped into the two ATIF fields reconciliation reads. + """pi's own session log, reshaped into the ATIF fields reconciliation reads. pi writes no `trajectory.json`, but it does write `agent/pi/sessions/*.jsonl`, and every assistant record there carries `usage.output`: the completion-token count for that call, which is exactly what `metrics.completion_tokens` provides in ATIF. So the cross-check is available for pi after all, just under a different name and shape. + + The text and tool calls are kept too. pi logs the proxy's budget stop like any other reply, + and `reconcile` can only tell it apart by its text; without it, every pi rollout that hits a + step or context limit fails reconciliation and cannot be trained on. """ sessions = sorted((trial_dir / "agent" / "pi" / "sessions").glob("*.jsonl")) if not sessions: @@ -72,9 +76,26 @@ def _pi_session_as_atif(trial_dir: Path) -> dict[str, Any] | None: if record.get("type") != "message" or message.get("role") != "assistant": continue usage = message.get("usage") or {} + content = message.get("content") or [] + if isinstance(content, str): + content = [{"type": "text", "text": content}] steps.append( { "source": "agent", + "message": "".join( + part.get("text") or "" + for part in content + if part.get("type") == "text" + ), + "tool_calls": [ + { + "tool_call_id": part.get("id"), + "function_name": part.get("name"), + "arguments": part.get("arguments"), + } + for part in content + if part.get("type") == "toolCall" + ], "metrics": {"completion_tokens": int(usage.get("output") or 0)}, } ) @@ -325,6 +346,26 @@ def reconcile(document: dict[str, Any], atif: dict[str, Any] | None) -> Report: ) return report + subagents = atif.get("subagent_trajectories") or [] + if subagents: + # FATAL, not WARN. The old text said subagent turns "must not be trained with the parent + # rollout's reward" and then did nothing to stop it: no node ids were collected, no role was + # changed, so if a subagent's calls landed in the same session as `agent` roots they shipped as + # trainable carrying the parent's reward — the exact outcome the sentence forbade. The aux path + # below demotes; this one only complained. + # + # Refusing rather than guessing which roots belong to the subagent: ATIF gives trajectories, + # not the node ids that would let us demote precisely, and picking roots by shape here would be + # inventing an attribution. A rollout whose reward cannot be attributed is not trainable. + report.add( + FATAL, + "atif_subagents", + f"ATIF reports {len(subagents)} subagent trajectory(ies) and the graph has " + f"{document['stats']['n_roots']} root(s). Subagent turns must not be trained with the " + "parent rollout's reward, and ATIF does not say which captured calls are theirs, so " + "this rollout cannot be attributed. Run this harness without subagents to train on it.", + ) + # Compare against EVERY call the agent made, in arrival order, across ALL agent roots. # # Two reasons this is the right comparison rather than the surviving training path: @@ -473,25 +514,6 @@ def reconcile(document: dict[str, Any], atif: dict[str, Any] | None) -> Report: f"Graph found {document['stats']['n_discarded']} discarded turn(s).", ) - subagents = atif.get("subagent_trajectories") or [] - if subagents: - # FATAL, not WARN. The old text said subagent turns "must not be trained with the parent - # rollout's reward" and then did nothing to stop it: no node ids were collected, no role was - # changed, so if a subagent's calls landed in the same session as `agent` roots they shipped as - # trainable carrying the parent's reward — the exact outcome the sentence forbade. The aux path - # right above demotes; this one only complained. - # - # Refusing rather than guessing which roots belong to the subagent: ATIF gives trajectories, - # not the node ids that would let us demote precisely, and picking roots by shape here would be - # inventing an attribution. A rollout whose reward cannot be attributed is not trainable. - report.add( - FATAL, - "atif_subagents", - f"ATIF reports {len(subagents)} subagent trajectory(ies) and the graph has " - f"{document['stats']['n_roots']} root(s). Subagent turns must not be trained with the " - "parent rollout's reward, and ATIF does not say which captured calls are theirs, so " - "this rollout cannot be attributed. Run this harness without subagents to train on it.", - ) return report diff --git a/src/core/openenv/harbor/capabilities.py b/src/core/openenv/harbor/capabilities.py index 2c0981d7ba488593fd3f0ba607d538b1b337d6aa..7da90b98bdf5248298e731870376b57e261c4b49 100644 --- a/src/core/openenv/harbor/capabilities.py +++ b/src/core/openenv/harbor/capabilities.py @@ -21,11 +21,6 @@ from typing import Any from . import seams -# Harbor agents that run HOST-SIDE, in this server's process, rather than being installed into the -# sandbox. The distinction is not cosmetic: their LLM traffic never leaves the host, so they reach -# the capture proxy on localhost and need no public URL at all. -HOST_SIDE_AGENTS = frozenset({"terminus-2", "computer-1", "oracle", "nop", "dspy-rlm"}) - # Backends worth advertising. Harbor registers 23; these are the ones with a credential story we # check and have exercised. Others still work via `--sandbox `, just unadvertised. KNOWN_SANDBOXES = ("docker", "e2b", "modal", "daytona", "hf-sandbox") @@ -288,7 +283,7 @@ def list_harnesses() -> list[HarnessStatus]: HarnessStatus( name=name, dialect=seam.dialect, - kind="base" if name in HOST_SIDE_AGENTS else "installed", + kind="base" if seam.host_side else "installed", status=seam.status, needs_subclass=seam.import_path is not None, notes=seam.notes, diff --git a/src/core/openenv/harbor/environment.py b/src/core/openenv/harbor/environment.py index 50e6963c53da175691a875e786d07b17116e74aa..64f40233231a07298eb0943d1db2a0e0f03b1c23 100644 --- a/src/core/openenv/harbor/environment.py +++ b/src/core/openenv/harbor/environment.py @@ -249,6 +249,22 @@ class HarborEnvironment(MCPEnvironment): from .models import HarborRolloutResult from .rollout import run_rollout as _run + # The client names the harness, and a `module:Class` name makes this server import that + # module. Only the import paths the operator allowed at startup are accepted. + allowed = { + entry.strip() + for entry in os.environ.get("OPENENV_HARBOR_ALLOW_HARNESS", "").split(",") + if entry.strip() + } + if ":" in harness and harness not in allowed: + return HarborRolloutResult( + ok=False, + error=f"harness {harness!r} is not allowed on this server: start it with " + f"`openenv harbor serve --allow-harness {harness}`", + harness=harness, + sandbox=sandbox, + ).model_dump_json() + service = self._service() if service is None: return HarborRolloutResult( @@ -266,6 +282,20 @@ class HarborEnvironment(MCPEnvironment): ok=False, error=str(exc)[:400], harness=harness, sandbox=sandbox ).model_dump_json() + # Same rule as the web UI: a task that gets this server's environment variables or files + # runs only on the server's own endpoint, since the caller's model would see the secrets. + if llm_url: + from .ui_data import reads_environment + + if reads_environment(split, int(task_index)): + return HarborRolloutResult( + ok=False, + error="this task passes the server's environment variables or files into " + "the sandbox, so it runs only on the server's own endpoint, not with llm_url", + harness=harness, + sandbox=sandbox, + ).model_dump_json() + # This tool is `async` on purpose. FastMCP dispatches a SYNC tool body through # `anyio.to_thread.run_sync` with no limiter (`fastmcp/utilities/async_utils.py`), which # uses anyio's default `CapacityLimiter(40)` — and the body holds that worker thread for the @@ -310,6 +340,7 @@ class HarborEnvironment(MCPEnvironment): sandbox=sandbox, registry=service.capture.registry, intercept_url=service.public_url, + local_intercept_url=service.local_url, model=served, trials_dir=_trials_dir(), dataset=split, diff --git a/src/core/openenv/harbor/rollout.py b/src/core/openenv/harbor/rollout.py index 9a9ae3b67b12ba1835646096f6c8f9e8f5806ea1..2037fd23db00a44158d52a368fd686352ece3640 100644 --- a/src/core/openenv/harbor/rollout.py +++ b/src/core/openenv/harbor/rollout.py @@ -43,6 +43,7 @@ from .models import ( HarborTurn, turns_from_document, ) +from .supervisor import get_supervisor # Harbor's own retry is deliberately off. A Harbor-level retry re-runs the agent against the SAME # capture session, so two attempts merge into one graph and the trace cross-check compares a @@ -150,6 +151,48 @@ def _finite_reward(key: str, value: Any) -> float: return number +def _graded_nonzero_exit(info: Any, reward: float | None) -> bool: + """Whether a trial's exception is only the agent's exit code, after the verifier graded the run. + + `opencode run` has been seen to exit 1 on runs that finished normally: the stream ends on a + `step_finish` with `reason: "stop"`, it carries no `error` event and stderr is empty. Harbor runs + the command under `set -o pipefail` and turns any non-zero status into + `NonZeroAgentExitCodeError` (agents/installed/base.py `_exec`), records it on the trial, and + still runs the verifier. Treating that record as the outcome failed solved and unsolved rollouts + alike. + + Only the plain exit code qualifies. Harbor's own classifications of the same failure (`ApiError` + and its subclasses, refusals) keep failing, and so does an opencode stream that carries an + `error` event, since that run was cut short by the provider rather than finished. + + Args: + info (`Any`): + The trial's `exception_info` (Harbor's `ExceptionInfo`). + reward (`float`, *optional*): + The headline reward already picked from the verifier, `None` when there is none. + + Returns: + `bool`: `True` when the exception should be kept as a warning rather than a failure. + """ + if reward is None: + return False + if getattr(info, "exception_type", None) != "NonZeroAgentExitCodeError": + return False + message = str(getattr(info, "exception_message", "") or "") + return ( + message.startswith("Command failed (exit ") and '"type":"error"' not in message + ) + + +def _first_line(info: Any) -> str: + """The exception's type and the first line of its message, for a one-line finding.""" + message = str(getattr(info, "exception_message", "") or "") + first = message.splitlines()[0] if message else "" + if len(first) > 200: + first = first[:200] + "..." + return f"{getattr(info, 'exception_type', None)}: {first}" + + def _pick_reward( rewards: dict[str, float], reward_key: str = "" ) -> tuple[float | None, str]: @@ -209,12 +252,15 @@ def build_trial_config( force_build: bool = False, training: bool = False, harness_profile: str | None = None, + environment_kwargs: dict[str, Any] | None = None, ) -> Any: """Assemble Harbor's `TrialConfig` for one rollout. The seam decides how this particular agent learns about the proxy — an env var, a constructor kwarg, or a config file written by a subclass. That is the only per-agent knowledge involved; everything downstream is identical. + + Backend kwargs in `environment_kwargs` pass to Harbor. `None` keeps Harbor's defaults. """ from harbor.models.trial.config import ( AgentConfig, @@ -270,6 +316,9 @@ def build_trial_config( ), delete=not keep_sandbox, force_build=force_build, + **( + {"kwargs": environment_kwargs} if environment_kwargs is not None else {} + ), ), verifier=VerifierConfig(), trial_name=trial_name, @@ -277,6 +326,17 @@ def build_trial_config( ) +async def _run_trial(trial: Any, on_trial_created: Callable[[Any], None] | None) -> Any: + """Close Harbor's trial log when a trusted hook prevents execution.""" + if on_trial_created is not None: + try: + on_trial_created(trial) + except BaseException: + trial._close_logger_handler() + raise + return await trial.run() + + async def run_rollout( *, task_dir: Path | str, @@ -288,6 +348,7 @@ async def run_rollout( trials_dir: Path | str, dataset: str = "", reward_key: str = "", + local_intercept_url: str = "", require_reward: bool = True, keep_sandbox: bool = False, agent_timeout_sec: float | None = None, @@ -302,6 +363,8 @@ async def run_rollout( eval_sampling: dict[str, Any] | None = None, harness_profile: str | None = None, on_session_created: Callable[[str], None] | None = None, + on_trial_created: Callable[[Any], None] | None = None, + environment_kwargs: dict[str, Any] | None = None, ) -> HarborRolloutResult: """Run one rollout end to end. Never raises. @@ -316,6 +379,10 @@ async def run_rollout( The live capture registry; a session is minted here and its id becomes the agent's key. intercept_url (`str`): Public URL of the capture proxy, as the sandbox must reach it. + local_intercept_url (`str`, *optional*): + The proxy's loopback URL. A host-side agent (`Seam.host_side`) is handed this instead of + `intercept_url`: it calls the model from this process, and every public hop is one more + place a long completion can be cut. Empty keeps `intercept_url` for every agent. model (`str`): Served model id. Normalised per harness by the seam. trials_dir (`Path` or `str`): @@ -344,6 +411,11 @@ async def run_rollout( on_session_created (`Callable[[str], None]`, *optional*): Receive this rollout's capture session ID before the agent starts. Live views must follow this ID rather than discover unrelated sessions from the shared registry. + on_trial_created (`Callable[[Any], None]`, *optional*): + Trusted infrastructure callback invoked with the native Harbor trial before it runs. + Exceptions fail the rollout and prevent trial execution. Not exposed through MCP. + environment_kwargs (`dict[str, Any]`, *optional*): + Backend kwargs passed to Harbor. `None` keeps Harbor's defaults. Returns: [`HarborRolloutResult`]: Reward, per-turn token ids and logprobs, and validation findings. @@ -431,6 +503,14 @@ async def run_rollout( enable_shared_templates() + # A host-side agent calls the model from this process, so it takes the loopback URL. A + # public forward is one more hop that can cut a long completion: a gradio share link + # answers 502 after about a minute while the upstream is still generating, the agent + # retries, and the capture records the same prompt again as a new root. + seam = seams.get(harness, profile=harness_profile) + if local_intercept_url and seam.host_side: + intercept_url = local_intercept_url + config_kwargs = dict( task_dir=task_dir, harness=harness, @@ -446,6 +526,7 @@ async def run_rollout( force_build=force_build, training=sampling is not None, harness_profile=harness_profile, + environment_kwargs=environment_kwargs, ) # Held across construction because Harbor's wrappers read `os.environ` while building the @@ -454,14 +535,14 @@ async def run_rollout( # I/O worth speaking of: the sandbox is booted later, by `trial.run()`, outside the lock. # Harbor's wrappers read `os.environ` while constructing the agent, so the seam's # process-level vars have to be in place across `Trial.create` and are put back after. - seam = seams.get(harness, profile=harness_profile) *_, proc_env = seam.resolve( base_url=intercept_url, session=session.session_id, model=model ) if not proc_env: config = build_trial_config(**config_kwargs) trial = await Trial.create(config) - trial_result = await trial.run() + get_supervisor().adopt(trial) + trial_result = await _run_trial(trial, on_trial_created) else: # The override has to span `run()`, not just construction. Harbor's goose wrapper reads # `os.environ["OPENAI_API_KEY"]` inside its own `run` (goose.py:653), long after @@ -493,7 +574,8 @@ async def run_rollout( with ctx_env_overlay(proc_env): config = build_trial_config(**config_kwargs) trial = await Trial.create(config) - trial_result = await trial.run() + get_supervisor().adopt(trial) + trial_result = await _run_trial(trial, on_trial_created) else: # Fallback: mutate the real environment under a lock, one rollout at a time. await _acquire_proc_env() @@ -501,7 +583,8 @@ async def run_rollout( with process_env(seam.name, proc_env): config = build_trial_config(**config_kwargs) trial = await Trial.create(config) - trial_result = await trial.run() + get_supervisor().adopt(trial) + trial_result = await _run_trial(trial, on_trial_created) finally: _PROC_ENV_LOCK.release() except Exception as exc: # noqa: BLE001 - a rollout failure is a RESULT, never an exception @@ -574,9 +657,17 @@ async def run_rollout( ) info = getattr(trial_result, "exception_info", None) if info is not None and result.error is None: - result.ok = False - result.exception_type = getattr(info, "exception_type", None) - result.error = str(getattr(info, "exception_message", ""))[:600] + if _graded_nonzero_exit(info, result.reward): + # The agent's exit status is not the outcome when the verifier graded the run. + # The capture checks below still decide `ok`, so an empty or broken capture fails. + result.findings.append( + "[WARN] agent exited non-zero after a graded run: " + + _first_line(info) + ) + else: + result.ok = False + result.exception_type = getattr(info, "exception_type", None) + result.error = str(getattr(info, "exception_message", ""))[:600] # --- capture -------------------------------------------------------- try: diff --git a/src/core/openenv/harbor/runner.py b/src/core/openenv/harbor/runner.py index f9853a7ad151b9fc3ef8972cf9e43e6615809a7c..fcf1672d28921d16b6bafb01ce07b89f92bdc871 100644 --- a/src/core/openenv/harbor/runner.py +++ b/src/core/openenv/harbor/runner.py @@ -11,6 +11,7 @@ from __future__ import annotations import os import secrets from pathlib import Path +from typing import Any, Callable from openenv.core.harness.capture import CaptureServer @@ -44,6 +45,10 @@ async def run_batch( auth_header: str = "Authorization", provider: str = "openai", admin_key: str | None = None, + agent_timeout_sec: float | None = None, + agent_step_limit: int | None = None, + on_trial_created: Callable[[Any], None] | None = None, + environment_kwargs: dict[str, Any] | None = None, ) -> list[HarborRolloutResult]: """Run `task_indices` from `dataset` and print a per-rollout report. @@ -64,6 +69,15 @@ async def run_batch( Key the capture proxy's session-management routes require. Defaults to `$OPENENV_CAPTURE_ADMIN_KEY`, else a random one minted for this batch. The proxy is published on a public URL, so these routes are never left open. + agent_timeout_sec (`float`, *optional*): + Override each agent's execution timeout in seconds. + agent_step_limit (`int`, *optional*): + Limit each rollout's agent steps and captured model calls. + on_trial_created (`Callable[[Any], None]`, *optional*): + Trusted infrastructure callback invoked with each native Harbor trial before it runs. + Exceptions fail that rollout and prevent trial execution. Not exposed through MCP. + environment_kwargs (`dict[str, Any]`, *optional*): + Backend kwargs passed to Harbor. `None` keeps Harbor's defaults. Returns: `list[HarborRolloutResult]`: One per index, in order. @@ -153,14 +167,24 @@ async def run_batch( sandbox=sandbox, registry=capture.registry, intercept_url=public_url, + local_intercept_url=f"http://127.0.0.1:{port}", model=model, trials_dir=trials_dir, dataset=dataset, reward_key=reward_key, + # A rollout to look at, not to train on: when the verifier wrote several rewards and + # `reward_key` names none of them, the capture is still usable and every reward stays + # in `rewards`. Failing it would report a graded rollout as an infra error. The + # training path (`run_rollout`'s default) still refuses to pick a signal. + require_reward=False, keep_sandbox=keep_sandbox, + agent_timeout_sec=agent_timeout_sec, + agent_step_limit=agent_step_limit, force_build=force_build, capture_level=capture_level, inference=capture.inference, + on_trial_created=on_trial_created, + environment_kwargs=environment_kwargs, ) results.append(result) print(" " + _summarise(result)) @@ -193,6 +217,12 @@ def _summarise(r: HarborRolloutResult) -> str: f"{status:<26} reward={reward:<6} turns={r.n_turns:<3} roots={r.n_roots:<3} " f"{mode:<11} {detail} atif={r.atif:<9} {r.wall_s:.0f}s" + (f"\n {r.error[:180]}" if r.error else "") + + ( + f"\n verifier wrote {r.rewards} but none is the headline reward: " + "pass --reward-key (a comma-separated preference order is accepted)" + if r.reward is None and r.rewards + else "" + ) ) @@ -202,15 +232,24 @@ def _report(results: list[HarborRolloutResult]) -> str: ok = sum(1 for r in results if r.ok) graded = [r for r in results if r.reward is not None] solved = sum(1 for r in graded if r.reward and r.reward > 0) + # Two different reasons for no reward. Only an empty `rewards` means the verifier never ran: + # with keys present it did run, and no key was chosen as the headline one. + no_headline = [r for r in results if r.reward is None and r.rewards] + never_ran = len(results) - len(graded) - len(no_headline) + ungraded = [] + if no_headline: + keys = sorted({key for r in no_headline for key in r.rewards}) + ungraded.append( + f"{len(no_headline)} ungraded: the verifier ran but no headline reward among " + f"{keys}, pass --reward-key" + ) + if never_ran: + ungraded.append(f"{never_ran} ungraded: the verifier never ran") lines = [ "=" * 78, f"capture {ok}/{len(results)} usable", f"solved {solved}/{len(graded)} graded" - + ( - f" ({len(results) - len(graded)} ungraded — the verifier never ran)" - if len(graded) != len(results) - else "" - ), + + "".join(f" ({reason})" for reason in ungraded), ] if all(r.rollout_type == "eval" for r in results): lines.append( diff --git a/src/core/openenv/harbor/seams.py b/src/core/openenv/harbor/seams.py index b31d22bf03c1b54e4a8469a00af949d403230007..4936ee3194481b29fa6068412d1a2acca8676601 100644 --- a/src/core/openenv/harbor/seams.py +++ b/src/core/openenv/harbor/seams.py @@ -109,6 +109,10 @@ def _pi(base_url: str, session: str, model: str) -> dict[str, Any]: logger = logging.getLogger(__name__) +# Harnesses already warned about an inexpressible step limit, in this process. The warning is a fact +# about the harness, not the rollout: repeating it for every rollout of a training run buries it. +_STEP_LIMIT_WARNED: set[str] = set() + @dataclass(frozen=True) class Seam: @@ -153,6 +157,9 @@ class Seam: # the loss step while every log line looks healthy. Harbor itself has no step cap — only a # timeout — and an earlier Qwen3-4B run micro-stepped to 451 turns and 10.1M prompt tokens. step_limit: Callable[[int], dict[str, Any]] | None = None + # The agent runs in OUR process (terminus-2, computer-1, a host-side agent of your own) and makes + # its model calls from here, so the proxy's loopback address reaches it: no public forward needed. + host_side: bool = False status: str = "untested" notes: str = "" @@ -183,11 +190,14 @@ class Seam: extra = _deep_merge(extra, self.training_kwargs) if step_limit: if self.step_limit is None: - logger.warning( - "%s has no native step-limit setting; the capture proxy enforces the " - "model-call budget and the agent timeout still applies", - self.name, - ) + if self.name not in _STEP_LIMIT_WARNED: + _STEP_LIMIT_WARNED.add(self.name) + logger.warning( + "%s has no native step-limit setting; the capture proxy enforces the " + "model-call budget and the agent timeout still applies (said once per " + "harness)", + self.name, + ) else: extra = _deep_merge(extra, self.step_limit(step_limit)) return self.model_fmt.format(model=model), extra, agent_env, proc_env @@ -430,6 +440,7 @@ SEAMS: dict[str, Seam] = { # --- second wave -------------------------------------------------------- "terminus-2": Seam( name="terminus-2", + host_side=True, status="validated", dialect="openai_chat", model_fmt="hosted_vllm/{model}", @@ -690,6 +701,7 @@ SEAMS: dict[str, Seam] = { # reason is RECORDED rather than assumed. "computer-1": Seam( name="computer-1", + host_side=True, dialect="openai_chat", model_fmt="hosted_vllm/{model}", # Host-side like terminus-2: drives litellm from our process with an `api_base` kwarg, so @@ -930,7 +942,103 @@ PRIORITY = [ ] +def _custom_kwargs(base_url: str, session: str, model: str) -> dict[str, Any]: + """A host-side agent of your own reaches the proxy through two constructor kwargs. + + The names are terminus-2's (`api_base`) and the OpenAI SDK's (`api_key`): an agent declares both + in its options and hands them to whatever client it uses. + """ + return {"api_base": f"{base_url}/v1", "api_key": session} + + +def custom(import_path: str) -> Seam: + """The seam for `--harness module:Class`, an agent Harbor builds from its import path. + + Harbor already constructs agents from an import path. What it cannot know is how to point one + at the capture proxy, and that depends only on what the class is: + + * a subclass of an agent with a seam (its `name()` is in `SEAMS`, e.g. your own opencode + subclass) is wired exactly like that agent. Where the seam's wiring lives in an OpenEnv + subclass (pi's `InterceptPi` writes models.json), yours must subclass that class; + * a host-side agent (a plain `BaseAgent`, like terminus-2) makes its model calls from THIS + process, so it gets `api_base` (the proxy's `/v1` URL) and `api_key` (the capture session + id) as constructor kwargs. Nothing reaches the sandbox or the verifier; + * any other agent installed into the sandbox is refused: there is no way to tell which env + var or config file it reads, and guessed wiring fails as a rollout with no model calls. + + The status is "untested" in every case: OpenEnv has no evidence about an agent it has not run. + """ + import importlib + import inspect + from dataclasses import replace + + from harbor.agents.base import BaseAgent + from harbor.agents.installed.base import BaseInstalledAgent + + module, _, attr = import_path.partition(":") + try: + cls = getattr(importlib.import_module(module), attr) + if not isinstance(cls, type): + raise TypeError(f"{attr} is not a class") + if not issubclass(cls, BaseAgent): + raise TypeError(f"{import_path} must subclass harbor.agents.base.BaseAgent") + except Exception as exc: # noqa: BLE001 - surface why, whatever the import raised + raise KeyError( + f"cannot import harness {import_path!r}: {type(exc).__name__}: {exc}" + ) from exc + try: + parent = cls.name() + except Exception: # noqa: BLE001 - a name() that needs an instance is not a known agent + parent = None + if parent in SEAMS: + wired_by = SEAMS[parent].import_path + if wired_by: + wired_module, _, wired_attr = wired_by.partition(":") + if not issubclass( + cls, getattr(importlib.import_module(wired_module), wired_attr) + ): + raise ValueError( + f"{import_path} subclasses {parent}, which OpenEnv points at the capture " + f"proxy through {wired_by}. Subclass {wired_by} instead." + ) + return replace( + SEAMS[parent], + name=import_path, + import_path=import_path, + status="untested", + notes=f"{import_path} is a {parent} subclass, wired like {parent}.", + ) + if issubclass(cls, BaseInstalledAgent): + raise ValueError( + f"{import_path} is installed into the sandbox, and OpenEnv cannot tell how to point it " + "at the capture proxy. Subclass an agent that has a seam, or add a Seam for it to " + f"openenv.harbor.seams.SEAMS. Known: {sorted(SEAMS)}" + ) + accepted = set(inspect.signature(cls.__init__).parameters) + # Harbor 0.22 predates options models; constructor parameters still work. + options_model = getattr(cls, "options_model", None) + if options_model is not None: + accepted.update(options_model.model_fields) + missing = {"api_base", "api_key"} - accepted + if missing: + raise ValueError( + f"{import_path} must declare {', '.join(sorted(missing))} as constructor " + "parameters or options fields; Harbor can silently ignore these kwargs." + ) + return Seam( + name=import_path, + dialect="openai_chat", + import_path=import_path, + kwargs=_custom_kwargs, + host_side=True, + status="untested", + notes="Host-side agent of your own: gets the proxy as api_base/api_key kwargs.", + ) + + def get(name: str, *, profile: str | None = None) -> Seam: + if name not in SEAMS and ":" in name and profile is None: + return custom(name) if name not in SEAMS: raise KeyError(f"no seam for {name!r}. Known: {sorted(SEAMS)}") if profile is None: diff --git a/src/core/openenv/harbor/serving.py b/src/core/openenv/harbor/serving.py index 6c73e9936d694cf650391c9e731bdad1b0d146a4..46d3dd967df456bdae7ff7139aeacec592025c60 100644 --- a/src/core/openenv/harbor/serving.py +++ b/src/core/openenv/harbor/serving.py @@ -25,6 +25,8 @@ from typing import Any from openenv.core.harness.capture import CaptureServer +from .supervisor import get_supervisor + # Where the capture app is mounted when the env server hosts it directly. CAPTURE_MOUNT = "/capture" @@ -139,6 +141,12 @@ class HarborService: raise return self.public_url + @property + def local_url(self) -> str: + """The proxy's loopback URL, for agents running in this process. Empty when it is mounted on a + Space's app, whose port this service does not own.""" + return "" if self.mounted else f"http://127.0.0.1:{self.capture.port}" + def stop(self) -> None: """Tear both halves down, even if the first half refuses to go. @@ -332,6 +340,10 @@ def build_app( # their browser start rollouts on this server's endpoint, or reach a server on their own machine # that the page itself cannot. Nothing a real visitor does is cross-site. app.add_middleware(SameOrigin) + # The UI runs each rollout under `asyncio.run` in a worker thread, where a sandbox start cannot + # install signal handlers. Startup runs on the main thread inside uvicorn's own signal capture, + # so the supervisor wraps uvicorn's handlers and a signal stops those sandboxes on their loops. + app.router.on_startup.append(lambda: get_supervisor().install_signal_handlers()) return app diff --git a/src/core/openenv/harbor/sft.py b/src/core/openenv/harbor/sft.py new file mode 100644 index 0000000000000000000000000000000000000000..9d168dd6d13778cc144f8f78b9a0ad5e0c96fb06 --- /dev/null +++ b/src/core/openenv/harbor/sft.py @@ -0,0 +1,285 @@ +# SPDX-License-Identifier: BSD-3-Clause + +"""Turn Harbor rollouts into supervised fine-tuning rows. + +An evaluation rollout against a hosted model carries no token ids, so it can't feed RL training, but its trace is +supervised data as it stands. The agent's last model call holds the whole conversation as the harness sent it +(system prompt, task, every earlier assistant turn with its tool calls, every tool output), and that call plus its +reply is one SFT row. This is the text-level export: it works on `eval` and `train` rollouts alike, and never goes +through the token-level training contract of `openenv.harbor.contract`. + +Rows are in the conversational format with a `tools` column, which TRL's `SFTTrainer` and chat templates read +directly. Each row keeps its reward. Filtering is the caller's choice (`min_reward`), since a recorder shouldn't +decide a training policy. + +Examples: + +```python +from openenv.harbor.sft import export_sft + +rows, stats = export_sft(results, min_reward=1.0) +``` +""" + +from __future__ import annotations + +import json +from collections.abc import Iterable +from dataclasses import dataclass, field +from typing import Any + +from .models import HarborRolloutResult + + +@dataclass +class SFTExportStats: + """ + What `export_sft` did with each rollout. + + Attributes: + rollouts (`int`): + Rollouts read. + rows (`int`): + Rows written. + below_min_reward (`int`): + Rollouts graded below `min_reward`. + ungraded (`int`): + Rollouts with no reward, dropped when `min_reward` is set. + no_agent_turn (`int`): + Rollouts with no agent call to the model. + capture_failed (`int`): + Rollouts whose capture is unusable (a `[FATAL]` finding, a trace that doesn't match the capture, or a + failed export), never exported. + empty_reply (`int`): + Rollouts whose last reply has neither text nor tool calls. + malformed_tool_call (`int`): + Rollouts with a tool call whose arguments aren't a JSON object. + ended_on_tool_call (`list[str]`): + Tasks whose agent stopped right after a tool call, worth running again. + """ + + rollouts: int = 0 + rows: int = 0 + below_min_reward: int = 0 + ungraded: int = 0 + no_agent_turn: int = 0 + capture_failed: int = 0 + empty_reply: int = 0 + malformed_tool_call: int = 0 + ended_on_tool_call: list[str] = field(default_factory=list) + + +def rollout_reward(result: HarborRolloutResult, reward_key: str = "") -> float | None: + """ + The reward a rollout was graded with. + + `result.reward` when it's set. Otherwise the verifier reported several named rewards and none was picked as the + training signal: `reward_key` names it, and a single named reward is used as it is. + + Args: + result ([`HarborRolloutResult`]): + One rollout. + reward_key (`str`, *optional*, defaults to `""`): + Key of `result.rewards` to fall back to, or a comma-separated preference order. + + Returns: + `float` or `None`: the reward, or `None` when the rollout was not graded. + """ + if result.reward is not None: + return result.reward + if reward_key: + # A literal key first, then a comma-separated preference order, as `openenv harbor rollout --reward-key`. + for key in [reward_key] + [k.strip() for k in reward_key.split(",")]: + if key in result.rewards: + return result.rewards[key] + return None # a key was named and isn't there: another reward would be a different signal + if len(result.rewards) == 1: + return next(iter(result.rewards.values())) + return None + + +def _normalize_tool_calls( + calls: Iterable[dict[str, Any]], +) -> list[dict[str, Any]] | None: + """OpenAI-style tool calls with `arguments` as a dict, or `None` if a call's arguments aren't a JSON object. + + Captured replies carry flat `{name, arguments}` and request messages nest them under `function`, and providers + send `arguments` as a JSON string. Chat templates such as Qwen3.5's iterate over the arguments, so they're parsed. + A call whose arguments don't parse to an object would teach the student a malformed call, so the row is dropped. + """ + out = [] + for call in calls: + fn = call.get("function", call) + args = fn.get("arguments") + if isinstance(args, str): + try: + args = json.loads(args) if args.strip() else {} + except json.JSONDecodeError: + return None + if args is None: + args = {} + if not isinstance(args, dict): + return None + normalized = { + "type": "function", + "function": {"name": fn.get("name", ""), "arguments": args}, + } + if call.get("id"): + normalized["id"] = call["id"] + out.append(normalized) + return out + + +def _capture_unusable(result: HarborRolloutResult) -> bool: + """The capture itself is broken, as opposed to the agent or the grading. + + Not `result.ok`: it is also false for a graded rollout whose agent exited non-zero, or whose verifier wrote + several rewards with none picked, and those conversations are sound. + """ + return ( + any("[FATAL" in finding for finding in result.findings) + or result.atif == "MISMATCH" + or (result.error or "").startswith(("capture failed", "capture export failed")) + ) + + +def _last_agent_turn(result: HarborRolloutResult): + turns = [ + t + for t in result.turns + if t.role == "agent" and not t.discarded and t.request_messages + ] + return turns[-1] if turns else None + + +def ended_on_tool_call(result: HarborRolloutResult) -> bool: + """ + Whether the agent stopped right after a tool call, with no final reply. + + It usually means a model call failed and the harness gave up, so the task is worth running again rather than + counting as a wrong answer. + + Args: + result ([`HarborRolloutResult`]): + One rollout. + + Returns: + `bool`: whether the last agent turn finished on a tool call. + """ + turn = _last_agent_turn(result) + return turn is not None and turn.finish_reason == "tool_calls" + + +def to_sft_row( + result: HarborRolloutResult, reward_key: str = "" +) -> dict[str, Any] | None: + """ + One conversational SFT row from a rollout, or `None` if it has no agent turn or a malformed tool call. + + The row is the agent's last request to the model plus the reply to it. Discarded retries are not part of it, and + neither are auxiliary calls the capture gives a sequence of their own (session titles, summaries). + + Args: + result ([`HarborRolloutResult`]): + One rollout. + reward_key (`str`, *optional*, defaults to `""`): + Passed to [`rollout_reward`]. + + Returns: + `dict` with keys: + - `messages` (`list[dict]`): the conversation, ending with the agent's last reply. + - `tools` (`list[dict]`): the tools the harness offered. + - `reward` (`float` or `None`): the rollout's reward. + - `rewards` (`dict[str, float]`): every reward the verifier reported. + - `task_name`, `dataset`, `harness`, `rollout_type` (`str`): where the row comes from. + - `n_turns` (`int`): model calls in the rollout. + """ + turn = _last_agent_turn(result) + if turn is None: + return None + reply: dict[str, Any] = {"role": "assistant", "content": turn.text or ""} + if turn.tool_calls: + reply["tool_calls"] = turn.tool_calls + messages = [dict(m) for m in turn.request_messages] + [reply] + for message in messages: + if message.get("role") == "assistant" and message.get("tool_calls"): + message["tool_calls"] = _normalize_tool_calls(message["tool_calls"]) + if message["tool_calls"] is None: + return None + return { + "messages": messages, + "tools": list(turn.request_tools or []), + "reward": rollout_reward(result, reward_key), + "rewards": dict(result.rewards), + "task_name": result.task_name, + "dataset": result.dataset, + "harness": result.harness, + "rollout_type": result.rollout_type, + "n_turns": result.n_turns, + } + + +def export_sft( + results: Iterable[HarborRolloutResult | dict[str, Any]], + min_reward: float | None = None, + reward_key: str = "", +) -> tuple[list[dict[str, Any]], SFTExportStats]: + """ + SFT rows from Harbor rollouts. + + Args: + results (`Iterable` of [`HarborRolloutResult`] or `dict`): + Rollouts, as returned by `run_batch` or read back from `openenv harbor rollout --out`. + min_reward (`float`, *optional*): + Keep only rollouts graded at least this. Ungraded rollouts are dropped too. Unset, every usable rollout + becomes a row, with its reward on it. Rollouts whose capture is unusable, whose last reply is empty + or that hold a malformed tool call are never exported, and [`SFTExportStats`] counts them. + reward_key (`str`, *optional*, defaults to `""`): + Passed to [`rollout_reward`]. + + Returns: + `tuple` of the rows and an [`SFTExportStats`]. + + Examples: + + ```python + import json + from openenv.harbor.sft import export_sft + + rows, stats = export_sft(json.load(open("result.json")), min_reward=1.0) + ``` + """ + rows, stats = [], SFTExportStats() + for item in results: + result = ( + item + if isinstance(item, HarborRolloutResult) + else HarborRolloutResult.model_validate(item) + ) + stats.rollouts += 1 + if ended_on_tool_call(result): + stats.ended_on_tool_call.append(result.task_name) + if _capture_unusable(result): + stats.capture_failed += 1 + continue + turn = _last_agent_turn(result) + if turn is None: + stats.no_agent_turn += 1 + continue + if not turn.text and not turn.tool_calls: + stats.empty_reply += 1 + continue + row = to_sft_row(result, reward_key) + if row is None: + stats.malformed_tool_call += 1 + continue + if min_reward is not None: + if row["reward"] is None: + stats.ungraded += 1 + continue + if row["reward"] < min_reward: + stats.below_min_reward += 1 + continue + rows.append(row) + stats.rows = len(rows) + return rows, stats diff --git a/src/core/openenv/harbor/supervisor.py b/src/core/openenv/harbor/supervisor.py new file mode 100644 index 0000000000000000000000000000000000000000..dc8be7f892f39ab70ef708b61214fec7ff47ccaf --- /dev/null +++ b/src/core/openenv/harbor/supervisor.py @@ -0,0 +1,364 @@ +"""Own the sandboxes this process starts: cap how many start at once, stop them on SIGINT/SIGTERM. + +Harbor already tears a sandbox down at the end of every trial: `Trial._finalize` shields +`agent_environment.stop()`. Three gaps remain once a run is large enough: + +- SIGTERM's default action kills the process before any `finally` runs, so every live sandbox is + stranded. SIGINT cancels, but `asyncio.run` closes its loop right after, which cancels the shielded + stop as well. +- Nothing caps how many sandboxes are being created at once. Providers throttle creation well below + the rollout concurrency a trainer wants, and a throttled create reads as a failed rollout. +- Cancelling a rollout while its sandbox is starting abandons the start mid-flight, and teardown + then races it. Harbor's docker backend leaves `docker compose up` running when `communicate()` is + cancelled (only its timeout path terminates the child); a remote backend can finish a create + request whose handle was dropped. Either way the sandbox can appear after `stop()` has run. + +`SandboxSupervisor.adopt(trial)` wraps the trial's own `agent_environment.start/stop`, so Harbor's +lifecycle is unchanged and the supervisor only sees sandboxes this process created. +""" + +from __future__ import annotations + +import asyncio +import collections +import os +import signal +import threading +from typing import Any + +# How long `stop()` waits for a start that is still in flight. Stopping first is what leaks, so it +# waits; but a start that never returns must not hold teardown forever. +_START_GRACE_S = 120.0 + +# How long a cleanup triggered by a signal may take before the signal is passed on anyway. A wedged +# backend must not turn Ctrl-C into a hang; a second signal skips the wait entirely. It covers a stop +# that first waits out an in-flight start, or a signal during creation would end the process with +# the start still running and nothing deleted. +_CLEANUP_TIMEOUT_S = _START_GRACE_S + 60.0 + +_SIGNALS = (signal.SIGINT, signal.SIGTERM) + + +class _StartLimit: + """At most `limit` concurrent starts across every event loop in the process. + + Not an `asyncio.Semaphore`: rollouts run on several loops (the UI runs each one under its own + `asyncio.run` in a worker thread), and an asyncio primitive binds to the first loop that waits on + it. Waiters queue FIFO and are woken on their own loop. + """ + + def __init__(self, limit: int): + self._limit = limit + self._active = 0 + self._waiters: collections.deque[asyncio.Future] = collections.deque() + self._lock = threading.Lock() + + async def acquire(self) -> None: + with self._lock: + if self._active < self._limit and not self._waiters: + self._active += 1 + return + waiter = asyncio.get_running_loop().create_future() + self._waiters.append(waiter) + try: + await waiter + except asyncio.CancelledError: + with self._lock: + if waiter in self._waiters: + self._waiters.remove(waiter) + raise + # The permit was handed over just as this waiter was cancelled: pass it on. + self.release() + raise + + def release(self) -> None: + with self._lock: + if not self._waiters: + self._active -= 1 + return + waiter = self._waiters.popleft() + waiter.get_loop().call_soon_threadsafe(self._grant, waiter) + + def _grant(self, waiter: asyncio.Future) -> None: + # A waiter cancelled after it was dequeued releases the permit itself, in `acquire`. + if not waiter.done(): + waiter.set_result(None) + + +class _Sandbox: + """One adopted agent environment and the loop its handles belong to.""" + + def __init__(self, env: Any, delete: bool): + self.env = env + self.delete = delete + self.loop: asyncio.AbstractEventLoop | None = None + self.start_task: asyncio.Future | None = None + self.stop_task: asyncio.Future | None = None + + +class _LoopHandler: + """A signal callback that was registered on an event loop with `add_signal_handler`.""" + + def __init__(self, loop: asyncio.AbstractEventLoop, callback: Any, args: tuple): + self.loop = loop + self.callback = callback + self.args = args + + +class SandboxSupervisor: + """Track the sandboxes this process starts and tear them down on request or on a signal. + + Args: + max_starts (`int`, *optional*): + How many sandboxes may be starting at once. `None` or `0` means no limit. This bounds + creation only; how many rollouts run at once is still `MAX_CONCURRENT_ENVS`, so a + rollout that has its sandbox no longer counts against it. + """ + + def __init__(self, max_starts: int | None = None): + self._limit = _StartLimit(max_starts) if max_starts else None + self._owned: set[_Sandbox] = set() + self._lock = threading.Lock() + self._previous: dict[int, Any] = {} + # Signals whose previous handler the event loop delivers by itself; see `install_signal_handlers`. + self._loop_delivers: set[int] = set() + self._handling = False + self._cleanup: asyncio.Future | None = None + # Set by `aclose` under `_lock`. A start that has not registered yet must not open a sandbox + # cleanup will never see, so it fails instead. + self._closing = False + + @property + def owned(self) -> int: + """How many sandboxes this supervisor started and has not yet stopped.""" + with self._lock: + return len(self._owned) + + def adopt(self, trial: Any) -> Any: + """Route `trial.agent_environment`'s start and stop through this supervisor. + + Call after `Trial.create` and before `trial.run()`. Harbor's own calls are unchanged; they + now pass through the creation limit, and `stop()` waits for a pending start. Concurrent + callers share cleanup; successful cleanup is cached and failed cleanup can be retried. + """ + # `getattr`, because callers and tests pass their own trial objects; one without an agent + # environment has no sandbox to supervise. + env = getattr(trial, "agent_environment", None) + if env is None or getattr(env, "_openenv_sandbox", None) is not None: + return trial + box = _Sandbox(env, delete=trial.config.environment.delete) + real_start, real_stop = env.start, env.stop + + async def start(force_build: bool) -> None: + box.loop = asyncio.get_running_loop() + self.install_signal_handlers() + if self._limit is not None: + await self._limit.acquire() + with self._lock: + closing = self._closing + if not closing: + self._owned.add(box) + if closing: + if self._limit is not None: + self._limit.release() + raise RuntimeError( + "sandbox supervisor is shutting down; not starting a new sandbox" + ) + # Shielded: a caller cancelled mid-start gets its CancelledError, but the start itself + # runs to completion so that `stop()` has a whole sandbox to delete, not half of one. + box.start_task = asyncio.ensure_future(real_start(force_build=force_build)) + if self._limit is not None: + box.start_task.add_done_callback(lambda _: self._limit.release()) + await asyncio.shield(box.start_task) + + async def stop(delete: bool) -> None: + # Share an in-flight stop and cache success, but allow failed cleanup to retry. + if box.stop_task is None or ( + box.stop_task.done() + and (box.stop_task.cancelled() or box.stop_task.exception() is not None) + ): + box.stop_task = asyncio.ensure_future(_stop_once(delete)) + await asyncio.shield(box.stop_task) + + async def _stop_once(delete: bool) -> None: + if box.start_task is not None: + await asyncio.wait({box.start_task}, timeout=_START_GRACE_S) + if not box.start_task.done(): + box.start_task.cancel() + # The backend can finish creating the sandbox while the start unwinds. + await asyncio.wait({box.start_task}) + if not box.start_task.cancelled(): + # A start failure is the trial's to report; retrieved so asyncio stays quiet. + box.start_task.exception() + await real_stop(delete=delete) + with self._lock: + self._owned.discard(box) + + env.start, env.stop = start, stop + env._openenv_sandbox = box + return trial + + async def aclose(self, timeout: float | None = None) -> None: + """Stop every sandbox this supervisor owns. Safe to call more than once, and concurrently. + + From the first call on, new starts are refused, so a rollout still queued for a creation + permit cannot open a sandbox while cleanup is running. + + Each stop runs on the loop that started the sandbox, since backends hold loop-bound handles + (docker's are asyncio subprocesses). A sandbox whose loop has already closed cannot be + reached from here and is left alone. `timeout` defaults to `_CLEANUP_TIMEOUT_S`. + """ + with self._lock: + # Same lock as the registration in `start`, so every sandbox is either in this snapshot + # or refused: none can be created after cleanup has looked. + self._closing = True + boxes = list(self._owned) + here = asyncio.get_running_loop() + pending = [] + for box in boxes: + if box.loop is here: + pending.append(asyncio.ensure_future(box.env.stop(delete=box.delete))) + elif box.loop is not None and box.loop.is_running(): + future = asyncio.run_coroutine_threadsafe( + box.env.stop(delete=box.delete), box.loop + ) + pending.append(asyncio.wrap_future(future)) + if not pending: + return + done, _ = await asyncio.wait( + pending, timeout=_CLEANUP_TIMEOUT_S if timeout is None else timeout + ) + for task in done: + if not task.cancelled(): + task.exception() # stop failures belong to the trial + + def install_signal_handlers(self, signals: tuple[int, ...] = _SIGNALS) -> bool: + """Stop owned sandboxes on these signals, then hand the signal to the previous handler. + + Called automatically when the first sandbox starts. Only the main thread can install signal + handlers, so this returns `False` elsewhere; a process that starts every sandbox from worker + threads should call it once from the main thread. The Harbor server does, at app startup + (`serving.build_app`), because the UI runs each rollout in a worker thread. Installing late + is deliberate: a server such as uvicorn replaces handlers when it starts serving, and this + one has to wrap its. + + A handler registered with `loop.add_signal_handler` (uvicorn before 0.29) is delivered by + the loop through the wakeup fd, whatever `signal.signal` holds, so wrapping that would let + the server start shutting down while cleanup is still running and then see the signal a + second time. On an asyncio loop the supervisor takes the loop's slot instead and puts the + callback back when cleanup is done. A loop that does not expose its callbacks (uvloop) + cannot be wrapped: cleanup then runs alongside the server's shutdown, and the signal is not + delivered again. + """ + if self._closing or threading.current_thread() is not threading.main_thread(): + return False + try: + loop = asyncio.get_running_loop() + except RuntimeError: + loop = None + for sig in signals: + current = signal.getsignal(sig) + # Private, but unchanged since asyncio was added: the public API can replace a loop's + # signal callback, not read it back. + handle = getattr(loop, "_signal_handlers", {}).get(sig) + if current == self._on_signal or ( + handle is not None and handle._callback == self._on_loop_signal + ): + continue + if handle is not None: + self._previous[sig] = _LoopHandler(loop, handle._callback, handle._args) + loop.add_signal_handler(sig, self._on_loop_signal, sig) + continue + if isinstance( + getattr(current, "__self__", None), asyncio.AbstractEventLoop + ): + self._loop_delivers.add(sig) + self._previous[sig] = current + signal.signal(sig, self._on_signal) + return True + + def _on_loop_signal(self, sig: int) -> None: + # Runs as an ordinary loop callback, so unlike `_on_signal` it may start the cleanup itself. + if self._handling: + self._chain(sig) + return + self._handling = True + self._start_cleanup(sig) + + def _on_signal(self, sig: int, frame: Any) -> None: + if self._handling: + # A second signal means "stop waiting". + self._chain(sig) + return + self._handling = True + try: + loop = asyncio.get_running_loop() + except RuntimeError: + loop = None + if loop is not None: + # The handler interrupts the loop mid-callback; scheduling is all it may do safely. + loop.call_soon_threadsafe(self._start_cleanup, sig) + return + # No loop on the main thread, so the sandboxes live on other threads' loops and waiting + # for them here cannot deadlock. + worker = threading.Thread( + target=asyncio.run, args=(self.aclose(),), daemon=True + ) + worker.start() + worker.join(_CLEANUP_TIMEOUT_S + 5) + self._chain(sig) + + def _start_cleanup(self, sig: int) -> None: + async def cleanup_then_chain() -> None: + try: + await self.aclose() + finally: + if self._handling: + self._chain(sig) + + self._cleanup = asyncio.ensure_future(cleanup_then_chain()) + + def _chain(self, sig: int) -> None: + """Put the previous handler back and re-deliver the signal to it. + + Re-raising rather than calling it keeps its semantics exactly: SIG_DFL still terminates, + the default SIGINT handler still raises KeyboardInterrupt, uvicorn still shuts down. + """ + self._handling = False + previous = self._previous.pop(sig, signal.SIG_DFL) + if isinstance(previous, _LoopHandler): + if previous.loop.is_closed(): + return + previous.loop.add_signal_handler(sig, previous.callback, *previous.args) + else: + signal.signal(sig, signal.SIG_DFL if previous is None else previous) + if sig in self._loop_delivers: + # The loop already ran its callback for this signal. + self._loop_delivers.discard(sig) + return + signal.raise_signal(sig) + + +_supervisor: SandboxSupervisor | None = None +_supervisor_lock = threading.Lock() + + +def get_supervisor() -> SandboxSupervisor: + """The process-wide supervisor that `run_rollout` adopts every trial into. + + `OPENENV_HARBOR_MAX_SANDBOX_STARTS` caps concurrent sandbox creation; unset or `0` leaves it + uncapped. It is read once, on first use. + """ + global _supervisor + with _supervisor_lock: + if _supervisor is None: + raw = os.environ.get("OPENENV_HARBOR_MAX_SANDBOX_STARTS", "0") or "0" + if not raw.isdigit(): + raise ValueError( + f"OPENENV_HARBOR_MAX_SANDBOX_STARTS must be a non-negative integer, got {raw!r}" + ) + _supervisor = SandboxSupervisor(max_starts=int(raw)) + return _supervisor + + +__all__ = ["SandboxSupervisor", "get_supervisor"] diff --git a/src/core/openenv/harbor/ui_pages.py b/src/core/openenv/harbor/ui_pages.py index 69bdcc7697237562a9077bb17bff003ee90b732c..bad6cb755f547d2e6638ed70776aba4765ab1a3e 100644 --- a/src/core/openenv/harbor/ui_pages.py +++ b/src/core/openenv/harbor/ui_pages.py @@ -128,7 +128,7 @@ def granted(token: str) -> str | None: # ── header ─────────────────────────────────────────────────────────────────────────────────────── -DOCS_URL = "https://huggingface.co/docs/openenv/environments/harbor" +DOCS_URL = "https://openenv.github.io/OpenEnv/main/environments/harbor" def header_html( diff --git a/src/core/openenv/harbor/ui_runs.py b/src/core/openenv/harbor/ui_runs.py index 679f09306a0b9ace60127fb2aac66f141c493c4c..3a6c1879cd25798458d16403108fea31a3f7cb93 100644 --- a/src/core/openenv/harbor/ui_runs.py +++ b/src/core/openenv/harbor/ui_runs.py @@ -437,6 +437,7 @@ async def _rollout( sandbox=sandbox, registry=service.capture.registry, intercept_url=service.public_url, + local_intercept_url=service.local_url, model=served, trials_dir=Path( os.environ.get("OPENENV_HARBOR_TRIALS_DIR", "/tmp/openenv-harbor-trials") diff --git a/src/core/openenv/validation/graders/__init__.py b/src/core/openenv/validation/graders/__init__.py index 03dda9811369b4c93ae61db843c233ad5fd611e3..88bbd02225fd66fde08bc645175656dae099e20c 100644 --- a/src/core/openenv/validation/graders/__init__.py +++ b/src/core/openenv/validation/graders/__init__.py @@ -13,7 +13,12 @@ from typing import Protocol, runtime_checkable from ..manifest import CapabilitiesSpec, NormalizedManifest from ..providers import RunningSubject from ..report import CheckResult -from ..runtime.contracts import RuntimeEvidence +from ..runtime.contracts import ( + HttpProbe, + IsolationEvidence, + OracleEvidence, + RuntimeEvidence, +) from ..types import Level, ProviderCapability ENTRY_POINT_GROUP = "openenv.validation.graders" @@ -38,6 +43,16 @@ class Subject: Where trajectory records and replay artifacts are written. network_evidence_json (`str`, *optional*): Provider-measured [`~openenv.validation.runtime.contracts.NetworkEvidence`]. + containment_evidence_json (`str`, *optional*): + Provider-measured [`~openenv.validation.runtime.contracts.ContainmentEvidence`]. + resource_evidence_json (`str`, *optional*): + Provider-measured [`~openenv.validation.runtime.contracts.ResourceEvidence`]. + isolation_evidence ([`~openenv.validation.runtime.contracts.IsolationEvidence`], *optional*): + Same-session and fresh episodes on the running subject. + oracle_http (`tuple[HttpProbe, ...]`): + GET probes for the declared oracle path on the control endpoint. + oracle_evidence ([`~openenv.validation.runtime.contracts.OracleEvidence`], *optional*): + Oracle, do-nothing and canary rewards for the Level 3 checks. """ root: Path @@ -47,6 +62,11 @@ class Subject: outputs_dir: Path runtime_evidence: RuntimeEvidence | None = None network_evidence_json: str | None = None + containment_evidence_json: str | None = None + resource_evidence_json: str | None = None + isolation_evidence: IsolationEvidence | None = None + oracle_http: tuple[HttpProbe, ...] = () + oracle_evidence: OracleEvidence | None = None @runtime_checkable diff --git a/src/core/openenv/validation/graders/runtime/__init__.py b/src/core/openenv/validation/graders/runtime/__init__.py index a667df64fc0a62ed8312bc726c82de1274b78c99..28766a0de7c67d1517ddcc71748c3d3a4a90aac2 100644 --- a/src/core/openenv/validation/graders/runtime/__init__.py +++ b/src/core/openenv/validation/graders/runtime/__init__.py @@ -1,11 +1,19 @@ -"""Runtime graders: raw reward, observation, state and network-policy contracts.""" +"""Runtime graders: raw reward, observation, state, network, containment, resource, isolation and oracle contracts.""" from .basic import ObservationSchemaGrader, RewardWellFormedGrader, StateContractGrader +from .containment import HostContainmentGrader +from .isolation import EpisodeIsolationGrader from .network import NetworkPolicyGrader +from .oracle import OracleContainmentGrader +from .resources import ResourceBoundsGrader __all__ = [ + "EpisodeIsolationGrader", + "HostContainmentGrader", "NetworkPolicyGrader", "ObservationSchemaGrader", + "OracleContainmentGrader", + "ResourceBoundsGrader", "RewardWellFormedGrader", "StateContractGrader", ] diff --git a/src/core/openenv/validation/graders/runtime/containment.py b/src/core/openenv/validation/graders/runtime/containment.py new file mode 100644 index 0000000000000000000000000000000000000000..b9b65f2c3f6ce357a67b7d7d7aaa9abcd5474472 --- /dev/null +++ b/src/core/openenv/validation/graders/runtime/containment.py @@ -0,0 +1,183 @@ +"""`runtime.host_containment`: judge measured isolation, never provider claims.""" + +import time + +from ...report import CheckResult +from ...runtime.contracts import ContainmentEvidence +from ...types import CheckStatus, Level, ProviderCapability + +# Mounts every container runtime adds. Anything else could expose host state. +_RUNTIME_MOUNTS = { + "/", + "/etc/hosts", + "/etc/hostname", + "/etc/resolv.conf", + # Docker binds its init at /sbin/docker-init, which resolves to + # /usr/sbin/docker-init in images where /sbin links to /usr/sbin. + "/sbin/docker-init", + "/usr/sbin/docker-init", + "/run/podman-init", +} +_PSEUDO_ROOTS = ("/proc", "/sys", "/dev") +_PSEUDO_FS = {"proc", "sysfs", "tmpfs", "devpts", "mqueue", "cgroup", "cgroup2"} +# Read-write filesystems of a hardened Docker launch that hold no subject files. +_NOT_STORAGE = { + # Kernel interfaces; Docker makes the sensitive entries read-only or masks them. + ("/proc", "proc"), + # Pseudo-terminal device nodes. + ("/dev/pts", "devpts"), + # POSIX message queues, bounded by the subject's own IPC namespace limits. + ("/dev/mqueue", "mqueue"), +} + + +class HostContainmentGrader: + """Check that the API-boundary subject cannot reach host state or privileges.""" + + check_id = "runtime.host_containment" + level = Level.RUNTIME + requires_capabilities = frozenset() + requires_provider = frozenset({ProviderCapability.INSPECTED_ISOLATION}) + depends_on = ("runtime.startup",) + + def applies_to(self, manifest) -> bool: + return True + + def run(self, subject) -> CheckResult: + started = time.monotonic() + status, problems, measured = self._grade(subject) + return CheckResult( + check_id=self.check_id, + status=status, + evidence=problems or ["measured isolation matches the agent boundary"], + measured=measured, + remediation=( + "Run the subject unprivileged from a read-only image, without host " + "namespaces, mounts or devices, and with writes confined to its " + "allotted roots." + if status is CheckStatus.FAIL + else None + ), + duration_s=time.monotonic() - started, + ) + + @staticmethod + def _grade(subject): + if subject.containment_evidence_json is None: + return CheckStatus.SKIP, ["containment evidence is unavailable"], {} + try: + evidence = ContainmentEvidence.model_validate_json( + subject.containment_evidence_json + ) + except ValueError: # includes pydantic's ValidationError + return CheckStatus.FAIL, ["malformed containment evidence"], {} + + launch = evidence.launch + problems = [] + if launch.privileged: + problems.append("subject runs privileged") + problems += [ + f"subject shares the host {ns} namespace" for ns in launch.host_namespaces + ] + problems += [f"capability added: {cap}" for cap in launch.cap_add] + problems += [f"host device passed in: {device}" for device in launch.devices] + problems += [f"confinement disabled: {option}" for option in launch.unconfined] + for process in evidence.processes: + label = f"process {process.pid} ({process.name})" + if 0 in process.uids: + problems.append(f"{label} runs as root") + if process.cap_eff: + problems.append(f"{label} holds capabilities {process.cap_eff:#x}") + if not process.no_new_privs: + problems.append(f"{label} can gain privileges") + if process.seccomp == 0: + problems.append(f"{label} runs without seccomp") + for mount in evidence.mounts: + pseudo = mount.fstype in _PSEUDO_FS and any( + mount.mount_point == root or mount.mount_point.startswith(root + "/") + for root in _PSEUDO_ROOTS + ) + allotted = ( + mount.mount_point in evidence.allotted and mount.fstype == "tmpfs" + ) + if mount.mount_point not in _RUNTIME_MOUNTS and not allotted and not pseudo: + problems.append( + f"unexpected mount at {mount.mount_point} ({mount.fstype})" + ) + # The read-write mounts are every filesystem the subject could store data in. + if any(m.mount_point == "/" and not m.read_only for m in evidence.mounts): + problems.append("the image root is writable") + # Docker's /dev tmpfs is also bound as /dev/null over masked /proc files. + # Only a complete subtree inventory can establish storage denial. + dev = { + m.device + for m in evidence.mounts + if (m.mount_point, m.fstype) == ("/dev", "tmpfs") + } + for mount in evidence.mounts: + if ( + mount.read_only + or mount.mount_point in ("/", *evidence.allotted) + or (mount.mount_point, mount.fstype) in _NOT_STORAGE + or mount.device in dev + ): + continue + problems.append( + "writable filesystem outside the allotted roots: " + f"{mount.mount_point} ({mount.fstype})" + ) + not_storage = { + m.mount_point + for m in evidence.mounts + if (m.mount_point, m.fstype) in _NOT_STORAGE + } + problems += [ + f"subject can write outside its allotted roots: {path}" + for path in evidence.writable + if path not in not_storage + ] + problems += [ + f"device filesystem {device} permits subject storage" + for device in dev + if device in evidence.device_storage + and evidence.device_storage[device].writable + ] + measured = { + "processes": len(evidence.processes), + "mounts": len(evidence.mounts), + "allotted_writable": evidence.allotted_writable, + "device_storage": { + device: reading.model_dump() + for device, reading in evidence.device_storage.items() + }, + } + # A failed control cannot erase an independently proven violation. + if problems: + return CheckStatus.FAIL, problems, measured + if not evidence.processes: + return CheckStatus.SKIP, ["no subject process could be measured"], measured + if not any(m.mount_point == "/" for m in evidence.mounts): + return ( + CheckStatus.SKIP, + ["the subject's mount table could not be read in full"], + measured, + ) + if sorted(evidence.allotted_writable) != sorted(evidence.allotted): + return ( + CheckStatus.SKIP, + [ + "the probe could not write an allotted root, so write denial is unproven" + ], + measured, + ) + if any( + device not in evidence.device_storage + or not evidence.device_storage[device].complete + for device in dev + ): + return ( + CheckStatus.SKIP, + ["the device filesystem storage inventory is incomplete"], + measured, + ) + return CheckStatus.PASS, [], measured diff --git a/src/core/openenv/validation/graders/runtime/discovery.py b/src/core/openenv/validation/graders/runtime/discovery.py new file mode 100644 index 0000000000000000000000000000000000000000..ac1801ee9654e8c04a2d6f5053c7d08f6d23b101 --- /dev/null +++ b/src/core/openenv/validation/graders/runtime/discovery.py @@ -0,0 +1,367 @@ +"""Declaration and rubric checks over bounded, independently collected evidence.""" + +import json +import math +import time +from decimal import Decimal + +from ...report import CheckResult +from ...types import CheckStatus +from .basic import _RuntimeGrader +from .repeatability import _difference + + +def _finite(value): + try: + return type(value) in (int, float, Decimal) and math.isfinite(value) + except OverflowError: + return False + + +def _json_decimal(value): + number = float(value) + if not math.isfinite(number): + raise ValueError("runtime JSON numbers must be finite") + # Retain the original token for configuration equality. + return Decimal(value) + + +def _arithmetic_value(value): + return float(value) if isinstance(value, Decimal) else value + + +class _EvidenceGrader(_RuntimeGrader): + """Discovery can be measured without an episode step; missing evidence cannot pass.""" + + unavailable_field = None + + def run(self, subject): + started = time.monotonic() + problems, incomplete = [], None + evidence = subject.runtime_evidence + if not self.applies_to(subject.manifest): + incomplete = "declared capability does not apply" + elif evidence is None: + incomplete = "runtime evidence is unavailable" + elif getattr(evidence, self.error_field): + problems = [f"{self.label} collection failed"] + elif self.unavailable_field and getattr(evidence, self.unavailable_field): + incomplete = getattr(evidence, self.unavailable_field) + elif getattr(evidence, self.field) is None: + incomplete = f"missing prerequisite: {self.label} evidence" + else: + try: + payload = json.loads( + getattr(evidence, self.field), + parse_float=_json_decimal, + parse_constant=_json_decimal, + ) + if not isinstance(payload, dict): + raise ValueError("evidence must be an object") + problems, incomplete = self.check(subject, payload) + except (ValueError, TypeError, KeyError, RecursionError, OverflowError): + problems = [f"malformed {self.label} evidence"] + status = ( + CheckStatus.FAIL + if problems + else CheckStatus.SKIP + if incomplete + else CheckStatus.PASS + ) + return CheckResult( + check_id=self.check_id, + status=status, + evidence=problems[:20] + or [incomplete or f"observed {self.label} contract holds"], + duration_s=time.monotonic() - started, + ) + + +class ToolDeclarationAccuracyGrader(_EvidenceGrader): + check_id = "runtime.tool_declaration_accuracy" + depends_on = () + field, error_field, label = "tools_json", "tools_error", "tool discovery" + unavailable_field = "tools_unavailable" + + def applies_to(self, manifest): + return "declared_tools" in manifest.capabilities.model_fields_set + + def check(self, subject, payload): + tools = payload["tools"] + if not isinstance(tools, list): + raise ValueError("tools must be a list") + names = [tool["name"] for tool in tools] + if any(not isinstance(name, str) or not name for name in names): + raise ValueError("invalid tool name") + cursor = payload.get("nextCursor") + if cursor is not None and not isinstance(cursor, str): + raise ValueError("invalid tool pagination cursor") + declared = subject.manifest.capabilities.declared_tools + problems = [] + if len(set(names)) != len(names): + problems.append("discovery contains duplicate tool names") + if len(set(declared)) != len(declared): + problems.append("declaration contains duplicate tool names") + missing = set(declared) - set(names) + extra = set(names) - set(declared) + if missing and cursor is None: + problems.append(f"{len(missing)} declared tools are missing from discovery") + if extra: + problems.append(f"{len(extra)} discovered tools are undeclared") + return problems, ( + "tool inventory is incomplete: pagination was not collected" + if cursor is not None + else None + ) + + +class TaskDeclarationAccuracyGrader(_EvidenceGrader): + check_id = "runtime.task_declaration_accuracy" + depends_on = () + field, error_field, label = "tasks_json", "tasks_error", "task discovery" + + def applies_to(self, manifest): + return manifest.capabilities.task_api or ( + "declared_task_count" in manifest.capabilities.model_fields_set + ) + + def check(self, subject, payload): + splits, counts, previews = ( + payload["splits"], + payload["counts"], + payload["previews"], + ) + if ( + not isinstance(splits, list) + or not isinstance(counts, dict) + or not isinstance(previews, dict) + ): + raise ValueError("invalid task discovery") + names = [split["name"] for split in splits] + if any(not isinstance(name, str) or not name for name in names) or len( + set(names) + ) != len(names): + raise ValueError("invalid split names") + if set(names) != counts.keys() or set(names) != previews.keys(): + raise ValueError("incomplete split discovery") + problems = [] + declared = subject.manifest.capabilities.declared_task_count + has_counts = ( + "declared_task_count" in subject.manifest.capabilities.model_fields_set + ) + if has_counts and set(names) != declared.keys(): + problems.append("discovered splits differ from declared task counts") + for name in names: + count, preview = counts[name], previews[name] + if type(count) is not int or count < 0: + raise ValueError("invalid task count") + if not isinstance(preview, list): + raise ValueError("invalid task preview") + if len(preview) > count or (count > 0 and not preview): + problems.append( + "task preview is inconsistent with the advertised count" + ) + if name in declared and count != declared[name]: + problems.append("advertised task count differs from the declaration") + return problems, None if has_counts else "task counts were not declared" + + +def _rubric_nodes(payload): + if not isinstance(payload, list) or not payload: + raise ValueError("missing rubric tree") + nodes = {} + for node in payload: + name = node["name"] + if not isinstance(name, str) or not all(name.split(".")) or name in nodes: + raise ValueError("invalid rubric name") + if not isinstance(node["class_name"], str) or not node["class_name"]: + raise ValueError("missing rubric class") + children = node["children"] + if not isinstance(children, list) or any( + not isinstance(child, str) for child in children + ): + raise ValueError("invalid rubric children") + if len(set(children)) != len(children): + raise ValueError("duplicate rubric children") + if type(node["config_available"]) is not bool or not isinstance( + node["config"], dict + ): + raise ValueError("invalid rubric configuration") + if type(node["evaluated"]) is not bool: + raise ValueError("invalid evaluation marker") + if node["evaluated"] and not _finite(node["score"]): + raise ValueError("evaluated score is not finite") + if not node["evaluated"] and node["score"] is not None: + raise ValueError("unevaluated score must be absent") + aggregation = node["aggregation"] + if aggregation not in {"weighted_sum", "sequential", "gate", "leaf", "unknown"}: + raise ValueError("invalid aggregation") + if aggregation == "leaf" and children: + raise ValueError("leaf has children") + if aggregation == "weighted_sum": + weights = node["config"]["weights"] + if ( + not isinstance(weights, list) + or len(weights) != len(children) + or not all(_finite(weight) for weight in weights) + ): + raise ValueError("invalid rubric weights") + if not math.isclose( + sum(_arithmetic_value(weight) for weight in weights), + 1, + rel_tol=0, + abs_tol=1e-6, + ): + raise ValueError("rubric weights do not sum to one") + if aggregation == "gate" and ( + len(children) != 1 or not _finite(node["config"]["threshold"]) + ): + raise ValueError("invalid rubric gate") + nodes[name] = node + if "root" not in nodes: + raise ValueError("missing rubric root") + linked = set() + for name, node in nodes.items(): + for child in node["children"]: + if ( + child not in nodes + or child in linked + or child.rsplit(".", 1)[0] != name + or child == name + ): + raise ValueError("invalid rubric edge") + linked.add(child) + if linked != nodes.keys() - {"root"}: + raise ValueError("disconnected rubric tree") + return nodes + + +class RubricIntrospectableGrader(_EvidenceGrader): + check_id = "runtime.rubric_introspectable" + requires_capabilities = frozenset({"rubric_tree"}) + field, error_field, label = "telemetry_json", "telemetry_error", "rubric telemetry" + unavailable_field = "telemetry_unavailable" + + def applies_to(self, manifest): + return manifest.capabilities.rubric_tree + + def check(self, subject, payload): + if type(payload["schema_version"]) is not int or payload["schema_version"] != 1: + raise ValueError("unsupported telemetry version") + if payload.get("rubric_error") is not None: + return ["subject reported unavailable rubric introspection"], None + nodes = _rubric_nodes(payload["rubric"]) + return ( + ["rubric configuration is unavailable"] + if any(not node["config_available"] for node in nodes.values()) + else [] + ), None + + +class RewardAttributionGrader(RubricIntrospectableGrader): + check_id = "runtime.reward_attribution" + depends_on = ("runtime.startup", "runtime.rubric_introspectable") + + def check(self, subject, payload): + problems, _ = super().check(subject, payload) + if subject.runtime_evidence.failure_reason: + problems.append("wire replay is incomplete") + if problems: + return problems, None + baseline = _rubric_nodes(payload["rubric"]) + steps = [ + row for row in subject.runtime_evidence.exchanges if row.operation == "step" + ] + records = payload["attribution"] + if not isinstance(records, list): + raise ValueError("invalid attribution") + if not steps: + return problems, "missing prerequisite: an observed step reward" + if len(records) != len(steps): + return problems + ["attribution does not cover every observed step"], None + + def definition(tree): + return { + name: { + key: value + for key, value in node.items() + if key not in {"score", "evaluated"} + } + for name, node in tree.items() + } + + unsupported = False + scored_steps = 0 + for index, (record, step) in enumerate(zip(records, steps, strict=True)): + if type(record["step_index"]) is not int or record["step_index"] != index: + problems.append( + f"step {index}: attribution identity differs from the wire" + ) + nodes = _rubric_nodes(record["rubric"]) + if _difference(definition(nodes), definition(baseline)): + problems.append(f"step {index}: rubric configuration changed") + data = json.loads(step.response_json)["data"] + reward = data["reward"] + root = nodes["root"] + unscored = reward is None and data.get("done") is False + scored_steps += not unscored + if not unscored and ( + not root["evaluated"] + or not _finite(reward) + or not math.isclose(root["score"], reward, rel_tol=1e-9, abs_tol=1e-9) + ): + problems.append( + f"step {index}: fresh root score differs from emitted reward" + ) + for node in nodes.values(): + if not node["evaluated"]: + continue + children = [nodes[name] for name in node["children"]] + aggregation = node["aggregation"] + if aggregation == "unknown": + unsupported = True + continue + if aggregation == "leaf": + continue + expected = 1.0 if aggregation == "sequential" else 0.0 + visited = 0 + for child in children: + if not child["evaluated"]: + problems.append( + f"step {index}: required child score was not evaluated" + ) + break + visited += 1 + score = _arithmetic_value(child["score"]) + if aggregation == "weighted_sum": + expected += score * _arithmetic_value( + node["config"]["weights"][visited - 1] + ) + elif aggregation == "gate": + expected = ( + 0.0 + if score < _arithmetic_value(node["config"]["threshold"]) + else score + ) + else: + expected = score + if score == 0: + break + if aggregation == "sequential" and any( + child["evaluated"] for child in children[visited:] + ): + problems.append( + f"step {index}: sequential evaluated children after its gate" + ) + if not _finite(expected) or not math.isclose( + node["score"], expected, rel_tol=1e-9, abs_tol=1e-9 + ): + problems.append( + f"step {index}: child attribution does not match the parent score" + ) + incomplete = ( + "unsupported custom rubric aggregation semantics" if unsupported else None + ) + if not scored_steps: + incomplete = "missing prerequisite: an observed numeric step reward" + return problems, incomplete diff --git a/src/core/openenv/validation/graders/runtime/isolation.py b/src/core/openenv/validation/graders/runtime/isolation.py new file mode 100644 index 0000000000000000000000000000000000000000..856799a64a96d1597d9457ceba3e6019d1f87def --- /dev/null +++ b/src/core/openenv/validation/graders/runtime/isolation.py @@ -0,0 +1,193 @@ +"""`runtime.episode_isolation`: a reset must leave no trace of the previous episode.""" + +import time +from json import JSONDecodeError + +from ...report import CheckResult +from ...runtime.json_values import loads, typed_json +from ...types import CheckStatus, Level + + +def _canonical(text): + """Compare exact decoded values while preserving JSON types and malformed text.""" + try: + value = loads(text) + except JSONDecodeError: + return text + try: + return typed_json(value) + except ValueError: + return text # Malformed text is compared exactly as it was sent. + + +def _trace(evidence): + trace, problems = [], [] + for x in evidence.exchanges: + values = [x.operation] + for text in (x.request_json, x.response_json): + try: + values.append(_canonical(text)) + except (RecursionError, ArithmeticError, ValueError) as exc: + # Unknown values are neither equal nor different, even when + # their raw bytes match. Keep the supported fields comparable. + values.append(None) + if isinstance(exc, RecursionError): + problem = "JSON nesting exceeds the parser depth" + elif isinstance(exc, ArithmeticError): + problem = "JSON numeric range exceeds Decimal support" + else: + problem = "JSON integer range exceeds parser support" + if problem not in problems: + problems.append(problem) + trace.append(tuple(values)) + return trace, problems + + +def _divergence(left, right, complete=True, controls=()): + """ + Describe the first supported difference, or `None` when none is established. + + When `left` is an incomplete recording, only its recorded exchanges count. + Unknown values cannot establish equality or a difference. A leak also + requires supported fresh controls at the differing position. + """ + fixed_inputs = True + for index, (a, b) in enumerate(zip(left, right)): + if controls: + fixed_inputs = ( + fixed_inputs + and None not in a[:2] + and None not in b[:2] + and a[:2] == b[:2] + and all( + index < len(control) and control[index][:2] == b[:2] + for control in controls + ) + ) + if controls and ( + not fixed_inputs + or None in a + or None in b + or any(index >= len(control) or control[index] != b for control in controls) + ): + continue + if any(x is not None and y is not None and x != y for x, y in zip(a, b)): + return f"exchange {index} ({a[0]})" + if complete and fixed_inputs and len(left) != len(right): + return f"exchange {min(len(left), len(right))} (trace length)" + return None + + +class EpisodeIsolationGrader: + """Compare an episode that follows a same-session reset with a fresh episode.""" + + check_id = "runtime.episode_isolation" + level = Level.RUNTIME + requires_capabilities = frozenset() + requires_provider = frozenset() + depends_on = ("runtime.startup",) + + def applies_to(self, manifest) -> bool: + return True + + def run(self, subject) -> CheckResult: + started = time.monotonic() + status, problems, measured = self._grade(subject) + return CheckResult( + check_id=self.check_id, + status=status, + evidence=problems or ["an episode after reset matches a fresh episode"], + measured=measured, + remediation=( + "Reset all episode state, including files, caches and rubric " + "state, at the start of every episode." + if status is CheckStatus.FAIL + else None + ), + duration_s=time.monotonic() - started, + ) + + @staticmethod + def _grade(subject): + isolation = subject.isolation_evidence + reference = subject.runtime_evidence + if isolation is None or reference is None: + return CheckStatus.SKIP, ["isolation evidence is unavailable"], {} + failure = isolation.sequential.failure_reason + fresh_failure = isolation.fresh.failure_reason + sequential, sequential_problems = _trace(isolation.sequential) + fresh, fresh_problems = _trace(isolation.fresh) + baseline, baseline_problems = _trace(reference) + problems = sequential_problems + fresh_problems + baseline_problems + if fresh_failure and not fresh_problems: + return ( + CheckStatus.SKIP, + ["the fresh reference episode failed: " + fresh_failure], + {}, + ) + resets = [ + i + for i, x in enumerate(isolation.sequential.exchanges) + if x.operation == "reset" + ] + if len(resets) < 2 and not failure: + return CheckStatus.SKIP, ["no second episode was recorded"], {} + split = resets[1] if len(resets) > 1 else len(sequential) + first, after_reset = sequential[:split], sequential[split:] + measured = {"exchanges": len(after_reset)} + # Isolation is only observable when fixed inputs give a fixed trace, so + # the first episode of every session must agree. + # A validator limit may leave a usable fresh prefix, but never proves + # equality with the unrecorded tail of a complete reference. + drift = _divergence(baseline, fresh, complete=not fresh_failure) or _divergence( + first, baseline, complete=not failure + ) + if drift: + return ( + CheckStatus.SKIP, + [f"two fresh episodes differ at {drift}, so isolation is unproven"], + measured, + ) + leak = _divergence( + after_reset, + fresh, + complete=not failure and not problems, + controls=(baseline, first), + ) + if leak: + return ( + CheckStatus.FAIL, + [ + f"the episode after a same-session reset differs from a fresh one at {leak}" + ], + measured, + ) + inputs = _divergence( + [x[:2] for x in after_reset], [x[:2] for x in fresh], complete=False + ) + if inputs: + return ( + CheckStatus.SKIP, + [ + f"the episode after reset used different inputs at {inputs}, so isolation is unproven" + ], + measured, + ) + if problems: + return ( + CheckStatus.SKIP, + [ + problem + ", so isolation is unproven" + for problem in dict.fromkeys(problems) + ], + measured, + ) + if failure: + # A deadline, size bound or transport failure that left no + # differing response is a gap in the experiment, not a leak. + return ( + CheckStatus.SKIP, + [f"the same-session episodes did not complete: {failure}"], + measured, + ) + return CheckStatus.PASS, [], measured diff --git a/src/core/openenv/validation/graders/runtime/oracle.py b/src/core/openenv/validation/graders/runtime/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..bc7f6ab4761e790968e8353aeac4b0394e9e2f13 --- /dev/null +++ b/src/core/openenv/validation/graders/runtime/oracle.py @@ -0,0 +1,277 @@ +"""`runtime.oracle_containment`: trace declared artifacts through collected responses.""" + +import os +import time +from dataclasses import dataclass +from pathlib import Path + +from ...report import CheckResult +from ...runtime.json_values import loads, typed_json +from ...types import CheckStatus, Level + +MAX_ORACLE_BYTES = 1024 * 1024 +MAX_ORACLE_FILES = 64 +_MIN_FINGERPRINT = 16 + + +@dataclass(frozen=True) +class OracleInventory: + """Bounded file content and explicit coverage of the declared artifact.""" + + files: tuple[tuple[str, str | None], ...] + bytes_read: int + omitted_files: int + omitted_bytes: int + errors: tuple[str, ...] = () + + +def oracle_inventory(root: Path, location: str) -> OracleInventory: + """Read bounded regular files inside the package; never trace truncated content.""" + package = root.resolve() + target = package / location + if not target.resolve().is_relative_to(package) or target.is_symlink(): + raise OSError("oracle is outside the package or is a symlink") + if not target.exists(): + raise OSError("oracle does not exist") + errors = [] + if target.is_dir(): + paths = [] + for directory, dirs, names in os.walk( + target, onerror=lambda exc: errors.append("oracle directory is unreadable") + ): + parent = Path(directory) + paths.extend(parent / name for name in names) + paths.extend(parent / name for name in dirs if (parent / name).is_symlink()) + paths.sort() + else: + paths = [target] + files, total, omitted_files, omitted_bytes = [], 0, 0, 0 + for index, path in enumerate(paths): + try: + if path.is_symlink() or not path.is_file(): + raise OSError("oracle entry is not a regular file") + size = path.stat().st_size + if index >= MAX_ORACLE_FILES or total >= MAX_ORACLE_BYTES: + omitted_files += 1 + omitted_bytes += size + continue + with path.open("rb") as stream: + data = stream.read(min(size, MAX_ORACLE_BYTES - total)) + total += len(data) + complete = len(data) == size + if not complete: + omitted_files += 1 + omitted_bytes += size - len(data) + files.append( + ( + path.relative_to(package).as_posix(), + data.decode("utf-8") if complete else None, + ) + ) + except (OSError, UnicodeError): + errors.append("oracle entry is unreadable or is not UTF-8 regular content") + return OracleInventory( + tuple(files), total, omitted_files, omitted_bytes, tuple(errors) + ) + + +def _json_values(text): + """Walk JSON values iteratively, retaining raw text for non-JSON responses.""" + try: + pending = [loads(text)] + except ValueError: + return + while pending: + value = pending.pop() + yield value + if isinstance(value, dict): + pending.extend(value.values()) + elif isinstance(value, list): + pending.extend(value) + + +def _appears(artifacts, strings, structured, text): + # Whole artifacts avoid conclusive failures from ordinary source-code lines. + if any(artifact in text for artifact in artifacts): + return True, True + parsed, complete = False, True + try: + for value in _json_values(text): + parsed = True + if isinstance(value, str) and any( + artifact in value for artifact in strings + ): + return True, complete + if structured and isinstance(value, (dict, list)): + try: + if typed_json(value) in structured: + return True, complete + except ValueError: + complete = False + except (ArithmeticError, RecursionError): + complete = False + return not parsed and any(artifact in text for artifact in strings), complete + + +class OracleContainmentGrader: + """Check for complete declared artifacts in the measured response surfaces.""" + + check_id = "runtime.oracle_containment" + level = Level.RUNTIME + requires_capabilities = frozenset({"oracle"}) + requires_provider = frozenset() + depends_on = ("runtime.startup",) + + def applies_to(self, manifest) -> bool: + return True + + def run(self, subject) -> CheckResult: + started = time.monotonic() + status, problems, measured = self._grade(subject) + return CheckResult( + check_id=self.check_id, + status=status, + evidence=problems + or [ + "no complete oracle artifact matched collected reset/step/state responses, " + "complete /schema responses or bounded same-origin HTTP file probes; " + "MCP tool access and reward-artifact writes were not tested" + ], + measured=measured, + remediation=( + "Keep oracle and reward artifacts out of observations, state and served files." + if status is CheckStatus.FAIL + else None + ), + duration_s=time.monotonic() - started, + ) + + @staticmethod + def _grade(subject): + if subject.runtime_evidence is None: + return CheckStatus.SKIP, ["runtime evidence is unavailable"], {} + location = subject.manifest.capabilities.oracle.location + try: + inventory = oracle_inventory(subject.root, location) + except (OSError, UnicodeError): + return ( + CheckStatus.SKIP, + [f"oracle artifact {location} is not readable inside the package"], + {}, + ) + artifacts = { + text.strip() + for _, text in inventory.files + if text and len(text.strip()) >= _MIN_FINGERPRINT + } + untraceable = sum( + text is not None and len(text.strip()) < _MIN_FINGERPRINT + for _, text in inventory.files + ) + # Structured artifacts are independent of indentation, key order and escaping. + structured = set() + strings = set(artifacts) + comparison_complete = True + for text in tuple(artifacts): + try: + value = loads(text) + except ValueError: + continue # Scripts and other plain text use whole-content matching. + except (ArithmeticError, RecursionError): + comparison_complete = False + continue + if isinstance(value, str) and len(value.strip()) >= _MIN_FINGERPRINT: + strings.add(value.strip()) + elif isinstance(value, (dict, list)): + try: + structured.add(typed_json(value)) + except ValueError: + comparison_complete = False + runs = [subject.runtime_evidence] + if subject.isolation_evidence: + runs += [ + subject.isolation_evidence.sequential, + subject.isolation_evidence.fresh, + ] + sources = [ + (f"{x.operation} response", x.response_json) + for run in runs + for x in run.exchanges + ] + sources += [ + ("schema response", run.schema_response_json) + for run in runs + if run.schema_response_json is not None + ] + sources += [ + (f"GET {probe.path}", body.decode("utf-8", "replace")) + for probe in subject.oracle_http + for body in (*probe.redirect_bodies, probe.body) + ] + leaks = set() + for label, text in sources: + matched, complete = _appears(artifacts, strings, structured, text) + comparison_complete &= complete + if matched: + leaks.add(label) + measured = { + "artifacts": len(inventory.files), + "bytes_read": inventory.bytes_read, + "omitted_files": inventory.omitted_files, + "omitted_bytes": inventory.omitted_bytes, + "inventory_errors": len(inventory.errors), + "untraceable_files": untraceable, + "json_comparison_complete": comparison_complete, + "sources": len(sources), + "http_probes": len(subject.oracle_http), + "mcp_tool_access_tested": False, + "reward_artifact_writes_tested": False, + } + if leaks: + return ( + CheckStatus.FAIL, + [ + f"oracle content is readable through the API: {label}" + for label in sorted(leaks) + ], + measured, + ) + incomplete = list(inventory.errors) + if not comparison_complete: + incomplete.append( + "structured oracle JSON exceeds supported comparison limits" + ) + if inventory.omitted_files: + incomplete.append("oracle inventory exceeds the file or byte bound") + if untraceable: + incomplete.append( + "some oracle files have no distinctive complete content to trace" + ) + if not artifacts: + incomplete.append( + "the oracle artifact has no distinctive complete content to trace" + ) + if any( + run.failure_reason or not run.exchanges or run.schema_response_json is None + for run in runs + ): + incomplete.append( + "runtime transcript or complete /schema response is unavailable or incomplete" + ) + required = {"/" + path for path, _ in inventory.files} + if ( + not required + or not required.issubset({probe.path for probe in subject.oracle_http}) + or any( + probe.status is None + or probe.failure + or probe.status >= 500 + or probe.status == 206 + or 300 <= probe.status < 400 + for probe in subject.oracle_http + ) + ): + incomplete.append("required oracle HTTP probes are missing or incomplete") + if incomplete: + return CheckStatus.SKIP, incomplete, measured + return CheckStatus.PASS, [], measured diff --git a/src/core/openenv/validation/graders/runtime/repeatability.py b/src/core/openenv/validation/graders/runtime/repeatability.py new file mode 100644 index 0000000000000000000000000000000000000000..7788015386291bb039d78e447e6e7499889c13fc --- /dev/null +++ b/src/core/openenv/validation/graders/runtime/repeatability.py @@ -0,0 +1,417 @@ +"""Seed forwarding, independent records and bounded fresh replay comparisons.""" + +import math +import statistics +import time +from decimal import Decimal, DecimalException +from fractions import Fraction + +from ...report import CheckResult +from ...runtime.json_values import dumps, loads +from ...types import CheckStatus +from .basic import _RuntimeGrader + +JUDGED_REPLAYS = 20 +MAX_JUDGED_NUMBER_DIGITS = 10_000 + + +def _json(text): + try: + return loads(text) + except DecimalException as error: + raise ValueError("unsupported JSON number") from error + + +def _trace(evidence, *, operation=None): + trace = [ + { + "operation": row.operation, + "request": _json(row.request_json), + "response": _json(row.response_json), + } + for row in evidence.exchanges + if operation is None or row.operation == operation + ] + for row in trace: + dumps(row) + operation, request, response = ( + row["operation"], + row["request"], + row["response"], + ) + if ( + operation not in {"reset", "step", "state"} + or not isinstance(request, dict) + or request.get("type") != operation + or not isinstance(response, dict) + or response.get("type") + != ("state" if operation == "state" else "observation") + or not isinstance(response.get("data"), dict) + ): + raise ValueError("malformed trace envelope") + return trace + + +def _difference(expected, observed, path="$"): + """First differing location, exposing indices and key ordinals only.""" + if type(expected) is not type(observed): + return path + if isinstance(expected, dict): + for index, key in enumerate(sorted(expected.keys() | observed.keys())): + child = f"{path}." + if key not in expected or key not in observed: + return child + mismatch = _difference(expected[key], observed[key], child) + if mismatch: + return mismatch + elif isinstance(expected, list): + for index, (left, right) in enumerate(zip(expected, observed)): + mismatch = _difference(left, right, f"{path}[{index}]") + if mismatch: + return mismatch + if len(expected) != len(observed): + return f"{path}[{min(len(expected), len(observed))}]" + elif expected != observed: + return path + return None + + +def _telemetry(evidence): + value = _json(evidence.telemetry_json) + if not isinstance(value, dict) or type(value.get("schema_version")) is not int: + raise ValueError("malformed telemetry") + if value["schema_version"] != 1: + raise ValueError("unsupported telemetry version") + return value + + +def _missing_telemetry(grader, evidence): + if evidence is not None and evidence.failure_reason: + # The shared runtime dependency reports incomplete primary collection. + return None + if evidence is not None and evidence.telemetry_json is None: + failure = evidence.telemetry_error + return CheckResult( + check_id=grader.check_id, + status=CheckStatus.FAIL if failure else CheckStatus.SKIP, + evidence=[ + failure + or evidence.telemetry_unavailable + or "session telemetry is unavailable" + ], + duration_s=0, + ) + return None + + +class SeedControlGrader(_RuntimeGrader): + """Require observed seed forwarding for the original and scheduled resets.""" + + check_id = "runtime.seed_control" + + def run(self, subject): + evidence = subject.runtime_evidence + result = _missing_telemetry(self, evidence) or super().run(subject) + if result.status is CheckStatus.PASS: + seed_replays = [ + replay.evidence for replay in evidence.replays if replay.scope == "seed" + ] + if not seed_replays: + return result.model_copy( + update={ + "status": CheckStatus.SKIP, + "evidence": [ + evidence.replay_failure_reason + or "different-seed reset experiment is unavailable" + ], + } + ) + unavailable = [ + sample.telemetry_unavailable + for sample in seed_replays + if sample.telemetry_unavailable + ] + if unavailable: + return result.model_copy( + update={"status": CheckStatus.SKIP, "evidence": unavailable} + ) + if any( + sample.failure_reason and sample.telemetry_json is None + for sample in seed_replays + ): + return result.model_copy( + update={ + "status": CheckStatus.SKIP, + "evidence": [ + "different-seed reset experiment did not produce seed telemetry" + ], + } + ) + if result.status is CheckStatus.PASS: + return result.model_copy( + update={ + "evidence": ["requested seeds were observed as forwarded to reset"] + } + ) + return result + + def check(self, subject, evidence): + problems = [] + original_seed = None + for index, sample in enumerate( + [evidence] + + [replay.evidence for replay in evidence.replays if replay.scope == "seed"] + ): + if sample.telemetry_error: + problems.append(f"replay {index}: telemetry collection failed") + continue + if sample.telemetry_unavailable: + continue + incomplete = sample.failure_reason and sample.telemetry_json is None + if incomplete: + # Failed later actions leave seed forwarding unproven; an + # observed reset rejection remains a seed experiment failure. + _trace(sample, operation="reset") + resets = [row for row in sample.exchanges if row.operation == "reset"] + if incomplete and not resets: + continue + if len(resets) != 1: + problems.append(f"replay {index}: expected one measured reset") + continue + seed = _json(resets[0].request_json)["data"]["seed"] + if type(seed) is not int: + problems.append(f"replay {index}: requested seed is not an integer") + continue + if index == 0: + original_seed = seed + elif seed == original_seed: + problems.append(f"replay {index}: scheduled seed was not changed") + if incomplete: + continue + if sample.telemetry_json is None: + problems.append(f"replay {index}: seed telemetry unavailable") + continue + observed = _telemetry(sample).get("seed") + if ( + not isinstance(observed, dict) + or observed.get("requested") is not True + or observed.get("accepted") is not True + or type(observed.get("value")) is not int + or observed["value"] != seed + ): + problems.append(f"replay {index}: seed was not observed as forwarded") + return problems + + +class TrajectoryRecordGrader(_RuntimeGrader): + """Compare a subject-emitted record with the independent collector transcript.""" + + check_id = "runtime.trajectory_record" + + def run(self, subject): + return _missing_telemetry(self, subject.runtime_evidence) or super().run( + subject + ) + + def check(self, subject, evidence): + if evidence.telemetry_error: + return [evidence.telemetry_error] + record = _telemetry(evidence).get("trajectory") + if not isinstance(record, dict): + return ["subject-emitted trajectory record is missing"] + if ( + type(record.get("schema_version")) is not int + or record["schema_version"] != 1 + or record.get("source") != "openenv-server" + ): + return ["subject-emitted trajectory record metadata is invalid"] + if record.get("complete") is not True: + return ["subject-emitted trajectory record is incomplete"] + if not isinstance(record.get("records"), list): + return ["subject-emitted trajectory records are malformed"] + mismatch = _difference(_trace(evidence), record["records"]) + return [f"subject record differs at {mismatch}"] if mismatch else [] + + +class EpisodeDeterminismGrader(_RuntimeGrader): + """Compare full traces, or per-step reward population variance for a judge.""" + + check_id = "runtime.episode_determinism" + + def run(self, subject): + started = time.monotonic() + evidence = subject.runtime_evidence + if evidence is None: + return super().run(subject) + measured = {} + try: + status, messages, measured = self._grade(subject, evidence) + except (ValueError, TypeError, KeyError, RecursionError, OverflowError): + status, messages = CheckStatus.FAIL, ["malformed replay evidence"] + return CheckResult( + check_id=self.check_id, + status=status, + evidence=messages, + measured=measured, + duration_s=time.monotonic() - started, + ) + + def _grade(self, subject, evidence): + if any( + row.scope not in {"session", "container", "seed"} + for row in evidence.replays + ): + return CheckStatus.FAIL, ["invalid replay scope"], {} + replays = [row for row in evidence.replays if row.scope != "seed"] + samples = [evidence] + [row.evidence for row in replays] + completed = [ + not row.failure_reason + and not row.failure_phase + and any(exchange.operation == "step" for exchange in row.exchanges) + for row in samples + ] + measured = {"completed_replays": sum(completed)} + judged = subject.manifest.capabilities.llm_judged + required = JUDGED_REPLAYS if judged else 3 + # Inspect retained content before reporting an incomplete schedule: a + # timeout cannot conceal malformed wire data or an observed divergence. + traces = [_trace(sample) for sample in samples] + rewards = [] + for trace in traces: + sample_rewards = [] + for row in trace: + if row["operation"] != "step": + continue + if judged: + data = row["response"]["data"] + reward = data["reward"] + if reward is None and data.get("done") is False: + sample_rewards.append(None) + continue + low, high = subject.manifest.reward.range + if ( + type(reward) not in (int, Decimal) + or not Decimal(reward).is_finite() + or not Decimal(str(low)) <= reward <= Decimal(str(high)) + ): + return ( + CheckStatus.FAIL, + ["invalid judged replay reward"], + measured, + ) + sample_rewards.append(Decimal(reward)) + # Keep null versus numeric positions visible to trace comparison. + data["reward"] = 0.0 + rewards.append(sample_rewards) + # Policy-owned volatile exclusions are deliberately empty. All replays + # use the same episode identity; no author field can suppress a difference. + for index, trace in enumerate(traces[1:], 1): + if completed[0] and completed[index]: + mismatch = _difference(traces[0], trace) + else: + shared = min(len(traces[0]), len(trace)) + mismatch = _difference(traces[0][:shared], trace[:shared]) + if mismatch: + return ( + CheckStatus.FAIL, + [f"replay {index}: first divergence at {mismatch}"], + measured, + ) + if ( + not all(completed) + or len(samples) < required + or {row.scope for row in replays} != {"session", "container"} + ): + return ( + CheckStatus.SKIP, + [ + evidence.replay_failure_reason + or f"requires {required} completed replays across fresh sessions and containers" + ], + measured, + ) + if judged and len(samples) != JUDGED_REPLAYS: + return ( + CheckStatus.FAIL, + ["judged procedure requires exactly 20 samples"], + measured, + ) + if judged: + bound = subject.manifest.reward.variance_tolerance + if type(bound) not in (int, float) or not math.isfinite(bound) or bound < 0: + return CheckStatus.FAIL, ["invalid declared variance bound"], measured + variances, unsupported = [], [] + for index, values in enumerate(zip(*rewards)): + if values[0] is None: + variance = None + # A short exponent token must not allocate an unbounded rational. + elif any( + len(value.as_tuple().digits) + abs(value.as_tuple().exponent) + > MAX_JUDGED_NUMBER_DIGITS + for value in values + ): + unsupported.append(index) + variance = None + else: + # Rational variance avoids float and Decimal-context rounding. + variance = statistics.pvariance(map(Fraction, values)) + variances.append(variance) + failure = next( + ( + index + for index, variance in enumerate(variances) + if variance is not None and variance > Decimal(str(bound)) + ), + None, + ) + if unsupported and failure is None: + return ( + CheckStatus.SKIP, + ["judged reward precision exceeds supported arithmetic bounds"], + measured, + ) + display = [] + unavailable = { + str(index): "exceeds supported arithmetic bounds" + for index in unsupported + } + for index, variance in enumerate(variances): + try: + display.append(None if variance is None else float(variance)) + except OverflowError: + display.append(None) + unavailable[str(index)] = "exceeds finite float display range" + measured.update( + reward_population_variance=display, + variance_units="reward_squared", + ) + if unavailable: + measured["reward_population_variance_unavailable"] = unavailable + if failure is not None: + return ( + CheckStatus.FAIL, + [ + f"step {failure}: reward population variance exceeds declared bound" + ], + measured, + ) + if not any(variance is not None for variance in variances): + return ( + CheckStatus.SKIP, + ["missing prerequisite: an observed numeric step reward"], + measured, + ) + if any( + row.scope == "container" and row.cleanup_complete is not True + for row in replays + ): + return ( + CheckStatus.SKIP, + ["fresh container cleanup was not confirmed"], + measured, + ) + return ( + CheckStatus.PASS, + ["fresh-session and fresh-container replays agree"], + measured, + ) diff --git a/src/core/openenv/validation/graders/runtime/resources.py b/src/core/openenv/validation/graders/runtime/resources.py new file mode 100644 index 0000000000000000000000000000000000000000..a69bbfd641150dc098ca6fb5f1fa45961cc72345 --- /dev/null +++ b/src/core/openenv/validation/graders/runtime/resources.py @@ -0,0 +1,199 @@ +"""`runtime.resource_bounds`: measured limits and enforcement against the declared budget.""" + +import time + +from ...report import CheckResult +from ...runtime.contracts import ResourceEvidence +from ...types import CheckStatus, Level, ProviderCapability + +_MIB = 1024 * 1024 +_PROBES = { + "memory": "cgroup_oom_kill", + "pids": "cgroup_pids_max", + "disk": "filesystem_full", + "exec_timeout": "exec_timeout", +} + + +class ResourceBoundsGrader: + """Check measured resource ceilings and Docker exec descendant cleanup.""" + + check_id = "runtime.resource_bounds" + level = Level.RUNTIME + requires_capabilities = frozenset() + requires_provider = frozenset({ProviderCapability.RESOURCE_ENFORCEMENT}) + depends_on = ("runtime.startup",) + + def applies_to(self, manifest) -> bool: + return True + + def run(self, subject) -> CheckResult: + started = time.monotonic() + status, problems, measured = self._grade(subject) + return CheckResult( + check_id=self.check_id, + status=status, + evidence=problems + or [ + "measured CPU, memory, PID and storage ceilings match the declaration; " + "Docker exec timeout removes descendants; episode deadline is not qualified" + ], + measured=measured, + remediation=( + "Run the subject under finite CPU, memory, swap, process and " + "writable-storage limits within its declared budget." + if status is CheckStatus.FAIL + else None + ), + duration_s=time.monotonic() - started, + ) + + @staticmethod + def _grade(subject): + if subject.resource_evidence_json is None: + return CheckStatus.SKIP, ["resource evidence is unavailable"], {} + try: + evidence = ResourceEvidence.model_validate_json( + subject.resource_evidence_json + ) + except ValueError: # includes pydantic's ValidationError + return CheckStatus.FAIL, ["malformed resource evidence"], {} + + declared = subject.manifest.resources + cgroup = evidence.cgroup + problems = [] + if cgroup is not None: + if "memory_max" in cgroup.unavailable: + pass + elif cgroup.memory_max is None: + problems.append("memory is unlimited") + elif cgroup.memory_max > declared.memory_mb * _MIB: + problems.append( + f"memory limit {cgroup.memory_max} B exceeds {declared.memory_mb} MiB" + ) + if "swap_max" not in cgroup.unavailable and cgroup.swap_max != 0: + problems.append("swap is not disabled") + if {"cpu_quota", "cpu_period"} & set(cgroup.unavailable): + pass + elif cgroup.cpu_quota is None: + problems.append("CPU is unlimited") + elif cgroup.cpu_period is None: + problems.append("CPU period is unavailable") + elif cgroup.cpu_quota / cgroup.cpu_period > declared.cpu + 1e-9: + problems.append( + f"CPU limit {cgroup.cpu_quota / cgroup.cpu_period:g} exceeds {declared.cpu:g}" + ) + if "pids_max" not in cgroup.unavailable and cgroup.pids_max is None: + problems.append("process count is unlimited") + inventory = evidence.containment + storage_unknown = inventory is None or not any( + mount.mount_point == "/" for mount in inventory.mounts + ) + filesystems = {} + if inventory is not None: + # Docker's device tmpfs is also bound over masked /proc files. Denial + # at /dev alone says nothing about nested directories or regular files. + dev = { + mount.device + for mount in inventory.mounts + if (mount.mount_point, mount.fstype) == ("/dev", "tmpfs") + } + if any( + device not in inventory.device_storage + or not inventory.device_storage[device].complete + for device in dev + ): + storage_unknown = True + for mount in inventory.mounts: + if mount.mount_point == "/" and not mount.read_only: + problems.append("the image root is writable") + if mount.read_only or (mount.mount_point, mount.fstype) in { + ("/proc", "proc"), + ("/dev/pts", "devpts"), + ("/dev/mqueue", "mqueue"), + }: + continue + if mount.device in dev and mount.mount_point not in inventory.allotted: + access = inventory.device_storage.get(mount.device) + if access is None or not access.writable: + continue + if mount.size_bytes is None: + storage_unknown = True + else: + filesystems[mount.device] = mount.size_bytes + if sorted(inventory.allotted_writable) != sorted(inventory.allotted): + storage_unknown = True + writable = sum(filesystems.values()) + if writable > declared.disk_mb * _MIB: + problems.append( + f"writable storage {writable} B exceeds {declared.disk_mb} MiB" + ) + results = {probe.kind: probe.result for probe in evidence.qualification} + problems += [ + f"the {kind} probe escaped its limit" + for kind, result in results.items() + if result == "escaped" + ] + measured = { + "cgroup": cgroup.model_dump() if cgroup else None, + "writable_bytes": writable, + "qualification": results, + } + # A failed control cannot erase an independently proven violation. + if problems: + return CheckStatus.FAIL, problems, measured + if cgroup is None: + return CheckStatus.SKIP, ["cgroup v2 limits could not be read"], measured + if cgroup.unavailable: + return ( + CheckStatus.SKIP, + ["unreadable cgroup limits: " + ", ".join(cgroup.unavailable)], + measured, + ) + if storage_unknown: + return ( + CheckStatus.SKIP, + ["complete writable-filesystem inventory is unavailable"], + measured, + ) + qualified = {probe.kind: probe for probe in evidence.qualification} + unproven = [] + for kind, reason in _PROBES.items(): + probe = qualified.get(kind) + if ( + probe is None + or not probe.started + or probe.result != "contained" + or probe.reason != reason + ): + unproven.append(kind) + continue + increased = ( + probe.counter_before is not None + and probe.counter_after is not None + and probe.counter_after > probe.counter_before + ) + corroborated = { + "memory": probe.oom_killed or increased, + "pids": increased, + "disk": all( + probe.free_bytes.get(path) == 0 + and (probe.free_bytes_before.get(path) or 0) > 0 + for path in inventory.allotted + ), + "exec_timeout": ( + probe.removed + and probe.parent_pid is not None + and probe.descendant_pid is not None + and probe.parent_pid != probe.descendant_pid + ), + }[kind] + if not corroborated: + unproven.append(kind) + if unproven: + return ( + CheckStatus.SKIP, + [f"enforcement not proven for {', '.join(unproven)}"], + measured, + ) + return CheckStatus.PASS, [], measured diff --git a/src/core/openenv/validation/graders/semantic/__init__.py b/src/core/openenv/validation/graders/semantic/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..08aadc2e4ddaaaf35cccfe4a4475e9c0df48d150 --- /dev/null +++ b/src/core/openenv/validation/graders/semantic/__init__.py @@ -0,0 +1,5 @@ +"""Semantic-level graders.""" + +from .oracle import CanaryFloorGrader, FloorGapGrader, OracleMaxGrader + +__all__ = ["CanaryFloorGrader", "FloorGapGrader", "OracleMaxGrader"] diff --git a/src/core/openenv/validation/graders/semantic/oracle.py b/src/core/openenv/validation/graders/semantic/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..9dd8a8d9f39e948b6207ce16b6c778ba16ba5b39 --- /dev/null +++ b/src/core/openenv/validation/graders/semantic/oracle.py @@ -0,0 +1,145 @@ +"""Verifier sanity over oracle, do-nothing and canary rewards (#778 tests #25, #28). + +The execution binding measures the rewards; these graders only compare them with the +manifest's declared range, tolerance and margin. Comparisons use exact rationals so a +tiny floor cannot round into the margin. +""" + +import time +from fractions import Fraction + +from ...report import CheckResult +from ...types import CheckStatus, Level + + +class _SemanticGrader: + level = Level.SEMANTIC + requires_capabilities = frozenset() + requires_provider = frozenset() + # RFC 008: episode determinism is a precondition of every semantic check. + depends_on = ("runtime.episode_determinism",) + remediation = "" + + def applies_to(self, manifest) -> bool: + return True + + def run(self, subject) -> CheckResult: + started = time.monotonic() + evidence = subject.oracle_evidence + if evidence is None: + return CheckResult( + check_id=self.check_id, + status=CheckStatus.ERROR, + evidence=["oracle evidence is unavailable"], + duration_s=0, + ) + reward = subject.manifest.reward + low, high = (Fraction(str(value)) for value in reward.range) + problems, measured = self.check( + evidence, + maximum=high, + width=high - low, + tolerance=Fraction(str(reward.oracle_tolerance)), + margin=Fraction(str(reward.floor_margin)), + ) + return CheckResult( + check_id=self.check_id, + status=CheckStatus.FAIL if problems else CheckStatus.PASS, + measured=measured, + evidence=problems or [self.passed], + remediation=self.remediation if problems else None, + duration_s=time.monotonic() - started, + ) + + +class OracleMaxGrader(_SemanticGrader): + """Every oracle run exits cleanly and meets the range-normalized tolerance.""" + + check_id = "semantic.oracle_max" + passed = "every oracle run reached the declared maximum within tolerance" + remediation = ( + "Fix the oracle or the verifier so a correct solution exits cleanly and " + "earns the declared maximum reward." + ) + + def check(self, evidence, *, maximum, width, tolerance, margin): + threshold = maximum - tolerance * width + problems = [] + for run, (reward, code) in enumerate( + zip(evidence.oracle, evidence.oracle_exit_codes, strict=True), start=1 + ): + if code != 0: + problems.append(f"oracle run {run} exited with code {code}") + if reward < threshold: + problems.append( + f"oracle run {run} earned {float(reward)}, below {float(threshold)}" + ) + return problems, { + "oracle_rewards": [float(reward) for reward in evidence.oracle], + "oracle_exit_codes": list(evidence.oracle_exit_codes), + "declared_max": float(maximum), + "oracle_tolerance": float(tolerance), + } + + +class FloorGapGrader(_SemanticGrader): + """ + The do-nothing reward sits at least `floor_margin` of the declared range below + the maximum and every oracle run. The oracle may sit up to the tolerance below + the maximum, so both gaps are required. + """ + + check_id = "semantic.floor_gap" + passed = "the do-nothing reward leaves the declared margin" + remediation = ( + "The verifier rewards doing nothing. Check for vacuous success conditions, " + "such as comparisons against empty output." + ) + + def check(self, evidence, *, maximum, width, tolerance, margin): + floor = evidence.floor + required_gap = margin * width + problems = [] + if maximum - floor < required_gap: + problems.append( + f"do-nothing reward {float(floor)} is within {float(maximum - floor)} " + f"of the maximum, below the required gap {float(required_gap)}" + ) + lowest = min(evidence.oracle) + if lowest - floor < required_gap: + problems.append( + f"oracle reward {float(lowest)} is within {float(lowest - floor)} " + f"of the do-nothing reward, below the required gap {float(required_gap)}" + ) + return problems, { + "measured_floor": float(floor), + "oracle_reward": float(lowest), + "declared_max": float(maximum), + "declared_margin": float(margin), + } + + +class CanaryFloorGrader(_SemanticGrader): + """Every declared canary, a known-wrong solution, earns no more than doing nothing.""" + + check_id = "semantic.canary_floor" + requires_capabilities = frozenset({"canaries"}) + passed = "every canary stayed at the do-nothing reward" + remediation = ( + "The verifier rewards a known-wrong solution. Tighten the tests so each " + "canary earns no more than doing nothing." + ) + + def check(self, evidence, *, maximum, width, tolerance, margin): + problems = [ + f"canary {name} earned {float(reward)}, above the do-nothing reward " + f"{float(evidence.floor)}" + for name, reward in evidence.canaries + if reward > evidence.floor + ] + return problems, { + "measured_floor": float(evidence.floor), + "canary_rewards": { + name: float(reward) for name, reward in evidence.canaries + }, + } diff --git a/src/core/openenv/validation/harbor.py b/src/core/openenv/validation/harbor.py new file mode 100644 index 0000000000000000000000000000000000000000..6932562ecbd917051e2257d81d86911b36e14252 --- /dev/null +++ b/src/core/openenv/validation/harbor.py @@ -0,0 +1,1549 @@ +"""Native Harbor execution: fresh trials graded through RFC 008 check ids. + +No served-protocol evidence is synthesized. On local Docker, a do-nothing trial +builds the image, or pulls the task's digest-pinned one, and the oracle, its replay +and any canaries run pinned to that image. On `hf-sandbox`, every trial starts at +once from the task's digest-pinned image, each in its own Hugging Face Job. +""" + +import asyncio +import hashlib +import json +import math +import os +import re +import shutil +import signal +import stat +import subprocess +import tempfile +import time +import uuid +from concurrent.futures import ThreadPoolExecutor +from dataclasses import replace +from decimal import Decimal +from fractions import Fraction +from functools import partial +from importlib.metadata import distribution +from pathlib import Path + +from .graders import GraderRegistry +from .graders.semantic import CanaryFloorGrader, FloorGapGrader, OracleMaxGrader +from .parsers.harbor_toml import ( + _unique_object, + canary_scripts, + HARBOR_PROFILE, + read_harbor_contract, + read_harbor_task, +) +from .policy import apply_policy +from .report import CheckResult, ValidationReportV2 +from .runtime.artifacts import write_runtime_bundle +from .runtime.contracts import OracleEvidence +from .runtime.json_values import dumps +from .runtime.scheduler import execute_graders +from .types import CheckStatus, Lane, Level + +_IMAGE_ID = re.compile(r"sha256:[0-9a-f]{64}\Z") +# A tag can move between validation and training; a digest cannot. +_PINNED_IMAGE = re.compile(r"[^@\s]+@sha256:[0-9a-f]{64}\Z") +_RESOURCE_ID = re.compile(r"[a-zA-Z0-9][a-zA-Z0-9_.-]*\Z") +_PROJECT = re.compile( + r"openenv-validation-[a-f0-9]+-(nop|oracle|oracle-replay|canary-[1-8])__env" +) +_MAX_REWARD_BYTES = 1024 * 1024 +# Failures the trial's teardown records over any earlier one. +_HOST_FAILURES = { + "HarborTeardownError", + "CleanupNotVerified", + "RewardArtifactDrift", + "UnsafeRewardArtifact", + "RetainedImageDrift", + "RetainedImageUnverified", +} +_TERMINAL_STAGES = {"COMPLETED", "CANCELED", "ERROR", "DELETED"} +_JOB_STOP_TIMEOUT_S = 60 +# Readiness budget inside the 600-second start budget; allocation can take longer. +_SANDBOX_START_TIMEOUT_S = 540 +# Checks this binding measures; every other local check is a named SKIP. +_IMPLEMENTED = { + "runtime.startup", + "runtime.reward_well_formed", + "runtime.episode_determinism", + "semantic.oracle_max", + "semantic.floor_gap", + "semantic.canary_floor", +} + + +class NativeEvidenceError(ValueError): + """A credential-safe diagnostic written by the trusted native collector.""" + + +def _digest(value): + return hashlib.sha256( + json.dumps(value, sort_keys=True, allow_nan=False).encode() + ).hexdigest() + + +class DockerInspector: + """Trusted host inspection and removal limited to run-owned resources.""" + + def __init__(self): + self._owned_volumes = {} + self._retained_image = None + + def _docker(self, *args): + result = subprocess.run( + ["docker", *args], capture_output=True, timeout=30, check=True + ) + if len(result.stdout) > 4 * 1024 * 1024: + raise NativeEvidenceError("Docker inspection exceeded its output limit") + return result.stdout.decode() + + def preflight(self): + info = json.loads(self._docker("info", "--format", "{{json .}}")) + if info["OSType"] != "linux": + raise NativeEvidenceError("Harbor requires a Linux Docker daemon") + self._docker("compose", "version") + return { + "os": info["OSType"], + "daemon_id": info["ID"], + "server_version": info["ServerVersion"], + } + + def inventory(self, project): + if not _PROJECT.fullmatch(project): + raise NativeEvidenceError("not a run-owned Harbor project") + label = f"label=com.docker.compose.project={project}" + inventory = {} + for kind, args in ( + ("containers", ("ps", "-aq", "--no-trunc")), + ("networks", ("network", "ls", "-q", "--no-trunc")), + ("volumes", ("volume", "ls", "-q")), + ): + ids = self._docker(*args, "--filter", label).split() + if any(not _RESOURCE_ID.fullmatch(item) for item in ids): + raise NativeEvidenceError("invalid Docker resource identity") + inventory[kind] = ids + images = self._docker( + "image", "ls", "-q", "--no-trunc", project + "-main:latest" + ).split() + if len(images) > 1 or any(not _IMAGE_ID.fullmatch(image) for image in images): + raise NativeEvidenceError("invalid Compose image identity") + inventory["images"] = images + return inventory + + def capture(self, project, retained_tag, *, retain=True): + inventory = self.inventory(project) + if retained_tag != "openenv-validation:" + project.split("-", 3)[2]: + raise NativeEvidenceError( + "retained image tag differs from its run-owned project" + ) + if len(inventory["containers"]) != 1: + raise NativeEvidenceError("Harbor requires exactly one main container") + item = json.loads(self._docker("inspect", inventory["containers"][0]))[0] + labels = item["Config"]["Labels"] + if ( + labels.get("com.docker.compose.project") != project + or labels.get("com.docker.compose.service") != "main" + ): + raise NativeEvidenceError( + "container does not match the native main service" + ) + if not item["State"]["Running"] or not _IMAGE_ID.fullmatch(item["Image"]): + raise NativeEvidenceError( + "native container is not running with an immutable image" + ) + if retain: + self._retained_image = (retained_tag, item["Image"]) + self._docker("image", "tag", item["Image"], retained_tag) + retained = json.loads(self._docker("image", "inspect", retained_tag))[0] + if (retain and retained["Id"] != item["Image"]) or retained["Os"] != "linux": + raise NativeEvidenceError("retained image binding changed") + host = item["HostConfig"] + # Dockerfile VOLUME creates anonymous volumes without Compose labels. + volumes = [ + mount["Name"] for mount in item["Mounts"] if mount["Type"] == "volume" + ] + if any(not _RESOURCE_ID.fullmatch(name) for name in volumes): + raise NativeEvidenceError("invalid mounted volume identity") + self._owned_volumes[project] = volumes + configuration = { + "image_ref": item["Image"], + "user": item["Config"]["User"], + "workdir": item["Config"]["WorkingDir"], + "environment_digest": _digest(sorted(item["Config"].get("Env") or [])), + "entrypoint": item["Config"].get("Entrypoint"), + "command": item["Config"].get("Cmd"), + "host": { + key: host.get(key) + for key in ( + "NanoCpus", + "Memory", + "MemorySwap", + "PidsLimit", + "ReadonlyRootfs", + "Privileged", + "CapAdd", + "CapDrop", + "SecurityOpt", + "Devices", + ) + }, + "network_mode": "compose-default" + if host["NetworkMode"] == project + "_default" + else host["NetworkMode"], + "mounts": sorted( + [ + { + "type": mount["Type"], + "destination": mount["Destination"], + "rw": mount["RW"], + } + for mount in item["Mounts"] + ], + key=lambda mount: mount["destination"], + ), + } + return { + "container_id": item["Id"], + "project": project, + "image_ref": item["Image"], + "retained_image_tag": retained_tag, + "configuration": configuration, + "configuration_digest": _digest(configuration), + "owned_volumes": volumes, + } + + def cleanup(self, project): + before = self.inventory(project) + for container in before["containers"]: + item = json.loads(self._docker("inspect", container))[0] + if item["Config"]["Labels"].get("com.docker.compose.project") != project: + raise NativeEvidenceError("cleanup container ownership changed") + volumes = [ + mount["Name"] for mount in item["Mounts"] if mount["Type"] == "volume" + ] + if any(not _RESOURCE_ID.fullmatch(name) for name in volumes): + raise NativeEvidenceError("invalid cleanup volume identity") + self._owned_volumes.setdefault(project, []).extend(volumes) + # Even a successful docker rm -v can leave an anonymous volume behind. + registered = self._owned_volumes.get(project, []) + existing = ( + set(self._docker("volume", "ls", "-q").split()) if registered else set() + ) + before["volumes"] = sorted( + set(before["volumes"]) | (set(registered) & existing) + ) + for key, args in ( + ("containers", ("rm", "-f", "-v")), + ("networks", ("network", "rm")), + ("volumes", ("volume", "rm")), + ): + remaining = before[key] + if key == "volumes" and remaining: + existing = set(self._docker("volume", "ls", "-q").split()) + remaining = [name for name in remaining if name in existing] + if remaining: + self._docker(*args, *remaining) + for image_ref in before["images"]: + tag = project + "-main:latest" + image = json.loads(self._docker("image", "inspect", tag))[0] + labels = image["Config"]["Labels"] + if ( + image["Id"] != image_ref + or labels.get("com.docker.compose.project") != project + or labels.get("com.docker.compose.service") != "main" + ): + raise NativeEvidenceError( + "Compose image ownership changed before removal" + ) + self._docker("image", "rm", "--no-prune", tag) + after = self.inventory(project) + if registered: + existing = set(self._docker("volume", "ls", "-q").split()) + after["volumes"] = sorted( + set(after["volumes"]) | (set(registered) & existing) + ) + return {"verified": not any(after.values()), "before": before, "after": after} + + def verify_image(self, tag, image_ref): + image = json.loads(self._docker("image", "inspect", tag))[0] + return image["Id"] == image_ref + + def remove_image(self): + if self._retained_image is not None: + tag, image_ref = self._retained_image + if not self.verify_image(tag, image_ref): + raise NativeEvidenceError( + "retained image ownership changed before removal" + ) + self._docker("image", "rm", "--no-prune", tag) + self._retained_image = None + + +def _job_labels(trial_name): + # openenv-validation-- + run_id, role = trial_name.split("-", 3)[2:] + return {"openenv-validation-run": run_id, "openenv-validation-role": role} + + +class HFJobsInspector: + """ + Trusted HF Jobs checks limited to sandbox jobs labelled with this run. + + The image identity is the digest requested from HF Jobs and read back from the + job; no runtime digest is measured inside the sandbox. + """ + + def __init__(self, image, flavor, namespace, resources): + self.image = image + self.flavor = flavor + self.namespace = namespace + self._resources = resources + self._api = None + self._observed_jobs = {} + + def preflight(self): + from huggingface_hub import HfApi + + self._api = HfApi() + if self.namespace is None: + self.namespace = self._api.whoami()["name"] + hardware = {item.name: item for item in self._api.list_jobs_hardware()} + if self.flavor not in hardware: + raise NativeEvidenceError(f"unknown HF Jobs flavor {self.flavor}") + item = hardware[self.flavor] + # The Hub lists specs as "2 vCPU", "16 GB" and "50 GB". + cpu, memory_gb, disk_gb = ( + int(spec.split()[0]) + for spec in (item.cpu, item.ram, item.ephemeral_storage) + ) + if ( + cpu < self._resources.cpu + or memory_gb * 1024 < self._resources.memory_mb + or disk_gb * 1024 < self._resources.disk_mb + ): + raise NativeEvidenceError( + f"HF Jobs flavor {self.flavor} ({item.cpu}, {item.ram} RAM, " + + f"{item.ephemeral_storage} disk) is smaller than the contract resources" + ) + return { + "flavor": self.flavor, + "namespace": self.namespace, + "hardware": { + "cpu": item.cpu, + "ram": item.ram, + "disk": item.ephemeral_storage, + }, + } + + def register_job(self, project, job_id): + # The Sandbox handle is authoritative even before AGENT_START or listing. + self._observed_jobs.setdefault(project, set()).add(job_id) + + def _jobs(self, project): + if not _PROJECT.fullmatch(project): + raise NativeEvidenceError("not a run-owned Harbor project") + labels = _job_labels(project.removesuffix("__env")) + jobs = list(self._api.list_jobs(labels=labels, namespace=self.namespace)) + # A listing omission does not prove a previously observed job terminated. + listed_ids = {job.id for job in jobs} + known_ids = self._observed_jobs.get(project, set()) + jobs.extend( + self._api.inspect_job(job_id=job_id, namespace=self.namespace) + for job_id in sorted(known_ids - listed_ids) + ) + # Cleanup cancels what this returns, so recheck the server-side filter. + if any( + not labels.items() <= (job.labels or {}).items() + or job.owner.name != self.namespace + for job in jobs + ): + raise NativeEvidenceError("HF Jobs returned a job outside this run") + self._observed_jobs[project] = known_ids | listed_ids + return jobs + + def inventory(self, project): + return {"jobs": sorted(job.id for job in self._jobs(project))} + + def capture(self, project, retained_tag, *, retain=True): + jobs = self._jobs(project) + if len(jobs) != 1: + raise NativeEvidenceError("HF Sandbox trial requires exactly one job") + job = jobs[0] + if ( + job.status.stage != "RUNNING" + or job.docker_image != self.image + or job.flavor != self.flavor + ): + raise NativeEvidenceError( + "HF Sandbox job is not running the pinned image on the requested flavor" + ) + configuration = { + "image_ref": job.docker_image, + "flavor": self.flavor, + "namespace": self.namespace, + } + return { + "container_id": job.id, + "project": project, + "image_ref": job.docker_image, + "configuration": configuration, + "configuration_digest": _digest(configuration), + } + + def cleanup(self, project): + # Startup settles allocation before teardown; inspect until each job ends. + deadline = time.monotonic() + _JOB_STOP_TIMEOUT_S + cancelled = set() + while True: + stages = {job.id: job.status.stage for job in self._jobs(project)} + running = { + job_id + for job_id, stage in stages.items() + if stage not in _TERMINAL_STAGES + } + for job_id in running - cancelled: + self._api.cancel_job(job_id=job_id, namespace=self.namespace) + cancelled.add(job_id) + if not running or time.monotonic() > deadline: + return { + "verified": not running, + "jobs": stages, + "cancelled": sorted(cancelled), + } + time.sleep(2) + + def verify_image(self, tag, image_ref): + return image_ref == self.image + + def remove_image(self): + pass # Nothing is pulled or tagged on this host. + + +def _unsupported(task, contract, sandbox): + config = task.config + env = config.environment + verifier_env = config.verifier.environment + environments = (env,) if verifier_env is None else (env, verifier_env) + if task.has_steps: + return "multi-step Harbor tasks" + if any(environment.os.value != "linux" for environment in environments): + return "non-Linux Harbor tasks" + if env.docker_image is not None and not _PINNED_IMAGE.fullmatch(env.docker_image): + return "task-declared environment.docker_image without a sha256 digest pin" + separate = verifier_env is not None or ( + config.verifier.environment_mode is not None + and config.verifier.environment_mode.value != "shared" + ) + if separate and sandbox != "hf-sandbox": + return "separate Harbor verifier environments outside hf-sandbox" + if ( + env.docker_image is None + and not (task.task_dir / "environment/Dockerfile").is_file() + ) or any( + path.name.lower() + in {"docker-compose.yaml", "docker-compose.yml", "compose.yaml", "compose.yml"} + for path in (task.task_dir / "environment").rglob("*") + ): + return "tasks without one Dockerfile or pinned image, or with task-authored Compose" + if contract.resources.gpus or any( + environment.gpus or environment.tpu or environment.mcp_servers + for environment in environments + ): + return "GPU/TPU or external MCP requirements" + if contract.requires_credentials: + return "external credential requirements" + if env.network_mode.value != "public" or any( + phase.network_mode is not None and phase.network_mode.value != "public" + for phase in (config.agent, config.verifier, verifier_env) + if phase is not None + ): + return "non-public or differing phase network policies" + if ( + any(environment.env for environment in environments) + or config.verifier.env + or config.solution.env + ): + return "task environment variables (including host credential substitutions)" + if ( + any( + environment.healthcheck or environment.skills_dir + for environment in environments + ) + or config.verifier.collect + ): + return "healthcheck, skills or collect extensions" + if config.artifacts and sandbox != "hf-sandbox": + return "artifact extensions outside hf-sandbox" + if sandbox == "hf-sandbox": + if env.docker_image is None: + return ( + "hf-sandbox tasks without environment.docker_image; build and push " + + "the image, then pin it as name@sha256:" + ) + if config.agent.user is not None or config.verifier.user is not None: + return "agent or verifier users on hf-sandbox, which cannot switch users" + # Harbor runs a separate verifier from verifier.environment.docker_image, + # else a tests/ Dockerfile, else the task image with tests/ uploaded. + if separate and ( + (verifier_env is not None and verifier_env.docker_image is not None) + or any( + (task.task_dir / "tests" / name).is_file() + for name in ("Dockerfile", "docker-compose.yaml") + ) + ): + return ( + "separate verifiers on hf-sandbox that use their own image; " + + "the verifier must reuse the task's pinned image" + ) + return None + + +async def _create_trial(config, register_job=None): + from harbor.environments.hf_sandbox import HFSandboxEnvironment + from harbor.trial.trial import Trial + + trial = await Trial.create(config) + environment = trial.agent_environment + trial._openenv_cancelled_compose = [] + if isinstance(environment, HFSandboxEnvironment): + start = partial( + _start_sandbox, + labels=_job_labels(config.trial_name), + namespace=config.environment.kwargs["namespace"], + ) + environment.start = partial(start, environment) + # Harbor checks a separate verifier's environment just before starting + # it, so its job gets the same labels and is registered for cleanup. + check_verifier = trial._validate_separate_verifier_env_policies + + def label_verifier(verifier, *, plan): + check_verifier(verifier, plan=plan) + + async def start_verifier(*, force_build): + try: + await start(verifier, force_build=force_build) + finally: + if verifier._sandbox is not None: + register_job(verifier._sandbox.id) + + verifier.start = start_verifier + + trial._validate_separate_verifier_env_policies = label_verifier + else: + environment._run_docker_compose_command = partial( + _run_compose, environment, cancelled=trial._openenv_cancelled_compose + ) + return trial + + +async def _start_sandbox(environment, *, force_build, labels, namespace): + # Harbor's hf-sandbox start, plus labels that let cleanup find every run-owned job. + from huggingface_hub import Sandbox + + creating = asyncio.create_task( + asyncio.to_thread( + Sandbox.create, + image=environment.task_env_config.docker_image, + flavor=environment._flavor, + idle_timeout=environment._idle_timeout, + namespace=namespace, + # The default job name is derived from the image, and a digest-pinned + # registry image makes it longer than the 100 characters HF Jobs allows. + labels={**labels, "name": environment.session_id}, + start_timeout=_SANDBOX_START_TIMEOUT_S, + ) + ) + try: + environment._sandbox = await asyncio.shield(creating) + except asyncio.CancelledError: + # A cancelled worker can still allocate a job. Settle it and preserve its + # handle before Harbor teardown and the final ownership/terminal checks. + # Both Harbor and the validator can cancel the same start at its deadline. + while not creating.done(): + try: + await asyncio.shield(creating) + except asyncio.CancelledError: + continue + environment._sandbox = creating.result() + raise + if workdir := environment.task_env_config.workdir: + await asyncio.to_thread(environment._sandbox.files.mkdir, workdir) + await environment.ensure_dirs(environment._mount_targets(writable_only=True)) + await environment._upload_environment_dir_after_start() + + +async def _run_compose( + environment, + command, + check=True, + timeout_sec=None, + stdin_data=None, + on_output=None, + *, + cancelled, +): + # Harbor's Compose collector does not reap the client on outer cancellation. + runtime = type(environment).runtime() + argv = [*runtime.compose, "--project-name", environment.session_id] + if runtime.supports_compose_project_directory: + argv.extend(["--project-directory", str(environment.environment_dir.resolve())]) + for path in environment._docker_compose_paths: + argv.extend(["-f", str(path.resolve())]) + spawn = asyncio.create_task( + asyncio.create_subprocess_exec( + *argv, + *command, + env=environment._compose_env_vars(include_os_env=True), + # A task with a prebuilt image may ship no environment directory. + cwd=str(environment.environment_dir.resolve()) + if environment.environment_dir.is_dir() + else None, + stdin=asyncio.subprocess.PIPE + if stdin_data is not None + else asyncio.subprocess.DEVNULL, + stdout=asyncio.subprocess.PIPE, + stderr=asyncio.subprocess.STDOUT, + start_new_session=True, + ) + ) + try: + process = await asyncio.shield(spawn) + if on_output is not None: + result = await environment._collect_streamed_output( + process, + timeout_sec=timeout_sec, + stdin_data=stdin_data, + on_output=on_output, + ) + else: + result = await environment._collect_buffered_output( + process, timeout_sec=timeout_sec, stdin_data=stdin_data + ) + if check and result.return_code != 0: + raise RuntimeError("Harbor Compose command failed") + return result + except BaseException as exc: + # Finish spawning before cleanup, even if cancellation raced with exec. + process = await spawn + try: + os.killpg(process.pid, signal.SIGKILL) + except ProcessLookupError: + pass + await process.wait() + if isinstance(exc, asyncio.CancelledError) and command[0] in { + "build", + "pull", + "up", + }: + cancelled.append( + { + "command": command[0], + "project": environment.session_id, + "client_group_killed": True, + "client_reaped": True, + "daemon_completion_verified": False, + } + ) + raise + + +def _read_output(path, root): + relative = path.relative_to(root) + current = root + for part in relative.parts: + current = current / part + if current.is_symlink(): + raise NativeEvidenceError("native output may not contain symbolic links") + try: + fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK) + except FileNotFoundError: + return None + with os.fdopen(fd, "rb") as stream: + info = os.fstat(stream.fileno()) + if not stat.S_ISREG(info.st_mode) or info.st_size > _MAX_REWARD_BYTES: + raise NativeEvidenceError( + "native reward output must be a bounded regular file" + ) + raw = stream.read(_MAX_REWARD_BYTES + 1) + if len(raw) > _MAX_REWARD_BYTES: + raise NativeEvidenceError("native reward output exceeded its size bound") + return raw + + +def _reward(raw_files, parsed, contract): + if "reward.json" in raw_files: + raw = json.loads( + raw_files["reward.json"], + object_pairs_hook=_unique_object, + parse_float=Decimal, + ) + elif "reward.txt" in raw_files: + raw = {"reward": Decimal(raw_files["reward.txt"].decode().strip())} + else: + raise NativeEvidenceError("verifier produced no raw reward file") + if not isinstance(raw, dict) or not raw or contract.reward_key not in raw: + raise NativeEvidenceError( + "verifier reward map is empty or lacks the declared key" + ) + low, high = (Decimal(str(value)) for value in contract.reward.range) + for value in raw.values(): + if ( + isinstance(value, bool) + or not isinstance(value, (int, Decimal)) + or not Decimal(value).is_finite() + or not low <= value <= high + ): + raise NativeEvidenceError( + "every reward must be finite, nonboolean and within the declared range" + ) + if ( + not isinstance(parsed, dict) + or any(isinstance(value, bool) for value in parsed.values()) + or raw != {key: Decimal(str(value)) for key, value in parsed.items()} + ): + raise NativeEvidenceError("raw verifier rewards differ from the Harbor result") + return raw + + +async def _trial( + root, + role, + agent, + work, + contract, + inspector, + run_id, + source_binding, + expected=None, + canary=None, +): + from harbor.models.environment_type import EnvironmentType + from harbor.models.trial.config import ( + AgentConfig, + EnvironmentConfig, + TaskConfig, + TrialConfig, + VerifierConfig, + ) + from harbor.trial.hooks import TrialEvent + + from .providers.docker import DockerValidationProvider + from .runner import _DIGEST_EXCLUDED_DIRS, source_digest + + name = f"openenv-validation-{run_id}-{role}" + project = name + "__env" + retained_tag = f"openenv-validation:{run_id}" + record = { + "role": role, + "agent": agent, + "project": project, + "raw_rewards": {}, + "cleanup": {"verified": False}, + } + raw_files = {} + trial = None + phase = "trial creation" + registered = False + hf = isinstance(inspector, HFJobsInspector) + try: + # Verify ownership before Trial.create can allocate anything. + record["pre_allocation_inventory"] = await asyncio.to_thread( + inspector.inventory, project + ) + if any(record["pre_allocation_inventory"].values()): + raise NativeEvidenceError( + "run-owned project was not empty before allocation" + ) + registered = True + task_copy = work / role / "task" + shutil.copytree( + root, + task_copy, + symlinks=True, + ignore=shutil.ignore_patterns(*_DIGEST_EXCLUDED_DIRS), + ) + copied_digest = source_digest(task_copy) + record["unmodified_task_digest"] = copied_digest + if copied_digest != source_binding: + raise NativeEvidenceError( + "private execution task differs from the validated source digest" + ) + overlay = {} + if expected: + task = read_harbor_task(task_copy) + task.config.environment.docker_image = retained_tag + (task_copy / "task.toml").write_text(task.config.model_dump_toml()) + overlay["environment.docker_image"] = retained_tag + if canary is not None: + # The oracle agent runs the canary in place of the reference solution. + script = (task_copy / canary).read_bytes() + (task_copy / "solution/solve.sh").write_bytes(script) + overlay["solution/solve.sh"] = { + "canary": canary, + "sha256": hashlib.sha256(script).hexdigest(), + } + digest_before = source_digest(task_copy) + record["execution_task_digest"] = digest_before + record["task_overlay"] = overlay + budget = contract.resources.episode_timeout_s + build_budget = ( + DockerValidationProvider().build_timeout_s if not expected else budget + ) + config = TrialConfig( + task=TaskConfig(path=task_copy.resolve()), + agent=AgentConfig( + name=agent, + override_timeout_sec=budget, + override_setup_timeout_sec=budget, + ), + environment=EnvironmentConfig( + type=EnvironmentType.HF_SANDBOX, + delete=True, + kwargs={ + "flavor": inspector.flavor, + "namespace": inspector.namespace, + # Idle shutdown must outlast the longest single command. + "job_timeout": math.ceil(budget) + 600, + }, + ) + if hf + else EnvironmentConfig( + type=EnvironmentType.DOCKER, + delete=False, + force_build=False, + override_cpus=contract.resources.cpu, + override_memory_mb=contract.resources.memory_mb, + override_storage_mb=contract.resources.disk_mb, + kwargs={"auto_mounting": False, "keep_containers": True}, + ), + verifier=VerifierConfig(override_timeout_sec=budget), + trial_name=name, + trials_dir=(work / role / "trials").resolve(), + ) + effective_config = config.model_dump(mode="json") + effective_config["task"]["path"] = "" + effective_config["trials_dir"] = "" + effective_config.pop("trial_name") + record["trial_config_digest"] = _digest(effective_config) + record["resources"] = contract.resources.model_dump() + trial = await _create_trial( + config, + register_job=partial(inspector.register_job, project) if hf else None, + ) + record["harbor_build_timeout_s"] = trial._environment_build_timeout_sec + trial._environment_build_timeout_sec = build_budget + if not expected: + record["build_timeout_s"] = build_budget + start_environment = trial.agent_environment.start + + async def build_and_start(*, force_build): + nonlocal phase + try: + async with asyncio.timeout(build_budget): + await start_environment(force_build=force_build) + finally: + if hf: + sandbox = trial.agent_environment._sandbox + record["job_handle_missing_after_start"] = sandbox is None + if sandbox is not None: + inspector.register_job(project, sandbox.id) + phase = "agent setup" + + trial.agent_environment.start = build_and_start + + async def environment_start(_event): + nonlocal phase + phase = "environment build/start" + + async def capture(_event): + nonlocal phase + phase = "agent" + if trial.agent_environment.session_id != project: + raise NativeEvidenceError( + "Harbor sandbox identity differs from the registered project" + ) + identity = await asyncio.to_thread( + inspector.capture, project, retained_tag, retain=not expected + ) + record.update(identity) + if expected and ( + identity["image_ref"] != expected["image_ref"] + or identity["configuration_digest"] != expected["configuration_digest"] + ): + raise NativeEvidenceError( + "fresh native trial image or effective container configuration drifted" + ) + + async def capture_exit(_event): + # Harbor writes the marker only for a nonzero exit. Later sandbox + # log synchronization can overwrite it, so this reading is trusted. + if agent == "oracle": + marker = _read_output( + trial.paths.agent_dir / "exit-code.txt", trial.paths.trial_dir + ) + record["oracle_exit_observed_at_agent_end"] = True + record["oracle_exit_code"] = int(marker) if marker is not None else 0 + if marker is not None: + raw_files["oracle-exit-code.txt"] = marker + + async def verification_start(_event): + nonlocal phase + phase = "verifier" + + trial.add_hook(TrialEvent.ENVIRONMENT_START, environment_start) + trial.add_hook(TrialEvent.AGENT_START, capture) + trial.add_hook(TrialEvent.AGENT_END, capture_exit) + trial.add_hook(TrialEvent.VERIFICATION_START, verification_start) + result = await trial.run() + if source_digest(task_copy) != digest_before: + raise NativeEvidenceError( + "private execution task changed during validation" + ) + if result.exception_info is not None: + failure = result.exception_info.exception_type + if failure in { + "RewardFileNotFoundError", + "RewardFileEmptyError", + "VerifierOutputParseError", + }: + if "container_id" not in record: + raise NativeEvidenceError( + "Harbor reward failure has no container identity" + ) + record["reward_error"] = True + raise NativeEvidenceError(f"Harbor verifier reward failed ({failure})") + if failure == "EnvironmentStartTimeoutError": + raise NativeEvidenceError( + f"validator build/start exceeded its {build_budget:g}-second budget" + ) + subject_phase = { + "SandboxBuildFailedError": "environment build/start", + "AgentSetupTimeoutError": "agent setup", + "AgentTimeoutError": "agent", + "VerifierTimeoutError": "verifier", + }.get(failure) + if failure == "RuntimeError" and phase == "environment build/start": + subject_phase = phase + if subject_phase: + record["subject_error"] = subject_phase + raise NativeEvidenceError( + f"Harbor subject failed during {subject_phase} ({failure})" + ) + raise NativeEvidenceError("Harbor Trial returned exception_info") + if "container_id" not in record: + raise NativeEvidenceError("Harbor Trial has no actual AGENT_START identity") + for filename, path in ( + ("reward.json", trial.paths.reward_json_path), + ("reward.txt", trial.paths.reward_text_path), + ): + raw = _read_output(path, trial.paths.trial_dir) + if raw is not None: + raw_files[filename] = raw + if agent == "oracle": + if not record.get("oracle_exit_observed_at_agent_end"): + raise NativeEvidenceError( + "oracle has no trusted AGENT_END exit observation" + ) + marker = _read_output( + trial.paths.agent_dir / "exit-code.txt", trial.paths.trial_dir + ) + if marker is not None and int(marker) != record["oracle_exit_code"]: + raise NativeEvidenceError("oracle exit marker changed after AGENT_END") + parsed = result.verifier_result.rewards if result.verifier_result else None + record["reward_error"] = True + record["rewards"] = _reward(raw_files, parsed, contract) + record.pop("reward_error") + except (Exception, KeyboardInterrupt) as exc: + record["failure"] = type(exc).__name__ + if isinstance(exc, TimeoutError): + record["reason"] = ( + f"validator build/start exceeded its {build_budget:g}-second budget" + if phase == "environment build/start" + else f"unexpected Harbor timeout during {phase}" + ) + # Error categories are safe; task-authored exception messages/logs are not. + if isinstance(exc, NativeEvidenceError): + record["reason"] = str(exc) + finally: + if trial is not None: + try: + async with asyncio.timeout(30): + await trial.agent_environment.stop(delete=hf) + except (Exception, KeyboardInterrupt): + record["failure"] = "HarborTeardownError" + if registered: + try: + record["cleanup"] = await asyncio.to_thread(inspector.cleanup, project) + if ( + hf + and record.get("job_handle_missing_after_start") + and not record["cleanup"]["jobs"] + ): + # Sandbox.create can fail after allocation and swallow a failed + # cancellation. An empty listing cannot prove no job was created. + record["cleanup"].update( + verified=False, + reason="sandbox creation returned no handle and no labelled job was recovered", + ) + if trial is not None and trial._openenv_cancelled_compose: + record["cleanup"].update( + { + "verified": False, + "pending_operations": trial._openenv_cancelled_compose, + } + ) + record["reason"] = ( + "Docker daemon completion after cancelled Compose allocation is unverified" + ) + if not record["cleanup"]["verified"]: + record["failure"] = "CleanupNotVerified" + except (Exception, KeyboardInterrupt) as exc: + record["cleanup"] = {"verified": False, "failure": type(exc).__name__} + record["failure"] = "CleanupNotVerified" + else: + record["cleanup"] = { + "verified": False, + "reason": "project ownership was not verified before allocation", + } + if trial is not None: + # Preserve raw verifier files even when Harbor rejects their values. + for filename, path in ( + ("reward.json", trial.paths.reward_json_path), + ("reward.txt", trial.paths.reward_text_path), + ("oracle-exit-code.txt", trial.paths.agent_dir / "exit-code.txt"), + ): + try: + raw = _read_output(path, trial.paths.trial_dir) + if raw is not None: + if filename in raw_files and raw_files[filename] != raw: + record["failure"] = "RewardArtifactDrift" + if filename == "oracle-exit-code.txt" and filename in raw_files: + continue + raw_files[filename] = raw + except (ValueError, OSError): + record["failure"] = "UnsafeRewardArtifact" + return record, raw_files + + +async def _collect(root, contract, work, inspector, source_binding, canaries=()): + run_id = uuid.uuid4().hex + # The replay makes episode determinism measurable before any semantic check. + plan = [ + ("nop", "nop", None), + ("oracle", "oracle", None), + ("oracle-replay", "oracle", None), + *( + (f"canary-{index}", "oracle", canary) + for index, canary in enumerate(canaries, start=1) + ), + ] + if isinstance(inspector, HFJobsInspector): + # Each running trial blocks a worker thread for every sandbox command, and + # a trial waiting for a free thread would spend its own phase budget. + asyncio.get_running_loop().set_default_executor( + ThreadPoolExecutor(max_workers=len(plan) + 4) + ) + host = await asyncio.to_thread(inspector.preflight) + run_trial = partial( + _trial, + root, + work=work, + contract=contract, + inspector=inspector, + run_id=run_id, + source_binding=source_binding, + ) + if isinstance(inspector, HFJobsInspector): + # A pinned image needs no build, so every trial starts at once. + outcomes = await asyncio.gather( + *(run_trial(role, agent, canary=canary) for role, agent, canary in plan) + ) + else: + outcomes = [] + for role, agent, canary in plan: + expected = outcomes[0][0] if outcomes else None + outcomes.append( + await run_trial(role, agent, expected=expected, canary=canary) + ) + if "failure" in outcomes[-1][0]: + break + trials, files = [], {} + for trial, raw in outcomes: + trials.append(trial) + for name, value in raw.items(): + relative = f"harbor-trials/{trial['role']}/{name}" + files[relative] = value + trial["raw_rewards"][name] = { + "path": relative, + "sha256": hashlib.sha256(value).hexdigest(), + } + if trials and "image_ref" in trials[0]: + try: + if not inspector.verify_image( + f"openenv-validation:{run_id}", trials[0]["image_ref"] + ): + trials[-1]["failure"] = "RetainedImageDrift" + except Exception: + trials[-1]["failure"] = "RetainedImageUnverified" + return host, trials, files + + +def _result(check_id, status, reason, measured=None): + return CheckResult( + check_id=check_id, + status=status, + evidence=[reason], + measured=measured or {}, + duration_s=0, + ) + + +def _reward_only(trial): + # `reward_error` marks a failure raised while parsing the verifier's reward: + # the package's defect, unless teardown or cleanup later found a host problem. + return trial.get("reward_error") and trial.get("failure") not in _HOST_FAILURES + + +def _skip_reason(entry, contract): + if entry.check_id not in _IMPLEMENTED: + if entry.level is Level.STATIC: + return "grader not implemented in this build" + return f"not implemented for the harbor_task binding ({HARBOR_PROFILE})" + if entry.check_id == "semantic.canary_floor" and contract.canaries is None: + return "no canaries declared in validation/openenv.json" + return "unmet dependency: native Harbor trials" + + +def validate_harbor( + subject, + *, + max_level, + policy, + results, + digest_before, + artifacts_dir, + report_target=None, + skip_build=False, + provider=None, + sandbox="docker", + flavor="cpu-basic", + namespace=None, +): + """Run fresh native Harbor trials and grade them up to the requested level.""" + from .runner import source_digest + + started = time.monotonic() + contract = read_harbor_contract(subject.root) + semantic = max_level >= Level.SEMANTIC + canaries = ( + canary_scripts(subject.root, contract.canaries) + if semantic and contract.canaries is not None + else [] + ) + record = { + "schema_version": "2", + "profile": HARBOR_PROFILE, + "sandbox": sandbox, + "task_effective_digest": digest_before, + "original_source_digest": contract.original_source_digest, + "contract_digest": _digest(contract.model_dump(mode="json")), + "reward_key": contract.reward_key, + "cleanup": {"verified": False}, + "trials": [], + } + harbor_dist = distribution("harbor") + record["harbor"] = {"version": harbor_dist.version} + direct_url = harbor_dist.read_text("direct_url.json") + if direct_url: + installed = json.loads(direct_url) + record["harbor"]["commit_id"] = installed.get("vcs_info", {}).get("commit_id") + files = {} + inspector = DockerInspector() + try: + attempted = False + task = read_harbor_task(subject.root) + problem = _unsupported(task, contract, sandbox) + if sandbox == "hf-sandbox": + inspector = HFJobsInspector( + task.config.environment.docker_image, + flavor, + namespace, + contract.resources, + ) + if skip_build: + problem = "image build skipped by --skip-build" + if provider is not None: + problem = ( + "served-package providers, including --space; " + + "run Harbor trials on HF Jobs with --sandbox hf-sandbox" + ) + if any(result.status is not CheckStatus.PASS for result in results): + problem = "unmet dependency: static.manifest" + startup = _result( + "runtime.startup", + CheckStatus.SKIP, + f"unsupported by {HARBOR_PROFILE}: {problem}", + ) + reward_result = _result( + "runtime.reward_well_formed", + CheckStatus.SKIP, + "unmet dependency: native Harbor trials", + ) + determinism = _result( + "runtime.episode_determinism", + CheckStatus.SKIP, + "unmet dependency: native Harbor trials", + ) + evidence = None + checks = [] + semantic_graded = False + if ( + semantic + and subject.manifest.capabilities.oracle is None + and all(result.status is CheckStatus.PASS for result in results) + ): + # RFC 008: a missing oracle is a graded FAIL, never a SKIP. + semantic_graded = True + checks.append( + CheckResult( + check_id="semantic.oracle_max", + status=CheckStatus.FAIL, + evidence=["the task has no oracle (solution/solve.sh)"], + remediation=( + "Add solution/solve.sh that drives the task to a correct solution." + ), + duration_s=0, + ) + ) + if not problem: + if subject.manifest.capabilities.oracle is None: + startup = _result( + "runtime.startup", + CheckStatus.SKIP, + "native Harbor trials need solution/solve.sh", + ) + else: + attempted = True + try: + with tempfile.TemporaryDirectory( + prefix="openenv-harbor-validation-" + ) as temp: + host, trials, files = asyncio.run( + _collect( + subject.root, + contract, + Path(temp), + inspector, + digest_before, + canaries, + ) + ) + record["trials"] = trials + if sandbox == "hf-sandbox": + record["hf_jobs"] = host + record["limitations"] = [ + "The image is the digest requested from HF Jobs and read " + + "back from each job, not a digest measured at runtime.", + "HF Sandbox cannot turn the network off or switch users, " + + "so every phase runs with public networking as the " + + "image's default user.", + ] + else: + record["daemon"] = host + record["cleanup"] = { + "verified": bool(trials) + and all(trial["cleanup"]["verified"] for trial in trials) + } + broken = [ + trial + for trial in trials + if "failure" in trial and not _reward_only(trial) + ] + malformed = any(_reward_only(trial) for trial in trials) + containers = [trial.get("container_id") for trial in trials] + if ( + broken + or (not malformed and len(trials) != 3 + len(canaries)) + or len(set(containers)) != len(containers) + ): + subject_failures = broken and all( + trial.get("subject_error") + and trial["failure"] not in _HOST_FAILURES + for trial in broken + ) + startup = _result( + "runtime.startup", + CheckStatus.FAIL if subject_failures else CheckStatus.ERROR, + "native Harbor subject failed during " + + ", ".join( + sorted({trial["subject_error"] for trial in broken}) + ) + if subject_failures + else "native Harbor trial, binding or cleanup failed", + { + "failures": [ + trial.get("reason", trial.get("failure")) + for trial in broken + ] + }, + ) + startup.evidence.extend( + trial["reason"] for trial in broken if "reason" in trial + ) + if malformed: + reward_result = _result( + "runtime.reward_well_formed", + CheckStatus.FAIL, + "native verifier reward violates the explicit contract", + ) + else: + record["image_ref"] = trials[0]["image_ref"] + startup = _result( + "runtime.startup", + CheckStatus.PASS, + "fresh native Harbor trials ran from one immutable image " + "with verified cleanup", + { + "profile": HARBOR_PROFILE, + "image_ref": trials[0]["image_ref"], + "roles": [trial["role"] for trial in trials], + "task_effective_digest": digest_before, + }, + ) + source_image = task.config.environment.docker_image + if source_image is not None: + record["source_image"] = source_image + startup.measured["source_image"] = source_image + if sandbox == "hf-sandbox": + startup.measured.update( + sandbox=sandbox, + flavor=host["flavor"], + namespace=host["namespace"], + job_ids=containers, + ) + if malformed: + reward_result = _result( + "runtime.reward_well_formed", + CheckStatus.FAIL, + "native verifier reward violates the explicit contract", + ) + determinism = _result( + "runtime.episode_determinism", + CheckStatus.SKIP, + "unmet dependency: runtime.reward_well_formed", + ) + else: + reward_result = _result( + "runtime.reward_well_formed", + CheckStatus.PASS, + "every raw verifier reward map matches Harbor and " + "satisfies the declared key/range", + { + "profile": HARBOR_PROFILE, + "reward_key": contract.reward_key, + }, + ) + complete_baseline = ( + len(trials) >= 3 + and all( + "failure" not in trial and trial["cleanup"]["verified"] + for trial in trials[:3] + ) + and len(set(containers[:3])) == 3 + ) + if complete_baseline: + nop, oracle, replay, *canary_trials = trials + same = ( + oracle["rewards"] == replay["rewards"] + and oracle["oracle_exit_code"] == replay["oracle_exit_code"] + ) + determinism = _result( + "runtime.episode_determinism", + CheckStatus.PASS if same else CheckStatus.FAIL, + "the oracle replay in a fresh container " + + ( + "reproduced every reward and the exit code" + if same + else "produced different rewards or a different exit code" + ), + { + "rewards": [ + json.loads(dumps(trial["rewards"])) + for trial in (oracle, replay) + ], + "exit_codes": [ + trial["oracle_exit_code"] + for trial in (oracle, replay) + ], + }, + ) + key = contract.reward_key + record.update( + { + "floor_reward": nop["rewards"][key], + "oracle_reward": oracle["rewards"][key], + } + ) + evidence = OracleEvidence( + floor=Fraction(nop["rewards"][key]), + oracle=tuple( + Fraction(trial["rewards"][key]) + for trial in (oracle, replay) + ), + oracle_exit_codes=tuple( + trial["oracle_exit_code"] for trial in (oracle, replay) + ), + canaries=tuple( + ( + trial["task_overlay"]["solution/solve.sh"][ + "canary" + ], + Fraction(trial["rewards"][key]), + ) + for trial in canary_trials + if "failure" not in trial + and trial["cleanup"]["verified"] + ), + ) + except (Exception, KeyboardInterrupt) as exc: + record["failure"] = type(exc).__name__ + reason = f"native Harbor collection failed ({type(exc).__name__})" + if isinstance(exc, NativeEvidenceError): + record["reason"] = str(exc) + reason += ": " + str(exc) + startup = _result( + "runtime.startup", + CheckStatus.ERROR, + reason, + ) + if semantic: + registry = GraderRegistry() + for grader in ( + OracleMaxGrader(), + FloorGapGrader(), + CanaryFloorGrader(), + ): + registry.register(grader) + selected = registry.select(subject.manifest, max_level) + if evidence is not None and len(evidence.canaries) != len(canaries): + selected = [ + grader + for grader in selected + if grader.check_id != "semantic.canary_floor" + ] + checks.append( + _result( + "semantic.canary_floor", + CheckStatus.SKIP, + "unmet dependency: complete canary trials with verified cleanup", + ) + ) + checks.extend( + execute_graders( + selected, + replace(subject, oracle_evidence=evidence), + prior=[startup, reward_result, determinism], + ) + ) + try: + unchanged = source_digest(subject.root) == digest_before + except (ValueError, OSError): + unchanged = False + if not unchanged: + record["failure"] = "SourceDrift" + startup = _result( + "runtime.startup", + CheckStatus.ERROR, + "task source changed during native validation", + ) + reward_result, determinism, *checks = ( + _result( + check.check_id, + CheckStatus.SKIP, + "unmet dependency: unchanged native task source", + ) + for check in (reward_result, determinism, *checks) + ) + startup.duration_s = time.monotonic() - started + record["cleanup"].update( + {"required": attempted, "completed": record["cleanup"]["verified"]} + ) + results = [*results, startup, reward_result, determinism, *checks] + present = {result.check_id for result in results} + for entry in policy.entries_for_lane(Lane.LOCAL).values(): + if entry.level <= max_level and entry.check_id not in present: + results.append( + _result( + entry.check_id, + CheckStatus.SKIP, + _skip_reason(entry, contract), + ) + ) + if any( + check.status in {CheckStatus.FAIL, CheckStatus.ERROR} for check in results + ): + try: + inspector.remove_image() + except (Exception, KeyboardInterrupt) as exc: + startup.status = CheckStatus.ERROR + startup.evidence.append( + f"retained image removal failed ({type(exc).__name__})" + ) + record["cleanup"].update(verified=False, completed=False) + elif "image_ref" in record and sandbox == "docker": + tag = trials[0]["retained_image_tag"] + startup.measured["retained_image_tag"] = tag + record["retained_image_tag"] = tag + levels = [Level.STATIC] + if attempted: + levels.append(Level.RUNTIME) + if semantic and (attempted or semantic_graded): + levels.append(Level.SEMANTIC) + report = ValidationReportV2( + report_schema_version="2", + target=str(subject.root) if report_target is None else report_target, + source_digest=digest_before, + signature=subject.manifest.signature, + manifest=subject.manifest, + policy_version=policy.policy_version, + lane=Lane.LOCAL, + levels_run=levels, + results=results, + verdict=apply_policy(results, policy, Lane.LOCAL), + ) + if artifacts_dir is not None: + write_runtime_bundle( + artifacts_dir, + report, + cleanup=record["cleanup"], + provider={ + "binding": "harbor_task", + "profile": HARBOR_PROFILE, + "sandbox": sandbox, + }, + ) + files["harbor-evidence.json"] = (dumps(record) + "\n").encode() + checksums = (artifacts_dir / "SHA256SUMS").read_text() + for name, raw in sorted(files.items()): + path = artifacts_dir / name + path.parent.mkdir(parents=True, exist_ok=True) + path.write_bytes(raw) + path.chmod(0o600) + checksums += f"{hashlib.sha256(raw).hexdigest()} {name}\n" + (artifacts_dir / "SHA256SUMS").write_text(checksums) + return report + except BaseException as original: + try: + inspector.remove_image() + except (Exception, KeyboardInterrupt) as exc: + record["cleanup"].update( + verified=False, completed=False, failure=type(exc).__name__ + ) + original.add_note( + f"retained image removal failed ({type(exc).__name__}); cleanup incomplete" + ) + raise diff --git a/src/core/openenv/validation/manifest.py b/src/core/openenv/validation/manifest.py index a4623da3b65c840540053d46ba6635c8abd0c1bb..f54c7546240ca47c24057a291340936499b7aaf8 100644 --- a/src/core/openenv/validation/manifest.py +++ b/src/core/openenv/validation/manifest.py @@ -9,7 +9,14 @@ import math from pathlib import PurePosixPath from typing import Annotated, Any, Literal -from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator +from pydantic import ( + BaseModel, + ConfigDict, + Field, + field_validator, + model_serializer, + model_validator, +) from .types import SignatureKind @@ -47,9 +54,13 @@ class RewardDeclaration(BaseModel): range (`tuple[float, float]`): Declared reward range, defaults to `(0.0, 1.0)`. Must be strictly increasing. oracle_tolerance (`float`): - The oracle check passes when `reward(oracle) >= max - oracle_tolerance`. + Fraction of the declared range allowed below the maximum. + The oracle check requires `reward(oracle) >= max - oracle_tolerance * width`, + where `width = max - min`. floor_margin (`float`): - The gap check requires `max - measured_floor >= floor_margin`. + Fraction of the declared range required below the maximum and every oracle. + Both `max - measured_floor` and `reward(oracle) - measured_floor` must be + at least `floor_margin * width`. variance_tolerance (`float`, *optional*): Required iff the environment declares `llm_judged`; bounds reward variance for variance-mode determinism checks. @@ -241,6 +252,14 @@ class CapabilitiesSpec(BaseModel): declared_tools: list[str] = Field(default_factory=list) declared_task_count: dict[str, int] = Field(default_factory=dict) + @model_serializer(mode="wrap") + def _preserve_declaration_presence(self, serialize): + data = serialize(self) + for field in ("declared_tools", "declared_task_count"): + if field not in self.model_fields_set: + data.pop(field, None) + return data + @model_validator(mode="after") def _injected_state_requires_set_state(self) -> "CapabilitiesSpec": if ( @@ -365,6 +384,18 @@ class ExecutionDeclaration(BaseModel): return value +class HarborExecutionDeclaration(BaseModel): + """Native process execution of a Harbor task through fresh Docker trials.""" + + model_config = ConfigDict(extra="forbid", frozen=True) + + kind: Literal["harbor_task"] + agent_boundary: Literal["process"] = "process" + profile: Literal["harbor-semantic-v1"] = "harbor-semantic-v1" + contract_path: Literal["validation/openenv.json"] = "validation/openenv.json" + requires_credentials: bool = Field(default=False, strict=True) + + class NormalizedManifestV2(NormalizedManifest): """ Version 2 adds the runtime execution declaration without changing schema 1. @@ -375,7 +406,7 @@ class NormalizedManifestV2(NormalizedManifest): """ manifest_schema_version: Literal["2"] - execution: ExecutionDeclaration + execution: ExecutionDeclaration | HarborExecutionDeclaration @model_validator(mode="after") def _finite_declarations(self) -> "NormalizedManifestV2": diff --git a/src/core/openenv/validation/parsers/harbor_toml.py b/src/core/openenv/validation/parsers/harbor_toml.py new file mode 100644 index 0000000000000000000000000000000000000000..39bce5d73f3c5570b20af50caecf65ea54819b36 --- /dev/null +++ b/src/core/openenv/validation/parsers/harbor_toml.py @@ -0,0 +1,226 @@ +"""Pure Harbor task parsing and the explicit, operator-supplied semantic contract.""" + +import json +import math +import stat +from decimal import Decimal +from importlib.metadata import PackageNotFoundError, version +from pathlib import Path, PurePosixPath +from typing import Literal + +from pydantic import BaseModel, ConfigDict, Field, field_validator, ValidationError + +from ..manifest import ( + ManifestError, + NormalizedManifestV2, + ResourceDeclaration, + RewardDeclaration, + TypeSpec, +) +from ..types import SignatureKind + +HARBOR_PROFILE = "harbor-semantic-v1" +MAX_CANARIES = 8 + + +class HarborContract(BaseModel): + """Trusted declarations absent from Harbor's task format; never inferred.""" + + model_config = ConfigDict(extra="forbid") + + profile: Literal["harbor-semantic-v1"] + reward_key: str = Field(min_length=1) + reward: RewardDeclaration + resources: ResourceDeclaration + types: TypeSpec + original_source_digest: str | None = Field(default=None, pattern="^[0-9a-f]{64}$") + requires_credentials: bool = Field(default=False, strict=True) + # Directory of known-wrong `solve.sh` replacements for `semantic.canary_floor`. + canaries: str | None = None + + @field_validator("canaries") + @classmethod + def _package_relative(cls, value): + path = PurePosixPath(value) + if ( + "\\" in value + or ":" in value + or "\x00" in value + or path.is_absolute() + or ".." in path.parts + or path == PurePosixPath(".") + ): + raise ValueError("canaries must be a portable package-relative directory") + return value + + +def _unique_object(pairs): + result = {} + for key, value in pairs: + if key in result: + raise ValueError("duplicate JSON object key") + result[key] = value + return result + + +def read_harbor_contract(package_root: Path) -> HarborContract: + """Read `validation/openenv.json` without importing or executing task code.""" + try: + raw = json.loads( + (package_root / "validation/openenv.json").read_text(), + object_pairs_hook=_unique_object, + parse_float=Decimal, + ) + if not isinstance(raw, dict): + raise ValueError("contract must be an object") + if ( + not {"range", "oracle_tolerance", "floor_margin"} + <= raw.get("reward", {}).keys() + ): + raise ValueError( + "reward range, oracle_tolerance and floor_margin must be explicit" + ) + for section, fields in ( + ("reward", RewardDeclaration.model_fields), + ("resources", ("cpu", "memory_mb", "disk_mb", "episode_timeout_s", "gpus")), + ): + pending = [raw.get(section, {}).get(field) for field in fields] + while pending: + item = pending.pop() + if isinstance(item, dict): + pending.extend(item.values()) + elif isinstance(item, list): + pending.extend(item) + elif isinstance(item, (bool, str)) or ( + isinstance(item, float) and not math.isfinite(item) + ): + raise ValueError( + "numeric declarations must be finite, nonboolean JSON numbers" + ) + # Graders compare against the stored float, so it must keep the + # declared value exactly: 0.100000000000000001 would become 0.1. + elif isinstance(item, (int, Decimal)) and Decimal( + repr(float(item)) + ) != Decimal(item): + raise ValueError( + "numeric declarations must keep their exact value as floats" + ) + return HarborContract.model_validate(raw) + except ( + OSError, + ValueError, + TypeError, + AttributeError, + OverflowError, + RecursionError, + ) as exc: + raise ManifestError( + [f"invalid trusted Harbor contract ({type(exc).__name__})"], + remediation="supply explicit reward/resources in validation/openenv.json", + ) from exc + + +def canary_scripts(package_root: Path, directory: str) -> list[str]: + """ + List the declared canary scripts without reading or running them. + + Args: + package_root (`Path`): + The task directory. + directory (`str`): + Package-relative directory holding one `*.sh` file per canary. + + Returns: + `list[str]`: package-relative script paths, sorted by name. + """ + root = package_root / directory + if root.is_symlink() or not root.is_dir(): + raise ValueError("the canaries directory does not exist") + scripts = [] + for path in sorted(root.iterdir()): + info = path.lstat() + if path.suffix != ".sh" or not stat.S_ISREG(info.st_mode): + raise ValueError("the canaries directory may hold only regular *.sh files") + scripts.append((PurePosixPath(directory) / path.name).as_posix()) + if not 1 <= len(scripts) <= MAX_CANARIES: + raise ValueError(f"declare between 1 and {MAX_CANARIES} canaries") + return scripts + + +def read_harbor_task(package_root: Path): + """Use the pinned Harbor data loader; constructing a Trial is runtime-only.""" + try: + installed = version("harbor") + except PackageNotFoundError as exc: + raise RuntimeError( + "Harbor task validation requires harbor==0.25.0; Harbor is not installed" + ) from exc + if installed != "0.25.0": + raise RuntimeError( + f"Harbor task validation requires harbor==0.25.0; installed {installed}" + ) + try: + from harbor.models.task.task import Task + + return Task(package_root) + except ( + ImportError, + OSError, + ValueError, + RuntimeError, + ) as exc: + raise ManifestError( + [f"invalid Harbor 0.25.0 task ({type(exc).__name__})"], + remediation="install Harbor 0.25.0 and supply a valid task.toml/task layout", + ) from exc + + +class HarborTaskParser: + """Normalize declarations only; no environment, Trial, build or subprocess.""" + + signature = SignatureKind.HARBOR_TASK + + def parse(self, package_root: Path) -> NormalizedManifestV2: + contract = read_harbor_contract(package_root) + task = read_harbor_task(package_root) + if contract.canaries is not None: + try: + canary_scripts(package_root, contract.canaries) + except (OSError, ValueError) as exc: + raise ManifestError( + [f"invalid canaries declaration ({exc})"], + remediation="declare a directory of 1 to 8 *.sh canary scripts", + ) from exc + oracle = ( + {"form": "script", "location": "solution/solve.sh"} + if (package_root / "solution/solve.sh").is_file() + else None + ) + try: + return NormalizedManifestV2.model_validate( + { + "manifest_schema_version": "2", + "signature": self.signature, + "name": task.name, + "version": task.config.task.version if task.config.task else None, + "reward": contract.reward.model_dump(), + "resources": contract.resources.model_dump(), + "types": contract.types.model_dump(), + "network": {"mode": task.config.environment.network_mode.value}, + "capabilities": { + "verifier": {"kind": "script", "entry": "tests/test.sh"}, + "oracle": oracle, + "canaries": contract.canaries, + }, + "execution": { + "kind": "harbor_task", + "agent_boundary": "process", + "profile": contract.profile, + "requires_credentials": contract.requires_credentials, + }, + } + ) + except ValidationError as exc: + raise ManifestError( + ["Harbor declarations do not match the manifest schema"] + ) from exc diff --git a/src/core/openenv/validation/parsers/openenv_yaml.py b/src/core/openenv/validation/parsers/openenv_yaml.py index 6d82d3cacc9287a94966c1e7e1409cc34f56b7e1..90722125c18552437e006a1033af6698e7081321 100644 --- a/src/core/openenv/validation/parsers/openenv_yaml.py +++ b/src/core/openenv/validation/parsers/openenv_yaml.py @@ -5,7 +5,12 @@ from pathlib import Path import yaml from pydantic import ValidationError -from ..manifest import ManifestError, NormalizedManifest, NormalizedManifestV2 +from ..manifest import ( + ExecutionDeclaration, + ManifestError, + NormalizedManifest, + NormalizedManifestV2, +) from ..types import SignatureKind VALIDATION_BLOCK_REMEDIATION = ( @@ -89,7 +94,15 @@ class OpenEnvYamlParser: data[key] = value if has_execution: - data["execution"] = validation["execution"] + try: + data["execution"] = ExecutionDeclaration.model_validate( + validation["execution"] + ) + except ValidationError as exc: + raise ManifestError( + [f"execution: {error}" for error in _format_validation_error(exc)], + remediation=SCHEMA_REMEDIATION, + ) from exc try: model = NormalizedManifestV2 if has_execution else NormalizedManifest diff --git a/src/core/openenv/validation/providers/__init__.py b/src/core/openenv/validation/providers/__init__.py index b81f382e76fb58e73d3978fee5aed1d6778cc739..66fccb5e57b116c9b96ef890c174b66e61c7e55a 100644 --- a/src/core/openenv/validation/providers/__init__.py +++ b/src/core/openenv/validation/providers/__init__.py @@ -25,6 +25,10 @@ class ProviderError(RuntimeError): """A bounded, sanitized provider operation failed.""" +class CleanupError(ProviderError): + """Run-owned resources remain or their removal could not be verified.""" + + class StartupError(ProviderError): """A subject did not become healthy within its startup deadline.""" diff --git a/src/core/openenv/validation/providers/_netns.py b/src/core/openenv/validation/providers/_netns.py index dc5e0312d8ab50abec6837e1cb160b7a85de1526..6bcde3e8695ca182e4533ec5a07ce25125248e0d 100644 --- a/src/core/openenv/validation/providers/_netns.py +++ b/src/core/openenv/validation/providers/_netns.py @@ -83,6 +83,13 @@ def icmp(): deadline = time.monotonic() + wait while time.monotonic() < deadline and outcome(tcp)["result"] != "reachable": time.sleep(0.2) +def up(name): + # Kernels add down fallback tunnels (gre0, sit0, ...) to every namespace, and + # /sys/class/net can hold regular files such as bonding_masters. Only up links + # carry traffic. Any other read error leaves link state unknown and fails the probe. + try: + with open(f"/sys/class/net/{{name}}/flags") as f: return int(f.read(), 16) & 1 + except NotADirectoryError: return False def lines(path): try: with open(path) as f: return f.read().splitlines() @@ -94,7 +101,7 @@ listening = sorted({{int(f[1].split(":")[1], 16) if len(f) > 3 and f[3] == "0A"}}) print(json.dumps({{ "namespace": {{ - "interfaces": sorted(os.listdir("/sys/class/net")), + "interfaces": sorted(n for n in os.listdir("/sys/class/net") if up(n)), "default_route": any(len(r) > 1 and r[1] == "00000000" for r in routes), "ipv6_non_loopback": sum(1 for f in v6 if f and f[-1] != "lo"), "listening_ports": listening, diff --git a/src/core/openenv/validation/providers/_pidns.py b/src/core/openenv/validation/providers/_pidns.py new file mode 100644 index 0000000000000000000000000000000000000000..a8a4a753efc029b9af73ed9fb3af830cd90ff6f4 --- /dev/null +++ b/src/core/openenv/validation/providers/_pidns.py @@ -0,0 +1,320 @@ +"""Trusted PID-namespace probe for the Docker-local provider. + +The probe runs from the validator's own digest-pinned image and joins only the +subject's PID namespace, so it never executes code from the subject's image. It reads +each subject process from `/proc` and reaches the subject's mount namespace through +`/proc/1/root`, as the subject's own user. +""" + +# Measures process identity, the mount table and writable mounts. argv: allotted roots. +PROBE_SCRIPT = """ +import errno, json, os, re, stat, sys, uuid +me = os.getpid() +allotted = sys.argv[1:] +processes = [] +for entry in sorted(os.listdir("/proc"), key=lambda e: (len(e), e)): + if not entry.isdigit() or int(entry) == me: + continue + try: + with open(f"/proc/{entry}/status") as f: + status = dict(l.rstrip("\\n").split(":", 1) for l in f if ":" in l) + except OSError: + continue + processes.append({ + "pid": int(entry), + "name": status["Name"].strip()[:64], + "uids": [int(u) for u in status["Uid"].split()], + "cap_eff": int(status["CapEff"], 16), + "no_new_privs": status.get("NoNewPrivs", "0").strip() == "1", + "seccomp": int(status.get("Seccomp", "0")), + }) +root = "/proc/1/root" +def size(path): + try: + info = os.statvfs(root + path) + except OSError: + return None + return info.f_blocks * info.f_frsize or None +try: + mounts = [] + with open("/proc/1/mountinfo") as f: + for line in f: + fields = line.split() + separator = fields.index("-") + mount_point = re.sub(r"\\\\([0-7]{3})", lambda m: chr(int(m[1], 8)), fields[4]) + mounts.append({ + "mount_point": mount_point, + "fstype": fields[separator + 1], + "device": fields[2], + # Writes need both the mount and its filesystem to be read-write. + "read_only": "ro" in fields[5].split(",") + fields[separator + 3].split(","), + "size_bytes": size(mount_point), + }) +except (OSError, ValueError, IndexError): + # A partial table could omit a writable filesystem. + mounts = [] +def writable(path): + target = os.path.join(root + path, ".openenv-containment-" + uuid.uuid4().hex) + try: + fd = os.open(target, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o600) + except OSError: + return False + os.close(fd) + os.unlink(target) + return True +# Every writable filesystem is a mount, so try each one outside the allotted roots. +candidates = { + m["mount_point"] for m in mounts if not m["read_only"] and m["mount_point"] not in allotted +} +writable_paths = {p for p in candidates if writable(p)} +# Only /dev's otherwise exempt tmpfs needs a subtree inventory. Separate mounts +# (including allotted /dev/shm), symlinks and device nodes are never traversed. +devices = {m["device"] for m in mounts if (m["mount_point"], m["fstype"]) == ("/dev", "tmpfs")} +device_storage = {d: {"complete": True, "writable": False} for d in devices} +boundaries = {m["mount_point"] for m in mounts} +remaining = 1024 +def scan(path, device, parent_fd, depth=0): + global remaining + reading = device_storage[device] + if depth and path in boundaries: + return + remaining -= 1 + if remaining < 0 or depth > 32: + reading["complete"] = False + return + target = path.rsplit("/", 1)[-1] + try: + info = os.stat(target, dir_fd=parent_fd, follow_symlinks=False) + directory = stat.S_ISDIR(info.st_mode) + if depth == 0 and stat.S_ISLNK(info.st_mode): + reading["complete"] = False + return + if not directory and not stat.S_ISREG(info.st_mode): + return + if directory and any(path == p or path.startswith(p + "/") for p in ("/proc", "/sys")): + reading["complete"] = False + return + if f"{os.major(info.st_dev)}:{os.minor(info.st_dev)}" != device: + reading["complete"] = False + return + # An owner can restore write permission without changing the launch. + flags = os.O_RDONLY | os.O_DIRECTORY if directory else os.O_WRONLY | os.O_APPEND | os.O_NONBLOCK + try: + fd = os.open(target, flags | os.O_NOFOLLOW, dir_fd=parent_fd) + except OSError as error: + if (directory or error.errno not in (errno.EACCES, errno.EPERM, errno.EROFS) + or (info.st_uid == os.geteuid() and error.errno in (errno.EACCES, errno.EPERM))): + reading["complete"] = False + return + try: + opened = os.fstat(fd) + if (opened.st_dev, opened.st_ino) != (info.st_dev, info.st_ino): + reading["complete"] = False + return + if directory: + name = ".openenv-containment-" + uuid.uuid4().hex + try: + probe = os.open(name, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o600, dir_fd=fd) + except OSError as error: + if (error.errno not in (errno.EACCES, errno.EPERM, errno.EROFS) + or (opened.st_uid == os.geteuid() and error.errno in (errno.EACCES, errno.EPERM))): + reading["complete"] = False + else: + reading["writable"] = True + writable_paths.add(path) + os.close(probe) + os.unlink(name, dir_fd=fd) + with os.scandir(fd) as entries: + for entry in entries: + if remaining <= 0: + reading["complete"] = False + break + scan(path + "/" + entry.name, device, fd, depth + 1) + else: + # Opening without truncation proves access without changing data. + reading["writable"] = True + writable_paths.add(path) + finally: + os.close(fd) + except OSError: + reading["complete"] = False +for mount in mounts: + if mount["device"] in devices and not mount["read_only"] and mount["mount_point"] not in allotted: + parent_fd = None + try: + parent_fd = os.open(root, os.O_RDONLY | os.O_DIRECTORY) + for part in mount["mount_point"].strip("/").split("/")[:-1]: + child_fd = os.open(part, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW, dir_fd=parent_fd) + os.close(parent_fd) + parent_fd = child_fd + scan(mount["mount_point"], mount["device"], parent_fd) + except OSError: + device_storage[mount["device"]]["complete"] = False + finally: + if parent_fd is not None: + os.close(parent_fd) +print(json.dumps({ + "processes": processes, + "mounts": mounts, + "allotted_writable": [a for a in allotted if writable(a)], + "writable": sorted(p for p in writable_paths if len(p) <= 1024)[:8], + "device_storage": device_storage, +})) +""" + +# Read limits independently: an unavailable file must not erase known violations. +LIMITS_SCRIPT = """ +import json +root = "/proc/1/root/sys/fs/cgroup/" +cgroup = {} +unavailable = [] +for filename, keys in [ + ("memory.max", ["memory_max"]), + ("memory.swap.max", ["swap_max"]), + ("cpu.max", ["cpu_quota", "cpu_period"]), + ("pids.max", ["pids_max"]), +]: + try: + with open(root + filename) as f: + values = f.read().split() + if len(values) != len(keys): + raise ValueError() + parsed = [None if value == "max" else int(value) for value in values] + if any(value is not None and value < 0 for value in parsed): + raise ValueError() + if "cpu_period" in keys and (parsed[1] is None or parsed[1] == 0): + raise ValueError() + except (OSError, ValueError): + parsed = [None] * len(keys) + unavailable.extend(keys) + cgroup.update(zip(keys, parsed)) +cgroup["unavailable"] = unavailable +print(json.dumps({"cgroup": cgroup})) +""" + +# Trusted pre/post stress evidence from the subject's cgroup and filesystem. +COUNTERS_SCRIPT = """ +import json, os, sys +root = "/proc/1/root" +result = {} +for filename, key, counter in [ + ("memory.events", "oom_kill", "oom_kill"), + ("pids.events", "pids_max", "max"), +]: + try: + with open(root + "/sys/fs/cgroup/" + filename) as f: + result[key] = int(dict(line.split() for line in f)[counter]) + except (OSError, ValueError, KeyError): + result[key] = None +result["free_bytes"] = {} +for path in sys.argv[1:]: + try: + info = os.statvfs(root + path) + result["free_bytes"][path] = info.f_bavail * info.f_frsize + except OSError: + result["free_bytes"][path] = None +print(json.dumps(result)) +""" + +# Observe a live fork from the nonce-correlated stimulus using the trusted image. +DESCENDANTS_SCRIPT = """ +import json, os, sys, time +proc = "/proc" +nonce, duration = sys.argv[1], float(sys.argv[2]) +expected = [b"exec_timeout", b"1", nonce.encode(), b"/tmp", b"/dev/shm"] +me = os.getpid() +def process(pid): + if pid == me: + return None + try: + with open(f"{proc}/{pid}/stat") as f: + before = f.read().rsplit(") ", 1)[1].split() + with open(f"{proc}/{pid}/cmdline", "rb") as f: + argv = f.read().rstrip(b"\\0").split(b"\\0") + with open(f"{proc}/{pid}/stat") as f: + after = f.read().rsplit(") ", 1)[1].split() + if (argv[-5:] != expected or before[0] in ("Z", "X") + or after[0] in ("Z", "X") or before[1] != after[1] + or before[19] != after[19]): + return None + return (pid, int(after[1]), int(after[19])) + except (OSError, ValueError, IndexError): + return None +witness = {} +deadline = time.monotonic() + duration +while time.monotonic() < deadline: + try: + entries = os.listdir(proc) + except OSError: + break + if len(entries) > 4096: + break + processes = {} + for entry in entries: + if entry.isdigit(): + reading = process(int(entry)) + if reading is not None: + processes[reading[0]] = reading + for child in processes.values(): + parent = processes.get(child[1]) + if (parent is not None and child[0] != parent[0] + and process(parent[0]) == parent and process(child[0]) == child): + witness = {"parent_pid": parent[0], "descendant_pid": child[0]} + break + if witness: + break + time.sleep(0.02) +print(json.dumps(witness), flush=True) +""" + +# Subject-image code is only a stimulus. Trusted counters corroborate its result. +QUALIFY_SCRIPT = """ +import errno, os, sys, time +kind, budget, nonce = sys.argv[1], int(sys.argv[2]), sys.argv[3] +print("openenv-probe-start:" + nonce, flush=True) +mib = 1 << 20 +if kind == "memory": + with open("/proc/self/oom_score_adj", "w") as f: + f.write("1000") + held = [] + while len(held) * 16 * mib < budget + 64 * mib: + held.append(b"\\x01" * (16 * mib)) + print("escaped", flush=True) +elif kind == "pids": + children = [] + try: + for _ in range(budget + 16): + pid = os.fork() + if pid == 0: + time.sleep(30) + os._exit(0) + children.append(pid) + print("escaped", flush=True) + except BlockingIOError: + print("contained", flush=True) + finally: + for pid in children: + os.kill(pid, 9) + os.waitpid(pid, 0) +elif kind == "disk": + written = 0 + for index, path in enumerate(sys.argv[4:]): + try: + with open(os.path.join(path, f"openenv-fill-{index}"), "wb") as f: + while written <= budget + 16 * mib: + f.write(b"\\x01" * mib) + f.flush() + written += mib + except OSError as exc: + if exc.errno not in (errno.ENOSPC, errno.EDQUOT): + print("inconclusive", flush=True) + sys.exit() + # Leave the files for trusted statvfs verification; this subject is disposable. + print("escaped" if written > budget else "contained", flush=True) +elif kind == "exec_timeout": + if os.fork() == 0: + time.sleep(300) + os._exit(0) + print("openenv-probe-descendant:" + nonce, flush=True) + time.sleep(300) +""" diff --git a/src/core/openenv/validation/providers/docker.py b/src/core/openenv/validation/providers/docker.py index e9fd81b8d1602b274a27ccd9979007e8dab7cfdb..2c51b587be12eaa0619318ffb3cc835e244f4e24 100644 --- a/src/core/openenv/validation/providers/docker.py +++ b/src/core/openenv/validation/providers/docker.py @@ -2,7 +2,8 @@ Public and no-network modes are enforced; allowlists are refused. No-network subjects are reached through a trusted helper sharing only their network namespace. Runtime -hardening is an execution baseline; it does not certify containment. +hardening is an execution baseline; `runtime.host_containment` judges its measured +effect. """ import json @@ -18,12 +19,24 @@ import time import urllib.error import urllib.request import uuid +from concurrent.futures import ThreadPoolExecutor from pathlib import Path from ..manifest import ExecutionDeclaration -from ..runtime.contracts import LaunchSpec, NetworkEvidence +from ..runtime.contracts import ( + ContainmentEvidence, + LaunchSpec, + NetworkEvidence, + ResourceEvidence, +) from ..types import ProviderCapability -from . import ExecResult, ProviderError, StartupError, UnsupportedCapability +from . import ( + CleanupError, + ExecResult, + ProviderError, + StartupError, + UnsupportedCapability, +) from ._netns import ( ExecRelayBridge, HARDENING, @@ -32,9 +45,18 @@ from ._netns import ( SINK_SCRIPT, WAIT_READY_SCRIPT, ) +from ._pidns import ( + COUNTERS_SCRIPT, + DESCENDANTS_SCRIPT, + LIMITS_SCRIPT, + PROBE_SCRIPT as PIDNS_PROBE_SCRIPT, + QUALIFY_SCRIPT, +) _LABEL = "org.openenv.validation.run" +# Writable roots granted to every subject; everything else is read-only. +_ALLOTTED = ("/tmp", "/dev/shm") _MAX_OUTPUT = 65536 _EXCLUDED = { ".git", @@ -76,6 +98,12 @@ def _safe_text(value: str, secrets: tuple[str, ...] = ()) -> str: ) +class _OperationTimeout(ProviderError): + def __init__(self, stdout: str): + super().__init__("Docker operation exceeded its deadline") + self.stdout = stdout + + def _command( argv: list[str], timeout_s: float, max_bytes: int = _MAX_OUTPUT ) -> tuple[int, str, str]: @@ -118,7 +146,9 @@ def _command( # The process group can exit between wait() and killpg(). pass process.wait() - raise ProviderError("Docker operation exceeded its deadline") from None + for thread in threads: + thread.join(timeout=1) + raise _OperationTimeout(buffers[0].decode("utf-8", "replace")) from None except BaseException: try: os.killpg(process.pid, signal.SIGKILL) @@ -250,7 +280,10 @@ class DockerValidationProvider: { ProviderCapability.IMAGE_BUILD, ProviderCapability.EXEC, + ProviderCapability.FRESH_CONTAINER, ProviderCapability.NETWORK_POLICY, + ProviderCapability.INSPECTED_ISOLATION, + ProviderCapability.RESOURCE_ENFORCEMENT, } ) supported_network_modes = frozenset({"public", "no-network"}) @@ -261,6 +294,7 @@ class DockerValidationProvider: build_timeout_s: float = 600, max_context_bytes: int = 2**30, helper_image: str = HELPER_IMAGE, + cleanup_subjects: list["DockerRunningSubject"] | None = None, ): if not math.isfinite(build_timeout_s) or build_timeout_s <= 0: raise ValueError("build_timeout_s must be positive and finite") @@ -271,6 +305,7 @@ class DockerValidationProvider: self.build_timeout_s = build_timeout_s self.max_context_bytes = max_context_bytes self.helper_image = helper_image + self._cleanup_subjects = cleanup_subjects def build(self, root: Path, execution: ExecutionDeclaration) -> str: deadline = time.monotonic() + self.build_timeout_s @@ -327,6 +362,8 @@ class DockerValidationProvider: _ensure_image(self.helper_image) name = f"openenv-validation-{spec.run_id}-{uuid.uuid4().hex[:12]}" subject = DockerRunningSubject(name, spec, helper_image=self.helper_image) + if self._cleanup_subjects is not None: + self._cleanup_subjects.append(subject) # tmpfs and /dev/shm share the declared aggregate writable-byte allowance. budget = spec.resources.disk_mb * 1024 * 1024 shm_bytes = min(64 * 1024 * 1024, budget // 2) @@ -342,6 +379,9 @@ class DockerValidationProvider: "--stop-timeout", "0", "--init", + # cgroup v1 daemons default to the host cgroup namespace. + "--cgroupns", + "private", "--user", "65532:65532", "--read-only", @@ -433,6 +473,10 @@ class DockerValidationProvider: try: subject.stop() except ProviderError as cleanup: + if self._cleanup_subjects is not None: + raise CleanupError( + "Disposable startup and teardown failed" + ) from cleanup raise StartupError( f"Startup failed; cleanup also failed: {cleanup}" ) from None @@ -450,12 +494,14 @@ class DockerRunningSubject: self.base_url = "" self._stopped = False self._secrets = tuple(spec.env_vars.values()) + self._spec = spec self._mode = spec.network.mode self._helper_image = helper_image self._helper: str | None = None self._bridge: ExecRelayBridge | None = None # Run-owned helper, sink and control containers, removed before the subject. self._auxiliary: list[str] = [] + self._disposables: list[DockerRunningSubject] = [] def _owned_create(self, name: str, argv: list[str], timeout_s: float) -> None: self._auxiliary.append(name) @@ -581,6 +627,338 @@ class DockerRunningSubject: self._remove_owned(sink) return evidence.model_dump(mode="json") + def _pidns_probe( + self, suffix: str, script: str, args: list[str], user: str, timeout_s: float + ) -> str: + """Run a validator-image probe joined only to the subject's PID namespace.""" + probe = f"{self.name}-{suffix}" + self._auxiliary.append(probe) + code, out, _ = _command( + [ + "docker", + "run", + "--rm", + "--name", + probe, + "--label", + f"{_LABEL}={self.run_id}", + "--pid", + f"container:{self.name}", + "--network", + "none", + *HARDENING, + # The last --user wins: probes act as the subject's own user. + "--user", + user, + self._helper_image, + "python3", + "-c", + script, + *args, + ], + timeout_s, + ) + if code: + raise ProviderError(f"The {suffix} probe failed") + return out + + def _measure_exec_timeout( + self, argv: list[str], nonce: str, user: str, timeout_s: float + ) -> dict: + """Witness the stimulus's fork before timing out and removing its container.""" + deadline = time.monotonic() + min(2.0, timeout_s) + witness = {} + with ThreadPoolExecutor(max_workers=1) as executor: + # The caller must latch the witness before removal can destroy /proc. + stimulus = executor.submit( + _command, + ["docker", "exec", "--", self.name, *argv], + deadline - time.monotonic(), + ) + try: + reading = json.loads( + self._pidns_probe( + "descendants", + DESCENDANTS_SCRIPT, + [nonce, "1"], + user, + deadline - time.monotonic(), + ) + ) + if not stimulus.done() and isinstance(reading, dict): + witness = reading + except CleanupError: + raise + except (ProviderError, ValueError): + # Witness collection is best effort; preserve timeout and cleanup. + pass + try: + stimulus.result() + except _OperationTimeout as exc: + try: + self.stop() + except ProviderError as cleanup: + raise CleanupError( + "Subject exec teardown failed: " + str(cleanup) + ) from exc + parent, child = witness.get("parent_pid"), witness.get("descendant_pid") + if ( + isinstance(parent, int) + and isinstance(child, int) + and parent > 0 + and child > 0 + and parent != child + ): + return dict( + started=True, + result="contained", + reason="exec_timeout", + removed=True, + parent_pid=parent, + descendant_pid=child, + ) + return {"removed": True} + return {} + + def measure_containment(self, timeout_s: float = 60) -> dict: + """ + Measure the subject's isolation from its inspected launch and its processes. + + A probe from the validator's image joins only the subject's PID namespace and + runs as the subject's user, so its writes stand for what the subject can write. + + Args: + timeout_s (`float`, *optional*, defaults to `60`): + Budget for inspection and the probe. + + Returns: + `dict`: a validated [`~openenv.validation.runtime.contracts.ContainmentEvidence`]. + """ + _ensure_image(self._helper_image) + deadline = time.monotonic() + timeout_s + details = self._raw_inspect(deadline - time.monotonic()) + host = details.get("HostConfig", {}) + out = self._pidns_probe( + "containment", + PIDNS_PROBE_SCRIPT, + list(_ALLOTTED), + details["Config"].get("User") or "0", + deadline - time.monotonic(), + ) + namespaces = { + "pid": "PidMode", + "ipc": "IpcMode", + "network": "NetworkMode", + "uts": "UTSMode", + "user": "UsernsMode", + "cgroup": "CgroupnsMode", + } + try: + evidence = ContainmentEvidence.model_validate( + { + **json.loads(out), + "allotted": list(_ALLOTTED), + "launch": { + "privileged": bool(host.get("Privileged")), + "host_namespaces": [ + ns + for ns, key in namespaces.items() + if host.get(key) == "host" + ], + "cap_add": host.get("CapAdd") or [], + "devices": [ + device.get("PathOnHost", "") + for device in host.get("Devices") or [] + ], + "unconfined": [ + option + for option in host.get("SecurityOpt") or [] + if option.replace(":", "=") + in { + "seccomp=unconfined", + "apparmor=unconfined", + "label=disable", + } + ], + }, + } + ) + except (ValueError, TypeError, AttributeError) as exc: + raise ProviderError("Containment probe returned invalid evidence") from exc + return evidence.model_dump(mode="json") + + def measure_resources(self, timeout_s: float = 180) -> dict: + """ + Read effective limits and qualify storage, memory, PIDs and exec cleanup. + + Each destructive probe has a fresh disposable subject registered for outer + cleanup. Exec cleanup does not qualify the declared episode deadline. + + Args: + timeout_s (`float`, *optional*, defaults to `180`): + Budget for measurement, disposable launches and probes. + + Returns: + `dict`: validated resource evidence with complete storage inventory. + """ + _ensure_image(self._helper_image) + deadline = time.monotonic() + timeout_s + + def remaining(): + return deadline - time.monotonic() + + user = self._raw_inspect(remaining())["Config"].get("User") or "0" + try: + measured = json.loads( + self._pidns_probe("limits", LIMITS_SCRIPT, [], user, remaining()) + ) + except ValueError as exc: + raise ProviderError("Limits probe returned invalid evidence") from exc + try: + containment = self.measure_containment(remaining()) + except CleanupError: + raise + except ProviderError: + containment = None + # Keep the original capacities and the full inventory that establishes coverage. + measured["containment"] = containment + measured["writable"] = [ + {"path": mount["mount_point"], "size_bytes": mount["size_bytes"]} + for mount in (containment["mounts"] if containment is not None else []) + if mount["mount_point"] in _ALLOTTED and mount["size_bytes"] is not None + ] + resources = self._spec.resources + budgets = { + "pids": (measured.get("cgroup") or {}).get("pids_max") or 0, + "disk": resources.disk_mb * 1024 * 1024, + "memory": resources.memory_mb * 1024 * 1024, + "exec_timeout": 1, + } + qualification = [] + for kind, budget in budgets.items(): + probe = {"kind": kind, "result": "inconclusive", "started": False} + qualification.append(probe) + if not budget: + continue + sibling = None + try: + sibling = DockerValidationProvider( + helper_image=self._helper_image, cleanup_subjects=self._disposables + ).start( + self._spec.model_copy( + update={ + "startup_timeout_s": min( + self._spec.startup_timeout_s, remaining() + ) + } + ) + ) + python = next( + ( + name + for name in ("python3", "python") + if sibling.exec([name, "-c", "pass"], remaining()).exit_code + == 0 + ), + None, + ) + if python is None: + continue + + def counters(): + return json.loads( + sibling._pidns_probe( + "counters", + COUNTERS_SCRIPT, + list(_ALLOTTED), + user, + remaining(), + ) + ) + + nonce = uuid.uuid4().hex + argv = [ + python, + "-c", + QUALIFY_SCRIPT, + kind, + str(budget), + nonce, + *_ALLOTTED, + ] + if kind == "exec_timeout": + probe.update( + sibling._measure_exec_timeout(argv, nonce, user, remaining()) + ) + continue + before = counters() + result = sibling.exec(argv, remaining()) + probe["started"] = ( + "openenv-probe-start:" + nonce in result.stdout.splitlines() + ) + if not probe["started"]: + continue + state = sibling._raw_inspect(remaining())["State"] + after = counters() if state["Running"] else {} + if kind == "memory": + previous, current = before.get("oom_kill"), after.get("oom_kill") + probe.update( + counter_before=previous, + counter_after=current, + oom_killed=bool(state.get("OOMKilled")), + ) + if state.get("OOMKilled") or ( + previous is not None + and current is not None + and current > previous + ): + probe.update(result="contained", reason="cgroup_oom_kill") + elif kind == "pids": + previous, current = before.get("pids_max"), after.get("pids_max") + probe.update(counter_before=previous, counter_after=current) + if ( + result.exit_code == 0 + and result.stdout.splitlines()[-1:] == ["contained"] + and previous is not None + and current is not None + and current > previous + ): + probe.update(result="contained", reason="cgroup_pids_max") + elif kind == "disk": + free = after.get("free_bytes", {}) + probe["free_bytes"] = free + probe["free_bytes_before"] = before.get("free_bytes", {}) + if ( + result.exit_code == 0 + and result.stdout.splitlines()[-1:] == ["contained"] + and all( + free.get(path) == 0 + and (probe["free_bytes_before"].get(path) or 0) > 0 + for path in _ALLOTTED + ) + ): + probe.update(result="contained", reason="filesystem_full") + except CleanupError: + raise + except (ProviderError, ValueError): + # A failed stimulus cannot establish enforcement, or erase other probes. + pass + finally: + try: + if sibling is not None: + sibling.stop() + except ProviderError as exc: + raise CleanupError( + "Disposable resource subject teardown failed" + ) from exc + try: + evidence = ResourceEvidence.model_validate( + {**measured, "qualification": qualification} + ) + except ValueError as exc: + raise ProviderError("Resource probes returned invalid evidence") from exc + return evidence.model_dump(mode="json") + def _run(self, argv: list[str], timeout_s: float, max_bytes: int = _MAX_OUTPUT): code, stdout, stderr = _command(argv, timeout_s, max_bytes) if code: @@ -666,7 +1044,9 @@ class DockerRunningSubject: try: self.stop() except ProviderError as cleanup: - raise cleanup from exc + raise CleanupError( + "Subject exec teardown failed: " + str(cleanup) + ) from exc raise return ExecResult( code, @@ -720,6 +1100,12 @@ class DockerRunningSubject: def stop(self) -> None: if self._stopped: return + disposable_cleanup_failed = False + for disposable in reversed(self._disposables): + try: + disposable.stop() + except ProviderError: + disposable_cleanup_failed = True if self._bridge is not None: self._bridge.close() self._bridge = None @@ -761,5 +1147,7 @@ class DockerRunningSubject: "Container removal could not be independently verified" ) if auxiliary_cleanup_failed: - raise ProviderError("Could not verify network helper cleanup") + raise CleanupError("Could not verify network helper cleanup") + if disposable_cleanup_failed: + raise CleanupError("Could not verify disposable resource subject cleanup") self._stopped = True diff --git a/src/core/openenv/validation/providers/hf_sandbox.py b/src/core/openenv/validation/providers/hf_sandbox.py new file mode 100644 index 0000000000000000000000000000000000000000..e0c232284a43e5e89818a43c68b0e2277f092aba --- /dev/null +++ b/src/core/openenv/validation/providers/hf_sandbox.py @@ -0,0 +1,303 @@ +"""Run a Hugging Face Space as a validation subject in a dedicated HF Sandbox. + +A Space revision pins the downloaded source, not the image selected by HF Jobs. +This integration has no supported source-to-image digest resolver, so runtime +startup reports the missing immutable_image capability before creating a job. +The sandbox subject below retains bounded serving, exec and cleanup support for +provider qualification once that binding is available. +""" + +import json +import re +import shlex +import time +from pathlib import Path + +import httpx + +from ...core.containers.runtime.hf_sandbox_provider import _LocalAuthProxy +from ..manifest import ExecutionDeclaration +from ..runtime.contracts import LaunchSpec +from ..types import ProviderCapability +from . import ExecResult, ProviderError, StartupError, UnsupportedCapability + +_TERMINAL_STAGES = {"COMPLETED", "CANCELED", "ERROR", "DELETED"} +_MAX_OUTPUT = 65536 + + +def _server_command(dockerfile: str) -> list[str]: + """The effective `CMD` of a Dockerfile, which a Sandbox job does not run itself.""" + if re.search(r"(?im)^#\s*escape\s*=\s*`\s*$", dockerfile): + raise UnsupportedCapability("hf-sandbox requires backslash Dockerfile escapes") + stages = {} + stage = {} + stage_number = 0 + lines = "\n".join( + line for line in dockerfile.splitlines() if not line.lstrip().startswith("#") + ) + # Docker continues only an unescaped backslash, allowing trailing spaces/tabs. + lines = re.sub(r"(? int: + """`app_port` from the Space card front matter; the Hub default is 7860.""" + front = readme.split("---", 2)[1] if readme.startswith("---") else "" + match = re.search(r"^app_port:\s*(\d+)\s*$", front, re.M) + return int(match.group(1)) if match else 7860 + + +class HFSandboxValidationProvider: + """ + Inspect a Hub Space for validation on HF Jobs hardware, including GPU flavors. + + Args: + space_id (`str`): + The Space to run, e.g. `"openenv/echo_env"`. + revision (`str`): + The full commit hash of the validated Space files; resolve a branch or + tag first. Runtime remains unsupported until an immutable image can + be bound to this source commit. + flavor (`str`, *optional*, defaults to `"cpu-basic"`): + HF Jobs hardware flavor, as listed by `hf jobs hardware`. + token (`str`, *optional*): + Hugging Face token; defaults to the locally saved one. + """ + + name = "hf-sandbox" + supported_network_modes = frozenset({"public"}) + + def __init__( + self, + space_id: str, + revision: str, + *, + flavor: str = "cpu-basic", + token: str | None = None, + ): + from huggingface_hub import HfApi + + if not re.fullmatch(r"[0-9a-f]{40}", revision): + raise ValueError(f"revision must be a full commit hash, not {revision!r}") + self.space_id = space_id + self.revision = revision + self.flavor = flavor + self._api = HfApi(token=token) + hardware = {h.name: h for h in self._api.list_jobs_hardware()} + if flavor not in hardware: + raise ValueError(f"unknown HF Jobs flavor {flavor!r}") + accelerator = hardware[flavor].accelerator + self.gpus = int(accelerator.quantity) if accelerator else 0 + self.capabilities = frozenset( + { + ProviderCapability.IMAGE_BUILD, + ProviderCapability.EXEC, + ProviderCapability.REMOTE, + *([ProviderCapability.GPU] if self.gpus else []), + } + ) + self._command: list[str] = [] + self._port = 7860 + + def _check_space(self) -> None: + """Compare source and reported runtime metadata without claiming image provenance.""" + try: + info = self._api.space_info(self.space_id) + except Exception as exc: + raise ProviderError(f"Could not read Space {self.space_id}") from exc + if info.sha != self.revision: + raise ProviderError( + f"Space {self.space_id} is at revision {info.sha}, not the " + + f"validated revision {self.revision}" + ) + # Raw runtime metadata is not provenance for a separately launched Job. + runtime = info.runtime.raw if info.runtime else {} + stage, runtime_revision = runtime.get("stage"), runtime.get("sha") + if stage not in (None, "RUNNING") or runtime_revision not in ( + None, + self.revision, + ): + raise ProviderError( + f"Space {self.space_id} reports stage {stage}, runtime revision " + + f"{runtime_revision}; expected RUNNING at source revision {self.revision}; " + + "job image identity remains unverified" + ) + if stage is None or runtime_revision is None: + raise UnsupportedCapability( + "missing provider capability: space_runtime_metadata; " + + "Space runtime stage or revision is unavailable; " + + "job image identity remains unverified; no job launched" + ) + + def build(self, root: Path, execution: ExecutionDeclaration) -> str: + """Read the server command and port from the validated Space files.""" + try: + dockerfile = (root / execution.dockerfile).read_text() + except OSError: + raise StartupError( + f"The Space has no Dockerfile at {execution.dockerfile}" + ) from None + self._command = _server_command(dockerfile) + readme = root / "README.md" + self._port = _app_port(readme.read_text() if readme.is_file() else "") + self._check_space() + raise UnsupportedCapability( + "missing provider capability: immutable_image; " + + f"Space source revision {self.revision} matches the Hub runtime revision, " + + "but no verified source-to-image digest binding is available; no job launched" + ) + + def start(self, spec: LaunchSpec) -> "HFSandboxSubject": + if spec.network.mode not in self.supported_network_modes: + raise UnsupportedCapability( + f"hf-sandbox does not enforce {spec.network.mode}" + ) + if spec.resources.gpus > self.gpus: + raise UnsupportedCapability( + f"flavor {self.flavor} has {self.gpus} GPUs, " + + f"{spec.resources.gpus} declared" + ) + self._check_space() + raise UnsupportedCapability( + "missing provider capability: immutable_image; " + + f"no verified image digest for Space source revision {self.revision}; " + + "no job launched" + ) + + +class HFSandboxSubject: + """A dedicated sandbox job serving one Space; stopping cancels the job.""" + + def __init__(self, sandbox, provider: HFSandboxValidationProvider): + self.base_url = "" + self._sandbox = sandbox + self._provider = provider + self._proxy: _LocalAuthProxy | None = None + self._stopped = False + + def _serve(self, command: list[str], port: int, timeout_s: float) -> None: + self._sandbox.run( + shlex.join(command) + + f" 2>&1 | {{ head -c {_MAX_OUTPUT} > /tmp/openenv-server.log; " + "cat > /dev/null; }", + shell=True, + background=True, + ) + target = self._sandbox.proxy_url_for(port, "/") + headers = self._sandbox.proxy_headers + deadline = time.monotonic() + timeout_s + # Until the subject binds its port, the sandbox's own server answers the + # proxy, including a healthy /health; wait for the subject's listener first. + listening = f"grep -qi ':{port:04X} 0\\+:0000 0A' /proc/net/tcp /proc/net/tcp6" + with httpx.Client(trust_env=False, follow_redirects=False) as client: + while time.monotonic() < deadline: + try: + check = self._sandbox.run( + listening, shell=True, check=False, timeout=5 + ) + if check.exit_code == 0: + response = client.get( + target + "health", headers=headers, timeout=5 + ) + if response.status_code == 200: + break + except httpx.HTTPError: + pass # The server is still starting. + time.sleep(1) + else: + raise StartupError( + "Subject did not return HTTP 200 from /health before its deadline" + ) + self._proxy = _LocalAuthProxy(target_url=target, headers=headers) + self.base_url = self._proxy.start() + + def inspect(self) -> dict: + return { + "job_id": self._sandbox.id, + "image": f"hf.co/spaces/{self._provider.space_id}", + # No source-bound image digest has been verified. + "image_verified": False, + "space_revision": self._provider.revision, + "built_revision": None, + "flavor": self._provider.flavor, + } + + def logs(self, max_bytes: int = _MAX_OUTPUT) -> str: + result = self._sandbox.run( + ["tail", "-c", str(max_bytes), "/tmp/openenv-server.log"], check=False + ) + return result.stdout[-max_bytes:] + + def exec(self, argv: list[str], timeout_s: float) -> ExecResult: + if self._stopped: + raise ProviderError("Subject has stopped") + started = time.monotonic() + result = self._sandbox.run(argv, shell=False, timeout=timeout_s, check=False) + return ExecResult( + result.exit_code, + result.stdout[-_MAX_OUTPUT:], + result.stderr[-_MAX_OUTPUT:], + time.monotonic() - started, + ) + + def stop(self) -> None: + if self._stopped: + return + try: + if self._proxy is not None: + self._proxy.stop() + self._proxy = None + finally: + self._sandbox.kill() + # kill() logs rather than raises on failure, so confirm with the Jobs API. + deadline = time.monotonic() + 60 + while time.monotonic() < deadline: + stage = self._provider._api.inspect_job( + job_id=self._sandbox.id + ).status.stage + if stage in _TERMINAL_STAGES: + break + time.sleep(2) + else: + raise ProviderError(f"HF Sandbox job {self._sandbox.id} did not stop") + self._stopped = True diff --git a/src/core/openenv/validation/runner.py b/src/core/openenv/validation/runner.py index e66856042da590fd05106df90736cecf3a8d42b7..4fd19388f7a785274de0c97aa158e6dcc2ea2c81 100644 --- a/src/core/openenv/validation/runner.py +++ b/src/core/openenv/validation/runner.py @@ -3,30 +3,64 @@ import hashlib import json import os +import secrets import stat import time import uuid from dataclasses import replace -from pathlib import Path +from pathlib import Path, PurePosixPath +from urllib.parse import quote + +import httpx from .graders import GraderRegistry, Subject from .graders.runtime import ( + EpisodeIsolationGrader, + HostContainmentGrader, NetworkPolicyGrader, ObservationSchemaGrader, + OracleContainmentGrader, + ResourceBoundsGrader, RewardWellFormedGrader, StateContractGrader, ) +from .graders.runtime.discovery import ( + RewardAttributionGrader, + RubricIntrospectableGrader, + TaskDeclarationAccuracyGrader, + ToolDeclarationAccuracyGrader, +) +from .graders.runtime.oracle import oracle_inventory +from .graders.runtime.repeatability import ( + EpisodeDeterminismGrader, + SeedControlGrader, + TrajectoryRecordGrader, +) from .graders.static import StaticManifestGrader from .manifest import ManifestError, NormalizedManifest, NormalizedManifestV2 from .parsers import ParserRegistry +from .parsers.harbor_toml import HarborTaskParser from .parsers.openenv_yaml import OpenEnvYamlParser from .policy import apply_policy, load_policy, PolicyError, SeverityPolicy -from .providers import ProviderError, StartupError, UnsupportedCapability +from .providers import CleanupError, ProviderError, StartupError, UnsupportedCapability from .report import CheckResult, ValidationReport, ValidationReportV2 from .runtime.artifacts import write_runtime_bundle -from .runtime.collector import collect_runtime_evidence, RuntimeCollectionInterrupted -from .runtime.contracts import LaunchSpec, load_runtime_plan, RuntimePlanError +from .runtime.collector import ( + collect_runtime_evidence, + RuntimeCollectionInterrupted, + RuntimeCollectionUnsupported, +) +from .runtime.contracts import ( + HttpProbe, + IsolationEvidence, + LaunchSpec, + load_runtime_plan, + RuntimeEvidence, + RuntimePlanError, +) +from .runtime.replay import collect_replays, REPLAY_BUDGET_SECONDS from .runtime.scheduler import execute_graders, order_graders +from .runtime.transport import http_deadline from .signature import detect_signature from .types import CheckStatus, Lane, Level, ProviderCapability @@ -34,6 +68,11 @@ REPORT_SCHEMA_VERSION = "1" _DIGEST_EXCLUDED_DIRS = {".git", "__pycache__", ".venv", ".worktrees", "outputs"} +# One deadline and one body budget cover the oracle's HTTP probes. +ORACLE_PROBE_TIMEOUT_S = 10.0 +MAX_ORACLE_PROBE_BYTES = 1024 * 1024 +MAX_REDIRECTS = 3 + def source_digest(package_root: Path) -> str: """ @@ -83,6 +122,7 @@ def default_parser_registry() -> ParserRegistry: """The parsers shipped in this build.""" registry = ParserRegistry() registry.register(OpenEnvYamlParser()) + registry.register(HarborTaskParser()) return registry @@ -93,7 +133,19 @@ def default_grader_registry(policy: SeverityPolicy) -> GraderRegistry: registry.register(RewardWellFormedGrader()) registry.register(ObservationSchemaGrader()) registry.register(StateContractGrader()) + registry.register(SeedControlGrader()) + registry.register(EpisodeDeterminismGrader()) + registry.register(TrajectoryRecordGrader()) + registry.register(ToolDeclarationAccuracyGrader()) + registry.register(TaskDeclarationAccuracyGrader()) + registry.register(RubricIntrospectableGrader()) + registry.register(RewardAttributionGrader()) + registry.register(NetworkPolicyGrader()) + registry.register(HostContainmentGrader()) + registry.register(ResourceBoundsGrader()) + registry.register(EpisodeIsolationGrader()) + registry.register(OracleContainmentGrader()) return registry @@ -107,23 +159,128 @@ def _outcome(check_id, status, reason, *, started=None, measured=None): ) +class _OracleCollectionInterrupted(KeyboardInterrupt): + """Cancellation carrying the bounded HTTP evidence already received.""" + + def __init__(self, probes): + super().__init__("oracle collection interrupted") + self.probes = tuple(probes) + + +def _get(base_url, location, deadline, max_bytes=MAX_ORACLE_PROBE_BYTES): + """ + GET a package-relative path from the control endpoint, unproxied and bounded. + + Same-origin redirects are followed up to `MAX_REDIRECTS` times. Every request + and body read ends at `deadline`, a `time.monotonic()` value. The probe keeps + bounded bodies from every redirect hop and names any incomplete response. + """ + path = "/" + PurePosixPath(location).as_posix() + url = httpx.URL(base_url.rstrip("/") + quote(path)) + origin = (url.scheme, url.host, url.port) + status, body = None, bytearray() + redirects = [] + retained = 0 + + def probe(failure=None): + return HttpProbe(path, status, bytes(body), failure, tuple(redirects)) + + try: + # Without keep-alive, every request opens a socket the deadline can abort. + with httpx.Client( + trust_env=False, + follow_redirects=False, + limits=httpx.Limits(max_keepalive_connections=0), + ) as client: + for hop in range(MAX_REDIRECTS + 1): + timeout = deadline - time.monotonic() + with ( + http_deadline(timeout) as extensions, + client.stream( + "GET", + url, + timeout=timeout, + headers={"Accept-Encoding": "identity"}, + extensions=extensions, + ) as response, + ): + status = response.status_code + # iter_bytes() would decompress before the byte bound applies. + encoding = response.headers.get("Content-Encoding", "identity") + if encoding.strip().lower() != "identity": + return probe("compressed response") + for chunk in response.iter_raw(): + if retained + len(body) + len(chunk) > max_bytes: + body.extend(chunk[: max_bytes - retained - len(body)]) + return probe("body exceeds the byte bound") + body.extend(chunk) + if not response.has_redirect_location: + return probe() + if hop == MAX_REDIRECTS: + return probe("too many redirects") + if retained + len(body) >= max_bytes: + return probe("body exceeds the byte bound") + url = url.join(response.headers["Location"]) + if (url.scheme, url.host, url.port) != origin: + return probe("cross-origin redirect") + redirects.append(bytes(body)) + retained += len(body) + body.clear() + status = None + except KeyboardInterrupt: + raise _OracleCollectionInterrupted((probe("KeyboardInterrupt"),)) from None + except (httpx.HTTPError, httpx.InvalidURL, TimeoutError) as exc: + # Exception text may include subject-controlled URLs. + return probe(type(exc).__name__) + return probe("too many redirects") + + +def _oracle_probes(base_url, root, location): + """Share one deadline and body budget across the bounded file inventory.""" + try: + inventory = oracle_inventory(root, location) + except (OSError, UnicodeError): + return () + deadline = time.monotonic() + ORACLE_PROBE_TIMEOUT_S + remaining = MAX_ORACLE_PROBE_BYTES + probes = [] + for path, _ in inventory.files: + if remaining <= 0 or time.monotonic() >= deadline: + probe = HttpProbe("/" + path, None, failure="oracle probe budget exhausted") + else: + try: + probe = _get(base_url, path, deadline, remaining) + except KeyboardInterrupt as exc: + interrupted = ( + exc.probes + if isinstance(exc, _OracleCollectionInterrupted) + else (HttpProbe("/" + path, None, failure="KeyboardInterrupt"),) + ) + raise _OracleCollectionInterrupted((*probes, *interrupted)) from None + probes.append(probe) + remaining -= len(probe.body) + sum(map(len, probe.redirect_bodies)) + return tuple(probes) + + def _applicable(check_id, manifest): if manifest is None: return True if check_id in {"runtime.rubric_introspectable", "runtime.reward_attribution"}: return manifest.capabilities.rubric_tree if check_id == "runtime.task_declaration_accuracy": - return manifest.capabilities.task_api or bool( - manifest.capabilities.declared_task_count - ) + return TaskDeclarationAccuracyGrader().applies_to(manifest) + if check_id == "runtime.tool_declaration_accuracy": + return ToolDeclarationAccuracyGrader().applies_to(manifest) return True -def _runtime(subject, graders, *, skip_build, provider): +def _runtime(subject, graders, *, skip_build, provider, sandbox): """Own build/start/collection/stop and retain failure evidence through teardown.""" manifest = subject.manifest plan = None evidence = None + isolation = None + oracle_http = () running = None inspection = {} cleanup = {"required": False, "completed": True} @@ -136,6 +293,11 @@ def _runtime(subject, graders, *, skip_build, provider): raise UnsupportedCapability( "--skip-build: build-dependent runtime checks skipped" ) + if sandbox != "docker": + raise UnsupportedCapability( + f"{sandbox} runs native Harbor tasks only; " + + "validate a served Space with --space" + ) if not isinstance(manifest, NormalizedManifestV2): raise UnsupportedCapability( "missing validation.execution declaration and runtime plan" @@ -166,12 +328,12 @@ def _runtime(subject, graders, *, skip_build, provider): resources=manifest.resources, network=manifest.network, run_id="validation-" + uuid.uuid4().hex, + env_vars={"OPENENV_VALIDATION_TOKEN": secrets.token_urlsafe(32)}, ) attempted = True image_ref = provider.build(subject.root, manifest.execution) - running = provider.start( - LaunchSpec.model_validate({**spec.model_dump(), "image_ref": image_ref}) - ) + spec = LaunchSpec.model_validate({**spec.model_dump(), "image_ref": image_ref}) + running = provider.start(spec) cleanup = {"required": True, "completed": False} inspection = running.inspect() result = _outcome( @@ -181,11 +343,19 @@ def _runtime(subject, graders, *, skip_build, provider): started=started, measured={"provider": provider.name, "image_ref": image_ref}, ) + replay_deadline = time.monotonic() + REPLAY_BUDGET_SECONDS evidence = collect_runtime_evidence( running.base_url, plan, - episode_timeout_s=manifest.resources.episode_timeout_s, + episode_timeout_s=min( + manifest.resources.episode_timeout_s, REPLAY_BUDGET_SECONDS + ), + validation_token=spec.env_vars["OPENENV_VALIDATION_TOKEN"], + collect_tools=_applicable("runtime.tool_declaration_accuracy", manifest), + collect_tasks=_applicable("runtime.task_declaration_accuracy", manifest), ) + # Independent isolation and oracle probes do not spend the replay budget. + replay_remaining_s = max(0.0, replay_deadline - time.monotonic()) # Protocol collection must finish before its dependent contract checks run. if evidence.failure_reason: result = _outcome( @@ -194,6 +364,59 @@ def _runtime(subject, graders, *, skip_build, provider): evidence.failure_reason, started=started, ) + if result.status is CheckStatus.PASS: + not_started = RuntimeEvidence( + failure_phase="not_started", + failure_reason="validation interrupted before the fresh episode", + ) + try: + # Later JSON limits leave primary contracts and other probes measurable. + try: + sequential = collect_runtime_evidence( + running.base_url, + plan, + episode_timeout_s=manifest.resources.episode_timeout_s, + episodes=2, + validation_token=spec.env_vars["OPENENV_VALIDATION_TOKEN"], + request_telemetry=False, + ) + except RuntimeCollectionUnsupported as exc: + sequential = exc.evidence + isolation = IsolationEvidence(sequential=sequential, fresh=not_started) + try: + fresh = collect_runtime_evidence( + running.base_url, + plan, + episode_timeout_s=manifest.resources.episode_timeout_s, + validation_token=spec.env_vars["OPENENV_VALIDATION_TOKEN"], + request_telemetry=False, + ) + except RuntimeCollectionUnsupported as exc: + fresh = exc.evidence + isolation = replace(isolation, fresh=fresh) + except RuntimeCollectionInterrupted as exc: + isolation = ( + IsolationEvidence(sequential=exc.evidence, fresh=not_started) + if isolation is None + else replace(isolation, fresh=exc.evidence) + ) + raise KeyboardInterrupt from None + if manifest.capabilities.oracle is not None: + oracle_http = _oracle_probes( + running.base_url, + subject.root, + manifest.capabilities.oracle.location, + ) + evidence = collect_replays( + provider, + running, + spec, + plan, + evidence, + capabilities=manifest.capabilities, + deadline=time.monotonic() + replay_remaining_s, + ) + network_json = None if ( result.status is CheckStatus.PASS @@ -207,18 +430,58 @@ def _runtime(subject, graders, *, skip_build, provider): inspection = {**inspection, "network": network} except ProviderError as exc: inspection = {**inspection, "network_error": str(exc)[:1024]} + containment_json = None + if ( + result.status is CheckStatus.PASS + and ProviderCapability.INSPECTED_ISOLATION in provider.capabilities + ): + try: + containment = running.measure_containment() + containment_json = json.dumps(containment, allow_nan=False) + inspection = {**inspection, "containment": containment} + except ProviderError as exc: + inspection = {**inspection, "containment_error": str(exc)[:1024]} + resource_json = None + if ( + result.status is CheckStatus.PASS + and ProviderCapability.RESOURCE_ENFORCEMENT in provider.capabilities + ): + try: + resources = running.measure_resources() + resource_json = json.dumps(resources, allow_nan=False) + inspection = {**inspection, "resources": resources} + except CleanupError: + raise + except ProviderError as exc: + inspection = {**inspection, "resources_error": str(exc)[:1024]} subject = replace( subject, image_ref=image_ref, running=running, runtime_evidence=evidence, network_evidence_json=network_json, + containment_evidence_json=containment_json, + resource_evidence_json=resource_json, + isolation_evidence=isolation, + oracle_http=oracle_http, ) - checks = execute_graders( - graders, - subject, - provider_capabilities=provider.capabilities, - prior=[result], + checks.extend( + execute_graders( + graders, + subject, + provider_capabilities=provider.capabilities, + prior=[result], + ) + ) + # Cleanup failure cannot invalidate evidence already collected from a + # healthy subject. Preserve its findings before failing the run closed. + if any(replay.cleanup_complete is False for replay in evidence.replays): + result.status = CheckStatus.ERROR + result.evidence.append("replay subject teardown failed") + except RuntimeCollectionUnsupported as exc: + evidence = exc.evidence + result = _outcome( + "runtime.startup", CheckStatus.SKIP, str(exc), started=started ) except UnsupportedCapability as exc: result = _outcome( @@ -241,6 +504,8 @@ def _runtime(subject, graders, *, skip_build, provider): except KeyboardInterrupt as exc: if isinstance(exc, RuntimeCollectionInterrupted): evidence = exc.evidence + elif isinstance(exc, _OracleCollectionInterrupted): + oracle_http = exc.probes result = _outcome( "runtime.startup", CheckStatus.ERROR, @@ -255,25 +520,66 @@ def _runtime(subject, graders, *, skip_build, provider): started=started, ) finally: - if running is not None: - try: - running.stop() - cleanup["completed"] = True - except (Exception, KeyboardInterrupt) as exc: - cleanup["completed"] = False - cleanup["reason"] = f"subject teardown failed ({type(exc).__name__})" - if result is None: + try: + # Discovery precedes the episode; its completed evidence remains usable + # when collection is unsupported or interrupted before normal grading. + graded = {check.check_id for check in checks} + independent = [ + grader + for grader in graders + if not grader.depends_on and grader.check_id not in graded + ] + if independent: + try: + checks.extend( + execute_graders( + independent, replace(subject, runtime_evidence=evidence) + ) + ) + except KeyboardInterrupt: result = _outcome( "runtime.startup", CheckStatus.ERROR, - "subject teardown failed", + "validation interrupted", started=started, ) - else: - result.status = CheckStatus.ERROR - result.evidence.append("subject teardown failed") - result.duration_s = time.monotonic() - started - return [result, *checks], attempted, plan, evidence, inspection, cleanup + finally: + if running is not None: + try: + running.stop() + cleanup["completed"] = not ( + evidence + and any( + replay.cleanup_complete is False + for replay in evidence.replays + ) + ) + except (Exception, KeyboardInterrupt) as exc: + cleanup["completed"] = False + cleanup["reason"] = ( + f"subject teardown failed ({type(exc).__name__})" + ) + if result is None: + result = _outcome( + "runtime.startup", + CheckStatus.ERROR, + "subject teardown failed", + started=started, + ) + else: + result.status = CheckStatus.ERROR + result.evidence.append("subject teardown failed") + result.duration_s = time.monotonic() - started + return ( + [result, *checks], + attempted, + plan, + evidence, + inspection, + cleanup, + isolation, + oracle_http, + ) def run_validation( @@ -284,6 +590,10 @@ def run_validation( policy: SeverityPolicy | None = None, provider=None, artifacts_dir: Path | None = None, + report_target: str | None = None, + sandbox: str = "docker", + flavor: str = "cpu-basic", + namespace: str | None = None, ) -> ValidationReport | ValidationReportV2: """ Validate a package end to end and return the report. @@ -293,7 +603,7 @@ def run_validation( [`~openenv.validation.signature.UnsupportedPackageError`] for recognized-but-unsupported ones (CLI exit code 2). A package whose declarations fail the manifest schema yields a normal report with a `static.manifest` FAIL - (exit code 1). + (exit code 1). An unknown `sandbox` raises `ValueError` before validation. Args: target (`Path`): @@ -308,10 +618,24 @@ def run_validation( Validation-only provider; defaults to Docker-local for runtime runs. artifacts_dir (`Path`, *optional*): Write a redacted reproduction bundle to this directory. + report_target (`str`, *optional*): + Durable source identity for the report; defaults to the package path. + sandbox (`str`, *optional*, defaults to `"docker"`): + Where native Harbor trials run: `"docker"` on the local daemon or + `"hf-sandbox"`, one Hugging Face Job per trial. Served packages run + on `"docker"` or `provider` only. + flavor (`str`, *optional*, defaults to `"cpu-basic"`): + HF Jobs hardware flavor for `"hf-sandbox"` trials, as listed by + `hf jobs hardware`. + namespace (`str`, *optional*): + User or organization that owns the `"hf-sandbox"` jobs; defaults to + the token's user. Returns: [`~openenv.validation.report.ValidationReport`]: the completed report. """ + if sandbox not in ("docker", "hf-sandbox"): + raise ValueError(f"unknown sandbox {sandbox!r}; expected docker or hf-sandbox") target = Path(target) wants_runtime = max_level >= Level.RUNTIME policy = policy or load_policy("v2" if wants_runtime else "v1") @@ -357,7 +681,8 @@ def run_validation( ) levels = [Level.STATIC] - plan = evidence = None + plan = evidence = isolation = None + oracle_http = () inspection = {} cleanup = {"required": False, "completed": True} if manifest is not None: @@ -382,7 +707,36 @@ def run_validation( ) ) if wants_runtime: - runtime_results, attempted, plan, evidence, inspection, cleanup = _runtime( + if ( + isinstance(manifest, NormalizedManifestV2) + and manifest.execution.kind == "harbor_task" + ): + from .harbor import validate_harbor + + return validate_harbor( + subject, + max_level=max_level, + policy=policy, + results=results, + digest_before=digest_before, + artifacts_dir=artifacts_dir, + report_target=report_target, + skip_build=skip_build, + provider=provider, + sandbox=sandbox, + flavor=flavor, + namespace=namespace, + ) + ( + runtime_results, + attempted, + plan, + evidence, + inspection, + cleanup, + isolation, + oracle_http, + ) = _runtime( subject, [ grader @@ -391,34 +745,35 @@ def run_validation( ], skip_build=skip_build, provider=provider, + sandbox=sandbox, ) results.extend(runtime_results) if attempted: levels.append(Level.RUNTIME) + # Policy IDs are an inventory, not evidence that a grader exists. Name every + # requested check that did not run, so a PASS never hides missing coverage. + present = {result.check_id for result in results} + for entry in policy.entries_for_lane(Lane.LOCAL).values(): + grader = graders.get(entry.check_id) + applicable = ( + manifest is None + or entry.check_id in selected + or (grader is None and _applicable(entry.check_id, manifest)) + ) + if entry.level <= max_level and entry.check_id not in present and applicable: + reason = "grader not implemented in this build" + if manifest is None: + reason = "unmet dependency: valid manifest" + elif entry.level is Level.SEMANTIC: + reason = "oracle execution is not implemented for served packages" + elif grader is not None and grader.depends_on: + reason = "unmet dependency: " + ", ".join(grader.depends_on) + elif grader is not None: + reason = "grader did not complete" + results.append(_outcome(entry.check_id, CheckStatus.SKIP, reason)) + if wants_runtime: - # Policy IDs are an inventory, not evidence that a grader exists. Keep the - # incomplete surface explicit throughout the staged implementation. - present = {result.check_id for result in results} - for entry in policy.entries_for_lane(Lane.LOCAL).values(): - grader = graders.get(entry.check_id) - applicable = ( - manifest is None - or entry.check_id in selected - or (grader is None and _applicable(entry.check_id, manifest)) - ) - if ( - entry.level in {Level.RUNTIME, Level.SEMANTIC} - and entry.level <= max_level - and entry.check_id not in present - and applicable - ): - reason = "grader not implemented in this build" - if manifest is None: - reason = "unmet dependency: valid manifest" - elif grader is not None and grader.depends_on: - reason = "unmet dependency: " + ", ".join(grader.depends_on) - results.append(_outcome(entry.check_id, CheckStatus.SKIP, reason)) source_problem = None if not digest_before: source_problem = "package source could not be verified before validation" @@ -435,6 +790,12 @@ def run_validation( ) if source_problem is not None: invalidated = {"runtime.startup"} + # Independent discovery also depends on the verified package source. + invalidated.update( + grader.check_id + for grader in selected.values() + if grader.level is Level.RUNTIME + ) for grader in order_graders(list(selected.values())): if invalidated.intersection(grader.depends_on): invalidated.add(grader.check_id) @@ -466,7 +827,7 @@ def run_validation( report_schema_version="2" if report_type is ValidationReportV2 else REPORT_SCHEMA_VERSION, - target=str(target), + target=str(target) if report_target is None else report_target, source_digest=digest_before, signature=signature, manifest=manifest, @@ -484,5 +845,7 @@ def run_validation( evidence=evidence, provider=inspection, cleanup=cleanup, + isolation=isolation, + oracle_http=oracle_http, ) return report diff --git a/src/core/openenv/validation/runtime/artifacts.py b/src/core/openenv/validation/runtime/artifacts.py index e69f9fcfd2adb9d0dcf717748fa65a6392a888d0..205ab4d26bd3b33e466ed753e42c28bb3e3a815e 100644 --- a/src/core/openenv/validation/runtime/artifacts.py +++ b/src/core/openenv/validation/runtime/artifacts.py @@ -1,13 +1,15 @@ """Small, bounded reproduction bundles; reports remain the public result contract.""" import hashlib -import json import math import platform import re from dataclasses import asdict +from decimal import Decimal from pathlib import Path +from .json_values import dumps, loads + _SECRET_KEY = re.compile(r"(?i)(password|secret|token|authorization|api[_-]?key)") _TOKEN_METADATA_KEYS = {"max_tokens", "prompt_token_ids"} _TOKEN = re.compile( @@ -16,6 +18,14 @@ _TOKEN = re.compile( _MAX_ARTIFACT_DEPTH = 64 +def _unique_object(pairs): + # A dict cannot retain earlier duplicate values for redaction or replay. + value = dict(pairs) + if len(value) != len(pairs): + raise ValueError("duplicate JSON object members") + return value + + def _redact(value, *, depth=0): if depth >= _MAX_ARTIFACT_DEPTH and isinstance(value, (dict, list)): return {"omitted": "artifact nesting limit exceeded"} @@ -32,45 +42,13 @@ def _redact(value, *, depth=0): return _TOKEN.sub("[REDACTED]", value) if isinstance(value, float) and not math.isfinite(value): return {"invalid_number": str(value)} + if isinstance(value, Decimal) and not value.is_finite(): + return {"invalid_number": str(value).lower()} return value -def write_runtime_bundle( - directory: Path, report, *, plan=None, evidence=None, provider=None, cleanup=None -): - """Write a credential-filtered trace, source/policy/plan provenance and coverage.""" - directory.mkdir(parents=True, exist_ok=True) - files = {} - coverage = { - "requested_runtime_checks": [ - r.check_id for r in report.results if r.check_id.startswith("runtime.") - ], - "executed": [r.check_id for r in report.results if r.status.value != "skip"], - "incomplete": [r.check_id for r in report.results if r.status.value == "skip"], - } - files["coverage.json"] = coverage - files["report.json"] = report.model_dump(mode="json") - files["cleanup.json"] = cleanup or {"required": False} - if plan: - files["runtime-plan.json"] = plan.model_dump(mode="json") - files["run-manifest.json"] = { - "bundle_schema_version": "1", - "source_digest": report.source_digest, - "policy_version": report.policy_version, - "manifest_schema_version": report.manifest.manifest_schema_version - if report.manifest - else None, - "plan_digest": hashlib.sha256(plan.model_dump_json().encode()).hexdigest() - if plan - else None, - "plan_redacted": bool( - plan - and _redact(plan.model_dump(mode="json")) != plan.model_dump(mode="json") - ), - "platform": platform.platform(), - "python": platform.python_version(), - "provider": provider or {}, - } +def _recording(evidence, trace_file): + """Use the same redaction and completion metadata for every session.""" trace = [] collector_metadata = None if evidence: @@ -79,28 +57,42 @@ def write_runtime_bundle( row = asdict(exchange) for key in ("request_json", "response_json"): try: - row[key] = json.loads(row[key]) - except (ValueError, RecursionError): - row[key] = "[malformed response omitted]" + row[key] = loads(row[key], object_pairs_hook=_unique_object) + except (ValueError, ArithmeticError, RecursionError): + row[key] = "[malformed or unsupported response omitted]" omitted_fields.append({"exchange_index": index, "field": key}) trace.append(row) schema = None schema_parse_failed = False if evidence.observation_schema_json is not None: try: - schema = json.loads(evidence.observation_schema_json) - except (ValueError, RecursionError): + schema = loads( + evidence.observation_schema_json, object_pairs_hook=_unique_object + ) + except (ValueError, ArithmeticError, RecursionError): schema_parse_failed = True reset_schema = None reset_schema_parse_failed = False if evidence.reset_observation_schema_json is not None: try: - reset_schema = json.loads(evidence.reset_observation_schema_json) - except (ValueError, RecursionError): + reset_schema = loads( + evidence.reset_observation_schema_json, + object_pairs_hook=_unique_object, + ) + except (ValueError, ArithmeticError, RecursionError): reset_schema_parse_failed = True + schema_response = None + schema_response_parse_failed = False + if evidence.schema_response_json is not None: + try: + schema_response = loads( + evidence.schema_response_json, object_pairs_hook=_unique_object + ) + except (ValueError, ArithmeticError, RecursionError): + schema_response_parse_failed = True collector_metadata = { "evidence_schema_version": "1", - "trace_file": "collector-trace.json", + "trace_file": trace_file, "observation_schema": schema, "schema_available": evidence.observation_schema_json is not None, "schema_parse_failed": schema_parse_failed, @@ -108,9 +100,14 @@ def write_runtime_bundle( "reset_schema_available": evidence.reset_observation_schema_json is not None, "reset_schema_parse_failed": reset_schema_parse_failed, + "schema_response": schema_response, + "schema_response_available": evidence.schema_response_json is not None, + "schema_response_parse_failed": schema_response_parse_failed, "omitted_trace_fields": omitted_fields, "failure_phase": evidence.failure_phase, "failure_reason": evidence.failure_reason, + "telemetry_error": evidence.telemetry_error, + "telemetry_unavailable": evidence.telemetry_unavailable, "complete": evidence.failure_phase is None and evidence.failure_reason is None, } @@ -118,16 +115,221 @@ def write_runtime_bundle( bool(omitted_fields) or schema_parse_failed or reset_schema_parse_failed + or schema_response_parse_failed or _redact(trace) != trace or _redact(collector_metadata) != collector_metadata ) - files["collector-trace.json"] = trace - files["collector-evidence.json"] = collector_metadata + return trace, collector_metadata + + +def _http_body(body): + text = body.decode("utf-8", errors="replace") + omitted = False + try: + value = loads(text.lstrip("\ufeff"), object_pairs_hook=_unique_object) + except (ValueError, ArithmeticError, RecursionError): + value = text + # Unparseable JSON loses the key context used by the structured redactor. + omitted = text.lstrip("\ufeff \t\r\n").startswith(("{", "[", '"')) + pending = [value] + while pending and not omitted: + child = pending.pop() + if isinstance(child, dict): + pending.extend(child.values()) + elif isinstance(child, list): + pending.extend(child) + elif isinstance(child, str) and _SECRET_KEY.search(child): + omitted = True + if omitted: + value = "[unstructured body omitted]" + return { + "body": value, + "body_sha256": hashlib.sha256(body).hexdigest(), + "retained_bytes": len(body), + "body_omitted": omitted, + "redacted": omitted or _redact(value) != value or text.encode("utf-8") != body, + } + + +def write_runtime_bundle( + directory: Path, + report, + *, + plan=None, + evidence=None, + provider=None, + cleanup=None, + isolation=None, + oracle_http=(), +): + """Write a credential-filtered trace, source/policy/plan provenance and coverage.""" + directory.mkdir(parents=True, exist_ok=True) + files = {} + coverage = { + "requested_runtime_checks": [ + r.check_id for r in report.results if r.check_id.startswith("runtime.") + ], + "executed": [r.check_id for r in report.results if r.status.value != "skip"], + "incomplete": [r.check_id for r in report.results if r.status.value == "skip"], + } + files["coverage.json"] = coverage + files["report.json"] = report.model_dump(mode="json") + files["cleanup.json"] = cleanup or {"required": False} + if plan: + files["runtime-plan.json"] = plan.model_dump(mode="json") + files["run-manifest.json"] = { + "bundle_schema_version": "1", + "json_numbers": "exact integer and decimal tokens; decode with Decimal", + "source_digest": report.source_digest, + "policy_version": report.policy_version, + "manifest_schema_version": report.manifest.manifest_schema_version + if report.manifest + else None, + "plan_digest": hashlib.sha256(plan.model_dump_json().encode()).hexdigest() + if plan + else None, + "plan_redacted": bool( + plan + and _redact(plan.model_dump(mode="json")) != plan.model_dump(mode="json") + ), + "platform": platform.platform(), + "python": platform.python_version(), + "provider": provider or {}, + } + recordings = [("collector", evidence)] + if isolation is not None: + recordings.extend( + [ + ("isolation-sequential", isolation.sequential), + ("isolation-fresh", isolation.fresh), + ] + ) + for session, recording in recordings: + trace_file = f"{session}-trace.json" + trace, metadata = _recording(recording, trace_file) + if metadata is not None: + metadata["session"] = session + if recording.telemetry_json is not None: + try: + telemetry = loads( + recording.telemetry_json, object_pairs_hook=_unique_object + ) + telemetry_file = ( + "session-telemetry.json" + if session == "collector" + else f"{session}-telemetry.json" + ) + files[telemetry_file] = telemetry + metadata["redacted"] |= _redact(telemetry) != telemetry + except (ValueError, ArithmeticError, RecursionError): + metadata["telemetry_error"] = "malformed telemetry omitted" + metadata["redacted"] = True + files[trace_file] = trace + files[f"{session}-evidence.json"] = metadata + probes = [] + for probe in oracle_http: + row = asdict(probe) + row.update(_http_body(row.pop("body"))) + row["redirect_bodies"] = [_http_body(body) for body in row["redirect_bodies"]] + row["redacted"] |= any(body["redacted"] for body in row["redirect_bodies"]) + probes.append(row) + retained_probes = _redact(probes) + # Evaluate modification flags at their actual depth in the saved document. + for original, retained in zip(probes, retained_probes): + retained["redacted"] |= original["body"] != retained["body"] + for before, after in zip( + original["redirect_bodies"], retained["redirect_bodies"] + ): + after["redacted"] |= before["body"] != after["body"] + retained["redacted"] |= after["redacted"] + files["oracle-http.json"] = retained_probes + if evidence: + discovery = {} + omitted = [] + for name in ("tools", "tasks"): + raw = getattr(evidence, name + "_json") + discovery[name + "_available"] = raw is not None + discovery[name + "_error"] = getattr(evidence, name + "_error") + if name == "tools": + discovery["tools_unavailable"] = evidence.tools_unavailable + try: + discovery[name] = ( + loads(raw, object_pairs_hook=_unique_object) + if raw is not None + else None + ) + except (ValueError, ArithmeticError, RecursionError): + discovery[name] = "[malformed evidence omitted]" + omitted.append(name) + discovery["omitted_fields"] = omitted + discovery["redacted"] = bool(omitted) or _redact(discovery) != discovery + files["discovery.json"] = discovery + if evidence and (evidence.replays or evidence.replay_failure_reason): + samples = [] + for replay in evidence.replays: + sample = replay.evidence + row = { + "scope": replay.scope, + "cleanup_complete": replay.cleanup_complete, + "failure_phase": sample.failure_phase, + "failure_reason": sample.failure_reason, + "telemetry_error": sample.telemetry_error, + "telemetry_unavailable": sample.telemetry_unavailable, + "trace": [], + "omitted_trace_fields": [], + "omitted_evidence_fields": [], + } + for index, exchange in enumerate(sample.exchanges): + item = {"operation": exchange.operation} + for key in ("request_json", "response_json"): + try: + item[key] = loads( + getattr(exchange, key), object_pairs_hook=_unique_object + ) + except (ValueError, ArithmeticError, RecursionError): + item[key] = "[malformed response omitted]" + row["omitted_trace_fields"].append( + {"exchange_index": index, "field": key} + ) + row["trace"].append(item) + for key, raw in ( + ("telemetry", sample.telemetry_json), + ("schema", sample.observation_schema_json), + ("reset_schema", sample.reset_observation_schema_json), + ("provider", replay.provider_json), + ): + row[f"{key}_available"] = raw is not None + try: + row[key] = ( + loads(raw, object_pairs_hook=_unique_object) + if raw is not None + else None + ) + except (ValueError, ArithmeticError, RecursionError): + row[key] = "[malformed evidence omitted]" + row["omitted_evidence_fields"].append(key) + row["redacted"] = ( + bool(row["omitted_trace_fields"]) + or bool(row["omitted_evidence_fields"]) + or _redact(row) != row + ) + samples.append(row) + files["replays.json"] = { + "schema_version": "1", + "failure_reason": evidence.replay_failure_reason, + "samples": samples, + } + for name in ( + "runtime-plan.json", + "session-telemetry.json", + "replays.json", + "discovery.json", + ): + if name not in files: + (directory / name).unlink(missing_ok=True) digests = [] for name, value in files.items(): - payload = ( - json.dumps(_redact(value), indent=2, sort_keys=True, allow_nan=False) + "\n" - ).encode() + payload = (dumps(_redact(value)) + "\n").encode() (directory / name).write_bytes(payload) digests.append(f"{hashlib.sha256(payload).hexdigest()} {name}\n") (directory / "SHA256SUMS").write_text("".join(digests)) diff --git a/src/core/openenv/validation/runtime/collector.py b/src/core/openenv/validation/runtime/collector.py index 4fd853094f729f8cff46de5cc46962b87e33bcdd..60290ba1599fb1e13a4c322a94d9f821933110e5 100644 --- a/src/core/openenv/validation/runtime/collector.py +++ b/src/core/openenv/validation/runtime/collector.py @@ -6,16 +6,29 @@ import time from urllib.parse import urlsplit, urlunsplit import httpx +from websockets.exceptions import ConnectionClosed from websockets.sync.client import connect from ...core.env_server.types import WSErrorCode from .contracts import RuntimeEvidence, RuntimePlan, WireExchange +from .discovery import collect_task_evidence +from .json_values import dumps, loads from .transport import abort_socket, http_deadline MAX_MESSAGE_BYTES = 1024 * 1024 MAX_TRACE_BYTES = 8 * 1024 * 1024 +def _server_error_code(response): + if isinstance(response, dict) and response.get("type") == "error": + data = response.get("data") + code = data.get("code") if isinstance(data, dict) else None + # Only protocol constants are safe diagnostics, never subject error text. + if isinstance(code, str) and code in {item.value for item in WSErrorCode}: + return code + return None + + def _bounded_call(connection, operation, timeout_s): if timeout_s <= 0: raise TimeoutError("episode deadline exceeded") @@ -54,12 +67,25 @@ class RuntimeCollectionInterrupted(KeyboardInterrupt): self.evidence = evidence +class RuntimeCollectionUnsupported(RuntimeError): + """A validator JSON limit carrying the retained collection prefix.""" + + def __init__(self, evidence: RuntimeEvidence, *, capability="json_numeric_range"): + super().__init__(f"{capability}: runtime JSON exceeds validator support") + self.evidence = evidence + + def collect_runtime_evidence( base_url: str, plan: RuntimePlan, *, episode_timeout_s: float, request_timeout_s: float | None = None, + episodes: int = 1, + validation_token: str | None = None, + collect_tools: bool = False, + collect_tasks: bool = False, + request_telemetry: bool = True, ) -> RuntimeEvidence: """ Preserve schema and reset/step/state responses without model coercion. @@ -74,19 +100,40 @@ def collect_runtime_evidence( plan ([`~openenv.validation.runtime.contracts.RuntimePlan`]): Validated, bounded reset and action inputs. episode_timeout_s (`float`): - Deadline for the complete collection, including schema retrieval. + Deadline for each episode. The first episode's budget also covers + schema retrieval and connecting. request_timeout_s (`float`, *optional*): Optional per-operation cap. By default, each operation may use the remaining declared episode budget. + episodes (`int`, *optional*, defaults to `1`): + Run the plan this many times on the same session, resetting between + episodes. Each later episode gets a fresh deadline and trace budget + at its reset, so one episode never spends what another saved and the + collection is bounded by `episodes` single-episode budgets. + validation_token (`str`, *optional*): + Run-scoped credential to omit from evidence; also authorizes optional + telemetry when `request_telemetry` is enabled. + collect_tools (`bool`, *optional*, defaults to `False`): + Discover tools on the measured WebSocket before reset. + collect_tasks (`bool`, *optional*, defaults to `False`): + Discover the server's environment namespace and sample its task metadata. + request_telemetry (`bool`, *optional*, defaults to `True`): + Request session telemetry with the provided authorization. Disable + for scrub-only collection with the ordinary protocol byte limits. Returns: [`~openenv.validation.runtime.contracts.RuntimeEvidence`]: raw evidence. """ deadline = time.monotonic() + episode_timeout_s exchanges = [] - schema_json = reset_schema_json = None + schema_json = reset_schema_json = schema_response_json = None phase = "schema" trace_bytes = 0 + telemetry_json = None + telemetry_error = None + tools_json = tools_error = tasks_json = tasks_error = None + tools_unavailable = None + telemetry_unavailable = None server_code = None def remaining() -> float: @@ -124,23 +171,25 @@ def collect_runtime_evidence( if len(payload) + len(chunk) > MAX_MESSAGE_BYTES: raise ValueError("schema exceeds size bound") payload.extend(chunk) - schema = json.loads(payload) + raw_schema = payload.decode("utf-8") + if not validation_token: + schema_response_json = raw_schema + # Only retain credential-aware schemas after both scans and parsing + # succeed. The raw body can include values lost to duplicate keys. + if validation_token and validation_token in raw_schema: + raise ValueError("schema contains validation credentials") + schema = loads(payload) + if validation_token and validation_token in dumps(schema): + raise ValueError("schema contains validation credentials") + schema_response_json = raw_schema if not isinstance(schema, dict) or "observation" not in schema: raise ValueError("missing observation schema") - schema_json = json.dumps( - schema["observation"], - allow_nan=False, - ensure_ascii=False, - separators=(",", ":"), - ) + schema_payload = dumps(schema["observation"]) + schema_json = schema_payload if "reset_observation" in schema: - reset_schema_json = json.dumps( - schema["reset_observation"], - allow_nan=False, - ensure_ascii=False, - separators=(",", ":"), - ) + reset_schema_payload = dumps(schema["reset_observation"]) + reset_schema_json = reset_schema_payload endpoint = urlsplit(base_url) ws_url = urlunsplit( @@ -158,13 +207,182 @@ def collect_runtime_evidence( proxy=None, open_timeout=remaining(), close_timeout=1, - max_size=MAX_MESSAGE_BYTES, + max_size=( + MAX_TRACE_BYTES + if validation_token and request_telemetry + else MAX_MESSAGE_BYTES + ), max_queue=1, compression=None, ) complete = False try: + def receive_response(request): + nonlocal server_code + try: + _bounded_call( + connection, lambda: connection.send(request), remaining() + ) + except ConnectionClosed: + # Session creation can fail before the first send. recv() still + # delivers a queued error, but the failed send cannot succeed. + try: + raw = connection.recv(timeout=remaining()) + if ( + isinstance(raw, str) + and len(raw.encode()) <= MAX_TRACE_BYTES + ): + server_code = _server_error_code(json.loads(raw)) + except Exception: + # Preserve the original ConnectionClosed if diagnostics fail. + pass + raise + return connection.recv(timeout=remaining()) + + def telemetry_request(operation, data, max_bytes=MAX_TRACE_BYTES): + request = json.dumps({"type": operation, "data": data}) + raw = receive_response(request) + if not isinstance(raw, str) or len(raw.encode()) > max_bytes: + raise ValueError("invalid telemetry response") + response = loads(raw) + if not isinstance(response, dict): + raise ValueError("invalid telemetry envelope") + return response + + capability = None + if validation_token and request_telemetry: + phase = "validation_open" + try: + response = telemetry_request( + phase, {"schema_version": 1, "token": validation_token} + ) + except (ValueError, RecursionError) as exc: + # A consumed malformed reply only invalidates optional telemetry. + # Transport failure still aborts this same-session collection. + telemetry_error = f"session telemetry failed ({type(exc).__name__})" + else: + code = _server_error_code(response) + if code in { + WSErrorCode.FACTORY_ERROR, + WSErrorCode.CAPACITY_REACHED, + WSErrorCode.SESSION_ERROR, + }: + server_code = code + raise ValueError("server returned a terminal error") + data = response.get("data") + if ( + response.get("type") == "validation_open" + and isinstance(data, dict) + and data.get("schema_version") == 1 + and isinstance(data.get("capability"), str) + and 16 <= len(data["capability"]) <= 256 + ): + capability = data["capability"] + elif code == WSErrorCode.UNKNOWN_TYPE: + telemetry_unavailable = ( + "unsupported capability: session_telemetry" + ) + else: + telemetry_error = ( + "session telemetry unavailable or authorization refused" + ) + + def contains_credential(value): + pending = [value] + while pending: + child = pending.pop() + if isinstance(child, str): + if any( + secret and secret in child + for secret in (validation_token, capability) + ): + return True + elif isinstance(child, dict): + pending.extend(child.keys()) + pending.extend(child.values()) + elif isinstance(child, list): + pending.extend(child) + return False + + if collect_tools: + phase = "tools/list" + try: + response = telemetry_request( + "mcp", + { + "jsonrpc": "2.0", + "id": 1, + "method": "tools/list", + "params": {}, + }, + MAX_MESSAGE_BYTES, + ) + if contains_credential(response): + raise ValueError("discovery contains validation credentials") + rpc = response.get("data") + if _server_error_code(response) == WSErrorCode.UNKNOWN_TYPE: + tools_unavailable = "unsupported capability: tool_discovery" + else: + if ( + response.get("type") != "mcp" + or not isinstance(rpc, dict) + or rpc.get("jsonrpc") != "2.0" + or type(rpc.get("id")) is not int + or rpc["id"] != 1 + ): + raise ValueError("invalid tool discovery envelope") + error = rpc.get("error") + if ( + isinstance(error, dict) + and type(error.get("code")) is int + and isinstance(error.get("message"), str) + and rpc.get("result") is None + and ( + error["code"] == -32601 + or ( + # Legacy non-MCP tools/list used INTERNAL_ERROR. + error["code"] == -32603 + and error["message"] + == "Environment does not support MCP" + and error.get("data") is None + ) + ) + ): + tools_unavailable = "unsupported capability: tool_discovery" + else: + if ( + error is not None + or not isinstance(rpc.get("result"), dict) + or not isinstance(rpc["result"].get("tools"), list) + ): + raise ValueError("invalid tool discovery response") + discovered = dumps(rpc["result"], ensure_ascii=False) + if len(discovered.encode()) > MAX_MESSAGE_BYTES: + raise ValueError("discovery exceeds size bound") + tools_json = discovered + except Exception as exc: + tools_error = f"tool discovery failed ({type(exc).__name__})" + + if collect_tasks: + phase = "tasks" + try: + discovered, tasks_error = collect_task_evidence( + base_url, + deadline=deadline, + request_timeout_s=request_timeout_s, + ) + if discovered is not None: + if contains_credential(discovered) or contains_credential( + json.loads(discovered) + ): + raise ValueError( + "discovery contains validation credentials" + ) + tasks_json = discovered + except Exception as exc: + tasks_error = f"task discovery failed ({type(exc).__name__})" + def exchange(operation: str, data: dict | None = None) -> dict: nonlocal phase, trace_bytes, server_code phase = operation @@ -172,17 +390,29 @@ def collect_runtime_evidence( if data is not None: request["data"] = data request_json = json.dumps(request, allow_nan=False) - _bounded_call( - connection, lambda: connection.send(request_json), remaining() - ) - raw = connection.recv(timeout=remaining()) + raw = receive_response(request_json) if not isinstance(raw, str): raise ValueError("binary response is not the JSON protocol") + if len(raw.encode("utf-8")) > MAX_MESSAGE_BYTES: + raise ValueError("response exceeds size bound") trace_bytes += len(raw.encode("utf-8")) + len( request_json.encode("utf-8") ) if trace_bytes > MAX_TRACE_BYTES: - raise ValueError("trace exceeds total size bound") + raise ValueError("episode trace exceeds size bound") + # Subjects can echo the authorization into arbitrary JSON fields. + # Check decoded values as well as raw text (which may be malformed). + if contains_credential(raw): + raise ValueError("response contains validation credentials") + try: + parsed = json.loads(raw) + except (ValueError, RecursionError): + # Malformed JSON cannot be checked for escaped credentials. + if validation_token: + raise + parsed = None + if contains_credential(parsed): + raise ValueError("response contains validation credentials") exchanges.append( WireExchange( operation=operation, @@ -192,14 +422,7 @@ def collect_runtime_evidence( ) response = json.loads(raw) if isinstance(response, dict) and response.get("type") == "error": - data = response.get("data") - code = data.get("code") if isinstance(data, dict) else None - # Only protocol constants are safe diagnostics; never echo an - # arbitrary server message or a subject-defined error code. - if isinstance(code, str) and code in { - item.value for item in WSErrorCode - }: - server_code = code + server_code = _server_error_code(response) raise ValueError("server returned an error") expected = "state" if operation == "state" else "observation" if ( @@ -212,13 +435,35 @@ def collect_runtime_evidence( reset = dict(plan.reset.options) reset.update(seed=plan.reset.seed, episode_id=plan.reset.episode_id) - observation = exchange("reset", reset) - exchange("state") - for action in plan.actions: - if observation.get("done") is True: - break - observation = exchange("step", action) + for episode in range(episodes): + if episode: + deadline = time.monotonic() + episode_timeout_s + trace_bytes = 0 + observation = exchange("reset", reset) exchange("state") + for action in plan.actions: + if observation.get("done") is True: + break + observation = exchange("step", action) + exchange("state") + if capability: + phase = "validation_read" + try: + response = telemetry_request( + phase, {"schema_version": 1, "capability": capability} + ) + if response.get("type") != "validation" or not isinstance( + response.get("data"), dict + ): + raise ValueError("invalid telemetry envelope") + if contains_credential(response["data"]): + raise ValueError("telemetry contains validation credentials") + snapshot = dumps(response["data"], ensure_ascii=False) + if len(snapshot.encode("utf-8")) > MAX_TRACE_BYTES: + raise ValueError("telemetry exceeds size bound") + telemetry_json = snapshot + except Exception as exc: + telemetry_error = f"session telemetry failed ({type(exc).__name__})" complete = True finally: # Teardown is best effort and cannot replace an in-episode failure @@ -239,6 +484,15 @@ def collect_runtime_evidence( return RuntimeEvidence( exchanges=tuple(exchanges), observation_schema_json=schema_json, + schema_response_json=schema_response_json, + telemetry_json=telemetry_json, + telemetry_error=telemetry_error, + tools_json=tools_json, + tools_error=tools_error, + tools_unavailable=tools_unavailable, + tasks_json=tasks_json, + tasks_error=tasks_error, + telemetry_unavailable=telemetry_unavailable, reset_observation_schema_json=reset_schema_json, ) except KeyboardInterrupt: @@ -246,17 +500,58 @@ def collect_runtime_evidence( RuntimeEvidence( exchanges=tuple(exchanges), observation_schema_json=schema_json, + schema_response_json=schema_response_json, reset_observation_schema_json=reset_schema_json, failure_phase=phase, failure_reason=f"{phase} failed (KeyboardInterrupt)", + telemetry_json=telemetry_json, + telemetry_error=telemetry_error, + tools_json=tools_json, + tools_error=tools_error, + tools_unavailable=tools_unavailable, + tasks_json=tasks_json, + tasks_error=tasks_error, + telemetry_unavailable=telemetry_unavailable, ) ) from None + except (ArithmeticError, RecursionError) as exc: + capability = ( + "json_numeric_range" if isinstance(exc, ArithmeticError) else "json_depth" + ) + raise RuntimeCollectionUnsupported( + RuntimeEvidence( + exchanges=tuple(exchanges), + observation_schema_json=schema_json, + reset_observation_schema_json=reset_schema_json, + schema_response_json=schema_response_json, + failure_phase=phase, + failure_reason=f"{phase} JSON exceeds validator support ({capability})", + telemetry_json=telemetry_json, + telemetry_error=telemetry_error, + tools_json=tools_json, + tools_error=tools_error, + tools_unavailable=tools_unavailable, + tasks_json=tasks_json, + tasks_error=tasks_error, + telemetry_unavailable=telemetry_unavailable, + ), + capability=capability, + ) from None except Exception as exc: # Exception text may include submitted payloads or URL credentials. return RuntimeEvidence( exchanges=tuple(exchanges), observation_schema_json=schema_json, + schema_response_json=schema_response_json, reset_observation_schema_json=reset_schema_json, failure_phase=phase, failure_reason=f"{phase} failed ({server_code or type(exc).__name__})", + telemetry_json=telemetry_json, + telemetry_error=telemetry_error, + tools_json=tools_json, + tools_error=tools_error, + tools_unavailable=tools_unavailable, + tasks_json=tasks_json, + tasks_error=tasks_error, + telemetry_unavailable=telemetry_unavailable, ) diff --git a/src/core/openenv/validation/runtime/contracts.py b/src/core/openenv/validation/runtime/contracts.py index 8f3e6d97a8d54fe9dfb6c0930535bb53f0c9186a..478ba53ace7ca43bde3fc4e588febd431f0594d3 100644 --- a/src/core/openenv/validation/runtime/contracts.py +++ b/src/core/openenv/validation/runtime/contracts.py @@ -4,6 +4,7 @@ import json import math import re from dataclasses import dataclass +from fractions import Fraction from pathlib import Path from typing import Any, Literal @@ -265,15 +266,54 @@ class RuntimeEvidence: Collector phase that failed; a truncated transcript cannot pass silently. failure_reason (`str`, *optional*): Credential-safe explanation of the collection failure. + telemetry_json (`str`, *optional*): + Subject-emitted session snapshot, independent of the wire transcript. + telemetry_error (`str`, *optional*): + Bounded telemetry failure without invalidating completed wire evidence. + tools_json (`str`, *optional*): + Raw tools/list result from the measured WebSocket session. + tools_unavailable (`str`, *optional*): + Named capability absent from a subject that explicitly rejects discovery. + tools_error (`str`, *optional*): + Sanitized tool-discovery failure, distinct from a successful empty list. + tasks_json (`str`, *optional*): + Task split descriptors, counts and bounded item samples. + tasks_error (`str`, *optional*): + Sanitized task-discovery failure, independent of tool discovery. + telemetry_unavailable (`str`, *optional*): + Named capability absent from a subject that explicitly rejects telemetry. reset_observation_schema_json (`str`, *optional*): Explicit `/schema` reset_observation value; absent means use the step schema. + schema_response_json (`str`, *optional*): + Complete bounded `/schema` response, including action, state and reset inputs. """ exchanges: tuple[WireExchange, ...] = () observation_schema_json: str | None = None failure_phase: str | None = None failure_reason: str | None = None + telemetry_json: str | None = None + telemetry_error: str | None = None + telemetry_unavailable: str | None = None + replays: tuple["ReplayEvidence", ...] = () + replay_failure_reason: str | None = None + tools_json: str | None = None + tools_error: str | None = None + tools_unavailable: str | None = None + tasks_json: str | None = None + tasks_error: str | None = None reset_observation_schema_json: str | None = None + schema_response_json: str | None = None + + +@dataclass(frozen=True) +class ReplayEvidence: + """A fresh replay and, for containers, inspected identity and cleanup evidence.""" + + scope: Literal["session", "container", "seed"] + evidence: RuntimeEvidence + provider_json: str | None = None + cleanup_complete: bool | None = None class ProbeOutcome(BaseModel): @@ -320,7 +360,7 @@ class NamespaceEvidence(BaseModel): Attributes: interfaces (`list[str]`): - Interface names in the namespace. + Names of the interfaces that are up in the namespace. default_route (`bool`): Whether an IPv4 default route exists. ipv6_non_loopback (`int`): @@ -361,3 +401,340 @@ class NetworkEvidence(BaseModel): subject_network_mode: str namespace: NamespaceEvidence probes: list[NetworkProbe] + + +class LaunchIsolation(BaseModel): + """ + Isolation settings inspected from outside the subject. + + Attributes: + privileged (`bool`): + Whether the subject runs privileged. + host_namespaces (`list[str]`): + Namespaces shared with the host, e.g. `"pid"` or `"network"`. + cap_add (`list[str]`): + Linux capabilities added to the launch. + devices (`list[str]`): + Host devices passed into the subject. + unconfined (`list[str]`): + Security options that disable a confinement profile. + """ + + model_config = ConfigDict(extra="forbid", frozen=True) + + privileged: bool + host_namespaces: list[str] + cap_add: list[str] + devices: list[str] + unconfined: list[str] + + +class ProcessIdentity(BaseModel): + """ + Identity of one subject process, read from `/proc//status`. + + Attributes: + pid (`int`): + Process ID inside the subject's PID namespace. + name (`str`): + Process name, for diagnostics only. + uids (`list[int]`): + Real, effective, saved and filesystem user IDs. + cap_eff (`int`): + Effective capability bit set. + no_new_privs (`bool`): + Whether the process can gain no new privileges. + seccomp (`int`): + Seccomp mode; `0` means disabled. + """ + + model_config = ConfigDict(extra="forbid", frozen=True) + + pid: int = Field(ge=1) + name: str = Field(max_length=64) + uids: list[int] = Field(min_length=1, max_length=4) + cap_eff: int = Field(ge=0) + no_new_privs: bool + seccomp: int = Field(ge=0) + + +class MountRecord(BaseModel): + """ + One mount in the subject's mount namespace. + + The mounts that are not read-only are the subject's complete writable-filesystem + inventory. + + Attributes: + mount_point (`str`): + Path inside the subject. + fstype (`str`): + Filesystem type. + device (`str`): + `major:minor` of the mounted filesystem; bind mounts of one filesystem + share it. + read_only (`bool`): + Whether the mount or its filesystem is read-only. + size_bytes (`int`, *optional*): + Capacity of the mounted filesystem from `statvfs`. `None` when unknown, + including kernel pseudo-filesystems and unbounded tmpfs, which report no + capacity. + """ + + model_config = ConfigDict(extra="forbid", frozen=True) + + mount_point: str = Field(max_length=4096) + fstype: str = Field(max_length=64) + device: str = Field(pattern=r"^\d+:\d+$") + read_only: bool + size_bytes: int | None = Field(ge=1) + + +class DeviceStorage(BaseModel): + """ + Subject storage access on an otherwise exempt device filesystem. + + Attributes: + complete (`bool`): + Whether all accessible directories and regular files were inventoried. + writable (`bool`): + Whether the subject could create a file or open a regular file for writing. + Positive evidence is retained even when enumeration is incomplete. + """ + + model_config = ConfigDict(extra="forbid", frozen=True) + + complete: bool + writable: bool + + +class ContainmentEvidence(BaseModel): + """ + Provider-neutral evidence for `runtime.host_containment`. + + Attributes: + schema_version (`int`): + Evidence format version. + launch ([`~openenv.validation.runtime.contracts.LaunchIsolation`]): + Settings inspected from outside the subject. + processes (`list[ProcessIdentity]`): + Every process measured in the subject's PID namespace. + mounts (`list[MountRecord]`): + The subject's complete mount table; empty if it could not be read. + allotted (`list[str]`): + Writable roots the provider grants the subject. + allotted_writable (`list[str]`): + Allotted roots the probe could write as the subject's identity. + writable (`list[str]`): + Bounded diagnostic sample of paths outside the allotted roots where + the subject could create a file or open a regular file for writing. + device_storage (`dict[str, DeviceStorage]`): + Bounded directory and regular-file inventories keyed by device identity. + Missing or incomplete inventories cannot establish storage denial. + """ + + model_config = ConfigDict(extra="forbid", frozen=True) + + schema_version: Literal[1] = 1 + launch: LaunchIsolation + processes: list[ProcessIdentity] = Field(max_length=1024) + mounts: list[MountRecord] = Field(max_length=1024) + allotted: list[str] + allotted_writable: list[str] + writable: list[str] = Field(max_length=1024) + device_storage: dict[str, DeviceStorage] = Field( + default_factory=dict, max_length=1024 + ) + + +class CgroupLimits(BaseModel): + """ + Effective cgroup v2 limits read from inside the subject. + + `None` means unlimited unless the field is listed in `unavailable`. + + Attributes: + memory_max (`int`, *optional*): + `memory.max` in bytes. + swap_max (`int`, *optional*): + `memory.swap.max` in bytes. + cpu_quota (`int`, *optional*): + CPU time allowed per period, in microseconds. + cpu_period (`int`): + CPU period in microseconds. + pids_max (`int`, *optional*): + `pids.max`. + unavailable (`list[str]`): + Fields whose cgroup files could not be read independently. + """ + + model_config = ConfigDict(extra="forbid", frozen=True) + + memory_max: int | None = Field(ge=0) + swap_max: int | None = Field(ge=0) + cpu_quota: int | None = Field(ge=0) + cpu_period: int | None = Field(gt=0) + pids_max: int | None = Field(ge=0) + unavailable: list[str] = Field(default_factory=list) + + +class WritableRoot(BaseModel): + """ + Capacity of one writable root, from `statvfs` inside the subject. + + Attributes: + path (`str`): + Path inside the subject. + size_bytes (`int`): + Total capacity of the filesystem mounted there. + """ + + model_config = ConfigDict(extra="forbid", frozen=True) + + path: str + size_bytes: int = Field(ge=0) + + +class QualificationProbe(BaseModel): + """ + One bounded stress probe, run in a disposable subject from the same image. + + Attributes: + kind (`str`): + `"memory"`, `"pids"`, `"disk"` or `"exec_timeout"`. + result (`str`): + `"contained"` when the limit stopped the probe, `"escaped"` when it + exceeded its budget, `"inconclusive"` otherwise. + started (`bool`): + Whether the stimulus emitted its fresh start marker, or a trusted observer + witnessed the exec-timeout stimulus with a live descendant. + reason (`str`, *optional*): + Trusted corroboration of the outcome. + counter_before (`int`, *optional*): + Cgroup event count before the stimulus. + counter_after (`int`, *optional*): + Cgroup event count after the stimulus. + oom_killed (`bool`): + Whether Docker recorded a container OOM kill. + free_bytes_before (`dict[str, int or None]`): + Trusted free capacity before the disk stimulus, per allotted root. + free_bytes (`dict[str, int or None]`): + Trusted free capacity after the disk stimulus, per allotted root. + parent_pid (`int`, *optional*): + Stimulus PID observed by the trusted helper before timeout. + descendant_pid (`int`, *optional*): + Live child whose kernel PPID and nonce-bearing command matched the stimulus. + removed (`bool`): + Whether timeout cleanup independently verified container removal. + """ + + model_config = ConfigDict(extra="forbid", frozen=True) + + kind: Literal["memory", "pids", "disk", "exec_timeout"] + result: Literal["contained", "escaped", "inconclusive"] + started: bool = False + reason: str | None = Field(default=None, max_length=256) + counter_before: int | None = Field(default=None, ge=0) + counter_after: int | None = Field(default=None, ge=0) + oom_killed: bool = False + free_bytes_before: dict[str, int | None] = Field(default_factory=dict) + free_bytes: dict[str, int | None] = Field(default_factory=dict) + parent_pid: int | None = Field(default=None, gt=0) + descendant_pid: int | None = Field(default=None, gt=0) + removed: bool = False + + +class ResourceEvidence(BaseModel): + """ + Provider-neutral evidence for `runtime.resource_bounds`. + + Attributes: + schema_version (`int`): + Evidence format version. + cgroup ([`~openenv.validation.runtime.contracts.CgroupLimits`], *optional*): + Limits measured in the subject; `None` if they could not be read. + writable (`list[WritableRoot]`): + Capacity of every writable root. + qualification (`list[QualificationProbe]`): + Enforcement measured by stress probes. + containment ([`~openenv.validation.runtime.contracts.ContainmentEvidence`], *optional*): + Complete filesystem inventory and write controls for storage accounting. + """ + + model_config = ConfigDict(extra="forbid", frozen=True) + + schema_version: Literal[1] = 1 + cgroup: CgroupLimits | None + writable: list[WritableRoot] + qualification: list[QualificationProbe] + containment: ContainmentEvidence | None = None + + +@dataclass(frozen=True) +class IsolationEvidence: + """ + Raw evidence for `runtime.episode_isolation`, collected on the running subject. + + Attributes: + sequential ([`~openenv.validation.runtime.contracts.RuntimeEvidence`]): + The plan run twice on one session: episode A, then a reset into B. + fresh ([`~openenv.validation.runtime.contracts.RuntimeEvidence`]): + The plan run once on a new session, as the reference for B. + """ + + sequential: RuntimeEvidence + fresh: RuntimeEvidence + + +@dataclass(frozen=True) +class OracleEvidence: + """ + Rewards for the Level 3 checks, measured by the execution binding. + + The binding runs every episode in a fresh subject from one immutable image and + selects the graded reward. Values are exact rationals parsed from the raw + verifier output. + + Attributes: + floor (`Fraction`): + Reward of the do-nothing episode. + oracle (`tuple[Fraction, ...]`): + Reward of each oracle run, in run order. + oracle_exit_codes (`tuple[int, ...]`): + Exit code of each oracle run, in run order. + canaries (`tuple[tuple[str, Fraction], ...]`, *optional*): + Name and reward of each declared canary run. + """ + + floor: Fraction + oracle: tuple[Fraction, ...] + oracle_exit_codes: tuple[int, ...] + canaries: tuple[tuple[str, Fraction], ...] = () + + +@dataclass(frozen=True) +class HttpProbe: + """ + One bounded HTTP GET against the subject's control endpoint. + + Attributes: + path (`str`): + Requested path. + status (`int`, *optional*): + Status of the last response, after same-origin redirects; `None` when no + response arrived. + body (`bytes`): + Bounded body of the final response, whatever its status. + failure (`str`, *optional*): + Why the probe is incomplete: a transport error, the deadline, a compressed + or oversized body, or a redirect that was not followed. + redirect_bodies (`tuple[bytes, ...]`): + Prior redirect response bodies, each retained separately for JSON decoding. + All bodies share the probe byte budget. + """ + + path: str + status: int | None + body: bytes = b"" + failure: str | None = None + redirect_bodies: tuple[bytes, ...] = () diff --git a/src/core/openenv/validation/runtime/discovery.py b/src/core/openenv/validation/runtime/discovery.py new file mode 100644 index 0000000000000000000000000000000000000000..0b792e07bf09c6554ca6621d4539958791321aa7 --- /dev/null +++ b/src/core/openenv/validation/runtime/discovery.py @@ -0,0 +1,128 @@ +"""Bounded task metadata sampling through the production task API.""" + +import json +import time +from urllib.parse import quote + +import httpx + +from .transport import http_deadline + +MAX_TASK_SPLITS = 64 +MAX_RESPONSE_BYTES = 1024 * 1024 +MAX_DISCOVERY_BYTES = 8 * 1024 * 1024 + + +def collect_task_evidence(base_url, *, deadline, request_timeout_s=None): + """Return raw counts and at most two task specs per split, never a full listing. + + ``deadline`` is the collector's absolute monotonic episode deadline. Optional + ``request_timeout_s`` may further cap each request. Errors are sanitized; + a failed/unsupported endpoint never becomes an empty success. + Task metadata routes intentionally use independent environment instances. + """ + total_bytes = 0 + + def remaining(): + budget = deadline - time.monotonic() + if request_timeout_s is not None: + budget = min(request_timeout_s, budget) + if budget <= 0: + raise TimeoutError("task discovery deadline exceeded") + return budget + + try: + prefix = base_url.rstrip("/") + with httpx.Client( + trust_env=False, + follow_redirects=False, + limits=httpx.Limits(max_keepalive_connections=0), + ) as client: + + def request(method, route, payload=None): + nonlocal total_bytes + # Each request opens a transport for its deadline watchdog; + # pooled connections do not emit the connection trace event. + with ( + http_deadline(remaining()) as extensions, + client.stream( + method, + prefix + route, + json=payload, + timeout=remaining(), + headers={"Accept-Encoding": "identity"}, + extensions=extensions, + ) as response, + ): + response.raise_for_status() + if ( + response.headers.get("Content-Encoding", "identity") + .strip() + .lower() + != "identity" + ): + raise ValueError("compressed discovery response") + body = bytearray() + for chunk in response.iter_bytes(): + remaining() + total_bytes += len(chunk) + if ( + len(body) + len(chunk) > MAX_RESPONSE_BYTES + or total_bytes > MAX_DISCOVERY_BYTES + ): + raise ValueError("task discovery exceeds byte budget") + body.extend(chunk) + return json.loads(body) + + environments = request("GET", "/list_environments") + if ( + not isinstance(environments, list) + or len(environments) != 1 + or not isinstance(environments[0], str) + or not environments[0] + or environments[0] in {".", ".."} + or "/" in environments[0] + or "\\" in environments[0] + ): + raise ValueError("expected one valid task environment namespace") + prefix += "/" + quote(environments[0], safe="") + splits = request("GET", "/splits") + if not isinstance(splits, list) or len(splits) > MAX_TASK_SPLITS: + raise ValueError("invalid or excessive splits") + counts, previews = {}, {} + for split in splits: + name = split["name"] + if not isinstance(name, str) or not name or name in counts: + raise ValueError("invalid or duplicate split name") + count = request("POST", "/num_tasks", {"split": name})["num_tasks"] + if type(count) is not int or count < 0: + raise ValueError("invalid task count") + counts[name] = count + previews[name] = [ + request("POST", "/task", {"split": name, "index": index})["task"] + for index in range(min(2, count)) + ] + discovered = json.dumps( + { + "environments": environments, + "splits": splits, + "counts": counts, + "previews": previews, + }, + allow_nan=False, + ensure_ascii=False, + separators=(",", ":"), + ) + if len(discovered.encode()) > MAX_DISCOVERY_BYTES: + raise ValueError("task evidence exceeds byte budget") + return discovered, None + except ( + httpx.HTTPError, + httpx.InvalidURL, + OSError, + ValueError, + TypeError, + KeyError, + RecursionError, + ) as error: + return None, f"task discovery failed ({type(error).__name__})" diff --git a/src/core/openenv/validation/runtime/json_values.py b/src/core/openenv/validation/runtime/json_values.py new file mode 100644 index 0000000000000000000000000000000000000000..8881ff19d874fa8106f8bd6c3ffd4cdab5c309c9 --- /dev/null +++ b/src/core/openenv/validation/runtime/json_values.py @@ -0,0 +1,75 @@ +"""Exact JSON values for byte-bounded runtime documents and redacted bundles.""" + +import json +from decimal import Decimal + + +def loads(text, *, object_pairs_hook=None): + # Match the stdlib's BOM handling for bytes after UTF-8 text retention. + if isinstance(text, str): + text = text.removeprefix("\ufeff") + return json.loads( + text, + parse_float=Decimal, + parse_constant=Decimal, + object_pairs_hook=object_pairs_hook, + ) + + +def typed_json(value): + """Flatten values so traversal and equality do not recurse through containers.""" + result, pending = [], [value] + while pending: + child = pending.pop() + if isinstance(child, dict): + result.append((dict, len(child))) + for key in sorted(child, reverse=True): + pending.extend((child[key], key)) + elif isinstance(child, list): + result.append((list, len(child))) + pending.extend(reversed(child)) + else: + if isinstance(child, Decimal) and not child.is_finite(): + raise ValueError("non-finite JSON constant") + result.append((type(child), child)) + return tuple(result) + + +def dumps(value, *, ensure_ascii=True): + """Serialize exact JSON numbers without recursing through containers.""" + chunks, pending = [], [(False, value)] + while pending: + literal, child = pending.pop() + if literal: + chunks.append(child) + elif isinstance(child, dict): + chunks.append("{") + pending.append((True, "}")) + for index, key in reversed(list(enumerate(sorted(child)))): + pending.extend( + [ + (False, child[key]), + (True, ":"), + (True, json.dumps(key, ensure_ascii=ensure_ascii)), + ] + ) + if index: + pending.append((True, ",")) + elif isinstance(child, list): + chunks.append("[") + pending.append((True, "]")) + for index, item in reversed(list(enumerate(child))): + pending.append((False, item)) + if index: + pending.append((True, ",")) + elif isinstance(child, Decimal): + if not child.is_finite(): + raise ValueError("non-finite JSON constant") + number = str(child) + # Decimal('1') came from a decimal/exponent token, never an integer. + chunks.append( + number if "." in number or "e" in number.lower() else number + ".0" + ) + else: + chunks.append(json.dumps(child, allow_nan=False, ensure_ascii=ensure_ascii)) + return "".join(chunks) diff --git a/src/core/openenv/validation/runtime/replay.py b/src/core/openenv/validation/runtime/replay.py new file mode 100644 index 0000000000000000000000000000000000000000..8298dee07213ef07a3ffb7f56ef2f48318729fa0 --- /dev/null +++ b/src/core/openenv/validation/runtime/replay.py @@ -0,0 +1,239 @@ +"""Bounded fresh-session and independently verified fresh-container experiments.""" + +import json +import secrets +import time +import uuid +from dataclasses import replace + +from ..types import ProviderCapability +from .collector import ( + collect_runtime_evidence, + RuntimeCollectionInterrupted, + RuntimeCollectionUnsupported, +) +from .contracts import ReplayEvidence, RuntimeEvidence + +REPLAY_BUDGET_SECONDS = 300.0 +MAX_REPLAY_BYTES = 32 * 1024 * 1024 +JUDGED_REPLAYS = 20 + + +def _evidence_bytes(evidence): + return sum( + len(value.encode("utf-8")) + for value in ( + evidence.observation_schema_json or "", + evidence.reset_observation_schema_json or "", + evidence.schema_response_json or "", + evidence.telemetry_json or "", + evidence.tools_json or "", + evidence.tasks_json or "", + *( + value + for row in evidence.exchanges + for value in (row.request_json, row.response_json) + ), + ) + ) + + +def collect_replays( + provider, running, spec, plan, evidence, *, capabilities, deadline=None +): + """ + Collect the fixed replay schedule without replacing the primary transcript. + + Args: + provider (`ValidationProvider`): + Provider used for the original subject and optional fresh container. + running (`RunningSubject`): + The original subject; its lifetime remains owned by the caller. + spec (`LaunchSpec`): + Original immutable image, resource limits and explicit authorization. + plan (`RuntimePlan`): + Fixed episode identity, seed, options and public action sequence. + evidence (`RuntimeEvidence`): + Independently collected primary episode. + capabilities (`CapabilitiesSpec`): + Manifest capabilities; judged rewards require 20 identical-input samples. + deadline (`float`, *optional*): + Absolute monotonic deadline for the remaining baseline-and-replay + budget, excluding intervening independent probes. Defaults to 300 + seconds from this call; every replay collection and launch shares it. + + Returns: + `RuntimeEvidence`: the original episode plus immutable replay evidence. + """ + retained_bytes = _evidence_bytes(evidence) + budget_failure = f"total retained replay evidence exceeds {MAX_REPLAY_BYTES} bytes" + if retained_bytes > MAX_REPLAY_BYTES: + # Normal collector bounds keep a primary episode below this limit. A + # malformed oversized input must not bypass the final artifact budget. + return RuntimeEvidence( + failure_phase="replay evidence budget", + failure_reason=budget_failure, + replay_failure_reason=budget_failure, + ) + if evidence.failure_reason: + return evidence + deadline = min( + deadline if deadline is not None else float("inf"), + time.monotonic() + REPLAY_BUDGET_SECONDS, + ) + replays = [] + phase = "fresh session" + failure = None + + def remaining(): + budget = deadline - time.monotonic() + if budget <= 0: + raise TimeoutError("total replay deadline exceeded") + return budget + + def collect(target, reset_plan, token): + return collect_runtime_evidence( + target.base_url, + reset_plan, + episode_timeout_s=min(spec.resources.episode_timeout_s, remaining()), + validation_token=token, + ) + + def retain(scope, sample, **metadata): + nonlocal retained_bytes, failure + size = _evidence_bytes(sample) + if retained_bytes + size > MAX_REPLAY_BYTES: + failure = budget_failure + if scope == "container": + # Keep inspected identity and cleanup even when the transcript + # cannot be retained. An empty sample cannot pass determinism. + replays.append(ReplayEvidence(scope, RuntimeEvidence(), **metadata)) + return False + retained_bytes += size + replays.append(ReplayEvidence(scope, sample, **metadata)) + return True + + def session(scope, reset_plan): + try: + sample = collect( + running, reset_plan, spec.env_vars.get("OPENENV_VALIDATION_TOKEN") + ) + except (RuntimeCollectionInterrupted, RuntimeCollectionUnsupported) as exc: + retain(scope, exc.evidence) + raise + if not retain(scope, sample): + raise ValueError("replay evidence byte budget exceeded") + if sample.failure_reason: + raise RuntimeError("replay collection failed") + + try: + session("session", plan) + phase = "different-seed session" + changed_seed = plan.reset.model_copy( + update={"seed": (plan.reset.seed + 1) % 2**32} + ) + session("seed", plan.model_copy(update={"reset": changed_seed})) + if ProviderCapability.FRESH_CONTAINER not in provider.capabilities: + failure = "missing provider capability: fresh_container" + else: + phase = "original container inspection" + remaining() + original = running.inspect() + if ( + not isinstance(original.get("container_id"), str) + or not original["container_id"] + or original.get("image_id") != spec.image_ref + ): + raise ValueError("original container identity unavailable") + phase = "fresh container start" + fresh_spec = spec.model_copy( + update={ + "run_id": "validation-replay-" + uuid.uuid4().hex, + "startup_timeout_s": min(spec.startup_timeout_s, remaining()), + "env_vars": { + **spec.env_vars, + "OPENENV_VALIDATION_TOKEN": secrets.token_urlsafe(32), + }, + } + ) + try: + fresh = provider.start(fresh_spec) + except (Exception, KeyboardInterrupt): + # No returned handle means this layer cannot verify teardown, + # including when the provider's startup cleanup itself failed. + retain( + "container", + RuntimeEvidence( + failure_phase=phase, + failure_reason="fresh container start failed; teardown could not be confirmed", + ), + cleanup_complete=False, + ) + raise + inspection_json = None + sample = None + cleanup = False + try: + phase = "fresh container inspection" + remaining() + inspection = fresh.inspect() + inspection_json = json.dumps(inspection, allow_nan=False) + if ( + not isinstance(inspection.get("container_id"), str) + or not inspection["container_id"] + or inspection["container_id"] == original["container_id"] + or inspection.get("image_id") != spec.image_ref + ): + raise ValueError("fresh container identity did not match") + phase = "fresh container replay" + sample = collect( + fresh, plan, fresh_spec.env_vars["OPENENV_VALIDATION_TOKEN"] + ) + except (RuntimeCollectionInterrupted, RuntimeCollectionUnsupported) as exc: + sample = exc.evidence + raise + finally: + cleanup_interrupted = False + try: + fresh.stop() + cleanup = True + except KeyboardInterrupt: + cleanup_interrupted = True + failure = "fresh container cleanup interrupted" + except Exception: + failure = "fresh container cleanup failed" + if sample is None: + sample = RuntimeEvidence( + failure_phase=phase, failure_reason=f"{phase} did not complete" + ) + retained = retain( + "container", + sample, + provider_json=inspection_json, + cleanup_complete=cleanup, + ) + if cleanup_interrupted: + raise KeyboardInterrupt + if not cleanup: + raise RuntimeError("fresh container cleanup failed") + if not retained: + raise ValueError("replay evidence byte budget exceeded") + if sample.failure_reason: + raise RuntimeError("fresh container replay failed") + phase = "judged replay sampling" + if capabilities.llm_judged: + # Primary + session + container are already three identical inputs. + for _ in range(JUDGED_REPLAYS - 3): + session("session", plan) + except KeyboardInterrupt: + interrupted = replace( + evidence, + replays=tuple(replays), + replay_failure_reason=failure or f"{phase} interrupted", + ) + raise RuntimeCollectionInterrupted(interrupted) from None + except RuntimeCollectionUnsupported as exc: + failure = failure or f"{phase} unsupported ({exc})" + except Exception as exc: + failure = failure or f"{phase} failed ({type(exc).__name__})" + return replace(evidence, replays=tuple(replays), replay_failure_reason=failure) diff --git a/src/core/openenv/validation/runtime/scheduler.py b/src/core/openenv/validation/runtime/scheduler.py index 7f9cfb39acbf960bd6ff01ec59cd02e4379d8f55..5fb879927c3a7a3cfd95d6122deb64f8afd66b72 100644 --- a/src/core/openenv/validation/runtime/scheduler.py +++ b/src/core/openenv/validation/runtime/scheduler.py @@ -24,8 +24,7 @@ def order_graders(graders: list) -> list: def execute_graders(graders, subject, *, provider_capabilities=frozenset(), prior=()): - """Run independent checks despite failures, and name unmet dependencies in SKIPs.""" - results = [] + """Yield completed checks despite failures, and name unmet dependencies in SKIPs.""" outcomes = {result.check_id: result for result in prior} for grader in order_graders(graders): blocked = [ @@ -66,5 +65,4 @@ def execute_graders(graders, subject, *, provider_capabilities=frozenset(), prio duration_s=time.monotonic() - started, ) outcomes[grader.check_id] = result - results.append(result) - return results + yield result diff --git a/src/core/openenv/validation/schemas/manifest-v2.schema.json b/src/core/openenv/validation/schemas/manifest-v2.schema.json index 93525bff6eb6558a3caf8c0e482b35fa3359d3ca..541b5d8c0a663b10239b82ac17ed6221324f2f12 100644 --- a/src/core/openenv/validation/schemas/manifest-v2.schema.json +++ b/src/core/openenv/validation/schemas/manifest-v2.schema.json @@ -111,6 +111,45 @@ "title": "ExecutionDeclaration", "type": "object" }, + "HarborExecutionDeclaration": { + "additionalProperties": false, + "description": "Native process execution of a Harbor task through fresh Docker trials.", + "properties": { + "agent_boundary": { + "const": "process", + "default": "process", + "title": "Agent Boundary", + "type": "string" + }, + "contract_path": { + "const": "validation/openenv.json", + "default": "validation/openenv.json", + "title": "Contract Path", + "type": "string" + }, + "kind": { + "const": "harbor_task", + "title": "Kind", + "type": "string" + }, + "profile": { + "const": "harbor-semantic-v1", + "default": "harbor-semantic-v1", + "title": "Profile", + "type": "string" + }, + "requires_credentials": { + "default": false, + "title": "Requires Credentials", + "type": "boolean" + } + }, + "required": [ + "kind" + ], + "title": "HarborExecutionDeclaration", + "type": "object" + }, "JudgePin": { "additionalProperties": false, "description": "Pinned judge configuration. Required iff `capabilities.llm_judged`.\n\nThe pin lives in the manifest, not the rubric object: `LLMJudge.state_dict()` does\nnot serialize model/version/params, so validation checks the declared pin.", @@ -234,7 +273,7 @@ }, "RewardDeclaration": { "additionalProperties": false, - "description": "Author-declared reward contract. Graders normalize measurements against it.\n\nDeclared tolerances are bounded by the severity policy; reports carry the declared\nvalues so hubs can apply stricter ceilings.\n\nAttributes:\n range (`tuple[float, float]`):\n Declared reward range, defaults to `(0.0, 1.0)`. Must be strictly increasing.\n oracle_tolerance (`float`):\n The oracle check passes when `reward(oracle) >= max - oracle_tolerance`.\n floor_margin (`float`):\n The gap check requires `max - measured_floor >= floor_margin`.\n variance_tolerance (`float`, *optional*):\n Required iff the environment declares `llm_judged`; bounds reward variance\n for variance-mode determinism checks.", + "description": "Author-declared reward contract. Graders normalize measurements against it.\n\nDeclared tolerances are bounded by the severity policy; reports carry the declared\nvalues so hubs can apply stricter ceilings.\n\nAttributes:\n range (`tuple[float, float]`):\n Declared reward range, defaults to `(0.0, 1.0)`. Must be strictly increasing.\n oracle_tolerance (`float`):\n Fraction of the declared range allowed below the maximum.\n The oracle check requires `reward(oracle) >= max - oracle_tolerance * width`,\n where `width = max - min`.\n floor_margin (`float`):\n Fraction of the declared range required below the maximum and every oracle.\n Both `max - measured_floor` and `reward(oracle) - measured_floor` must be\n at least `floor_margin * width`.\n variance_tolerance (`float`, *optional*):\n Required iff the environment declares `llm_judged`; bounds reward variance\n for variance-mode determinism checks.", "properties": { "floor_margin": { "minimum": 0.0, @@ -398,7 +437,15 @@ "$ref": "#/$defs/CapabilitiesSpec" }, "execution": { - "$ref": "#/$defs/ExecutionDeclaration" + "anyOf": [ + { + "$ref": "#/$defs/ExecutionDeclaration" + }, + { + "$ref": "#/$defs/HarborExecutionDeclaration" + } + ], + "title": "Execution" }, "judge": { "anyOf": [ diff --git a/src/core/openenv/validation/schemas/manifest.schema.json b/src/core/openenv/validation/schemas/manifest.schema.json index d91a469c9655bf835446019da2689892d4e733fc..1c342e0342b9de9b4ec67d00fa46c0ab8bc50192 100644 --- a/src/core/openenv/validation/schemas/manifest.schema.json +++ b/src/core/openenv/validation/schemas/manifest.schema.json @@ -194,7 +194,7 @@ }, "RewardDeclaration": { "additionalProperties": false, - "description": "Author-declared reward contract. Graders normalize measurements against it.\n\nDeclared tolerances are bounded by the severity policy; reports carry the declared\nvalues so hubs can apply stricter ceilings.\n\nAttributes:\n range (`tuple[float, float]`):\n Declared reward range, defaults to `(0.0, 1.0)`. Must be strictly increasing.\n oracle_tolerance (`float`):\n The oracle check passes when `reward(oracle) >= max - oracle_tolerance`.\n floor_margin (`float`):\n The gap check requires `max - measured_floor >= floor_margin`.\n variance_tolerance (`float`, *optional*):\n Required iff the environment declares `llm_judged`; bounds reward variance\n for variance-mode determinism checks.", + "description": "Author-declared reward contract. Graders normalize measurements against it.\n\nDeclared tolerances are bounded by the severity policy; reports carry the declared\nvalues so hubs can apply stricter ceilings.\n\nAttributes:\n range (`tuple[float, float]`):\n Declared reward range, defaults to `(0.0, 1.0)`. Must be strictly increasing.\n oracle_tolerance (`float`):\n Fraction of the declared range allowed below the maximum.\n The oracle check requires `reward(oracle) >= max - oracle_tolerance * width`,\n where `width = max - min`.\n floor_margin (`float`):\n Fraction of the declared range required below the maximum and every oracle.\n Both `max - measured_floor` and `reward(oracle) - measured_floor` must be\n at least `floor_margin * width`.\n variance_tolerance (`float`, *optional*):\n Required iff the environment declares `llm_judged`; bounds reward variance\n for variance-mode determinism checks.", "properties": { "floor_margin": { "minimum": 0.0, diff --git a/src/core/openenv/validation/schemas/report-v2.schema.json b/src/core/openenv/validation/schemas/report-v2.schema.json index 4f4d16e311c9b83beca040bad5e30e0a30bd59b9..9da03461a2e8a16aaff6cf6436e6a1c3857551b4 100644 --- a/src/core/openenv/validation/schemas/report-v2.schema.json +++ b/src/core/openenv/validation/schemas/report-v2.schema.json @@ -172,6 +172,45 @@ "title": "ExecutionDeclaration", "type": "object" }, + "HarborExecutionDeclaration": { + "additionalProperties": false, + "description": "Native process execution of a Harbor task through fresh Docker trials.", + "properties": { + "agent_boundary": { + "const": "process", + "default": "process", + "title": "Agent Boundary", + "type": "string" + }, + "contract_path": { + "const": "validation/openenv.json", + "default": "validation/openenv.json", + "title": "Contract Path", + "type": "string" + }, + "kind": { + "const": "harbor_task", + "title": "Kind", + "type": "string" + }, + "profile": { + "const": "harbor-semantic-v1", + "default": "harbor-semantic-v1", + "title": "Profile", + "type": "string" + }, + "requires_credentials": { + "default": false, + "title": "Requires Credentials", + "type": "boolean" + } + }, + "required": [ + "kind" + ], + "title": "HarborExecutionDeclaration", + "type": "object" + }, "JudgePin": { "additionalProperties": false, "description": "Pinned judge configuration. Required iff `capabilities.llm_judged`.\n\nThe pin lives in the manifest, not the rubric object: `LLMJudge.state_dict()` does\nnot serialize model/version/params, so validation checks the declared pin.", @@ -328,7 +367,15 @@ "$ref": "#/$defs/CapabilitiesSpec" }, "execution": { - "$ref": "#/$defs/ExecutionDeclaration" + "anyOf": [ + { + "$ref": "#/$defs/ExecutionDeclaration" + }, + { + "$ref": "#/$defs/HarborExecutionDeclaration" + } + ], + "title": "Execution" }, "judge": { "anyOf": [ @@ -475,7 +522,7 @@ }, "RewardDeclaration": { "additionalProperties": false, - "description": "Author-declared reward contract. Graders normalize measurements against it.\n\nDeclared tolerances are bounded by the severity policy; reports carry the declared\nvalues so hubs can apply stricter ceilings.\n\nAttributes:\n range (`tuple[float, float]`):\n Declared reward range, defaults to `(0.0, 1.0)`. Must be strictly increasing.\n oracle_tolerance (`float`):\n The oracle check passes when `reward(oracle) >= max - oracle_tolerance`.\n floor_margin (`float`):\n The gap check requires `max - measured_floor >= floor_margin`.\n variance_tolerance (`float`, *optional*):\n Required iff the environment declares `llm_judged`; bounds reward variance\n for variance-mode determinism checks.", + "description": "Author-declared reward contract. Graders normalize measurements against it.\n\nDeclared tolerances are bounded by the severity policy; reports carry the declared\nvalues so hubs can apply stricter ceilings.\n\nAttributes:\n range (`tuple[float, float]`):\n Declared reward range, defaults to `(0.0, 1.0)`. Must be strictly increasing.\n oracle_tolerance (`float`):\n Fraction of the declared range allowed below the maximum.\n The oracle check requires `reward(oracle) >= max - oracle_tolerance * width`,\n where `width = max - min`.\n floor_margin (`float`):\n Fraction of the declared range required below the maximum and every oracle.\n Both `max - measured_floor` and `reward(oracle) - measured_floor` must be\n at least `floor_margin * width`.\n variance_tolerance (`float`, *optional*):\n Required iff the environment declares `llm_judged`; bounds reward variance\n for variance-mode determinism checks.", "properties": { "floor_margin": { "minimum": 0.0, diff --git a/src/core/openenv/validation/schemas/report.schema.json b/src/core/openenv/validation/schemas/report.schema.json index 104c69bd0609c8e00f46a8cab49efa3431211650..ca908b59d9394abbfeab283d38cb21980776df96 100644 --- a/src/core/openenv/validation/schemas/report.schema.json +++ b/src/core/openenv/validation/schemas/report.schema.json @@ -353,7 +353,7 @@ }, "RewardDeclaration": { "additionalProperties": false, - "description": "Author-declared reward contract. Graders normalize measurements against it.\n\nDeclared tolerances are bounded by the severity policy; reports carry the declared\nvalues so hubs can apply stricter ceilings.\n\nAttributes:\n range (`tuple[float, float]`):\n Declared reward range, defaults to `(0.0, 1.0)`. Must be strictly increasing.\n oracle_tolerance (`float`):\n The oracle check passes when `reward(oracle) >= max - oracle_tolerance`.\n floor_margin (`float`):\n The gap check requires `max - measured_floor >= floor_margin`.\n variance_tolerance (`float`, *optional*):\n Required iff the environment declares `llm_judged`; bounds reward variance\n for variance-mode determinism checks.", + "description": "Author-declared reward contract. Graders normalize measurements against it.\n\nDeclared tolerances are bounded by the severity policy; reports carry the declared\nvalues so hubs can apply stricter ceilings.\n\nAttributes:\n range (`tuple[float, float]`):\n Declared reward range, defaults to `(0.0, 1.0)`. Must be strictly increasing.\n oracle_tolerance (`float`):\n Fraction of the declared range allowed below the maximum.\n The oracle check requires `reward(oracle) >= max - oracle_tolerance * width`,\n where `width = max - min`.\n floor_margin (`float`):\n Fraction of the declared range required below the maximum and every oracle.\n Both `max - measured_floor` and `reward(oracle) - measured_floor` must be\n at least `floor_margin * width`.\n variance_tolerance (`float`, *optional*):\n Required iff the environment declares `llm_judged`; bounds reward variance\n for variance-mode determinism checks.", "properties": { "floor_margin": { "minimum": 0.0, diff --git a/src/core/openenv/validation/signature.py b/src/core/openenv/validation/signature.py index d6b9c6d15a125fb244ab2ccbc1ac8182294aea4b..80312ae5953118990a0db078faee4dad1700815e 100644 --- a/src/core/openenv/validation/signature.py +++ b/src/core/openenv/validation/signature.py @@ -6,6 +6,7 @@ from .types import SignatureKind WELL_KNOWN_FILES: dict[SignatureKind, str] = { SignatureKind.OPENENV_SERVED: "openenv.yaml", + SignatureKind.HARBOR_TASK: "task.toml", } """Formats this build can parse. Values are the enum filenames.""" diff --git a/src/core/openenv/validation/types.py b/src/core/openenv/validation/types.py index bb775596f108d79e97cfa744b4afd9db43db5ac3..0cbf0fd8e7fe3ee2f38a263ab605c8485dc73bfc 100644 --- a/src/core/openenv/validation/types.py +++ b/src/core/openenv/validation/types.py @@ -82,7 +82,10 @@ class ProviderCapability(str, Enum): """Capabilities a validation provider may declare; graders require them by name.""" NETWORK_POLICY = "network_policy" + INSPECTED_ISOLATION = "inspected_isolation" + RESOURCE_ENFORCEMENT = "resource_enforcement" EXEC = "exec" IMAGE_BUILD = "image_build" GPU = "gpu" REMOTE = "remote" + FRESH_CONTAINER = "fresh_container" diff --git a/src/core/rubrics/base.py b/src/core/rubrics/base.py index 0e2753047f755f2fcd1a5f263f3f25d5cd67b55d..276de7b3c456ed1d0c0f8b7e5831bd9bc9e1eb40 100644 --- a/src/core/rubrics/base.py +++ b/src/core/rubrics/base.py @@ -46,6 +46,7 @@ class Rubric(ABC): object.__setattr__(self, "_forward_hooks", []) object.__setattr__(self, "_forward_pre_hooks", []) object.__setattr__(self, "last_score", None) + object.__setattr__(self, "_evaluation_count", 0) def __setattr__(self, name: str, value: Any) -> None: # Auto-register child rubrics when assigned as attributes @@ -118,6 +119,7 @@ class Rubric(ABC): def _finish_forward(self, action: Any, observation: Any, result: float) -> float: """Store the result and run post-forward hooks synchronously.""" self.last_score = result + self._evaluation_count += 1 # Post-forward hooks for hook in self._forward_hooks: @@ -130,6 +132,7 @@ class Rubric(ABC): ) -> float: """Store the result and run post-forward hooks from an async call path.""" self.last_score = result + self._evaluation_count += 1 # Post-forward hooks for hook in self._forward_hooks: @@ -234,8 +237,22 @@ class Rubric(ABC): return current def reset(self) -> None: - """Reset any internal state. Override in subclasses if needed.""" - pass + """Reset internal state, including every child rubric. + + Override to clear your own state and call `super().reset()` so child + rubrics are reset too. + """ + for child in self.children(): + child.reset() + + def validation_config(self) -> Optional[Dict[str, Any]]: + """Return explicitly public configuration for authorized validation. + + Override to expose JSON configuration without credentials or runtime state. + ``None`` means configuration introspection is unavailable. Stock aggregation + containers expose their weights/threshold directly through the server. + """ + return None def state_dict(self) -> Dict[str, Any]: """Serialize rubric configuration for checkpointing.""" diff --git a/src/core/rubrics/containers.py b/src/core/rubrics/containers.py index ed796aaa1d64a425f2d1d1cf3e0206bf5e695750..17d88a8dbe934e551fef52df0f67b4e65a30d3f2 100644 --- a/src/core/rubrics/containers.py +++ b/src/core/rubrics/containers.py @@ -76,6 +76,8 @@ class Sequential(Rubric): # Pre-hooks run before any child is evaluated ran = self._run_leading_sync_pre_hooks(action, observation) + if ran < len(self._forward_pre_hooks): + return self._call_async_detected(action, observation, None, ran) # Call first rubric to see if it's async first_result = self._rubric_list[0](action, observation) @@ -85,8 +87,7 @@ class Sequential(Rubric): else: # Continue with sync path if first_result == 0.0: - self._run_forward_pre_hooks(action, observation, start=ran) - return self._finish_forward(action, observation, 0.0) + return self._finish_sync(action, observation, 0.0, ran) final_result = first_result for i, rubric in enumerate(self._rubric_list[1:], start=1): @@ -102,16 +103,21 @@ class Sequential(Rubric): ran, ) if score == 0.0: - self._run_forward_pre_hooks(action, observation, start=ran) - return self._finish_forward(action, observation, 0.0) + return self._finish_sync(action, observation, 0.0, ran) final_result = score - # All sync - check if in async context - if _in_async_context(): - return self._wrap_sync_result(action, observation, final_result, ran) - else: - self._run_forward_pre_hooks(action, observation, start=ran) - return self._finish_forward(action, observation, final_result) + return self._finish_sync(action, observation, final_result, ran) + + def _finish_sync(self, action, observation, result, ran=0): + """Finish a run where every evaluated child was sync. + + In an async context, return an awaitable even when a child stopped + the chain, so callers can always ``await`` the result. + """ + if _in_async_context(): + return self._wrap_sync_result(action, observation, result, ran) + self._run_forward_pre_hooks(action, observation, start=ran) + return self._finish_forward(action, observation, result) async def _empty_async(self, action, observation): """Async path for empty sequential.""" @@ -124,10 +130,16 @@ class Sequential(Rubric): return await self._finish_forward_async(action, observation, result) async def _call_async_detected(self, action, observation, first_coro, ran=0): - """Async path when first child is async.""" + """Async path for an async first child or pending pre-hooks.""" await self._run_forward_pre_hooks_async(action, observation, start=ran) - result = await first_coro + result = ( + self._rubric_list[0](action, observation) + if first_coro is None + else first_coro + ) + if inspect.iscoroutine(result): + result = await result if result == 0.0: return await self._finish_forward_async(action, observation, result) @@ -207,6 +219,8 @@ class Gate(Rubric): """Override to handle async child.""" # Pre-hooks run before the child is evaluated ran = self._run_leading_sync_pre_hooks(action, observation) + if ran < len(self._forward_pre_hooks): + return self._call_async(action, observation, None, ran) # Call child score = self.rubric(action, observation) @@ -224,7 +238,9 @@ class Gate(Rubric): """Async path.""" await self._run_forward_pre_hooks_async(action, observation, start=ran) - score = await score_coro + score = self.rubric(action, observation) if score_coro is None else score_coro + if inspect.iscoroutine(score): + score = await score result = 0.0 if score < self.threshold else score return await self._finish_forward_async(action, observation, result) @@ -282,6 +298,8 @@ class WeightedSum(Rubric): """Override to handle async children with parallel execution.""" # Pre-hooks run before any child is evaluated ran = self._run_leading_sync_pre_hooks(action, observation) + if ran < len(self._forward_pre_hooks): + return self._call_async(action, observation, None, ran) # Call all rubrics results = [rubric(action, observation) for rubric in self._rubric_list] @@ -304,6 +322,9 @@ class WeightedSum(Rubric): """Async path with parallel execution.""" await self._run_forward_pre_hooks_async(action, observation, start=ran) + if results is None: + results = [rubric(action, observation) for rubric in self._rubric_list] + # Separate sync and async results async_tasks = [] async_indices = [] diff --git a/src/core/rubrics/trajectory.py b/src/core/rubrics/trajectory.py index 6a62aceb5a19df77fe007d950266a58c2c3f8434..db94ee10bb4026ecc5d8caf3ab45be84bfb64c4a 100644 --- a/src/core/rubrics/trajectory.py +++ b/src/core/rubrics/trajectory.py @@ -118,6 +118,7 @@ class TrajectoryRubric(Rubric): def reset(self) -> None: """Clear accumulated trajectory. Call on env.reset().""" + super().reset() self._trajectory = [] @property diff --git a/src/core/sync_client.py b/src/core/sync_client.py index 0de088a095c6f8382bc10d6accc842ecc2350c51..4c94ce5732af67b5e405df6162a6d977e3e4c784 100644 --- a/src/core/sync_client.py +++ b/src/core/sync_client.py @@ -243,8 +243,15 @@ class SyncEnvClient(Generic[ActT, ObsT, StateT]): WebSocket can fail and is surfaced as a connection error. """ async_client = self._async._create_session_client() - client = SyncEnvClient(async_client) - client.connect() + client = async_client.sync() + try: + client.connect() + except Exception: + # No caller receives this child on failure. Release its loop here + # while preserving the connection error if cleanup also fails. + with suppress(Exception): + client.close() + raise self._child_clients.append(client) return client diff --git a/src/core/tools/git_server_client.py b/src/core/tools/git_server_client.py index b0100a444e7835784eec48478184b855feba5c7e..ea20134e225c62c86f66e0b49be11621ac0a2d50 100644 --- a/src/core/tools/git_server_client.py +++ b/src/core/tools/git_server_client.py @@ -10,6 +10,7 @@ instances share the same Gitea server but have isolated workspaces. import atexit import json import os +import re import shlex import shutil import subprocess @@ -17,7 +18,82 @@ import tempfile import time from dataclasses import dataclass from pathlib import Path -from urllib.parse import urlparse +from urllib.parse import quote, urlparse + +# Git subcommands an agent may run. Left out: those that run other programs (submodule, bisect, +# difftool, filter-branch) or read files outside the repository (hash-object, apply, am), and +# global options before the subcommand (`-c`, `-C`, `--git-dir`). +_AGENT_SUBCOMMANDS = frozenset( + { + "add", + "blame", + "branch", + "checkout", + "cherry-pick", + "commit", + "config", + "describe", + "diff", + "fetch", + "grep", + "init", + "log", + "ls-files", + "merge", + "mv", + "pull", + "push", + "rebase", + "remote", + "reset", + "restore", + "rev-parse", + "revert", + "rm", + "shortlog", + "show", + "stash", + "status", + "switch", + "tag", + } +) +# Options that run a program or read or write a path outside the repository. Git also accepts any +# unambiguous prefix of a long option, so prefixes are refused too. +_BLOCKED_LONG_OPTIONS = ( + "--config", + "--exec", + "--ext-diff", + "--extcmd", + "--file", + "--no-index", + "--open-files-in-pager", + "--output", + "--pathspec-from-file", + "--receive-pack", + "--template", + "--upload-pack", +) +_BLOCKED_SHORT_OPTIONS = "FOx" # -F , grep -O , rebase -x +_SECRET_ENV_NAME = re.compile(r"(^|_)(TOKEN|KEY|SECRET|PASSWORD)(_|$)", re.IGNORECASE) + + +def _refusal(args: list[str]) -> str | None: + """Why an agent's git arguments are refused, or `None` when they may run.""" + if not args or args[0] not in _AGENT_SUBCOMMANDS: + return f"git {args[0] if args else ''} is not available here" + if args[0] == "config" and ( + len(args) > 3 or args[1:2] not in (["--get"], ["--get-all"], ["--list"]) + ): + return "git config is not available here, except --get , --get-all and --list" + for arg in args[1:]: + name = arg.split("=", 1)[0] + if name.startswith("--") and len(name) > 2: + if any(option.startswith(name) for option in _BLOCKED_LONG_OPTIONS): + return f"{name} is not available here" + elif name.startswith("-") and set(name[1:]) & set(_BLOCKED_SHORT_OPTIONS): + return f"{name} is not available here" + return None @dataclass @@ -101,10 +177,13 @@ class GitServerClient: config_dir = Path(tempfile.mkdtemp(prefix="openenv-git-")) atexit.register(shutil.rmtree, config_dir, ignore_errors=True) - # Git credentials - git_credentials = ( - f"http://{self.username}:{self.password}@{self.domain}:{self.port}\n" - ) + # Git credentials. The entry must match the URL git is given (scheme and + # host[:port]), and the user name and password must be percent-encoded + # so characters such as "@", ":", "/" or "#" do not break the URL. + parsed = urlparse(self.gitea_url) + user = quote(self.username, safe="") + password = quote(self.password, safe="") + git_credentials = f"{parsed.scheme}://{user}:{password}@{parsed.netloc}\n" gitcreds_path = config_dir / "git-credentials" gitcreds_path.write_text(git_credentials) gitcreds_path.chmod(0o600) @@ -121,7 +200,12 @@ class GitServerClient: gitconfig_path = config_dir / "gitconfig" gitconfig_path.write_text(git_config) - self._git_env = {**os.environ, "GIT_CONFIG_GLOBAL": str(gitconfig_path)} + # Agents run git in this environment, so it carries no credentials of the server. + self._git_env = { + **{k: v for k, v in os.environ.items() if not _SECRET_ENV_NAME.search(k)}, + "GIT_CONFIG_GLOBAL": str(gitconfig_path), + "GIT_ALLOW_PROTOCOL": "http:https", + } def wait_for_ready(self, timeout: int = 30) -> bool: """ @@ -219,7 +303,10 @@ class GitServerClient: raise RuntimeError("Gitea server is not ready") target_dir = target_dir or repo_name - target_path = self.workspace_dir / target_dir + workspace = self.workspace_dir.resolve() + target_path = (workspace / target_dir).resolve() + if target_path == workspace or not target_path.is_relative_to(workspace): + raise ValueError(f"target_dir {target_dir!r} is outside the workspace") # Remove existing directory if present if target_path.exists(): @@ -349,14 +436,19 @@ class GitServerClient: Returns: `tuple` of (exit_code, stdout, stderr). """ - work_path = ( - self.workspace_dir / working_dir if working_dir else self.workspace_dir - ) + workspace = self.workspace_dir.resolve() + work_path = (workspace / working_dir).resolve() + if not work_path.is_relative_to(workspace): + return (1, "", f"working_dir {working_dir!r} is outside the workspace") if not work_path.exists(): return (1, "", f"Working directory does not exist: {work_path}") - cmd_parts = ["git"] + shlex.split(command) + args = shlex.split(command) + refusal = _refusal(args) + if refusal: + return (1, "", refusal) + cmd_parts = ["git"] + args result = subprocess.run( cmd_parts, diff --git a/src/core/tools/local_python_executor.py b/src/core/tools/local_python_executor.py index ac73730da739f2f042bf184b5452f9ef2bfa4a97..0d5e5762e826482acb8acbcaf4ade12fd0b192f1 100644 --- a/src/core/tools/local_python_executor.py +++ b/src/core/tools/local_python_executor.py @@ -35,6 +35,12 @@ class PyExecutor: LocalPythonExecutor that can be used by the executed code to format exceptions and to safely stringify results for improved error reporting. + + LocalPythonExecutor is an interpreter that restricts imports and + attributes, not a sandbox: the code runs in the current process and can + reach what that process holds. Run model code with it in a separate + process that has no secrets (environment variables, tokens in memory), + as `coding_env` does with one worker process per session. """ def __init__(self, additional_imports: list[str] | None = None): diff --git a/src/core/utils.py b/src/core/utils.py index 70c14ae7a49299d111ad97d74a91524361ff5c9f..9dd72c4a5bd5e3e3b0f29e588905f90182fb41a8 100644 --- a/src/core/utils.py +++ b/src/core/utils.py @@ -4,6 +4,8 @@ import asyncio import concurrent.futures +import json +import os import re @@ -71,3 +73,43 @@ def hf_space_subdomain(repo_id: str) -> str: The Space subdomain. """ return re.sub(r"[^a-z0-9]", "-", repo_id.lower()) + + +_SECRET_PATTERN = re.compile( + r"hf_[A-Za-z0-9]{30,}" + r"|sk-[A-Za-z0-9_-]{20,}" + r"|gh[pousr]_[A-Za-z0-9]{30,}|github_pat_[A-Za-z0-9_]{30,}" + r"|(?:AKIA|ASIA)[A-Z0-9]{16}" + r"|-----BEGIN [A-Z ]*PRIVATE KEY-----.*?-----END [A-Z ]*PRIVATE KEY-----", + re.DOTALL, +) +_SECRET_ENV_NAME = re.compile(r"(^|_)(TOKEN|KEY|SECRET|PASSWORD)(_|$)", re.IGNORECASE) + + +def redact_secrets(text: str) -> tuple[str, int]: + """ + Replace credentials in `text` with ``. + + Covers Hugging Face, OpenAI/Anthropic, GitHub and AWS keys, private key blocks, and the value of + every environment variable of this process with `TOKEN`, `KEY`, `SECRET` or `PASSWORD` as a part + of its name (`HF_TOKEN`, `OPENAI_API_KEY`), also in its JSON-escaped form. Agent traces can hold + any of them: a model that runs `env` or reads a config file puts the value in its own output. + + Args: + text (`str`): + Text to scan. + + Returns: + `tuple[str, int]`: The redacted text and the number of secrets replaced. + """ + count = 0 + for name, value in os.environ.items(): + if not _SECRET_ENV_NAME.search(name) or len(value) < 8: + continue + # Traces are JSON, where quotes, backslashes and non-ASCII characters are escaped. The + # escaped form goes first: it can contain the raw one (a value ending in a backslash). + for form in (json.dumps(value)[1:-1], value): + count += text.count(form) + text = text.replace(form, "") + text, matches = _SECRET_PATTERN.subn("", text) + return text, count + matches diff --git a/src/openenv/auto/auto_action.py b/src/openenv/auto/auto_action.py index d093d796ea966c1144d17efe07160a38bf501af1..8b9a86b74c9f79ad520601fa77e13dd622326bca 100644 --- a/src/openenv/auto/auto_action.py +++ b/src/openenv/auto/auto_action.py @@ -89,9 +89,9 @@ class AutoAction: Args: name: Environment name or HuggingFace Hub repo ID Examples: - - "coding" / "coding-env" / "coding_env" - - "openenv/coding_env" (Hub repo ID) - - "https://huggingface.co/openenv/coding_env" (Hub URL) + - `"coding"` / `"coding-env"` / `"coding_env"` + - `"openenv/coding_env"` (Hub repo ID) + - `"https://huggingface.co/openenv/coding_env"` (Hub URL) skip_install: If True, skip package installation and return GenericAction class instead. Use this when working with GenericEnvClient to avoid installing remote packages. diff --git a/src/openenv/auto/auto_env.py b/src/openenv/auto/auto_env.py index 467af30c9c21cebc739cca90e91581f98f8dc7fc..954e0d7f4a03072185b6aadd14d55ae2935eaff8 100644 --- a/src/openenv/auto/auto_env.py +++ b/src/openenv/auto/auto_env.py @@ -518,9 +518,9 @@ class AutoEnv: Args: name: Environment name or HuggingFace Hub repo ID Examples: - - "coding" / "coding-env" / "coding_env" - - "openenv/coding_env" (Hub repo ID) - - "https://huggingface.co/openenv/coding_env" (Hub URL) + - `"coding"` / `"coding-env"` / `"coding_env"` + - `"openenv/coding_env"` (Hub repo ID) + - `"https://huggingface.co/openenv/coding_env"` (Hub URL) base_url: Optional base URL for HTTP connection docker_image: Optional Docker image name (overrides default) container_provider: Optional container provider diff --git a/src/openenv/cli/__main__.py b/src/openenv/cli/__main__.py index bdaafb09c045f43e06fa9aaf5b0e347d1e88486f..b4f32159eca5a4319019a22ab03dddecdc17b13c 100644 --- a/src/openenv/cli/__main__.py +++ b/src/openenv/cli/__main__.py @@ -51,9 +51,10 @@ app.command( name="push", help="Push an OpenEnv environment to Hugging Face Spaces or custom registry", )(push.push) -app.command(name="serve", help="Serve environments locally (TODO: Phase 4)")( - serve.serve -) +app.command( + name="serve", + help="Run an environment on the host for local development (no container isolation)", +)(serve.serve) app.command( name="fork", help="Fork (duplicate) a Hugging Face Space to your account", diff --git a/src/openenv/cli/commands/build.py b/src/openenv/cli/commands/build.py index 7b56a5eb3367d18e27ee9661f3bd14696e415673..9a9512e2c51bd12b84c6952c96d09441e21defc7 100644 --- a/src/openenv/cli/commands/build.py +++ b/src/openenv/cli/commands/build.py @@ -14,6 +14,11 @@ from typing import Annotated import typer +try: + import tomllib +except ModuleNotFoundError: + import tomli as tomllib + from .._cli_utils import console app = typer.Typer(help="Build Docker images for OpenEnv environments") @@ -96,26 +101,13 @@ def _prepare_standalone_build(env_path: Path, temp_dir: Path) -> Path: pyproject_path = build_dir / "pyproject.toml" if pyproject_path.exists(): with open(pyproject_path, "rb") as f: - try: - import tomli - - pyproject = tomli.load(f) - deps = pyproject.get("project", {}).get("dependencies", []) - - # Check if openenv dependency is declared - has_openenv = any(dep.startswith("openenv") for dep in deps) - - if not has_openenv: - console.print( - "[yellow]Warning:[/yellow] pyproject.toml doesn't list the openenv dependency", - ) - console.print( - "[yellow]You may need to add:[/yellow] openenv>=0.2.0", - ) - except ImportError: - console.print( - "[yellow]Warning:[/yellow] tomli not available, skipping dependency check", - ) + pyproject = tomllib.load(f) + deps = pyproject.get("project", {}).get("dependencies", []) + if not any(dep.startswith("openenv") for dep in deps): + console.print( + "[yellow]Warning:[/yellow] pyproject.toml doesn't list the openenv dependency", + ) + console.print("[yellow]You may need to add:[/yellow] openenv>=0.2.0") return build_dir @@ -156,45 +148,27 @@ def _prepare_inrepo_build(env_path: Path, repo_root: Path, temp_dir: Path) -> Pa pyproject_path = build_dir / "pyproject.toml" if pyproject_path.exists(): with open(pyproject_path, "rb") as f: - try: - import tomli - - pyproject = tomli.load(f) - deps = pyproject.get("project", {}).get("dependencies", []) - - # Replace OpenEnv package references with local source. - new_deps = [] - for dep in deps: - if _is_openenv_runtime_dependency(dep): - # Skip - we'll use local core - continue - new_deps.append(dep) - - # Write back with local OpenEnv reference - pyproject["project"]["dependencies"] = new_deps + [ - "openenv @ file:///app/env/openenv" - ] - - # Write updated pyproject.toml - with open(pyproject_path, "wb") as out_f: - import tomli_w - - tomli_w.dump(pyproject, out_f) - - console.print( - "[cyan]Updated pyproject.toml to use local core[/cyan]" - ) - - # Remove old lockfile since dependencies changed - lockfile = build_dir / "uv.lock" - if lockfile.exists(): - lockfile.unlink() - console.print("[cyan]Removed outdated uv.lock[/cyan]") - - except ImportError: - console.print( - "[yellow]Warning:[/yellow] tomli/tomli_w not available, using pyproject.toml as-is", - ) + pyproject = tomllib.load(f) + deps = pyproject.get("project", {}).get("dependencies", []) + pyproject["project"]["dependencies"] = [ + dep for dep in deps if not _is_openenv_runtime_dependency(dep) + ] + ["openenv @ file:///app/env/openenv"] + + try: + import tomli_w + except ImportError: + console.print( + "[yellow]Warning:[/yellow] tomli_w not available, using pyproject.toml as-is", + ) + else: + with open(pyproject_path, "wb") as out_f: + tomli_w.dump(pyproject, out_f) + console.print("[cyan]Updated pyproject.toml to use local core[/cyan]") + lockfile = build_dir / "uv.lock" + if lockfile.exists(): + lockfile.unlink() + console.print("[cyan]Removed outdated uv.lock[/cyan]") + else: console.print( "[yellow]Warning:[/yellow] OpenEnv package not found, building without it" diff --git a/src/openenv/cli/commands/harbor.py b/src/openenv/cli/commands/harbor.py index 8d509d4f661412ceeefbcb5f768c2ebf7a960774..68a20b8519f855657680d3262f88da1870e92979 100644 --- a/src/openenv/cli/commands/harbor.py +++ b/src/openenv/cli/commands/harbor.py @@ -1,9 +1,10 @@ """`openenv harbor` — run Harbor tasks with token-level capture. -Four commands, in the order you would use them: +Five commands, in the order you would use them: openenv harbor info what can this machine run right now? openenv harbor rollout --task-index 0 one rollout, end to end, no server + openenv harbor export-sft results/ rollouts as SFT rows (messages + tools) openenv harbor serve the env server, for trainers and clients openenv harbor push the same server, deployed to a Space @@ -187,6 +188,52 @@ def _hub_not_found(exc: Exception) -> bool: return getattr(response, "status_code", None) == 404 +def _check_harness(harness: str, model: str) -> dict[str, Any]: + """Construct the rollout's agent with dummy capture credentials, without setup or run.""" + import io + + result: dict[str, Any] = {"name": harness, "ok": False} + try: + # Imports, constructors and the process-env warning may print. Keep --json readable. + with ( + contextlib.redirect_stdout(io.StringIO()), + tempfile.TemporaryDirectory() as tmp, + ): + from harbor.agents.factory import AgentFactory + from openenv.harbor import seams + from openenv.harbor.rollout import build_trial_config, process_env + + seam = seams.get(harness) + url, session = "http://127.0.0.1:9", "openenv-harness-preflight" + *_, proc_env = seam.resolve(base_url=url, session=session, model=model) + config = build_trial_config( + task_dir=tmp, + harness=harness, + sandbox="docker", + intercept_url=url, + session_id=session, + model=model, + trial_name="preflight", + trials_dir=tmp, + ) + with process_env(harness, proc_env): + AgentFactory.create_agent_from_config(config.agent, logs_dir=Path(tmp)) + result.update( + ok=True, + import_path=seam.import_path, + dialect=seam.dialect, + host_side=seam.host_side, + status=seam.status, + model=config.agent.model_name, + kwargs=config.agent.kwargs, + agent_env=config.agent.env, + process_env=proc_env, + ) + except (Exception, SystemExit) as exc: # noqa: BLE001 - a failed check is report data + result["detail"] = f"{type(exc).__name__}: {exc}" + return result + + @app.command("info") def info( llm_url: Annotated[str, typer.Option("--llm-url", help=_LLM_HELP_OPTIONAL)] = "", @@ -207,6 +254,14 @@ def info( env_file: Annotated[ str, typer.Option("--env-file", help="dotenv file with provider credentials.") ] = "", + harness: Annotated[ + str, + typer.Option( + "--harness", + help="Check a seam name or trusted `module:Class` by constructing it with dummy " + "capture credentials. Runs no agent or sandbox.", + ), + ] = "", verbose: Annotated[ bool, typer.Option("--verbose", help="List every harness, not only validated ones."), @@ -228,11 +283,23 @@ def info( api_key=api_key or None, auth_header=auth_header, ) - print( - json.dumps(caps.to_dict(), indent=2) - if json_output - else caps.render(verbose=verbose) + checked = ( + _check_harness(harness, model or caps.llm.get("model") or "preflight-model") + if harness + else None ) + if json_output: + data = caps.to_dict() + if checked is not None: + data["harness"] = checked + print(json.dumps(data, indent=2)) + else: + print(caps.render(verbose=verbose)) + if checked is not None: + print("\nharness preflight (construction only; capture is untested)") + print(json.dumps(checked, indent=2)) + if checked is not None and not checked["ok"]: + raise typer.Exit(1) @app.command("rollout") @@ -272,7 +339,11 @@ def rollout( ] = "", reward_key: Annotated[ str, - typer.Option("--reward-key", help="Which reward key is the training signal."), + typer.Option( + "--reward-key", + help="Which reward key is the headline one, or a comma-separated preference " + "order (e.g. `correctness,reward`) for a dataset whose tasks write different keys.", + ), ] = "", keep_sandbox: Annotated[ bool, @@ -327,6 +398,111 @@ def rollout( raise typer.Exit(0 if all(r.ok for r in results) else 1) +def _read_results(paths: list[str]) -> list[dict[str, Any]]: + """Rollouts from `rollout --out` files, or from every `*.json` in a directory.""" + files: list[Path] = [] + for spec in paths: + path = Path(spec) + if not path.exists(): + raise typer.BadParameter(f"{spec} does not exist") + files.extend(sorted(path.glob("*.json")) if path.is_dir() else [path]) + results: list[dict[str, Any]] = [] + for file in files: + data = json.loads(file.read_text()) + items = data if isinstance(data, list) else [data] + # a directory can hold other JSON (a run summary): keep what looks like a rollout + results.extend(i for i in items if isinstance(i, dict) and "turns" in i) + return results + + +@app.command("export-sft") +def export_sft_command( + results: Annotated[ + list[str], + typer.Argument( + help="Result JSONs written by `rollout --out`, or directories of them." + ), + ], + out: Annotated[ + str, typer.Option("--out", help="JSON Lines file for the SFT rows.") + ] = "sft_rows.jsonl", + min_reward: Annotated[ + Optional[float], + typer.Option( + "--min-reward", + help="Keep only rollouts graded at least this, e.g. 1.0 for solved tasks. Unset, every rollout is kept with its reward.", + ), + ] = None, + reward_key: Annotated[ + str, + typer.Option( + "--reward-key", + help="Reward to read when the verifier reported several and none was picked at rollout time. A comma-separated list is a preference order, e.g. correctness,reward.", + ), + ] = "", + push_to: Annotated[ + str, + typer.Option("--push-to", help="Hub dataset repo to upload the rows to."), + ] = "", + private: Annotated[ + Optional[bool], + typer.Option( + "--private", + help="Create --push-to as a private dataset. Unset, the namespace's default visibility applies.", + ), + ] = None, +) -> None: + """Turn rollouts into conversational SFT rows (`messages` + `tools`), one per rollout. + + Works on evaluation rollouts against a hosted model: SFT needs the conversation, not token ids. To train on the + rows, type `messages` and `tools` with the `Json` feature of `datasets`: a schema inferred from the rows gives + every tool call the argument names of every other tool, as `None`. + """ + from openenv.core.utils import redact_secrets + from openenv.harbor.sft import export_sft + + rows, stats = export_sft( + _read_results(results), min_reward=min_reward, reward_key=reward_key + ) + # Rows hold what the agent saw and printed, which can include credentials. + text, redacted = redact_secrets("".join(json.dumps(row) + "\n" for row in rows)) + path = Path(out) + path.write_text(text) + print(f"{stats.rows} rows from {stats.rollouts} rollouts -> {path}") + if redacted: + print(f" redacted {redacted} secret(s)") + if stats.below_min_reward or stats.ungraded: + print( + f" dropped: {stats.below_min_reward} below --min-reward, {stats.ungraded} ungraded" + ) + skipped = { + "had no agent turn": stats.no_agent_turn, + "had an unusable capture": stats.capture_failed, + "ended on an empty reply": stats.empty_reply, + "held a tool call whose arguments aren't a JSON object": stats.malformed_tool_call, + } + for reason, count in skipped.items(): + if count: + print(f" {count} rollouts {reason}, skipped") + if stats.ended_on_tool_call: + print( + f" {len(stats.ended_on_tool_call)} rollouts ended right after a tool call, usually a failed model call" + f" worth rerunning: {', '.join(stats.ended_on_tool_call)}" + ) + if push_to: + from huggingface_hub import HfApi + + api = HfApi() + api.create_repo(push_to, repo_type="dataset", private=private, exist_ok=True) + api.upload_file( + path_or_fileobj=path, + path_in_repo=f"data/{path.name}", + repo_id=push_to, + repo_type="dataset", + ) + print(f"pushed to https://huggingface.co/datasets/{push_to}") + + @app.command("serve") def serve( llm_url: Annotated[str, typer.Option("--llm-url", help=_LLM_HELP)] = "", @@ -395,6 +571,16 @@ def serve( reward_key: Annotated[ str, typer.Option("--reward-key", help=_REWARD_KEY_HELP) ] = "", + allow_harness: Annotated[ + Optional[list[str]], + typer.Option( + "--allow-harness", + help=( + "Accept this `module:Class` harness in clients' rollouts. Naming a class imports " + "its module on this server, so other import paths are refused. Repeatable." + ), + ), + ] = None, ) -> None: """Serve Harbor tasks over the OpenEnv Task API and MCP. @@ -418,6 +604,8 @@ def serve( ) # The UI's laptop defaults (this machine's token, private URLs) are for a loopback-only server. os.environ["OPENENV_HARBOR_UI_HOST"] = host + if allow_harness: + os.environ["OPENENV_HARBOR_ALLOW_HARNESS"] = ",".join(allow_harness) serve_harbor( llm_url=llm_url, model=model or None, diff --git a/src/openenv/cli/commands/push.py b/src/openenv/cli/commands/push.py index 0e8abd6c4df4e259d487ab6ce4fbb74265a5ba06..735fdf732a7f931c1ebec106e87da22c54d18907 100644 --- a/src/openenv/cli/commands/push.py +++ b/src/openenv/cli/commands/push.py @@ -5,7 +5,6 @@ from __future__ import annotations import shutil -import sys import tempfile from fnmatch import fnmatch from pathlib import Path @@ -407,14 +406,14 @@ def _prepare_staging_directory( # Add base_path to existing frontmatter lines = readme_content.split("\n") new_lines = [] - _in_frontmatter = True for i, line in enumerate(lines): new_lines.append(line) if line.strip() == "---" and i > 0: # End of frontmatter, add base_path before this line if "base_path:" not in "\n".join(new_lines): new_lines.insert(-1, "base_path: /web") - _in_frontmatter = False + new_lines.extend(lines[i + 1 :]) + break readme_path.write_text("\n".join(new_lines)) else: # No frontmatter, add it @@ -682,7 +681,6 @@ def push( if no_interface and interface: console.print( "[bold red]Error:[/bold red] Cannot specify both --interface and --no-interface", - file=sys.stderr, ) raise typer.Exit(1) diff --git a/src/openenv/cli/commands/serve.py b/src/openenv/cli/commands/serve.py index fa847f8d02b0e183fc470ad40ac8689f63d13c9a..c2d0e32438dc67af9f70572e29d209a08e4dfd72 100644 --- a/src/openenv/cli/commands/serve.py +++ b/src/openenv/cli/commands/serve.py @@ -1,20 +1,20 @@ # SPDX-License-Identifier: BSD-3-Clause -"""Serve OpenEnv environments locally (TO BE IMPLEMENTED).""" +"""Serve an OpenEnv environment locally (uvicorn, from ``openenv.yaml``).""" from __future__ import annotations +import os +import sys from pathlib import Path from typing import Annotated import typer +import yaml -from .._cli_utils import console +from .._cli_utils import console, validate_env_structure -app = typer.Typer(help="Serve OpenEnv environments locally") - -@app.command() def serve( env_path: Annotated[ str | None, @@ -23,68 +23,133 @@ def serve( ), ] = None, port: Annotated[ - int, - typer.Option("--port", "-p", help="Port to serve on"), - ] = 8000, + int | None, + typer.Option( + "--port", + "-p", + help="Port to bind (default: ``port`` in openenv.yaml, else 8000)", + ), + ] = None, host: Annotated[ str, - typer.Option("--host", help="Host to bind to"), - ] = "0.0.0.0", + typer.Option("--host", help="Host interface to bind (local development only)"), + ] = "127.0.0.1", reload: Annotated[ bool, - typer.Option("--reload", help="Enable auto-reload on code changes"), + typer.Option("--reload", help="Enable autoreload (development)"), ] = False, ) -> None: """ - Serve an OpenEnv environment locally. - - TODO: This command is currently not implemented and has been deferred for later. + Run the environment FastAPI app on the host for local development. - Planned functionality: - - Run environment server locally without Docker - - Support multiple deployment modes (local, notebook, cluster) - - Auto-reload for development - - Integration with environment's [project.scripts] entry point + Uses ``openenv.yaml`` fields ``app`` (e.g. ``server.app:app``), ``port``, and + ``runtime`` (must be ``fastapi``). Matches ``uv run --project . server`` layout: + the environment directory is the working directory. Package-qualified app + paths also support the environment package and the repo's ``envs`` package. - For now, use Docker-based serving: - 1. Build the environment: openenv build - 2. Run the container: docker run -p 8000:8000 - - Or use uv directly: - uv run --project . server --port 8000 + For production or training, use Docker (``openenv build``) — this command runs + on the host for local development only. """ - console.print("[bold yellow]⚠ This command is not yet implemented[/bold yellow]\n") - - console.print( - "The [bold cyan]openenv serve[/bold cyan] command has been deferred for later." - ) - - console.print("[bold]Alternative approaches:[/bold]\n") + import uvicorn - console.print("[cyan]Option 1: Docker-based serving (recommended)[/cyan]") - console.print(" 1. Build the environment:") - console.print(" [dim]$ openenv build[/dim]") - console.print(" 2. Run the Docker container:") - console.print( - f" [dim]$ docker run -p {port}:{port} openenv-:latest[/dim]\n" + env_path_obj = ( + Path.cwd().resolve() if env_path is None else Path(env_path).resolve() ) - console.print("[cyan]Option 2: Direct execution with uv[/cyan]") - - # Determine environment path - if env_path is None: - env_path_obj = Path.cwd() - else: - env_path_obj = Path(env_path) - - # Check for openenv.yaml - openenv_yaml = env_path_obj / "openenv.yaml" - if openenv_yaml.exists(): - console.print(" From your environment directory:") - console.print(f" [dim]$ cd {env_path_obj}[/dim]") - console.print(f" [dim]$ uv run --project . server --port {port}[/dim]\n") - else: - console.print(" From an environment directory with pyproject.toml:") - console.print(f" [dim]$ uv run --project . server --port {port}[/dim]\n") - - raise typer.Exit(1) + if not env_path_obj.exists(): + typer.echo(f"Error: Path does not exist: {env_path_obj}", err=True) + raise typer.Exit(1) + + if not env_path_obj.is_dir(): + typer.echo(f"Error: Path is not a directory: {env_path_obj}", err=True) + raise typer.Exit(1) + + try: + validate_env_structure(env_path_obj) + except FileNotFoundError as exc: + raise typer.BadParameter(f"Not a valid OpenEnv environment: {exc}") from exc + + manifest_path = env_path_obj / "openenv.yaml" + try: + with manifest_path.open("r", encoding="utf-8") as handle: + manifest = yaml.safe_load(handle) + except OSError as exc: + raise typer.BadParameter(f"Failed to read openenv.yaml: {exc}") from exc + except yaml.YAMLError as exc: + raise typer.BadParameter(f"Invalid YAML in openenv.yaml: {exc}") from exc + + if not isinstance(manifest, dict): + raise typer.BadParameter("openenv.yaml must be a YAML dictionary") + + app_spec = manifest.get("app") + if not app_spec or not isinstance(app_spec, str): + raise typer.BadParameter( + "openenv.yaml must contain a string 'app' field (e.g. server.app:app)" + ) + if ":" not in app_spec: + raise typer.BadParameter( + f"openenv.yaml 'app' must look like 'module.path:attribute', got {app_spec!r}" + ) + + runtime = str(manifest.get("runtime", "fastapi")).lower() + if runtime != "fastapi": + raise typer.BadParameter( + f"openenv serve only supports runtime 'fastapi' (got {runtime!r})" + ) + + raw_port = port if port is not None else manifest.get("port", 8000) + try: + listen_port = int(raw_port) + except (TypeError, ValueError) as exc: + raise typer.BadParameter( + f"Invalid port {raw_port!r}; expected an integer" + ) from exc + if not (1 <= listen_port <= 65535): + raise typer.BadParameter( + f"Invalid port {listen_port}; expected a value between 1 and 65535" + ) + + original_path = list(sys.path) + prev_cwd = os.getcwd() + env_root = str(env_path_obj) + app_dir = env_path_obj + module_name = app_spec.split(":", 1)[0] + # Prefer a module inside the environment, even when its package name matches + # the environment directory (for example, /work/server/server/app.py). + local_module = env_path_obj.joinpath(*module_name.split(".")) + if not ( + local_module.with_suffix(".py").is_file() + or (local_module / "__init__.py").is_file() + ): + if env_path_obj.parent.name == "envs" and module_name.startswith( + f"envs.{env_path_obj.name}." + ): + app_dir = env_path_obj.parent.parent + elif module_name.startswith(f"{env_path_obj.name}."): + app_dir = env_path_obj.parent + + try: + os.chdir(env_root) + + console.print( + f"[bold green]Serving[/bold green] [cyan]{app_spec}[/cyan] on " + f"[bold]http://{host}:{listen_port}/[/bold] (cwd: {env_root})" + ) + + try: + uvicorn.run( + app_spec, + host=host, + port=listen_port, + reload=reload, + app_dir=str(app_dir), + ) + except OSError as exc: + typer.echo(f"Error: {exc}", err=True) + raise typer.Exit(1) from exc + finally: + try: + os.chdir(prev_cwd) + except OSError: + pass + sys.path[:] = original_path diff --git a/src/openenv/cli/commands/skills.py b/src/openenv/cli/commands/skills.py index 3c1c66930f4d3363d4ab4bf91fb4146bd1b2fc0b..8bb7fcd06a50ca1705da5e231af18feaf1d16408 100644 --- a/src/openenv/cli/commands/skills.py +++ b/src/openenv/cli/commands/skills.py @@ -38,7 +38,7 @@ _SKILL_TIPS = """ Use `openenv --help` for full flag reference. -Full CLI reference: https://huggingface.co/docs/openenv/reference/cli +Full CLI reference: https://openenv.github.io/OpenEnv/main/reference/cli """ CENTRAL_LOCAL = Path(".agents/skills") diff --git a/src/openenv/cli/commands/validate.py b/src/openenv/cli/commands/validate.py index 036cad3fe606d99f3d565a6ce6aa28c818bb7441..f4bcc831a77fc78ccfe9eb62da9362836b46bdb4 100644 --- a/src/openenv/cli/commands/validate.py +++ b/src/openenv/cli/commands/validate.py @@ -3,9 +3,13 @@ """OpenEnv validate command.""" import json +import shutil import signal +import tempfile import threading -from contextlib import contextmanager +from contextlib import contextmanager, ExitStack +from dataclasses import dataclass +from functools import cached_property from pathlib import Path from typing import Annotated, Any @@ -30,6 +34,39 @@ EXIT_UNSUPPORTED = 2 EXIT_INTERNAL = 3 +@dataclass +class _LazyHFSandboxProvider: + """Defer Jobs hardware preflight until the runner needs runtime capabilities.""" + + name = "hf-sandbox" + + space_id: str + revision: str + flavor: str + + @cached_property + def _provider(self): + from openenv.validation.providers.hf_sandbox import HFSandboxValidationProvider + + return HFSandboxValidationProvider( + self.space_id, self.revision, flavor=self.flavor + ) + + @property + def supported_network_modes(self): + return self._provider.supported_network_modes + + @property + def capabilities(self): + return self._provider.capabilities + + def build(self, root, execution): + return self._provider.build(root, execution) + + def start(self, spec): + return self._provider.start(spec) + + @contextmanager def _sigterm_as_interrupt(): """Treat SIGTERM like Ctrl-C so the runner cleans up its subject.""" @@ -168,15 +205,63 @@ def validate( min=0.1, ), ] = 5.0, + space: Annotated[ + str | None, + typer.Option( + "--space", + help="Validate a Hugging Face Space (e.g. openenv/echo_env) on HF Jobs", + ), + ] = None, + revision: Annotated[ + str | None, + typer.Option( + "--revision", + help="Space branch, tag or commit hash to validate (default: main)", + ), + ] = None, + flavor: Annotated[ + str, + typer.Option( + "--flavor", + help=( + "HF Jobs hardware flavor for --space or --sandbox hf-sandbox, " + "e.g. cpu-basic or t4-small" + ), + ), + ] = "cpu-basic", + sandbox: Annotated[ + str, + typer.Option( + "--sandbox", + help=( + "Where Harbor task trials run: docker (local daemon) or " + "hf-sandbox (one HF Job per trial)" + ), + ), + ] = "docker", + namespace: Annotated[ + str | None, + typer.Option( + "--namespace", + help="User or organization that owns the --sandbox hf-sandbox jobs", + ), + ] = None, ) -> None: """ Validate a local package or a running OpenEnv server. Local validation detects the package format by its well-known file (the - formats this build can parse; currently `openenv.yaml`), parses it into the + formats this build can parse: `openenv.yaml` or Harbor `task.toml`), parses it into the normalized manifest, runs the applicable graders up to the requested level, applies the severity policy, and emits a report. + Native Harbor tasks require the optional Harbor dependency and an explicit + `validation/openenv.json` contract. Fresh trials grade the oracle, the + do-nothing floor and any declared canaries under the semantic check ids. They + run on the local Docker daemon, or with `--sandbox hf-sandbox` as one Hugging + Face Job per trial from the task's digest-pinned image. Checks without an + implementation are named SKIPs, so the report is WARN at best. + Exit codes: 0 pass/warn · 1 fail · 2 unrecognized/unsupported package · 3 internal or policy error. @@ -194,8 +279,43 @@ def validate( # Probe a running server (legacy runtime probe) openenv validate --url http://localhost:8000 + + # Validate a Hub Space on HF Jobs GPU hardware + openenv validate --space openenv/echo_env --level runtime --flavor t4-small + + # Run a Harbor task's trials as HF Jobs instead of local Docker + openenv validate path/to/task --sandbox hf-sandbox --flavor cpu-upgrade ``` """ + if space is not None and (target is not None or url is not None or local): + typer.echo( + "Error: --space cannot be combined with a path, --url or --local", err=True + ) + raise typer.Exit(EXIT_FAIL) + if sandbox not in ("docker", "hf-sandbox"): + typer.echo( + f"Error: unknown sandbox {sandbox!r}; expected docker or hf-sandbox", + err=True, + ) + raise typer.Exit(EXIT_FAIL) + hf_sandbox = sandbox == "hf-sandbox" + running_url = url is not None or (target is not None and _looks_like_url(target)) + if hf_sandbox and (space is not None or running_url): + typer.echo( + "Error: --sandbox cannot be combined with --space or a running URL", + err=True, + ) + raise typer.Exit(EXIT_FAIL) + if space is None and revision is not None: + typer.echo("Error: --revision requires --space", err=True) + raise typer.Exit(EXIT_FAIL) + if space is None and not hf_sandbox and flavor != "cpu-basic": + typer.echo("Error: --flavor requires --space or --sandbox hf-sandbox", err=True) + raise typer.Exit(EXIT_FAIL) + if namespace is not None and not hf_sandbox: + typer.echo("Error: --namespace requires --sandbox hf-sandbox", err=True) + raise typer.Exit(EXIT_FAIL) + runtime_target = url if ( runtime_target is not None @@ -249,22 +369,52 @@ def validate( raise typer.Exit(EXIT_INTERNAL) package_root = Path(target) if target is not None else Path.cwd() - if not package_root.is_dir(): + if space is None and not package_root.is_dir(): typer.echo(f"Error: not a package directory: {package_root}", err=True) raise typer.Exit(EXIT_UNSUPPORTED) try: if output is not None and not output.parent.is_dir(): raise OSError("report output directory does not exist") - with _sigterm_as_interrupt(): + with ExitStack() as stack: + provider = None + if space is not None: + from huggingface_hub import HfApi, snapshot_download + + # Download and report one commit, even if a branch moves. + revision = ( + HfApi() + .space_info( + space, revision="main" if revision is None else revision + ) + .sha + ) + package_root = ( + Path(stack.enter_context(tempfile.TemporaryDirectory())) / "source" + ) + # Copy the repository snapshot out of the SDK cache, dereferencing + # its blob links without adding local_dir download metadata. + shutil.copytree( + snapshot_download(space, repo_type="space", revision=revision), + package_root, + ) + provider = _LazyHFSandboxProvider(space, revision, flavor) + stack.enter_context(_sigterm_as_interrupt()) validation_report = run_validation( package_root, max_level=_LEVELS[level], skip_build=skip_build, policy=load_policy(policy_version) if policy_version else None, + provider=provider, artifacts_dir=( output.parent / (output.stem + ".artifacts") if output else None ), + report_target=f"spaces/{space}@{revision}" + if space is not None + else None, + sandbox=sandbox, + flavor=flavor, + namespace=namespace, ) report_json = write_report(validation_report, output) except (SignatureError, UnsupportedPackageError) as exc: diff --git a/src/openenv/cli/importers/__init__.py b/src/openenv/cli/importers/__init__.py index 9519278cfd4ace6e172fe9226fa4df37049663a1..ba216e89716a07224f4d2be8aeccda5385fed726 100644 --- a/src/openenv/cli/importers/__init__.py +++ b/src/openenv/cli/importers/__init__.py @@ -1,12 +1,14 @@ """Deterministic source importers for OpenEnv environments.""" +from .agentenv import AgentEnvImporter from .base import DetectedEnvironment, EnvironmentImporter, ImporterRegistry from .ors import ORSImporter from .verifiers import VerifiersImporter -DEFAULT_IMPORTERS = [ORSImporter(), VerifiersImporter()] +DEFAULT_IMPORTERS = [ORSImporter(), VerifiersImporter(), AgentEnvImporter()] __all__ = [ + "AgentEnvImporter", "DEFAULT_IMPORTERS", "DetectedEnvironment", "EnvironmentImporter", diff --git a/src/openenv/cli/importers/agentenv.py b/src/openenv/cli/importers/agentenv.py new file mode 100644 index 0000000000000000000000000000000000000000..05d8d3694b1637758d08acf85632f8fdd09e779e --- /dev/null +++ b/src/openenv/cli/importers/agentenv.py @@ -0,0 +1,163 @@ +"""AgentEnv bundle source importer.""" + +from __future__ import annotations + +import json +from pathlib import Path + +from packaging.requirements import InvalidRequirement, Requirement +from packaging.specifiers import SpecifierSet +from packaging.utils import canonicalize_name + +from .._cli_utils import console +from .base import ( + append_dependency_files, + collect_source_dependencies, + DetectedEnvironment, + iter_directories, + prepare_import_package, + render_importer_template, + write_text, +) + + +_FRAMEWORK = "agentenv-framework" +_FRAMEWORK_EXTRA = "openenv" +_FRAMEWORK_VERSION = "0.9.1366" +_FRAMEWORK_FLOOR = f">={_FRAMEWORK_VERSION}" +_ADAPTER_SOURCE = ( + "https://github.com/scaleapi/agentenv-framework/blob/" + f"v{_FRAMEWORK_VERSION}/src/agent_env/openenv" +) +_REQUIRES_PYTHON = ">=3.11.4" + + +def _is_task_file(path: Path) -> bool: + try: + steps = json.loads(path.read_text(encoding="utf-8")) + except (OSError, UnicodeDecodeError, ValueError): + return False + return ( + isinstance(steps, list) + and bool(steps) + and all( + isinstance(step, dict) + and isinstance(step.get("id"), str) + and isinstance(step.get("type"), str) + for step in steps + ) + ) + + +def detect_agentenv_bundles(source: Path) -> list[DetectedEnvironment]: + """Detect AgentEnv bundles, folders whose tasks/ holds task files, without importing source.""" + source = source.resolve() + matches: list[DetectedEnvironment] = [] + + for tasks_dir in iter_directories(source, "tasks"): + if not any(_is_task_file(path) for path in sorted(tasks_dir.glob("*.json"))): + continue + bundle = tasks_dir.parent + matches.append( + DetectedEnvironment( + source_type="agentenv", + class_name=bundle.name, + module_path="" + if bundle == source + else bundle.relative_to(source).as_posix(), + file_path=bundle, + ) + ) + + return matches + + +def _with_framework_floor(dependencies: list[str]) -> list[str]: + """The bundle's dependencies, with agentenv-framework's openenv extra at least the version that serves bundles.""" + for index, dependency in enumerate(dependencies): + try: + requirement = Requirement(dependency) + except InvalidRequirement: + continue + if canonicalize_name(requirement.name) == _FRAMEWORK: + if requirement.url is not None: + raise ValueError( + f"Cannot verify {_FRAMEWORK}{_FRAMEWORK_FLOOR} from a direct " + "reference. In the bundle's pyproject.toml or requirements.txt, " + "replace the framework direct reference with a version constraint " + f"such as {_FRAMEWORK}[{_FRAMEWORK_EXTRA}]{_FRAMEWORK_FLOOR}, " + "preserving any additional extras and environment marker." + ) + requirement.extras.add(_FRAMEWORK_EXTRA) + requirement.specifier &= SpecifierSet(_FRAMEWORK_FLOOR) + dependencies[index] = str(requirement) + return dependencies + return [*dependencies, f"{_FRAMEWORK}[{_FRAMEWORK_EXTRA}]{_FRAMEWORK_FLOOR}"] + + +class AgentEnvImporter: + """Importer for AgentEnv bundles, served by agentenv-framework's OpenEnv server.""" + + source_type = "agentenv" + + def detect(self, source: Path) -> list[DetectedEnvironment]: + return detect_agentenv_bundles(source) + + def generate( + self, + *, + source: Path, + destination: Path, + env_name: str, + detected: DetectedEnvironment, + ) -> None: + bundle = detected.file_path + dependencies = _with_framework_floor(collect_source_dependencies(bundle)) + package = prepare_import_package( + bundle, destination, env_name, vendor_dir=bundle.name + ) + client = f"{package.class_name_prefix}Env" + (destination / "server" / f"{env_name}_environment.py").unlink() + (destination / "models.py").unlink() + for name, template in ( + ("client.py", "agentenv_client.py.tpl"), + ("__init__.py", "agentenv_init.py.tpl"), + ): + write_text( + destination / name, + render_importer_template(template, env_name=env_name, client=client), + ) + write_text( + destination / "server" / "__init__.py", + f'"""{env_name} environment server: an AgentEnv bundle."""\n', + ) + write_text( + destination / "server" / "app.py", + render_importer_template( + "agentenv_app.py.tpl", bundle=json.dumps(bundle.name) + ), + ) + write_text( + destination / "README.md", + render_importer_template( + "agentenv_README.md.tpl", + env_name=env_name, + bundle=bundle.name, + framework=f"{_FRAMEWORK}[{_FRAMEWORK_EXTRA}]{_FRAMEWORK_FLOOR}", + adapter=_ADAPTER_SOURCE, + client=client, + ), + ) + console.print( + "[yellow]Warning:[/yellow] AgentEnv requires local Docker: a Docker CLI " + "and a running daemon accessible to the server for image builds and episode " + "containers. The generated server/Dockerfile does not provide this " + "runtime; openenv build / openenv push alone do not produce a working " + "deployment. See README.md for prerequisites." + ) + append_dependency_files( + destination, + env_name, + dependencies, + requires_python=_REQUIRES_PYTHON, + ) diff --git a/src/openenv/cli/importers/base.py b/src/openenv/cli/importers/base.py index f106af091ec49f087e6de0cc355e4154e209a541..ab2209b054be1e14e8e9f320a19548a2b715bacb 100644 --- a/src/openenv/cli/importers/base.py +++ b/src/openenv/cli/importers/base.py @@ -133,6 +133,14 @@ def iter_python_files(source: Path) -> list[Path]: ] +def iter_directories(source: Path, name: str) -> list[Path]: + return [ + path + for path in sorted(source.rglob(name)) + if path.is_dir() and not _is_excluded(path.relative_to(source)) + ] + + def module_path(source: Path, file_path: Path) -> str: rel = file_path.relative_to(source).with_suffix("") parts = list(rel.parts) @@ -196,6 +204,7 @@ def append_dependency_files( env_dir: Path, env_name: str, dependencies: list[str], + requires_python: str | None = None, ) -> None: requirements = env_dir / "server" / "requirements.txt" if requirements.exists(): @@ -231,6 +240,8 @@ def append_dependency_files( project_dependencies.append(dependency) existing.add(_dependency_name(dependency)) project["dependencies"] = project_dependencies + if requires_python: + project["requires-python"] = requires_python tool = data.setdefault("tool", {}) setuptools = tool.setdefault("setuptools", {}) @@ -266,7 +277,7 @@ class ImportPackageContext: def prepare_import_package( - source: Path, destination: Path, env_name: str + source: Path, destination: Path, env_name: str, vendor_dir: str | None = None ) -> ImportPackageContext: from openenv.cli.commands.init import ( _copy_template_directory, @@ -282,7 +293,7 @@ def prepare_import_package( env_name, ) - vendor_dir = safe_vendor_dir_name(source) + vendor_dir = vendor_dir or safe_vendor_dir_name(source) vendor_path = destination / "vendor" / vendor_dir copy_source_tree(source, vendor_path) ensure_vendor_package(vendor_path) diff --git a/src/openenv/cli/importers/templates/agentenv_README.md.tpl b/src/openenv/cli/importers/templates/agentenv_README.md.tpl new file mode 100644 index 0000000000000000000000000000000000000000..f2ad1c69d780a6bade33d05ae7c15a7a8d693fed --- /dev/null +++ b/src/openenv/cli/importers/templates/agentenv_README.md.tpl @@ -0,0 +1,82 @@ +# ${env_name}: AgentEnv bundle + +This package serves the vendored `${bundle}` bundle through +`agent_env.openenv.build_app`. The bundle keeps its original folder name at +`vendor/${bundle}`; the generated package name is `${env_name}`. + +## Prerequisites + +- Python >=3.11.4 and `${framework}` (declared in + `pyproject.toml` and `server/requirements.txt`). +- Local Docker: a Docker CLI and a running daemon accessible to the server. + The delegated server builds the bundle's environment images at startup and + deploys episode containers using local Docker by default. +- A self-contained bundle: tasks, environment definitions, verifiers, data and + dependencies must be included in the bundle or provided by agentenv-framework. + Only the selected bundle is vendored; external plugin registrations and files + elsewhere in the source repository are not included. + +## Run locally + +From this generated package directory, after setting up Docker: + +```bash +uv sync +MAX_CONCURRENT_ENVS=8 uv run server --host 127.0.0.1 --port 8000 +``` + +`MAX_CONCURRENT_ENVS` (default 8) caps the concurrent sessions. Each session +plays its own episode on its own deployment. + +The `server` entry point runs `server/app.py`, which passes +`vendor/${bundle}` to `build_app`. Task selection, splits, tools and rewards +are defined by the bundle and agentenv-framework. The served environment is +`agent_env.openenv`'s `AgentEnvEnvironment`; read it, and `build_app`, at the +minimum supported version: [environment.py](${adapter}/environment.py) and +[app.py](${adapter}/app.py). Follow +[AgentEnv's OpenEnv documentation](https://www.agentenvframework.com/docs/openenv) +for its API and client usage. + +## Client + +`client.py` defines `${client}`, an `MCPToolClient`: the served environment +takes OpenEnv's MCP actions (`ListToolsAction`, `CallToolAction`), which +`__init__.py` also exports. + +```python +from ${env_name} import ${client} + +async with ${client}(base_url="http://127.0.0.1:8000") as env: + await env.reset(split="all", index=0) + tools = await env.list_tools() + ended = await env.call_tool("end_turn", response="Done.") + print(ended["done"], ended["reward"]) +``` + +The tools are the bundle environment's MCP tools plus `end_turn`, which ends +the turn with its `response`. Its result carries the next turn's prompt, or, +once `done`, the task's reward. A step before `reset` raises. + +`list_tools()` discovers fresh tools by default because tools can change after +reset, `end_turn`, or a bundle tool call. `get_tool()` and `has_tool()` also use +fresh discovery. Pass `list_tools(use_cache=True)` explicitly to reuse the last +discovery result. + +## Deployment limitations + +**Warning:** `server/Dockerfile` does not provide the Docker runtime required +by the delegated server. `openenv build` / `openenv push` alone do not produce +a working deployment, including on Hugging Face Spaces. Deployment requires +separately provisioning the server's image-build and episode-container runtime; +this importer does not configure it. Review AgentEnv's runtime requirements +before choosing a deployment host. + +## Generated files + +- `server/app.py`: delegated application and local server entry point. +- `vendor/${bundle}`: the selected bundle and its data. +- `pyproject.toml`: package dependencies and the `server` entry point. +- `server/requirements.txt`: server dependencies. +- `openenv.yaml`: generated OpenEnv manifest. +- `server/Dockerfile`: shared image template with the limitation described above. +- `client.py`, `__init__.py`: the client and the MCP action types it sends. diff --git a/src/openenv/cli/importers/templates/agentenv_app.py.tpl b/src/openenv/cli/importers/templates/agentenv_app.py.tpl new file mode 100644 index 0000000000000000000000000000000000000000..4ea4d0b60089df4444676707060f901acaf2bde8 --- /dev/null +++ b/src/openenv/cli/importers/templates/agentenv_app.py.tpl @@ -0,0 +1,29 @@ +from __future__ import annotations + +import os +from pathlib import Path + +from agent_env.openenv import build_app + + +BUNDLE = Path(__file__).resolve().parents[1] / "vendor" / ${bundle} + +app = build_app( + BUNDLE, max_concurrent_envs=int(os.getenv("MAX_CONCURRENT_ENVS", "8")) +) + + +def main(): + import argparse + + import uvicorn + + parser = argparse.ArgumentParser() + parser.add_argument("--host", default="0.0.0.0") + parser.add_argument("--port", type=int, default=8000) + args = parser.parse_args() + uvicorn.run(app, host=args.host, port=args.port) + + +if __name__ == "__main__": + main() diff --git a/src/openenv/cli/importers/templates/agentenv_client.py.tpl b/src/openenv/cli/importers/templates/agentenv_client.py.tpl new file mode 100644 index 0000000000000000000000000000000000000000..c98c527b1accb2377cf2a430a4db4eb4d81b2b60 --- /dev/null +++ b/src/openenv/cli/importers/templates/agentenv_client.py.tpl @@ -0,0 +1,29 @@ +"""${env_name} client. + +The served AgentEnv bundle takes OpenEnv's MCP actions, so this client is an +``MCPToolClient``. Reset to a task, call the bundle's tools, and end each turn +with ``end_turn``. Its result carries the next turn's prompt, or once ``done`` +the task's reward: + + >>> async with ${client}(base_url="http://localhost:8000") as env: + ... await env.reset(split="all", index=0) + ... tools = await env.list_tools() + ... ended = await env.call_tool("end_turn", response="Done.") + ... print(ended["done"], ended["reward"]) +""" + +from openenv.core.env_server.mcp_types import Tool +from openenv.core.mcp_client import MCPToolClient + + +class ${client}(MCPToolClient): + """Client for the ${env_name} environment.""" + + async def list_tools(self, use_cache: bool = False) -> list[Tool]: + """Discover the current task and turn's tools. + + Args: + use_cache (`bool`, *optional*, defaults to `False`): + Set to `True` to reuse the last discovery result. + """ + return await super().list_tools(use_cache=use_cache) diff --git a/src/openenv/cli/importers/templates/agentenv_init.py.tpl b/src/openenv/cli/importers/templates/agentenv_init.py.tpl new file mode 100644 index 0000000000000000000000000000000000000000..860105f5b3a5df1b693db33e3b161969bc82565f --- /dev/null +++ b/src/openenv/cli/importers/templates/agentenv_init.py.tpl @@ -0,0 +1,7 @@ +"""${env_name} environment: an AgentEnv bundle served through agentenv-framework.""" + +from openenv.core.env_server.mcp_types import CallToolAction, ListToolsAction + +from .client import ${client} + +__all__ = ["${client}", "CallToolAction", "ListToolsAction"] diff --git a/src/openenv/cli/templates/openenv_env/README.md b/src/openenv/cli/templates/openenv_env/README.md index 24a51add9c9eedde5435ae4c03ad180a1fe6d7f9..e9b425d0f60bb070b7b346ccf88082d1da9bfd95 100644 --- a/src/openenv/cli/templates/openenv_env/README.md +++ b/src/openenv/cli/templates/openenv_env/README.md @@ -253,6 +253,8 @@ __ENV_NAME__/ ├── uv.lock # Locked dependencies (generated) ├── client.py # __ENV_CLASS_NAME__Env client ├── models.py # Action and Observation models +├── validation/ +│ └── runtime.json # Replay plan for `openenv validate --level runtime` └── server/ ├── __init__.py # Server module exports ├── __ENV_NAME___environment.py # Core environment logic diff --git a/src/openenv/cli/templates/openenv_env/openenv.yaml b/src/openenv/cli/templates/openenv_env/openenv.yaml index 70d59278d87ea1e9ea257e4699cd5f1e6322a0c6..e0ea9dade44430109787f09a8834892efb7356fe 100644 --- a/src/openenv/cli/templates/openenv_env/openenv.yaml +++ b/src/openenv/cli/templates/openenv_env/openenv.yaml @@ -6,6 +6,11 @@ runtime: fastapi app: server.app:app port: 8000 validation: + execution: + kind: openenv_ws + probe_path: validation/runtime.json + dockerfile: server/Dockerfile + context: . reward: range: [0.0, 1.0] oracle_tolerance: 0.0 diff --git a/src/openenv/cli/templates/openenv_env/pyproject.toml b/src/openenv/cli/templates/openenv_env/pyproject.toml index c8da6c3bee44a88ec38bdda440f19d6c6ecb36c2..a0624cd2220f5563683e4aa0604b557005487052 100644 --- a/src/openenv/cli/templates/openenv_env/pyproject.toml +++ b/src/openenv/cli/templates/openenv_env/pyproject.toml @@ -12,7 +12,7 @@ requires-python = ">=3.10" dependencies = [ # Core OpenEnv runtime (provides FastAPI server + HTTP client types) # install from github - # "openenv @ git+https://github.com/huggingface/OpenEnv.git", + # "openenv @ git+https://github.com/openenv/OpenEnv.git", "openenv>=0.2.2", # Environment-specific dependencies # Add all dependencies needed for your environment here diff --git a/src/openenv/cli/templates/openenv_env/server/Dockerfile b/src/openenv/cli/templates/openenv_env/server/Dockerfile index 947a379621678def8cd68b93b45734657566873b..4bcd055350c3d89ba2f9ad64dddba2ddd9e01f67 100644 --- a/src/openenv/cli/templates/openenv_env/server/Dockerfile +++ b/src/openenv/cli/templates/openenv_env/server/Dockerfile @@ -84,4 +84,5 @@ HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \ # Run the FastAPI server # The module path is constructed to work with the /app/env structure -CMD ["sh", "-c", "cd /app/env && uvicorn server.app:app --host 0.0.0.0 --port 8000"] +# exec makes the server PID 1, so it gets SIGTERM from `docker stop` and shuts down cleanly +CMD ["sh", "-c", "cd /app/env && exec uvicorn server.app:app --host 0.0.0.0 --port 8000"] diff --git a/src/openenv/cli/templates/openenv_env/server/app.py b/src/openenv/cli/templates/openenv_env/server/app.py index 988d1f93b574319b717addbf4edfd4633e61226c..afb9d3565bb83554c97d52bc849611bf9f47bfa8 100644 --- a/src/openenv/cli/templates/openenv_env/server/app.py +++ b/src/openenv/cli/templates/openenv_env/server/app.py @@ -10,7 +10,7 @@ Endpoints: - POST /reset: Reset the environment - POST /step: Execute an action - GET /state: Get current environment state - - GET /schema: Get action/observation schemas + - GET /schema: Get action/observation/state/reset schemas - WS /ws: WebSocket endpoint for persistent sessions Usage: diff --git a/src/openenv/cli/templates/openenv_env/validation/runtime.json b/src/openenv/cli/templates/openenv_env/validation/runtime.json new file mode 100644 index 0000000000000000000000000000000000000000..2f3c181a8097917f99516c404ba848e1ccdf2c33 --- /dev/null +++ b/src/openenv/cli/templates/openenv_env/validation/runtime.json @@ -0,0 +1,8 @@ +{ + "plan_schema_version": "1", + "reset": {"episode_id": "__ENV_NAME__-smoke", "seed": 0}, + "actions": [ + {"message": "Hello"}, + {"message": "Hello, World!"} + ] +} diff --git a/src/openenv/core/README.md b/src/openenv/core/README.md index 0caa1bed7a0684b2eb822b05d18df1f48209c930..d5e098767963de732725e46784ef36ef71ad2e0f 100644 --- a/src/openenv/core/README.md +++ b/src/openenv/core/README.md @@ -165,14 +165,14 @@ provider.wait_for_ready(base_url) provider.stop_container() ``` -### Kubernetes Provider (Coming Soon) +### Kubernetes Provider ```python -from openenv.core.containers.runtime import KubernetesProvider +from openenv.core.containers.runtime.kubernetes_provider import KubernetesProvider provider = KubernetesProvider(namespace="envs") base_url = provider.start_container("my-env:latest") -# Use environment... +provider.wait_for_ready(base_url) provider.stop_container() ``` @@ -232,6 +232,6 @@ Contributions are welcome! Please see the main OpenEnv repository for contributi ## Links -- **Homepage**: https://github.com/huggingface/OpenEnv -- **Documentation**: https://github.com/huggingface/OpenEnv/blob/main/README.md -- **Bug Tracker**: https://github.com/huggingface/OpenEnv/issues +- **Homepage**: https://github.com/openenv/OpenEnv +- **Documentation**: https://github.com/openenv/OpenEnv/blob/main/README.md +- **Bug Tracker**: https://github.com/openenv/OpenEnv/issues diff --git a/src/openenv/core/__init__.py b/src/openenv/core/__init__.py index b365f5ff730e07d626068c3c6ac1053c3811a2f0..1f62b60f6f3b9de01af8463c6fa153229c8ec789 100644 --- a/src/openenv/core/__init__.py +++ b/src/openenv/core/__init__.py @@ -11,7 +11,7 @@ from . import env_server from .env_server import * # noqa: F403 if TYPE_CHECKING: - from .env_client import EnvClient + from .env_client import EnvClient, SessionLostError from .generic_client import GenericAction, GenericEnvClient from .llm_client import ( AnthropicClient, @@ -26,6 +26,7 @@ if TYPE_CHECKING: __all__ = [ "EnvClient", + "SessionLostError", "SyncEnvClient", "GenericEnvClient", "GenericAction", @@ -42,6 +43,7 @@ __all__ = [ _LAZY_ATTRS = { "EnvClient": (".env_client", "EnvClient"), + "SessionLostError": (".env_client", "SessionLostError"), "SyncEnvClient": (".sync_client", "SyncEnvClient"), "GenericEnvClient": (".generic_client", "GenericEnvClient"), "GenericAction": (".generic_client", "GenericAction"), diff --git a/src/openenv/core/containers/runtime/__init__.py b/src/openenv/core/containers/runtime/__init__.py index 9a3ce762257cb409cbccece4bb08465d43d438da..16caec4c81a593e3579337edc78226db25f1e828 100644 --- a/src/openenv/core/containers/runtime/__init__.py +++ b/src/openenv/core/containers/runtime/__init__.py @@ -5,7 +5,6 @@ from .providers import ( ContainerProvider, DockerSwarmProvider, - KubernetesProvider, LocalDockerProvider, RuntimeProvider, ) @@ -20,7 +19,6 @@ __all__ = [ "ContainerProvider", "DockerSwarmProvider", "LocalDockerProvider", - "KubernetesProvider", "RuntimeProvider", "UVProvider", ] diff --git a/src/openenv/core/containers/runtime/_server_config.py b/src/openenv/core/containers/runtime/_server_config.py index 8eb3f96d60b57b16057946ef80186454bda26224..aff5fff74ec948fd272014e3c5d12176a92752ad 100644 --- a/src/openenv/core/containers/runtime/_server_config.py +++ b/src/openenv/core/containers/runtime/_server_config.py @@ -30,11 +30,48 @@ def parse_openenv_app_field(yaml_content: str) -> str | None: def parse_dockerfile_cmd(dockerfile_content: str) -> str | None: """Extract the server command from the last Dockerfile ``CMD``.""" last_cmd: str | None = None + instruction = "" + escape = "\\" + directives = True for line in dockerfile_content.splitlines(): - stripped = line.strip() + stripped = line.lstrip() if stripped.startswith("#"): + if directives: + directive = re.fullmatch( + r"#\s*(syntax|check|escape)\s*=\s*(.+)", + stripped, + flags=re.IGNORECASE, + ) + if directive is None: + directives = False + elif directive[1].lower() == "escape" and directive[2].strip() in ( + "\\", + "`", + ): + escape = directive[2].strip() continue - match = re.match(r"CMD\s+(.+)", stripped, flags=re.IGNORECASE) + if not stripped.strip(): + directives = False + continue + directives = False + if not instruction: + match = re.match(r"\s*CMD\s+(.+)", line, flags=re.IGNORECASE) + if match: + last_cmd = match.group(1).strip() + continuation = re.search( + rf"(?=0.10`` +Requires the ``daytona`` SDK: ``pip install 'daytona>=0.10,<1'`` """ from __future__ import annotations diff --git a/src/openenv/core/containers/runtime/hf_sandbox_provider.py b/src/openenv/core/containers/runtime/hf_sandbox_provider.py index 05d6ce250f69b3e271ca9852a475546bfa174c90..112e0297c81d1492def0fa04aace5fb0d9adda2f 100644 --- a/src/openenv/core/containers/runtime/hf_sandbox_provider.py +++ b/src/openenv/core/containers/runtime/hf_sandbox_provider.py @@ -10,6 +10,7 @@ from __future__ import annotations import asyncio import hashlib +import logging import socket import threading import time @@ -24,6 +25,8 @@ from websockets.exceptions import ConnectionClosed from .providers import ContainerProvider +logger = logging.getLogger(__name__) + _DEFAULT_PORT = 8000 _SERVER_COMMAND = ( 'export SBX_PROXY_DIR="${SBX_PROXY_DIR:-$HOME/.sbx/proxy}"; ' @@ -95,6 +98,17 @@ def _get_pool(image: str, flavor: str) -> Any: class _LocalAuthProxy: + """Loopback proxy that adds the HF auth headers to every request. + + Copied into agent_sandbox_provider._LocalAuthProxy; keep the copies + aligned. + + Limitations: bodies are buffered (a streamed upstream response such as + SSE is withheld until it ends), only JSON text frames are relayed + upstream (binary client frames and close codes are not forwarded), and + upstream redirects are rejected. EnvClient uses none of these. + """ + def __init__(self, *, target_url: str, headers: dict[str, str]): self.target_url = target_url.rstrip("/") self.headers = headers @@ -131,13 +145,20 @@ class _LocalAuthProxy: data=body, headers=headers, timeout=60.0, - allow_redirects=True, + allow_redirects=False, ) except requests.RequestException: return Response( content=b"upstream HF job unreachable", status_code=502, ) + if 300 <= upstream.status_code < 400: + # Following a redirect would replay the body and the injected + # headers to another origin and could downgrade https to http. + return Response( + content=b"upstream HF job redirected; rejected", + status_code=502, + ) response_headers = { key: value for key, value in upstream.headers.items() @@ -156,7 +177,16 @@ class _LocalAuthProxy: if query: target = f"{target}?{query}" headers = {**self.headers, "accept": "*/*"} - upstream = await self._connect_upstream_websocket(target, headers) + try: + upstream = await self._connect_upstream_websocket(target, headers) + except Exception: + # Never propagate the upstream exception: its message can embed + # the target URL, which may carry credentials. Deny generically + # instead. + logger.warning("HF sandbox WebSocket upstream handshake failed") + with suppress(Exception): + await websocket.close(code=1011) + return await websocket.accept() try: to_upstream = asyncio.create_task( @@ -201,13 +231,18 @@ class _LocalAuthProxy: ) -> Any: last_error: Exception | None = None for _ in range(5): + connector = ws_connect( + target, + additional_headers=headers, + max_size=_MAX_WS_MESSAGE_SIZE, + compression=None, + ) + # Never follow handshake redirects: websockets replays + # additional_headers to the redirect target, which would leak the + # auth headers to another origin. + connector.process_redirect = lambda exc: exc try: - return await ws_connect( - target, - additional_headers=headers, - max_size=_MAX_WS_MESSAGE_SIZE, - compression=None, - ) + return await connector except Exception as exc: last_error = exc await asyncio.sleep(0.5) @@ -227,10 +262,18 @@ class _LocalAuthProxy: await websocket.send_text(message) def stop(self) -> None: + """Shut the proxy down. Raises `RuntimeError` if the thread will not + exit; the handles are then retained so a later call can retry, instead + of silently leaking a thread that keeps the loopback port bound.""" if self._server is None or self._thread is None: return self._server.should_exit = True + # Bound the graceful drain: do not wait out long-lived upstream + # responses that would outlive the 5s join below. + self._server.force_exit = True self._thread.join(timeout=5.0) + if self._thread.is_alive(): + raise RuntimeError("HF sandbox auth proxy did not stop") self._server = None self._thread = None @@ -272,8 +315,11 @@ class HFSandboxProvider(ContainerProvider): env_vars: dict[str, str] | None = None, **kwargs: Any, ) -> str: - if self._sandbox is not None: - raise RuntimeError("HFSandboxProvider already has an active service") + if self._sandbox is not None or self._proxy is not None: + raise RuntimeError( + "HFSandboxProvider already has an active service, or a proxy " + "still awaits cleanup. Call stop_container() first." + ) if kwargs: unsupported = ", ".join(sorted(kwargs)) raise ValueError( @@ -311,14 +357,20 @@ class HFSandboxProvider(ContainerProvider): raise def stop_container(self) -> None: + proxy_error: RuntimeError | None = None if self._proxy is not None: - self._proxy.stop() - self._proxy = None + try: + self._proxy.stop() + self._proxy = None + except RuntimeError as exc: + proxy_error = exc if self._sandbox is not None: sandbox = self._sandbox self._sandbox = None with suppress(Exception): sandbox.kill() + if proxy_error is not None: + raise proxy_error def wait_for_ready(self, base_url: str, timeout_s: float = 120.0) -> None: deadline = time.time() + timeout_s diff --git a/src/openenv/core/containers/runtime/kubernetes_provider.py b/src/openenv/core/containers/runtime/kubernetes_provider.py new file mode 100644 index 0000000000000000000000000000000000000000..94652b1b53404ea79a0eec99c89f2c9bf60e2f36 --- /dev/null +++ b/src/openenv/core/containers/runtime/kubernetes_provider.py @@ -0,0 +1,985 @@ +# SPDX-License-Identifier: BSD-3-Clause + +""" +Kubernetes container provider for running OpenEnv environments in-cluster. + +Requires the ``kubernetes`` client: ``pip install openenv[kubernetes]`` + +One provider instance owns one Pod and one Service, matching +``LocalDockerProvider`` owning one container. The returned ``base_url`` is the +short in-cluster Service address ``http://{name}.{namespace}:{port}``. Pod DNS +search completes that to the cluster domain, so the provider does not hardcode +``.svc.cluster.local``. That plaintext URL is the in-cluster exception +confirmed for this provider: ``ModalProvider`` and ``ACASandboxProvider`` still +refuse non-HTTPS tunnel URLs. This provider never returns a URL it did not +construct from a validated name, namespace, and port, and it does not copy +that URL or raw API bodies into errors. +""" + +from __future__ import annotations + +import re +import secrets +import time +from typing import Any, Mapping, Optional + +from .providers import ContainerProvider + +_CONTAINER_PORT = 8000 +_CONTAINER_NAME = "env" +_DEFAULT_NAMESPACE = "default" +_NAME_PREFIX = "openenv-" + +# ``openenv-`` + slug + ``-`` + millisecond timestamp + ``-`` + 4 hex chars. +_SLUG_MAX = 32 + +_DNS_LABEL = re.compile(r"^[a-z0-9]([-a-z0-9]*[a-z0-9])?$") +_LABEL_NAME = re.compile(r"^[A-Za-z0-9]([A-Za-z0-9_.-]{0,61}[A-Za-z0-9])?$") +_LABEL_VALUE = re.compile(r"^([A-Za-z0-9]([A-Za-z0-9_.-]{0,61}[A-Za-z0-9])?)?$") +_SAFE_REASON = re.compile(r"^[A-Za-z][A-Za-z0-9]{0,63}$") + +# Applied last so a caller-supplied label cannot drop ownership or retarget +# the Service selector. +_SELECTOR_KEY = "app.kubernetes.io/instance" + +_START_KWARGS = { + "resources", + "runtime_class_name", + "image_pull_secrets", + "labels", + "service_account_name", + "automount_service_account_token", +} + + +def _raise_install_error(exc: ImportError) -> None: + raise RuntimeError( + "KubernetesProvider requires the kubernetes client. " + "Install it with `pip install openenv[kubernetes]`." + ) from exc + + +def _dns_label(value: str, *, max_length: int, what: str) -> str: + """Return *value* as a DNS-1123 label, or raise ``ValueError``. + + Namespace and runtime class names are validated, not rewritten: rewriting + them would target a different object than the one the caller named. + """ + if not isinstance(value, str) or not _DNS_LABEL.fullmatch(value): + raise ValueError( + f"{what} must be a DNS-1123 label: lowercase alphanumeric " + "characters or '-', starting and ending with an alphanumeric." + ) + if not 1 <= len(value) <= max_length: + raise ValueError(f"{what} must be 1 to {max_length} characters.") + return value + + +def _slug(image: str) -> str: + """DNS-1123 slug from an image reference. Raises if nothing usable remains.""" + raw = image.split("/")[-1].split("@")[0].split(":")[0] + cleaned = re.sub(r"[^a-z0-9]+", "-", raw.lower()).strip("-") + cleaned = re.sub(r"-{2,}", "-", cleaned)[:_SLUG_MAX].strip("-") + if not cleaned or not _DNS_LABEL.fullmatch(cleaned): + raise ValueError( + "image does not yield a valid Kubernetes name. " + "Use an image reference with an alphanumeric name." + ) + return cleaned + + +def _resource_name(image: str) -> str: + suffix = f"{int(time.time() * 1000)}-{secrets.token_hex(2)}" + name = f"{_NAME_PREFIX}{_slug(image)}-{suffix}" + if len(name) > 63 or not _DNS_LABEL.fullmatch(name): + raise ValueError("generated Kubernetes name is not a valid DNS-1123 label.") + return name + + +def _label_key(key: str) -> str: + if not isinstance(key, str) or len(key) > 253: + raise ValueError( + "Kubernetes label keys must be strings of at most 253 characters." + ) + prefix, sep, name = key.rpartition("/") + if not _LABEL_NAME.fullmatch(name): + raise ValueError(f"Invalid Kubernetes label key {key!r}.") + if sep and (len(prefix) > 253 or not _dns_subdomain(prefix)): + raise ValueError(f"Invalid Kubernetes label key prefix {prefix!r}.") + return key + + +def _dns_subdomain(value: str) -> bool: + if not value or len(value) > 253: + return False + return all(_DNS_LABEL.fullmatch(part) for part in value.split(".")) + + +def _label_value(value: str) -> str: + if not isinstance(value, str) or not _LABEL_VALUE.fullmatch(value): + raise ValueError( + "Kubernetes label values must be 63 characters or fewer and contain " + "only alphanumeric characters, '-', '_' or '.'." + ) + return value + + +def _ownership_labels(name: str) -> dict[str, str]: + return { + "app.kubernetes.io/name": "openenv", + "app.kubernetes.io/instance": name, + "app.kubernetes.io/managed-by": "openenv", + "app.kubernetes.io/part-of": "openenv", + "app.kubernetes.io/component": "environment", + } + + +def _merged_labels(name: str, extra: Optional[Mapping[str, str]]) -> dict[str, str]: + labels: dict[str, str] = {} + if extra: + if not isinstance(extra, Mapping): + raise ValueError("labels must be a mapping of strings.") + for key, value in extra.items(): + labels[_label_key(key)] = _label_value(value) + labels.update(_ownership_labels(name)) + return labels + + +def _safe_reason(reason: Optional[str]) -> Optional[str]: + """Keep kubelet reason codes. Drop anything else so API text cannot leak.""" + if isinstance(reason, str) and _SAFE_REASON.fullmatch(reason): + return reason + return None + + +class _NamespaceMissing(RuntimeError): + """Creating a namespaced object returned 404: the namespace is absent.""" + + +class _CreateConflict(RuntimeError): + """Creating a namespaced object returned 409: the name is already taken.""" + + +class _TransientStatusError(RuntimeError): + """A Pod status read can be retried within the readiness deadline.""" + + +def _incluster_base_url(name: str, namespace: str, port: int) -> str: + # *name* and *namespace* are already DNS-1123 labels and *port* is an int, + # so this cannot be steered by a status field from the API server. + # ``name.namespace`` is completed by the Pod DNS search list + # (``svc.``), which works when the cluster domain is not + # ``cluster.local``. + return f"http://{name}.{namespace}:{port}" + + +def _owned_by_provider(labels: Any, name: str) -> bool: + if not isinstance(labels, Mapping): + return False + return ( + labels.get("app.kubernetes.io/managed-by") == "openenv" + and labels.get("app.kubernetes.io/instance") == name + ) + + +class _DefaultKubernetesAdapter: + """Thin adapter over the official ``kubernetes`` client. + + The provider talks to this private adapter instead of spreading SDK details + through its own logic; tests inject a duck-typed fake in its place. + """ + + def __init__( + self, + *, + namespace: str, + kubeconfig: Optional[str], + context: Optional[str], + ): + try: + from kubernetes import client, config + from kubernetes.client.exceptions import ApiException + except ImportError as exc: + _raise_install_error(exc) + + self._client = client + self._ApiException = ApiException + self._namespace = namespace + self._load_config(config, kubeconfig=kubeconfig, context=context) + configuration = client.Configuration.get_default_copy() + # Readiness owns the retry deadline; SDK retries would multiply it. + configuration.retries = 0 + self._api = client.CoreV1Api(client.ApiClient(configuration=configuration)) + + def _load_config( + self, config: Any, *, kubeconfig: Optional[str], context: Optional[str] + ) -> None: + if kubeconfig is not None or context is not None: + config.load_kube_config(config_file=kubeconfig, context=context) + return + try: + config.load_incluster_config() + except config.ConfigException: + config.load_kube_config() + + def _api_error(self, exc: Exception, action: str, *, missing_ok: bool) -> None: + status = getattr(exc, "status", None) + if missing_ok and status == 404: + return + if status == 409: + raise _CreateConflict( + f"Kubernetes {action} name is already in use" + ) from None + if status == 404 and action.startswith("create "): + raise _NamespaceMissing( + "Kubernetes namespace does not exist. " + "KubernetesProvider does not create namespaces." + ) from None + # The API body can echo object contents. Do not chain it into the error. + raise RuntimeError(f"Failed to {action} Kubernetes resource") from None + + def create_pod(self, manifest: Mapping[str, Any]) -> None: + try: + self._api.create_namespaced_pod(self._namespace, self._pod(manifest)) + except self._ApiException as exc: + self._api_error(exc, "create Pod", missing_ok=False) + + def create_service(self, manifest: Mapping[str, Any]) -> None: + try: + self._api.create_namespaced_service( + self._namespace, self._service(manifest) + ) + except self._ApiException as exc: + self._api_error(exc, "create Service", missing_ok=False) + + def pod_labels(self, name: str) -> Optional[dict[str, str]]: + """Return Pod labels, or ``None`` when the Pod does not exist.""" + return self._resource_labels(name, self._api.read_namespaced_pod, "read Pod") + + def service_labels(self, name: str) -> Optional[dict[str, str]]: + """Return Service labels, or ``None`` when the Service does not exist.""" + return self._resource_labels( + name, self._api.read_namespaced_service, "read Service" + ) + + def _resource_labels( + self, name: str, read: Any, action: str + ) -> Optional[dict[str, str]]: + try: + obj = read(name, self._namespace) + except self._ApiException as exc: + if getattr(exc, "status", None) == 404: + return None + self._api_error(exc, action, missing_ok=False) + raise RuntimeError(f"Failed to {action} Kubernetes resource") from None + metadata = getattr(obj, "metadata", None) + labels = getattr(metadata, "labels", None) if metadata is not None else None + if not isinstance(labels, Mapping): + return {} + return {str(key): str(value) for key, value in labels.items()} + + def delete_pod(self, name: str) -> None: + try: + self._api.delete_namespaced_pod(name, self._namespace) + except self._ApiException as exc: + self._api_error(exc, "delete Pod", missing_ok=True) + + def delete_service(self, name: str) -> None: + try: + self._api.delete_namespaced_service(name, self._namespace) + except self._ApiException as exc: + self._api_error(exc, "delete Service", missing_ok=True) + + def pod_status( + self, name: str, timeout_s: float = 30.0 + ) -> dict[str, Optional[str]]: + from urllib3.exceptions import HTTPError + + try: + # Older supported SDKs ignore a float timeout. Split the budget + # between connect and read using their supported tuple form. + pod = self._api.read_namespaced_pod( + name, + self._namespace, + _request_timeout=(timeout_s / 2, timeout_s / 2), + ) + except Exception as exc: + status = getattr(exc, "status", None) + if ( + isinstance(exc, (TimeoutError, HTTPError)) + or status == 429 + or (isinstance(status, int) and 500 <= status < 600) + ): + raise _TransientStatusError( + "Kubernetes Pod status read failed" + ) from None + self._api_error(exc, "read Pod", missing_ok=False) + raise RuntimeError("Failed to read Kubernetes Pod") from None + status = getattr(pod, "status", None) + phase = getattr(status, "phase", None) if status is not None else None + reason = None + if status is not None: + for container in status.container_statuses or []: + state = getattr(container, "state", None) + waiting = getattr(state, "waiting", None) if state is not None else None + terminated = ( + getattr(state, "terminated", None) if state is not None else None + ) + if waiting is not None and getattr(waiting, "reason", None): + reason = waiting.reason + elif terminated is not None and getattr(terminated, "reason", None): + reason = terminated.reason + return {"phase": phase or "Unknown", "reason": reason} + + def _metadata(self, meta: Mapping[str, Any]) -> Any: + return self._client.V1ObjectMeta( + name=meta["name"], + namespace=meta["namespace"], + labels=dict(meta["labels"]), + ) + + def _pod(self, manifest: Mapping[str, Any]) -> Any: + spec = manifest["spec"] + container = spec["containers"][0] + container_kwargs: dict[str, Any] = { + "name": container["name"], + "image": container["image"], + "ports": [ + self._client.V1ContainerPort( + name=port["name"], container_port=port["container_port"] + ) + for port in container["ports"] + ], + } + if container.get("env"): + container_kwargs["env"] = [ + self._client.V1EnvVar(name=item["name"], value=item["value"]) + for item in container["env"] + ] + resources = container.get("resources") + if resources: + container_kwargs["resources"] = self._client.V1ResourceRequirements( + requests=resources.get("requests"), + limits=resources.get("limits"), + ) + pod_kwargs: dict[str, Any] = { + "restart_policy": spec["restart_policy"], + "automount_service_account_token": spec["automount_service_account_token"], + "containers": [self._client.V1Container(**container_kwargs)], + } + if spec.get("runtime_class_name"): + pod_kwargs["runtime_class_name"] = spec["runtime_class_name"] + if spec.get("service_account_name"): + pod_kwargs["service_account_name"] = spec["service_account_name"] + if spec.get("image_pull_secrets"): + pod_kwargs["image_pull_secrets"] = [ + self._client.V1LocalObjectReference(name=secret) + for secret in spec["image_pull_secrets"] + ] + return self._client.V1Pod( + metadata=self._metadata(manifest["metadata"]), + spec=self._client.V1PodSpec(**pod_kwargs), + ) + + def _service(self, manifest: Mapping[str, Any]) -> Any: + spec = manifest["spec"] + port = spec["ports"][0] + return self._client.V1Service( + metadata=self._metadata(manifest["metadata"]), + spec=self._client.V1ServiceSpec( + selector=dict(spec["selector"]), + ports=[ + self._client.V1ServicePort( + name=port["name"], + port=port["port"], + target_port=port["target_port"], + protocol=port["protocol"], + ) + ], + ), + ) + + +class KubernetesProvider(ContainerProvider): + """ + Container provider that runs one environment as one Pod and one Service. + + ``start_container`` returns ``http://{name}.{namespace}:{port}``. That + address is reachable only from inside the cluster: Pod DNS search expands + it under ``svc.``. It is plaintext on purpose: in-cluster + HTTP is the connectivity decision for this provider. Cloud sandbox + providers keep their own HTTPS requirement. + + The namespace must already exist. This provider does not create namespaces, + Deployments, Ingress objects, or port-forwards. + + Only one Pod is active per provider. Calling ``start_container`` again + before ``stop_container()`` / ``close()`` raises ``RuntimeError`` rather + than orphaning the running Pod. A failed start deletes a resource only + after its OpenEnv ownership labels match. When a create response is lost + and that read fails, the resource stays unconfirmed: ``stop_container`` + reads the labels again and deletes only on a match. ``stop_container`` is + safe to call more than once. + + The Pod does not mount a service-account token unless + ``automount_service_account_token=True`` is passed to ``start_container``. + + Example: + ```python + from openenv.core.containers.runtime.kubernetes_provider import ( + KubernetesProvider, + ) + + provider = KubernetesProvider(namespace="openenv") + base_url = provider.start_container("echo-env:latest") + provider.wait_for_ready(base_url) + provider.stop_container() + ``` + """ + + def __init__( + self, + *, + image: str | None = None, + env_vars: dict[str, str] | None = None, + namespace: str = _DEFAULT_NAMESPACE, + kubeconfig: str | None = None, + context: str | None = None, + _adapter: Any = None, + ): + """ + Args: + image (`str`, *optional*): + Registry image used when ``start_container()`` is called + without an image. + env_vars (`dict`, *optional*): + Environment variables used when ``start_container()`` is called + without ``env_vars``. + namespace (`str`, *optional*, defaults to ``"default"``): + Existing namespace for the Pod and Service. Not created. + kubeconfig (`str`, *optional*): + Kubeconfig path. When omitted, in-cluster config is tried and + then the default kubeconfig. + context (`str`, *optional*): + Kubeconfig context. Implies kubeconfig loading rather than + in-cluster config. + """ + self._image = image + self._env_vars = env_vars + self._namespace = _dns_label(namespace, max_length=63, what="namespace") + self._name: str | None = None + self._base_url: str | None = None + self._service_port: int | None = None + self._pod_created = False + self._service_created = False + self._pod_unconfirmed = False + self._service_unconfirmed = False + + if _adapter is None: + self._adapter: Any = _DefaultKubernetesAdapter( + namespace=self._namespace, + kubeconfig=kubeconfig, + context=context, + ) + else: + self._adapter = _adapter + + @property + def base_url(self) -> str: + """URL returned by the last successful ``start_container``.""" + if self._base_url is None: + raise RuntimeError( + "KubernetesProvider has no active base_url. Start the provider " + "before reading base_url." + ) + return self._base_url + + def start_container( + self, + image: str | None = None, + port: int | None = None, + env_vars: dict[str, str] | None = None, + **kwargs: Any, + ) -> str: + """ + Create one Pod and one Service and return the in-cluster base URL. + + Args: + image (`str`, *optional*): + Registry image. May be omitted when supplied to the constructor. + port (`int`, *optional*): + Service port. Defaults to 8000. The container always listens + on 8000, matching ``LocalDockerProvider``. + env_vars (`dict`, *optional*): + Environment variables for the container. Replaces constructor + ``env_vars`` when passed, including an empty dict. + **kwargs: + ``resources``, ``runtime_class_name``, ``image_pull_secrets``, + ``labels``, ``service_account_name``, and + ``automount_service_account_token``. Unknown keys raise + ``ValueError``. + + Returns: + `str`: ``http://{name}.{namespace}:{port}``. + """ + if self._has_tracked_resources() or self._base_url is not None: + raise RuntimeError( + "KubernetesProvider already has an active Pod. Call " + "stop_container() (or close()) before starting another — a " + "second start would orphan the running Pod." + ) + + unknown = set(kwargs) - _START_KWARGS + if unknown: + raise ValueError( + f"Unsupported kwargs for KubernetesProvider: {sorted(unknown)}" + ) + + effective_image = image if image is not None else self._image + if not isinstance(effective_image, str) or not effective_image: + raise ValueError( + "KubernetesProvider requires an image. Pass it to the " + "constructor or start_container()." + ) + service_port = _CONTAINER_PORT if port is None else port + if isinstance(service_port, bool) or not isinstance(service_port, int): + raise ValueError("port must be an integer.") + if not 1 <= service_port <= 65535: + raise ValueError("port must be between 1 and 65535.") + + effective_env = self._env_vars if env_vars is None else env_vars + env_list = _env_list(effective_env) + resources = _resources(kwargs.get("resources")) + runtime_class_name = _optional_dns_subdomain( + kwargs.get("runtime_class_name"), what="runtime_class_name" + ) + service_account_name = _optional_dns_subdomain( + kwargs.get("service_account_name"), what="service_account_name" + ) + image_pull_secrets = _secret_names(kwargs.get("image_pull_secrets")) + automount = kwargs.get("automount_service_account_token", False) + if not isinstance(automount, bool): + raise ValueError("automount_service_account_token must be a bool.") + + name = _resource_name(effective_image) + labels = _merged_labels(name, kwargs.get("labels")) + self._name = name + self._service_port = service_port + try: + self._adapter.create_pod( + _pod_manifest( + name=name, + namespace=self._namespace, + labels=labels, + image=effective_image, + env_list=env_list, + resources=resources, + runtime_class_name=runtime_class_name, + service_account_name=service_account_name, + image_pull_secrets=image_pull_secrets, + automount_service_account_token=automount, + ) + ) + self._pod_created = True + self._adapter.create_service( + _service_manifest( + name=name, + namespace=self._namespace, + labels=labels, + service_port=service_port, + ) + ) + self._service_created = True + except BaseException as exc: + # Interrupts can also arrive after the API created a resource. + # A cleanup failure must not mask the original error. + try: + self._cleanup_after_failed_start(exc) + except Exception: + pass + raise + + self._base_url = _incluster_base_url(name, self._namespace, service_port) + return self._base_url + + def _cleanup_after_failed_start(self, exc: BaseException) -> None: + """Delete objects this start may have created. + + A 409 is someone else's name, and a 404 means the namespace is + missing, so those do not probe. Any other create error may mean the + API server applied the object and the client lost the response. Only + the resource whose create was attempted is checked. It is deleted only + when the OpenEnv ownership labels match. A failed read is recorded as + unconfirmed, which is not the same as a successful create: a later + ``stop_container()`` reads the labels again before deleting. + """ + uncertain = not isinstance(exc, (_CreateConflict, _NamespaceMissing)) + # Service create runs only after Pod create has succeeded. + service_was_attempted = self._pod_created + self._release("pod", uncertain=uncertain) + self._release("service", uncertain=uncertain and service_was_attempted) + if not self._has_tracked_resources(): + self._name = None + self._base_url = None + self._service_port = None + + def _release(self, kind: str, *, uncertain: bool) -> None: + if self._created(kind): + self._delete_tracked(kind) + return + if not uncertain: + return + owned = self._lookup_owned(kind) + if owned is None: + self._set_unconfirmed(kind, True) + return + if not owned: + return + self._set_created(kind, True) + self._delete_tracked(kind) + + def _lookup_owned(self, kind: str) -> Optional[bool]: + """Return whether *kind* at ``_name`` is ours. + + ``None`` means the read itself failed. Callers record that as + unconfirmed. They do not treat it as a confirmed create. + """ + if self._name is None: + return False + try: + if kind == "pod": + labels = self._adapter.pod_labels(self._name) + else: + labels = self._adapter.service_labels(self._name) + except Exception: + return None + if labels is None: + return False + return _owned_by_provider(labels, self._name) + + def _delete_tracked(self, kind: str) -> None: + """Delete a resource already known to be ours. + + A failed delete stays confirmed so ``stop_container()`` can retry it. + """ + if self._name is None: + return + try: + if kind == "pod": + self._adapter.delete_pod(self._name) + else: + self._adapter.delete_service(self._name) + except Exception: + self._set_created(kind, True) + return + self._set_created(kind, False) + + def _created(self, kind: str) -> bool: + if kind == "pod": + return self._pod_created + return self._service_created + + def _set_created(self, kind: str, created: bool) -> None: + if kind == "pod": + self._pod_created = created + else: + self._service_created = created + + def _unconfirmed(self, kind: str) -> bool: + if kind == "pod": + return self._pod_unconfirmed + return self._service_unconfirmed + + def _set_unconfirmed(self, kind: str, unconfirmed: bool) -> None: + if kind == "pod": + self._pod_unconfirmed = unconfirmed + else: + self._service_unconfirmed = unconfirmed + + def _has_tracked_resources(self) -> bool: + return ( + self._pod_created + or self._service_created + or self._pod_unconfirmed + or self._service_unconfirmed + ) + + def stop_container(self) -> None: + """Delete the Pod and Service this provider created. + + Safe when nothing was started and safe to call twice. A 404 from the + API is treated as already deleted. A confirmed resource is deleted by + name. An unconfirmed one is deleted only after a fresh ownership-label + match. If that read fails, the unconfirmed state is kept for another + retry. Objects this instance does not own are left in place, including + a name that was already taken. + """ + if self._name is None and not self._has_tracked_resources(): + self._base_url = None + self._service_port = None + return + + errors: list[str] = [] + self._stop_kind("pod", errors) + self._stop_kind("service", errors) + if errors: + raise RuntimeError( + "Failed to delete Kubernetes resources created by this provider. " + "Call stop_container() again to retry." + ) + self._name = None + self._base_url = None + self._service_port = None + + def _stop_kind(self, kind: str, errors: list[str]) -> None: + if self._name is None: + return + if self._unconfirmed(kind): + owned = self._lookup_owned(kind) + if owned is None: + errors.append(kind) + return + self._set_unconfirmed(kind, False) + if not owned: + return + self._set_created(kind, True) + if not self._created(kind): + return + try: + if kind == "pod": + self._adapter.delete_pod(self._name) + else: + self._adapter.delete_service(self._name) + except Exception: + errors.append(kind) + return + self._set_created(kind, False) + + def close(self) -> None: + """Stop the active Pod and Service. + + Overrides the base no-op so a caller holding a bare ``ContainerProvider`` + reference can release the Pod polymorphically (also invoked on + context-manager exit). Equivalent to ``stop_container()``. + """ + self.stop_container() + + def __exit__(self, exc_type, exc, tb) -> None: + try: + self.close() + except Exception: + if exc_type is None: + raise + + def wait_for_ready(self, base_url: str, timeout_s: float = 120.0) -> None: + """ + Wait until the Pod is Running and ``GET /health`` returns 200. + + A Failed or Succeeded Pod raises immediately instead of consuming the + timeout. The URL is not included in errors: this method only polls the + Service URL returned by ``start_container``. + + Args: + base_url (`str`): + URL returned by ``start_container()``. + timeout_s (`float`, *optional*, defaults to `120.0`): + Maximum seconds to wait. Image pulls are slower than local Docker. + + Raises: + TimeoutError: If the Pod does not become ready in time. + RuntimeError: If the Pod has already ended. + ValueError: If ``base_url`` is not the URL this provider returned. + """ + import requests + + expected = self._base_url + if expected is None or not isinstance(base_url, str): + raise ValueError( + "base_url does not match the in-cluster Service URL for this provider." + ) + if base_url.rstrip("/") != expected: + raise ValueError( + "base_url does not match the in-cluster Service URL for this provider." + ) + if isinstance(timeout_s, bool) or not isinstance(timeout_s, (int, float)): + raise ValueError("timeout_s must be a number.") + if timeout_s < 0: + raise ValueError("timeout_s must be non-negative.") + + health_url = f"{expected}/health" + proxies = {"http": "", "https": "", "all": ""} + deadline = time.monotonic() + timeout_s + while (remaining := deadline - time.monotonic()) > 0: + try: + phase, reason = self._phase(remaining) + except _TransientStatusError: + phase, reason = "Unknown", None + if phase in ("Failed", "Succeeded"): + raise RuntimeError(self._ended_message(phase, reason)) + remaining = deadline - time.monotonic() + if remaining <= 0: + break + if phase == "Running": + try: + response = requests.get( + health_url, timeout=min(2.0, remaining), proxies=proxies + ) + if response.status_code == 200: + return + except requests.RequestException: + pass + time.sleep(min(0.5, max(0.0, deadline - time.monotonic()))) + + raise TimeoutError(f"Kubernetes Pod did not become ready within {timeout_s}s.") + + def _phase(self, timeout_s: float) -> tuple[str, Optional[str]]: + if self._name is None: + raise RuntimeError( + "KubernetesProvider has no active Pod. Start the provider " + "before waiting for readiness." + ) + status = self._adapter.pod_status(self._name, timeout_s=timeout_s) + phase = status.get("phase") if isinstance(status, Mapping) else None + reason = status.get("reason") if isinstance(status, Mapping) else None + if not isinstance(phase, str) or not _SAFE_REASON.fullmatch(phase): + phase = "Unknown" + return phase, _safe_reason(reason if isinstance(reason, str) else None) + + def _ended_message(self, phase: str, reason: Optional[str]) -> str: + if reason is None: + return ( + f"Kubernetes Pod entered phase {phase} before it became ready. " + "The Service URL and Pod status message are omitted." + ) + return ( + f"Kubernetes Pod entered phase {phase} ({reason}) before it became " + "ready. The Service URL and Pod status message are omitted." + ) + + +def _env_list(env_vars: Optional[Mapping[str, str]]) -> list[dict[str, str]]: + if env_vars is None: + return [] + if not isinstance(env_vars, Mapping): + raise ValueError("env_vars must be a mapping of strings.") + items: list[dict[str, str]] = [] + for key, value in env_vars.items(): + if not isinstance(key, str) or not isinstance(value, str): + raise ValueError("env_vars keys and values must be strings.") + items.append({"name": key, "value": value}) + return items + + +def _resources(resources: Any) -> Optional[dict[str, dict[str, str]]]: + if resources is None: + return None + if not isinstance(resources, Mapping): + raise ValueError("resources must be a mapping of requests and limits.") + unknown = set(resources) - {"requests", "limits"} + if unknown: + raise ValueError( + f"Unsupported resources keys for KubernetesProvider: {sorted(unknown)}" + ) + parsed: dict[str, dict[str, str]] = {} + for section in ("requests", "limits"): + values = resources.get(section) + if values is None: + continue + if not isinstance(values, Mapping) or not values: + raise ValueError(f"resources.{section} must be a non-empty mapping.") + parsed[section] = {} + for key, value in values.items(): + if not isinstance(key, str) or not isinstance(value, str) or not value: + raise ValueError( + f"resources.{section} keys and values must be non-empty strings." + ) + parsed[section][key] = value + return parsed or None + + +def _optional_dns_subdomain(value: Any, *, what: str) -> Optional[str]: + if value is None: + return None + if not isinstance(value, str) or not _dns_subdomain(value): + raise ValueError( + f"{what} must be a DNS-1123 subdomain: lowercase labels separated by '.'." + ) + return value + + +def _secret_names(value: Any) -> list[str]: + if value is None: + return [] + if isinstance(value, str) or not isinstance(value, (list, tuple)): + raise ValueError("image_pull_secrets must be a list of secret names.") + names: list[str] = [] + for item in value: + if not isinstance(item, str) or not _dns_subdomain(item): + raise ValueError("image_pull_secrets entries must be DNS-1123 subdomains.") + names.append(item) + return names + + +def _pod_manifest( + *, + name: str, + namespace: str, + labels: dict[str, str], + image: str, + env_list: list[dict[str, str]], + resources: Optional[dict[str, dict[str, str]]], + runtime_class_name: Optional[str], + service_account_name: Optional[str], + image_pull_secrets: list[str], + automount_service_account_token: bool, +) -> dict[str, Any]: + container: dict[str, Any] = { + "name": _CONTAINER_NAME, + "image": image, + "ports": [{"name": "http", "container_port": _CONTAINER_PORT}], + } + if env_list: + container["env"] = env_list + if resources: + container["resources"] = resources + spec: dict[str, Any] = { + "restart_policy": "Never", + "automount_service_account_token": automount_service_account_token, + "containers": [container], + } + if runtime_class_name: + spec["runtime_class_name"] = runtime_class_name + if service_account_name: + spec["service_account_name"] = service_account_name + if image_pull_secrets: + spec["image_pull_secrets"] = image_pull_secrets + return { + "metadata": {"name": name, "namespace": namespace, "labels": labels}, + "spec": spec, + } + + +def _service_manifest( + *, + name: str, + namespace: str, + labels: dict[str, str], + service_port: int, +) -> dict[str, Any]: + return { + "metadata": {"name": name, "namespace": namespace, "labels": labels}, + "spec": { + "selector": {_SELECTOR_KEY: name}, + "ports": [ + { + "name": "http", + "port": service_port, + "target_port": _CONTAINER_PORT, + "protocol": "TCP", + } + ], + }, + } + + +__all__ = ["KubernetesProvider"] diff --git a/src/openenv/core/containers/runtime/modal_provider.py b/src/openenv/core/containers/runtime/modal_provider.py index e504ad266c3ffae97a26b8337a46d2d121068335..5db4e605beb1049eee66710f9086097afbb850cb 100644 --- a/src/openenv/core/containers/runtime/modal_provider.py +++ b/src/openenv/core/containers/runtime/modal_provider.py @@ -3,30 +3,23 @@ """ Modal container provider for running OpenEnv environments in Modal sandboxes. -Requires the ``modal`` SDK: ``pip install modal>=1.4`` +Requires the ``modal`` SDK: ``pip install modal>=1.6.3`` The provider boots an OpenEnv server inside a Modal sandbox, exposes it on an encrypted tunnel, and returns an ``https://`` URL that ``EnvClient`` connects to over ``wss://``. - -Supports both the stable Sandbox API (``modal.Sandbox.create``) and the beta -Sandbox v2 API (``modal.Sandbox._experimental_create``). Sandbox v2 is opt-in -via ``use_sandbox_v2=True`` because it is an experimental, private SDK feature; -see https://modal.com/docs/guide/sandbox-v2 . """ from __future__ import annotations -import logging import shlex import time +import warnings from typing import Any, Dict, Optional from ._server_config import parse_dockerfile_cmd, parse_openenv_app_field from .providers import ContainerProvider -logger = logging.getLogger(__name__) - _DEFAULT_MODAL_PORT = 8000 # Modal's default per-container resource requests. We pass configured cpu/memory @@ -58,28 +51,14 @@ class _DefaultModalAdapter: """Thin adapter over the ``modal`` SDK. The provider talks to this private adapter instead of spreading SDK details - through its own logic; tests inject a duck-typed fake in its place. Keeping - the SDK surface here also localizes the feature check for the private - Sandbox v2 (``_experimental_create``) API. + through its own logic; tests inject a duck-typed fake in its place. """ - def __init__(self, *, app_name: str, use_sandbox_v2: bool): + def __init__(self, *, app_name: str): import modal self._modal = modal self._app_name = app_name - self._use_sandbox_v2 = use_sandbox_v2 - - # Sandbox v2 rides on a private SDK entry point that is not present in - # every modal release. Fail fast at construction with clear guidance - # rather than at start_container time with an AttributeError. - if use_sandbox_v2 and not hasattr(modal.Sandbox, "_experimental_create"): - raise RuntimeError( - "use_sandbox_v2=True requires modal.Sandbox._experimental_create, " - "which is not available in the installed modal SDK. Upgrade modal, " - "or use the stable Sandbox API (use_sandbox_v2=False). Sandbox v2 " - "is an experimental feature; contact support@modal.com for access." - ) def image_from_registry(self, tag: str) -> Any: return self._modal.Image.from_registry(tag) @@ -111,10 +90,6 @@ class _DefaultModalAdapter: # The sandbox is started with a keep-alive entrypoint; the server # command is launched via exec afterwards (see ModalProvider). - if self._use_sandbox_v2: - return self._modal.Sandbox._experimental_create( - "sleep", "infinity", **kwargs - ) return self._modal.Sandbox.create("sleep", "infinity", **kwargs) def exec(self, sandbox: Any, command: str, *, timeout: int = 10) -> str: @@ -164,11 +139,6 @@ class ModalProvider(ContainerProvider): provider.wait_for_ready(base_url) # sandbox terminated on exit ``` - - Sandbox v2 (beta) is opt-in: - ```python - provider = ModalProvider(app_name="openenv", use_sandbox_v2=True) - ``` """ _dockerfile_registry: Dict[str, Dict[str, Any]] = {} @@ -179,7 +149,7 @@ class ModalProvider(ContainerProvider): image: str | None = None, env_vars: dict[str, str] | None = None, app_name: str = "openenv", - use_sandbox_v2: bool = False, + use_sandbox_v2: bool | None = None, timeout: int = 300, cmd: str | None = None, cpu: float | None = None, @@ -198,12 +168,11 @@ class ModalProvider(ContainerProvider): app_name (`str`, *optional*, defaults to `"openenv"`): Modal app name the sandbox is created under. Looked up (and created if missing) via ``modal.App.lookup``. - use_sandbox_v2 (`bool`, *optional*, defaults to `False`): - When `True`, sandboxes are created via the beta - ``modal.Sandbox._experimental_create`` API (Sandbox v2). This is - an experimental, private SDK feature and is therefore off by - default; a feature check fails fast at construction if the - installed SDK lacks it. See https://modal.com/docs/guide/sandbox-v2 . + use_sandbox_v2 (`bool`, *optional*): + Deprecated and ignored; will be removed in OpenEnv 0.15.0. + Modal 1.6+ creates Sandbox v2 sandboxes through + ``modal.Sandbox.create`` by default. Set ``MODAL_SANDBOX_V2=0`` + to use Sandbox v1. timeout (`int`, *optional*, defaults to `300`): Maximum sandbox lifetime in seconds. cmd (`str`, *optional*): @@ -225,10 +194,18 @@ class ModalProvider(ContainerProvider): orchestrator/CI logs. When `True`, a best-effort redacted, length-bounded excerpt is included in startup-crash errors. """ + if use_sandbox_v2 is not None: + warnings.warn( + "`use_sandbox_v2` is deprecated, has no effect, and will be removed " + "in OpenEnv 0.15.0. Remove the argument: Modal 1.6+ creates Sandbox " + "v2 sandboxes through `modal.Sandbox.create` by default. Set " + "`MODAL_SANDBOX_V2=0` to use Sandbox v1.", + FutureWarning, + stacklevel=2, + ) self._image = image self._env_vars = env_vars self._app_name = app_name - self._use_sandbox_v2 = use_sandbox_v2 self._timeout = timeout self._cmd = cmd self._cpu = cpu @@ -241,20 +218,12 @@ class ModalProvider(ContainerProvider): self._redact_values: set[str] = set() if _adapter is None: - # Import eagerly (inside the adapter) so SDK/configuration errors — - # including the Sandbox v2 feature check — surface at construction. - self._adapter: Any = _DefaultModalAdapter( - app_name=app_name, use_sandbox_v2=use_sandbox_v2 - ) + # Import eagerly (inside the adapter) so SDK/configuration errors + # surface at construction. + self._adapter: Any = _DefaultModalAdapter(app_name=app_name) else: self._adapter = _adapter - if use_sandbox_v2: - logger.info( - "Using Modal Sandbox v2 (experimental). This feature must be " - "explicitly enabled. Contact support@modal.com to get access." - ) - def _discover_server_cmd(self, port: int = _DEFAULT_MODAL_PORT) -> str: """Discover the server command from ``openenv.yaml`` inside the sandbox. diff --git a/src/openenv/core/containers/runtime/providers.py b/src/openenv/core/containers/runtime/providers.py index 3b7575f70173262b5b534d060c7584f4d9607b1c..95e5ff44836a2f96a4c02cd73debc035f6db1207 100644 --- a/src/openenv/core/containers/runtime/providers.py +++ b/src/openenv/core/containers/runtime/providers.py @@ -9,19 +9,76 @@ This module provides a pluggable architecture for different container providers from __future__ import annotations +import os +import tempfile from abc import ABC, abstractmethod -from typing import Any, Dict, Optional, Sequence, TypeVar +from contextlib import contextmanager +from typing import ( + Any, + Dict, + Iterator, + List, + Mapping, + Optional, + Sequence, + Tuple, + TypeVar, +) _ContainerProviderT = TypeVar("_ContainerProviderT", bound="ContainerProvider") +@contextmanager +def _env_file_args( + env_vars: Optional[Mapping[str, str]], +) -> Iterator[Tuple[List[str], Optional[str]]]: + """ + Yield `--env-file` arguments for the container's environment variables, + and the text to send to docker's stdin. + + The values (often tokens) stay out of the command line, which other + processes can read and errors include, and out of the docker CLI's own + environment, where names like `DOCKER_HOST` or `PATH` would change how + the CLI runs. Docker reads them from its stdin (`/dev/stdin`), so no file + is written and a CLI with a private `/tmp` (snap) still gets them. Windows + has no `/dev/stdin`: there they go in a temporary file only this user can + read, removed once docker returns. + """ + if not env_vars: + yield [], None + return + lines = [] + for key, value in env_vars.items(): + key, value = str(key), str(value) + if not key or key.startswith("#") or any(c in key for c in "= \t\r\n\0"): + raise ValueError(f"Invalid environment variable name: {key!r}") + if any(c in value for c in "\r\n\0"): + raise ValueError( + f"Environment variable {key!r}: values can't contain line breaks " + "or NUL characters" + ) + lines.append(f"{key}={value}\n") + if os.name != "nt": + yield ["--env-file", "/dev/stdin"], "".join(lines) + return + fd, path = tempfile.mkstemp(prefix="openenv-env-") + try: + with os.fdopen(fd, "w") as env_file: + env_file.writelines(lines) + yield ["--env-file", path], None + finally: + os.unlink(path) + + class ContainerProvider(ABC): """ Abstract base class for container providers. Providers implement this interface to support different container platforms: - LocalDockerProvider: Runs containers on local Docker daemon - - KubernetesProvider: Runs containers in Kubernetes cluster + - DockerSwarmProvider: Runs containers as a Docker Swarm service + - KubernetesProvider: optional ``openenv[kubernetes]`` extra + (``kubernetes_provider.py``) - FargateProvider: Runs containers on AWS Fargate - CloudRunProvider: Runs containers on Google Cloud Run @@ -175,8 +232,10 @@ class LocalDockerProvider(ContainerProvider): Port to expose. If `None`, finds an available port. env_vars (`dict`, *optional*): Environment variables for the container. - **kwargs: - Additional Docker run options. + volumes (`dict`, *optional*): + Mapping of host paths or volume names to mount configuration. + Each configuration must contain a `bind` container path and may + contain a `mode` such as `"ro"` or `"rw"`. Returns: `str`: Base URL to connect to the container. @@ -184,6 +243,8 @@ class LocalDockerProvider(ContainerProvider): import subprocess import time + volumes: Optional[Mapping[str, Mapping[str, str]]] = kwargs.get("volumes") + # Find available port if not specified if port is None: port = self._find_available_port() @@ -202,17 +263,33 @@ class LocalDockerProvider(ContainerProvider): f"{port}:8000", # Map port ] - # Add environment variables - if env_vars: - for key, value in env_vars.items(): - cmd.extend(["-e", f"{key}={value}"]) + # Add volume mounts before the image name. + if volumes: + for source, config in volumes.items(): + bind = config.get("bind") + if not bind: + raise ValueError( + f"Volume config for {source!r} must include a non-empty 'bind'" + ) + mode = config.get("mode") + volume_spec = f"{source}:{bind}" + if mode: + volume_spec = f"{volume_spec}:{mode}" + cmd.extend(["--volume", volume_spec]) # Add image cmd.append(image) # Run container try: - result = subprocess.run(cmd, capture_output=True, text=True, check=True) + with _env_file_args(env_vars) as (env_args, env_input): + result = subprocess.run( + cmd[:2] + env_args + cmd[2:], + input=env_input, + capture_output=True, + text=True, + check=True, + ) self._container_id = result.stdout.strip() except subprocess.CalledProcessError as e: error_msg = f"Failed to start Docker container.\nCommand: {' '.join(cmd)}\nExit code: {e.returncode}\nStderr: {e.stderr}\nStdout: {e.stdout}" @@ -441,10 +518,6 @@ class DockerSwarmProvider(ContainerProvider): if self._overlay_network: cmd.extend(["--network", self._overlay_network]) - if env_vars: - for key, value in env_vars.items(): - cmd.extend(["--env", f"{key}={value}"]) - if cpu_limit is not None: cmd.extend(["--limit-cpu", str(cpu_limit)]) @@ -468,12 +541,14 @@ class DockerSwarmProvider(ContainerProvider): cmd.extend(command_override) try: - result = subprocess.run( - cmd, - capture_output=True, - text=True, - check=True, - ) + with _env_file_args(env_vars) as (env_args, env_input): + result = subprocess.run( + cmd[:3] + env_args + cmd[3:], + input=env_input, + capture_output=True, + text=True, + check=True, + ) self._service_id = result.stdout.strip() except subprocess.CalledProcessError as e: error_msg = ( @@ -644,19 +719,6 @@ class DockerSwarmProvider(ContainerProvider): return f"{clean_image}-swarm-{timestamp}" -class KubernetesProvider(ContainerProvider): - """ - Planned container provider for Kubernetes clusters. - - Not yet implemented: this is a placeholder for the planned Kubernetes - backend and does not implement the abstract `ContainerProvider` methods, so - it cannot be instantiated. Use `LocalDockerProvider`, `DockerSwarmProvider`, - `DaytonaProvider`, or `ACASandboxProvider` instead. - """ - - pass - - class RuntimeProvider(ABC): """ Abstract base class for runtime providers that are not container providers. diff --git a/src/openenv/core/containers/runtime/uv_provider.py b/src/openenv/core/containers/runtime/uv_provider.py index 3dc3f5e72a4299639440b32d2a0c198e36eb1d87..f1f17012ee3476686ad20fb438e4ed5beb94181d 100644 --- a/src/openenv/core/containers/runtime/uv_provider.py +++ b/src/openenv/core/containers/runtime/uv_provider.py @@ -2,6 +2,7 @@ from __future__ import annotations +import logging import os import shutil import socket @@ -12,6 +13,9 @@ from typing import Dict, Optional import requests +from ...utils import _SECRET_ENV_NAME + +logger = logging.getLogger(__name__) from .providers import RuntimeProvider GIT_URL_PREFIX = "git+" @@ -137,7 +141,11 @@ class UVProvider(RuntimeProvider): reload (`bool`, *optional*, defaults to `False`): Whether to enable uvicorn's reload mode. env_vars (`dict`, *optional*): - Environment variables to pass through to the spawned process. + Environment variables to pass through to the spawned process. The + server inherits this process's environment except variables named + like credentials (`TOKEN`, `KEY`, `SECRET` or `PASSWORD` as a part + of the name, such as `HF_TOKEN`), so a credential the server needs + has to be passed here. context_timeout_s (`float`, *optional*, defaults to `60.0`): How long to wait for the environment to become ready. @@ -195,7 +203,8 @@ class UVProvider(RuntimeProvider): port (`int`, *optional*): The port to bind the environment to. env_vars (`dict`, *optional*): - Environment variables to pass to the environment. + Environment variables to pass to the environment, on top of + the constructor's. Credentials reach the server only this way. workers (`int`, *optional*, defaults to `1`): The number of workers to use. @@ -232,13 +241,23 @@ class UVProvider(RuntimeProvider): project_path=project_path, ) - env = os.environ.copy() + # Environment servers can run code a model wrote: they don't inherit + # this process's credentials, only the ones passed in env_vars. + env = {k: v for k, v in os.environ.items() if not _SECRET_ENV_NAME.search(k)} if self.env_vars: env.update(self.env_vars) if env_vars: env.update(env_vars) + dropped = sorted(k for k in os.environ if k not in env) + if dropped: + logger.warning( + "Not passing %s to the environment server. Pass the ones it " + "needs with env_vars.", + ", ".join(dropped), + ) + try: self._process = subprocess.Popen(command, env=env) except OSError as exc: diff --git a/src/openenv/core/env_client.py b/src/openenv/core/env_client.py index 01abe1aeb9df4f8bc7e7ba3327464d751198288b..01b72643fe80ccb3531e6db278b0b966f36b00a4 100644 --- a/src/openenv/core/env_client.py +++ b/src/openenv/core/env_client.py @@ -275,6 +275,15 @@ async def _best_effort_graceful_close(ws: ClientConnection) -> None: await _best_effort_close(ws) +class SessionLostError(ConnectionError): + """The connection to the server was lost in the middle of an episode. + + The server keeps one environment per WebSocket connection, so reconnecting + opens a new session with an environment this client never reset. Call + `reset()` to start a new episode. + """ + + class EnvClient(ABC, Generic[ActT, ObsT, StateT]): """ Async environment client for persistent sessions. @@ -386,6 +395,8 @@ class EnvClient(ABC, Generic[ActT, ObsT, StateT]): # Strong references for fire-and-forget socket closes (see _receive), # so the task isn't garbage-collected mid-close. Discarded on done. self._pending_close_tasks: set[asyncio.Task] = set() + # The socket that carries the episode started by `reset()`, if one is open. + self._episode_ws: Optional[ClientConnection] = None if base_url is not None: self._set_base_url(base_url) @@ -517,6 +528,7 @@ class EnvClient(ABC, Generic[ActT, ObsT, StateT]): coro_factory: Callable[[], Any], *, allow_async_handoff: bool = False, + stop_loop: bool = False, ) -> Any: """Run an async operation through the sync wrapper.""" if allow_async_handoff and self._execution_mode == "async": @@ -525,9 +537,15 @@ class EnvClient(ABC, Generic[ActT, ObsT, StateT]): self._claim_execution_mode("sync") if self._sync_client is None: self._sync_client = self.sync() - return self._sync_client._run(coro_factory()) + try: + return self._sync_client._run(coro_factory()) + finally: + if stop_loop: + self._sync_client._stop_loop() - def _dispatch(self, coro_factory: Callable[[], Any]) -> Any: + def _dispatch( + self, coro_factory: Callable[[], Any], *, stop_loop: bool = False + ) -> Any: """Return an awaitable in async code and a concrete result in sync code.""" try: running_loop = asyncio.get_running_loop() @@ -538,15 +556,17 @@ class EnvClient(ABC, Generic[ActT, ObsT, StateT]): sync_loop = ( self._sync_client._loop if self._sync_client is not None else None ) - if running_loop is sync_loop: + if running_loop is not None and running_loop is sync_loop: return coro_factory() - return self._run_sync(coro_factory) + return self._run_sync(coro_factory, stop_loop=stop_loop) if running_loop is not None: if self._execution_mode == "async": return coro_factory() return _AutoAsyncResult(self, coro_factory) - return self._run_sync(coro_factory, allow_async_handoff=True) + return self._run_sync( + coro_factory, allow_async_handoff=True, stop_loop=stop_loop + ) def connect(self) -> Any: return self._dispatch(self._connect_async) @@ -653,6 +673,7 @@ class EnvClient(ABC, Generic[ActT, ObsT, StateT]): # leave a stale socket cached for a later operation. self._ws = None self._ws_loop = None + self._episode_ws = None same_loop = ws_loop is asyncio.get_running_loop() if same_loop: # Keep ownership of the handshake if this caller is cancelled. @@ -929,6 +950,8 @@ class EnvClient(ABC, Generic[ActT, ObsT, StateT]): `start_container` (docker) or to the `UVProvider` constructor/start (uv). When `use_docker=False`, the `project_path` argument can be used to override the default git URL (`git+https://huggingface.co/spaces/{repo_id}`). + With `use_docker=False` the server doesn't inherit variables named like + credentials (such as `HF_TOKEN`): pass the ones it needs in `env_vars`. Returns: `_BootstrapResult`: `await` for a connected async client, or call @@ -996,8 +1019,12 @@ class EnvClient(ABC, Generic[ActT, ObsT, StateT]): "type": "reset", "data": kwargs, } + # A reset may reconnect: it starts a new episode on whatever session it lands on. + self._episode_ws = None response = await self._send_and_receive(message) - return self._parse_result(response.get("data", {})) + result = self._parse_result(response.get("data", {})) + self._episode_ws = None if result.done else self._ws + return result def step(self, action: ActT, **kwargs: Any) -> Any: return self._dispatch(lambda: self._step_async(action, **kwargs)) @@ -1019,8 +1046,12 @@ class EnvClient(ABC, Generic[ActT, ObsT, StateT]): "type": "step", "data": self._step_payload(action), } + self._raise_if_session_lost() response = await self._send_and_receive(message) - return self._parse_result(response.get("data", {})) + result = self._parse_result(response.get("data", {})) + if result.done: + self._episode_ws = None + return result def state(self) -> Any: return self._dispatch(self._state_async) @@ -1033,11 +1064,33 @@ class EnvClient(ABC, Generic[ActT, ObsT, StateT]): State object with environment state information """ message = {"type": "state"} + self._raise_if_session_lost() response = await self._send_and_receive(message) return self._parse_state(response.get("data", {})) + def _raise_if_session_lost(self) -> None: + """Raise `SessionLostError` if the socket that carried the episode is gone. + + `_connect_async()` would replace it with a new socket, which the server + treats as a new session, and the call would run on an environment this + client never reset. It keeps raising until `reset()`, so a retried call + does not land on the new session either. + """ + ws = self._episode_ws + if ws is None: + return + if ( + self._ws is not ws + or ws.state in (State.CLOSING, State.CLOSED) + or self._ws_loop is not asyncio.get_running_loop() + ): + raise SessionLostError( + f"Lost the connection to {self._ws_url} in the middle of an episode. " + "Call reset() to start a new one." + ) + def close(self) -> Any: - return self._dispatch(self._close_async) + return self._dispatch(self._close_async, stop_loop=True) async def _close_child_clients(self) -> asyncio.CancelledError | None: """Close every captured child while deferring caller cancellation.""" @@ -1164,7 +1217,7 @@ class EnvClient(ABC, Generic[ActT, ObsT, StateT]): def __exit__(self, exc_type, exc_val, exc_tb) -> None: """Exit sync context manager, closing connection.""" - self._run_sync(self._close_async) + self._run_sync(self._close_async, stop_loop=True) def sync(self) -> "SyncEnvClient": """ diff --git a/src/openenv/core/env_server/exceptions.py b/src/openenv/core/env_server/exceptions.py index bc2261654e18a7c390ac1bd593e3ff9d59e86929..437b0e15add1cc1f601bf06ac91c2f9ae892cac2 100644 --- a/src/openenv/core/env_server/exceptions.py +++ b/src/openenv/core/env_server/exceptions.py @@ -44,7 +44,10 @@ class SessionCapacityError(OpenEnvError): Raised when the server cannot accept new sessions due to capacity limits. This error is raised when a new WebSocket connection is attempted but - the server has already reached max_concurrent_envs active sessions. + the server has already reached max_concurrent_envs active sessions. The + default message tells the caller which server setting limits the number of + sessions, since the client (e.g. a trainer opening one session per + concurrent episode) usually cannot see the server configuration. """ def __init__( @@ -59,7 +62,13 @@ class SessionCapacityError(OpenEnvError): if message is None: message = ( f"Server at capacity: {active_sessions}/{max_sessions} sessions active. " - f"Cannot accept new connections." + f"Cannot accept new connections. To serve more concurrent sessions, " + f"start the server with a higher max_concurrent_envs (most " + f"environment servers read it from the MAX_CONCURRENT_ENVS " + f"environment variable). Values above 1 also require an environment " + f"that isolates per-session state and declares " + f"SUPPORTS_CONCURRENT_SESSIONS=True. Otherwise, open fewer " + f"sessions at once or close idle ones." ) super().__init__(message) diff --git a/src/openenv/core/env_server/http_server.py b/src/openenv/core/env_server/http_server.py index 92b40d642a2e20350f8c0150354e5d30f6d83751..640905b386692a8fda782fde2ae149b8fc75332d 100644 --- a/src/openenv/core/env_server/http_server.py +++ b/src/openenv/core/env_server/http_server.py @@ -14,9 +14,10 @@ import inspect import json import logging import os +import secrets import time import uuid -from concurrent.futures import ThreadPoolExecutor +from concurrent.futures import Future, ThreadPoolExecutor from contextlib import AsyncExitStack from typing import ( Any, @@ -56,11 +57,23 @@ from .mcp_types import ( ListToolsAction, ListToolsObservation, McpMethod, + ToolErrorType, WSMCPMessage, WSMCPResponse, ) from .route_config import GetEndpointConfig, register_get_endpoints from .serialization import deserialize_action, serialize_observation +from .session_telemetry import ( + rubric_counts, + rubric_snapshot, + SeedAcceptance, + SessionTelemetry, + ValidationOpenedData, + ValidationOpenedResponse, + ValidationOpenMessage, + ValidationReadMessage, + ValidationResponse, +) from .types import ( Action, ConcurrencyConfig, @@ -181,6 +194,7 @@ class HTTPEnvServer: state_cls: Type[State] = State, *, reset_observation_cls: Optional[Type[Observation]] = None, + reset_cls: Type[ResetRequest] = ResetRequest, ): """ Initialize HTTP server wrapper. @@ -208,6 +222,10 @@ class HTTPEnvServer: The `State` subclass this environment reports. Used for the `/state` response model and the `state` entry of `/schema`, so that fields declared by the subclass are published and serialized. + reset_cls (`Type[ResetRequest]`, *optional*, defaults to `ResetRequest`): + The `ResetRequest` subclass describing this environment's reset parameters. + Published as the `reset` entry of `/schema`. It is not used to validate + reset requests. Raises: `ValueError`: If both `max_concurrent_envs` and `concurrency_config` are provided. @@ -253,6 +271,7 @@ class HTTPEnvServer: self.observation_cls = observation_cls self.reset_observation_cls = reset_observation_cls or observation_cls self.state_cls = state_cls + self.reset_cls = reset_cls self.env_name = env_name or self._default_env_name() # Session management for WebSocket connections @@ -260,8 +279,12 @@ class HTTPEnvServer: self._session_executors: Dict[str, ThreadPoolExecutor] = {} self._session_stacks: Dict[str, AsyncExitStack] = {} self._session_info: Dict[str, SessionInfo] = {} + self._session_modes: Dict[str, Optional[str]] = {} self._session_websocket_attachments: set[str] = set() self._session_pending_closes: set[str] = set() + # WebSocket messages being handled, per session; such sessions are never + # idle-reaped. A count, since an attached socket can share the session. + self._session_operations_in_flight: Dict[str, int] = {} self._session_lock = asyncio.Lock() # Create thread pool for running sync code in async context @@ -270,8 +293,10 @@ class HTTPEnvServer: self._requires_single_thread_executor = self._detect_single_thread_requirement() self._shared_session_executor: Optional[ThreadPoolExecutor] = None + self._shared_session_creation_lock: Optional[asyncio.Lock] = None if self._requires_single_thread_executor: self._shared_session_executor = ThreadPoolExecutor(max_workers=1) + self._shared_session_creation_lock = asyncio.Lock() # Idle session reaper configuration. # Timeout is taken from ConcurrencyConfig.session_timeout; @@ -280,6 +305,7 @@ class HTTPEnvServer: self._concurrency_config.session_timeout ) self._reaper_task: Optional[asyncio.Task[None]] = None + self._reaper_stop_event = asyncio.Event() def _default_env_name(self) -> str: factory = self._env_factory @@ -370,7 +396,9 @@ class HTTPEnvServer: return valid_kwargs - async def _create_session(self) -> tuple[str, Environment]: + async def _create_session( + self, mode: Optional[str | ServerMode] = None + ) -> tuple[str, Environment]: """ Create a new WebSocket session with its own environment instance. @@ -400,58 +428,220 @@ class HTTPEnvServer: self._session_executors[session_id] = executor self._sessions[session_id] = None # placeholder until env is ready + # Every await from here to registration runs with the slot reserved, so + # cancellation has to release it. CancelledError is not an Exception, so + # the handlers below never see it, and a surviving reservation is + # permanent: capacity counts _sessions, while the idle reaper only scans + # sessions that reached _session_info. + env: Optional[Environment] = None + stack: Optional[AsyncExitStack] = None + factory_future: Optional[Future[Environment]] = None + mcp_entry_task: Optional[asyncio.Task[Any]] = None + cleanup_task: Optional[asyncio.Task[None]] = None + creation_lock_acquired = False + + def start_cleanup() -> asyncio.Task[None]: + # Startup failure and cancellation share one cleanup owner. Whoever + # gets here first starts the task; a later caller joins the same one + # instead of submitting a second env.close(). + nonlocal cleanup_task + if cleanup_task is None: + cleanup_task = asyncio.create_task( + self._discard_reserved_session( + session_id, + executor, + env, + stack, + factory_future, + mcp_entry_task, + ) + ) + return cleanup_task + + async def drain_cleanup(task: asyncio.Task[None]) -> None: + # ASGI cancel scopes may cancel a request repeatedly. Keep awaiting + # the shielded cleanup task until it reaches a terminal state so + # cancellation cannot escape while the reservation still exists. + try: + await asyncio.shield(task) + except asyncio.CancelledError: + while not task.done(): + try: + await asyncio.shield(task) + except asyncio.CancelledError: + pass + task.result() + raise + try: - # Create environment in the executor thread (outside lock) - loop = asyncio.get_event_loop() - env = await loop.run_in_executor(executor, self._env_factory) - except Exception as e: - async with self._session_lock: - if executor is not self._shared_session_executor: - executor.shutdown(wait=False) - self._session_executors.pop(session_id, None) - self._sessions.pop(session_id, None) - factory_name = getattr( - self._env_factory, "__name__", str(self._env_factory) - ) - raise EnvironmentFactoryError(factory_name) from e - - # Hold the MCP session open for the lifetime of this session, - # matching the WebSocket path's AsyncExitStack pattern. This - # prevents per-request MCP transport teardown/reconnection and - # preserves FastMCP session state (ctx.set_state / ctx.get_state) - # across HTTP calls within the same OpenEnv session. - stack = AsyncExitStack() - try: - mcp_session_factory = getattr(env, "mcp_session", None) - if callable(mcp_session_factory): - mcp_session_cm = cast(AsyncContextManager[Any], mcp_session_factory()) - await stack.enter_async_context(mcp_session_cm) - except Exception: - # MCP transport failed to start — clean up the reserved slot, - # the env, and the executor so they don't leak permanently - # against _max_concurrent_envs. - await stack.aclose() # best-effort + if self._shared_session_creation_lock is not None: + await self._shared_session_creation_lock.acquire() + creation_lock_acquired = True + + try: + # Create environment in the executor thread (outside lock). + # submit() plus wrap_future() is what run_in_executor() does + # internally; spelling it out keeps the thread's future, which is + # the only handle on an environment still being built when the + # await is cancelled. + loop = asyncio.get_event_loop() + factory_future = executor.submit(self._env_factory) + env = await asyncio.wrap_future(factory_future, loop=loop) + mode_val = ( + mode.value + if isinstance(mode, ServerMode) + else (str(mode) if mode is not None else None) + ) + if mode_val is not None and hasattr(env, "set_mode"): + env.set_mode(mode_val) + except Exception as e: + async with self._session_lock: + if executor is not self._shared_session_executor: + executor.shutdown(wait=False) + self._session_executors.pop(session_id, None) + self._sessions.pop(session_id, None) + factory_name = getattr( + self._env_factory, "__name__", str(self._env_factory) + ) + raise EnvironmentFactoryError(factory_name) from e + + # The factory result is delivered, so the shared executor thread is + # free. Release the creation lock before MCP startup: it exists to + # order factory calls (and disposal of a factory cancelled + # mid-flight) on that one thread, and holding it through an MCP + # handshake lets a single stalled connection starve every later + # session's constructor. Cancellation during construction keeps the + # lock instead, so late-factory disposal still precedes the next + # constructor. + if creation_lock_acquired: + assert self._shared_session_creation_lock is not None + self._shared_session_creation_lock.release() + creation_lock_acquired = False + + # Hold the MCP session open for the lifetime of this session, + # matching the WebSocket path's AsyncExitStack pattern. This + # prevents per-request MCP transport teardown/reconnection and + # preserves FastMCP session state (ctx.set_state / ctx.get_state) + # across HTTP calls within the same OpenEnv session. + stack = AsyncExitStack() + try: + mcp_session_factory = getattr(env, "mcp_session", None) + if callable(mcp_session_factory): + mcp_session_cm = cast( + AsyncContextManager[Any], mcp_session_factory() + ) + # Enter in its own task and await it shielded. An entry that + # blocks before yielding may release resources in its own + # finally, and the stack cannot replay that cleanup: it + # registers the exit callback only once __aenter__ returns. + # Shielding keeps repeated cancellation off the entry, so + # the cleanup owner can cancel it exactly once and drain the + # unwind instead of aborting it part-way. + mcp_entry_task = asyncio.create_task( + stack.enter_async_context(mcp_session_cm) + ) + await asyncio.shield(mcp_entry_task) + except Exception: + # MCP transport failed to start — clean up the reserved slot, + # the env, and the executor so they don't leak permanently + # against _max_concurrent_envs. Cancellation arriving mid-close + # joins this same task rather than closing the env twice. + await drain_cleanup(start_cleanup()) + raise + async with self._session_lock: - self._sessions.pop(session_id, None) - self._session_executors.pop(session_id, None) - self._session_info.pop(session_id, None) - await self._cleanup_session_resources(env, executor) + self._sessions[session_id] = env + self._session_stacks[session_id] = stack + if mode is not None: + self._session_modes[session_id] = mode_val + now = time.time() + self._session_info[session_id] = SessionInfo( + session_id=session_id, + created_at=current_time, + last_activity_at=now, + step_count=0, + environment_type=type(env).__name__, + ) + except asyncio.CancelledError: + # Joins the cleanup already under way if startup failure began one, + # so the environment is closed by a single owner. + try: + await drain_cleanup(start_cleanup()) + except asyncio.CancelledError: + pass raise - - async with self._session_lock: - self._sessions[session_id] = env - self._session_stacks[session_id] = stack - now = time.time() - self._session_info[session_id] = SessionInfo( - session_id=session_id, - created_at=current_time, - last_activity_at=now, - step_count=0, - environment_type=type(env).__name__, - ) + finally: + if creation_lock_acquired: + assert self._shared_session_creation_lock is not None + self._shared_session_creation_lock.release() return session_id, env + async def _discard_reserved_session( + self, + session_id: str, + executor: ThreadPoolExecutor, + env: Optional[Environment] = None, + stack: Optional[AsyncExitStack] = None, + factory_future: Optional[Future[Environment]] = None, + mcp_entry_task: Optional[asyncio.Task[Any]] = None, + ) -> None: + """ + Release a session slot reserved by `_create_session` that never opened. + + Drops every mapping the slot may have reached and closes whatever the + interrupted creation built, so the slot stops counting against + `max_concurrent_envs` and no environment outlives it. + + Args: + session_id (`str`): + The reserved session ID to release. + executor (`ThreadPoolExecutor`): + The executor reserved alongside the slot. + env (`Environment`, *optional*): + The environment, if the factory already returned one. + stack (`AsyncExitStack`, *optional*): + The MCP session stack, if one was already entered. + factory_future (`Future`, *optional*): + The factory's thread future, if the factory call was reached. + Used to close an environment the thread is still building. + mcp_entry_task (`asyncio.Task`, *optional*): + The in-flight MCP session entry, if MCP startup was reached. + Cancelled and drained here so an entry interrupted before it + yielded can finish releasing what it had already acquired. + """ + if mcp_entry_task is not None: + # Cancel at most once: a second cancellation would abort the entry's + # own unwind, and the stack holds no exit callback to replay it. + if not mcp_entry_task.done(): + mcp_entry_task.cancel() + try: + await mcp_entry_task + except (asyncio.CancelledError, Exception): + # A cancelled or failed entry has unwound itself. If it did + # finish, `stack` owns the context and closes it below. + pass + + if env is None and factory_future is not None: + # Cancelling the await can cancel a queued future, but cannot stop a + # factory whose executor thread is already running. In that case, + # keep the capacity reservation until its result can be disposed of. + if not factory_future.cancel(): + try: + env = await asyncio.wrap_future(factory_future) + except (asyncio.CancelledError, Exception): + # A cancelled or failed factory produced no environment to + # close. Its capacity reservation still has to be released. + env = None + + await self._cleanup_session_resources(env, executor, stack) + async with self._session_lock: + self._sessions.pop(session_id, None) + self._session_executors.pop(session_id, None) + self._session_stacks.pop(session_id, None) + self._session_info.pop(session_id, None) + self._session_modes.pop(session_id, None) + async def _destroy_session(self, session_id: str) -> None: """ Destroy a WebSocket session and cleanup resources. @@ -465,6 +655,7 @@ class HTTPEnvServer: executor = self._session_executors.pop(session_id, None) stack = self._session_stacks.pop(session_id, None) self._session_info.pop(session_id, None) + self._session_modes.pop(session_id, None) self._session_websocket_attachments.discard(session_id) self._session_pending_closes.discard(session_id) @@ -533,17 +724,26 @@ class HTTPEnvServer: interval = max(timeout / 4, 5.0) # check frequently enough while True: try: - await asyncio.sleep(interval) + try: + await asyncio.wait_for( + self._reaper_stop_event.wait(), timeout=interval + ) + return + except asyncio.TimeoutError: + pass now = time.time() stale_ids: list[str] = [] async with self._session_lock: for sid, info in self._session_info.items(): if ( sid not in self._session_websocket_attachments + and sid not in self._session_operations_in_flight and now - info.last_activity_at > timeout ): stale_ids.append(sid) for sid in stale_ids: + if self._reaper_stop_event.is_set(): + return # Re-check under lock: activity may have arrived since # the snapshot was taken, making this session active again. # Refresh `now` so slow _destroy_session calls don't cause @@ -554,6 +754,7 @@ class HTTPEnvServer: if ( info is None or sid in self._session_websocket_attachments + or sid in self._session_operations_in_flight or (now - info.last_activity_at) <= timeout ): continue @@ -569,12 +770,14 @@ class HTTPEnvServer: def _start_reaper(self) -> None: """Start the idle-session reaper if a timeout is configured.""" if self._session_idle_timeout_s is not None and self._reaper_task is None: + self._reaper_stop_event.clear() self._reaper_task = asyncio.create_task(self._reap_idle_sessions()) - def _stop_reaper(self) -> None: - """Cancel the reaper background task.""" + async def _stop_reaper(self) -> None: + """Stop the reaper after any in-progress session cleanup finishes.""" if self._reaper_task is not None: - self._reaper_task.cancel() + self._reaper_stop_event.set() + await self._reaper_task self._reaper_task = None def get_session_info(self, session_id: str) -> Optional[SessionInfo]: @@ -879,20 +1082,30 @@ class HTTPEnvServer: f"Invalid mode: '{mode}'. Must be one of: {valid_modes}" ) - # Wire up idle-session reaper lifecycle via app events + # Only explicitly provisioned simulation servers accept validation controls. + validation_token = os.environ.get("OPENENV_VALIDATION_TOKEN", "") + validation_enabled = ( + mode == ServerMode.SIMULATION and 32 <= len(validation_token) <= 256 + ) + + # Wire up session lifecycle via app events server_ref = self async def _start_session_reaper() -> None: server_ref._start_reaper() - async def _stop_session_reaper() -> None: - server_ref._stop_reaper() + async def _shutdown_sessions() -> None: + await server_ref._stop_reaper() + async with server_ref._session_lock: + session_ids = list(server_ref._sessions) + for session_id in session_ids: + await server_ref._destroy_session(session_id) if server_ref._shared_session_executor is not None: server_ref._shared_session_executor.shutdown(wait=True) if not getattr(app.router, "_openenv_reaper_registered", False): app.router.on_startup.append(_start_session_reaper) - app.router.on_shutdown.append(_stop_session_reaper) + app.router.on_shutdown.append(_shutdown_sessions) app.router._openenv_reaper_registered = True # type: ignore[attr-defined] # Helper function to handle reset endpoint @@ -993,7 +1206,7 @@ class HTTPEnvServer: request_id=request_id, ) try: - created_session_id, _ = await self._create_session() + created_session_id, _ = await self._create_session(mode=mode) except SessionCapacityError as e: return JsonRpcResponse.error_response( JsonRpcErrorCode.SERVER_ERROR, @@ -1033,6 +1246,21 @@ class HTTPEnvServer: ) async with self._session_lock: + session_mode = self._session_modes.get(target_session_id) + if ( + ( + target_session_id in self._sessions + or target_session_id in self._session_websocket_attachments + ) + and session_mode is not None + and session_mode != mode.value + ): + return JsonRpcResponse.error_response( + JsonRpcErrorCode.INVALID_PARAMS, + f"Session '{target_session_id}' belongs to mode '{session_mode}', not '{mode.value}'", + request_id=request_id, + ) + if target_session_id in self._session_websocket_attachments: env = _MISSING attached = True @@ -1046,6 +1274,7 @@ class HTTPEnvServer: executor = self._session_executors.pop(target_session_id, None) stack = self._session_stacks.pop(target_session_id, None) self._session_info.pop(target_session_id, None) + self._session_modes.pop(target_session_id, None) elif not attached: executor = None stack = None @@ -1099,6 +1328,7 @@ class HTTPEnvServer: elif requested_session_id: async with self._session_lock: _env = self._sessions.get(requested_session_id, _MISSING) + session_mode = self._session_modes.get(requested_session_id) if _env is _MISSING: return JsonRpcResponse.error_response( @@ -1107,6 +1337,13 @@ class HTTPEnvServer: request_id=request_id, ) + if session_mode is not None and session_mode != mode.value: + return JsonRpcResponse.error_response( + JsonRpcErrorCode.INVALID_PARAMS, + f"Session '{requested_session_id}' belongs to mode '{session_mode}', not '{mode.value}'", + request_id=request_id, + ) + if _env is None: return JsonRpcResponse.error_response( JsonRpcErrorCode.INVALID_REQUEST, @@ -1118,6 +1355,8 @@ class HTTPEnvServer: managed_session_id = requested_session_id else: _env = self._env_factory() + if hasattr(_env, "set_mode"): + _env.set_mode(mode.value) should_close = True try: mcp_client = getattr(_env, "mcp_client", None) @@ -1142,6 +1381,27 @@ class HTTPEnvServer: } if method == McpMethod.TOOLS_LIST: + if hasattr(_env, "_async_handle_list_tools"): + obs = await _env._async_handle_list_tools() + if obs.metadata and "error" in obs.metadata: + return JsonRpcResponse.error_response( + JsonRpcErrorCode.INTERNAL_ERROR, + obs.metadata["error"], + request_id=request_id, + ) + tools = [ + { + "name": t.name, + "description": t.description or "", + "inputSchema": t.input_schema, + } + for t in obs.tools + ] + return JsonRpcResponse.success( + result={"tools": tools}, + request_id=request_id, + ) + # Check if environment is MCP-enabled if mcp_client is None and mcp_server is None: if supports_mcp_style_actions: @@ -1164,7 +1424,7 @@ class HTTPEnvServer: request_id=request_id, ) return JsonRpcResponse.error_response( - JsonRpcErrorCode.INTERNAL_ERROR, + JsonRpcErrorCode.METHOD_NOT_FOUND, "Environment does not support MCP", request_id=request_id, ) @@ -1180,7 +1440,7 @@ class HTTPEnvServer: return JsonRpcResponse.success( result={ "tools": [ - t.model_dump() + t.model_dump(by_alias=True) if hasattr(t, "model_dump") else dict(t) for t in tools @@ -1221,6 +1481,32 @@ class HTTPEnvServer: request_id=request_id, ) + if hasattr(_env, "_mode_tools") and any( + m is not None for m in _env._mode_tools.get(tool_name, {}) + ): + obs = await _env._async_handle_call_tool( + CallToolAction(tool_name=tool_name, arguments=arguments) + ) + if obs.error: + err_code = ( + JsonRpcErrorCode.INVALID_PARAMS + if obs.error.error_type + in ( + ToolErrorType.INVALID_ARGS, + ToolErrorType.TOOL_NOT_FOUND, + ) + else JsonRpcErrorCode.INTERNAL_ERROR + ) + return JsonRpcResponse.error_response( + err_code, + obs.error.message, + request_id=request_id, + ) + return JsonRpcResponse.success( + result=_make_json_serializable(obs.result), + request_id=request_id, + ) + if mcp_client is None and mcp_server is None: if supports_mcp_style_actions: observation = await call_mcp_style_step( @@ -1242,7 +1528,7 @@ class HTTPEnvServer: request_id=request_id, ) return JsonRpcResponse.error_response( - JsonRpcErrorCode.INTERNAL_ERROR, + JsonRpcErrorCode.METHOD_NOT_FOUND, "Environment does not support MCP", request_id=request_id, ) @@ -1414,7 +1700,7 @@ class HTTPEnvServer: try: # Create session with dedicated environment - session_id, session_env = await self._create_session() + session_id, session_env = await self._create_session(mode=mode) if session_env is None: raise RuntimeError( "Session environment not initialized for MCP websocket" @@ -1661,13 +1947,14 @@ The structure of the state object is defined by the environment's State model. tags=["Schema"], summary="Get all JSON schemas", description=""" -Get JSON schemas for actions, observations, and state in a single response. +Get JSON schemas for actions, observations, state, and reset parameters in a single response. Returns a combined schema object containing: - **action**: JSON schema for actions accepted by this environment - **observation**: JSON schema for observations returned by step - **reset_observation**: JSON schema for observations returned by reset - **state**: JSON schema for environment state objects +- **reset**: JSON schema for reset parameters accepted by this environment This is more efficient than calling individual schema endpoints and provides all schema information needed to interact with the environment. @@ -1690,6 +1977,10 @@ all schema information needed to interact with the environment. "type": "object", "properties": {"step_count": {"type": "integer"}}, }, + "reset": { + "type": "object", + "properties": {"seed": {"type": "integer"}}, + }, } } }, @@ -1703,6 +1994,7 @@ all schema information needed to interact with the environment. observation=self.observation_cls.model_json_schema(), reset_observation=self.reset_observation_cls.model_json_schema(), state=self.state_cls.model_json_schema(), + reset=self.reset_cls.model_json_schema(), ) # Register MCP endpoint for production mode (direct MCP access) @@ -1753,6 +2045,8 @@ all schema information needed to interact with the environment. session_env = None owns_session = False attached_session = False + telemetry = None + operations_started = False try: requested_session_id = websocket.query_params.get("session_id") @@ -1761,10 +2055,15 @@ all schema information needed to interact with the environment. attached_env = self._sessions.get( requested_session_id, _MISSING ) + session_mode = self._session_modes.get(requested_session_id) if attached_env is _MISSING: raise RuntimeError( f"Unknown session_id: {requested_session_id}" ) + if session_mode is not None and session_mode != mode.value: + raise RuntimeError( + f"Session '{requested_session_id}' belongs to mode '{session_mode}', not '{mode.value}'" + ) if attached_env is None: raise RuntimeError( f"Session {requested_session_id} is still initializing" @@ -1780,7 +2079,7 @@ all schema information needed to interact with the environment. attached_session = True self._update_session_activity(session_id) else: - session_id, session_env = await self._create_session() + session_id, session_env = await self._create_session(mode=mode) owns_session = True if session_env is None: @@ -1803,6 +2102,19 @@ all schema information needed to interact with the environment. # Receive message from client raw_message = await websocket.receive_text() + # The reaper or shutdown may have destroyed this + # session (closing its env and freeing its slot). + if session_id not in self._sessions: + error_resp = WSErrorResponse( + data={ + "message": "Session expired or was closed; " + "open a new connection", + "code": WSErrorCode.SESSION_ERROR, + } + ) + await websocket.send_text(error_resp.model_dump_json()) + break + try: message_dict = json.loads(raw_message) except json.JSONDecodeError as e: @@ -1817,6 +2129,67 @@ all schema information needed to interact with the environment. msg_type = message_dict.get("type", "") + if msg_type in {"validation_open", "validation_read"}: + # Do not return Pydantic input/error details: these messages + # contain credentials and must never echo or log them. + try: + if not validation_enabled or not owns_session: + raise ValueError("Validation unavailable") + if msg_type == "validation_open": + auth = ValidationOpenMessage.model_validate( + message_dict + ) + if telemetry is not None or operations_started: + raise ValueError("Validation already started") + if not secrets.compare_digest( + validation_token.encode(), + auth.data.token.get_secret_value().encode(), + ): + raise ValueError("Unauthorized") + telemetry = SessionTelemetry() + response = ValidationOpenedResponse( + data=ValidationOpenedData( + capability=telemetry.capability + ) + ) + else: + auth = ValidationReadMessage.model_validate( + message_dict + ) + if telemetry is None or not telemetry.authorized( + auth.data.capability.get_secret_value() + ): + raise ValueError("Unauthorized") + response = ValidationResponse( + data=telemetry.snapshot + ) + except Exception: + response = WSErrorResponse( + data={ + "message": "Validation unavailable or unauthorized", + "code": WSErrorCode.VALIDATION_ERROR, + } + ) + await websocket.send_text(response.model_dump_json()) + continue + + seed_acceptance = None + before_scores = None + if msg_type in {"reset", "step", "state"}: + operations_started = True + if telemetry is not None and msg_type == "step": + try: + before_scores = rubric_counts( + getattr(session_env, "rubric", None) + ) + except Exception: + telemetry.snapshot.rubric_error = ( + "Rubric introspection unavailable" + ) + + in_flight = self._session_operations_in_flight + in_flight[session_id] = in_flight.get(session_id, 0) + 1 + self._update_session_activity(session_id) try: match msg_type: case "reset": @@ -1848,7 +2221,12 @@ all schema information needed to interact with the environment. ) ) - self._update_session_activity(session_id) + if telemetry is not None: + seed_acceptance = SeedAcceptance( + requested="seed" in msg.data, + value=msg.data.get("seed"), + accepted="seed" in valid_kwargs, + ) response = WSObservationResponse( data=serialize_observation(observation), @@ -1925,9 +2303,39 @@ all schema information needed to interact with the environment. } ) + if telemetry is not None and msg_type in { + "reset", + "step", + "state", + }: + nodes = None + try: + if msg_type in {"reset", "step"}: + nodes = rubric_snapshot( + getattr(session_env, "rubric", None), + before_scores, + ) + except Exception: + nodes = [] + telemetry.snapshot.rubric_error = ( + "Rubric introspection unavailable" + ) + telemetry.append( + msg_type, + message_dict, + response.model_dump(mode="json"), + seed=seed_acceptance, + rubric=nodes, + ) await websocket.send_text(response.model_dump_json()) except ValidationError as e: + if telemetry is not None and msg_type in { + "reset", + "step", + "state", + }: + telemetry.incomplete("Session operation failed") error_resp = WSErrorResponse( data={ "message": "Invalid message", @@ -1937,6 +2345,12 @@ all schema information needed to interact with the environment. ) await websocket.send_text(error_resp.model_dump_json()) except Exception as e: + if telemetry is not None and msg_type in { + "reset", + "step", + "state", + }: + telemetry.incomplete("Session operation failed") error_resp = WSErrorResponse( data={ "message": str(e), @@ -1944,6 +2358,11 @@ all schema information needed to interact with the environment. } ) await websocket.send_text(error_resp.model_dump_json()) + finally: + in_flight[session_id] -= 1 + if in_flight[session_id] == 0: + del in_flight[session_id] + self._update_session_activity(session_id) except WebSocketDisconnect: pass @@ -2003,6 +2422,7 @@ def create_app( *, mode: Optional[ServerMode | str] = None, reset_observation_cls: Optional[Type[Observation]] = None, + reset_cls: Type[ResetRequest] = ResetRequest, ) -> FastAPI: """ Create a FastAPI application with or without web interface. @@ -2047,6 +2467,9 @@ def create_app( state_cls (`Type[State]`, *optional*, defaults to `State`): The `State` subclass this environment reports, used for the `/state` response model and the `state` entry of `/schema`. + reset_cls (`Type[ResetRequest]`, *optional*, defaults to `ResetRequest`): + The `ResetRequest` subclass describing this environment's reset parameters, + published as the `reset` entry of `/schema`. Not used for validation. mode (`ServerMode` or `str`, *optional*): Server mode. When `None`, resolved from the `OPENENV_MODE` environment variable, defaulting to simulation. @@ -2074,6 +2497,7 @@ def create_app( max_concurrent_envs, concurrency_config, state_cls=state_cls, + reset_cls=reset_cls, reset_observation_cls=reset_observation_cls, gradio_builder=gradio_builder, custom_tab_name=custom_tab_name, @@ -2092,6 +2516,7 @@ def create_app( concurrency_config, env_name=env_name, state_cls=state_cls, + reset_cls=reset_cls, reset_observation_cls=reset_observation_cls, mode=mode, ) @@ -2108,6 +2533,7 @@ def create_fastapi_app( *, mode: Optional[ServerMode | str] = None, reset_observation_cls: Optional[Type[Observation]] = None, + reset_cls: Type[ResetRequest] = ResetRequest, ) -> FastAPI: """ Create a FastAPI application with comprehensive documentation. @@ -2133,6 +2559,9 @@ def create_fastapi_app( state_cls (`Type[State]`, *optional*, defaults to `State`): The `State` subclass this environment reports, used for the `/state` response model and the `state` entry of `/schema`. + reset_cls (`Type[ResetRequest]`, *optional*, defaults to `ResetRequest`): + The `ResetRequest` subclass describing this environment's reset parameters, + published as the `reset` entry of `/schema`. Not used for validation. mode (`ServerMode` or `str`, *optional*): Server mode. When `None`, resolved from the `OPENENV_MODE` environment variable, defaulting to simulation. @@ -2160,7 +2589,7 @@ HTTP API for interacting with OpenEnv environments through a standardized interf * **Environment Reset**: Initialize or restart episodes * **Action Execution**: Send actions and receive observations * **State Inspection**: Query current environment state -* **Schema Access**: Retrieve JSON schemas for actions and observations +* **Schema Access**: Retrieve JSON schemas for actions, observations, state, and reset parameters ## Workflow @@ -2190,7 +2619,7 @@ HTTP API for interacting with OpenEnv environments through a standardized interf }, { "name": "Schema", - "description": "JSON Schema endpoints for actions, observations, and state", + "description": "JSON Schema endpoints for actions, observations, state, and reset parameters", }, {"name": "Health", "description": "Service health and status checks"}, ], @@ -2199,11 +2628,11 @@ HTTP API for interacting with OpenEnv environments through a standardized interf openapi_url="/openapi.json", contact={ "name": "OpenEnv Team", - "url": "https://github.com/huggingface/OpenEnv", + "url": "https://github.com/openenv/OpenEnv", }, license_info={ "name": "BSD-3-Clause", - "url": "https://github.com/huggingface/OpenEnv/blob/main/LICENSE", + "url": "https://github.com/openenv/OpenEnv/blob/main/LICENSE", }, ) @@ -2215,9 +2644,14 @@ HTTP API for interacting with OpenEnv environments through a standardized interf concurrency_config=concurrency_config, env_name=env_name, state_cls=state_cls, + reset_cls=reset_cls, reset_observation_cls=reset_observation_cls, ) if mode is None: mode = os.environ.get("OPENENV_MODE", ServerMode.SIMULATION.value) server.register_routes(app, mode=mode) + + from .security import attach_guard + + attach_guard(app) return app diff --git a/src/openenv/core/env_server/interfaces.py b/src/openenv/core/env_server/interfaces.py index 707547697748e694990f52568eeef3261a0b6cf8..8cd15ed7a8e37fe35375ccecbf83eeec23b48480 100644 --- a/src/openenv/core/env_server/interfaces.py +++ b/src/openenv/core/env_server/interfaces.py @@ -105,7 +105,7 @@ class TaskProvider(Protocol): Selecting a task is not part of this protocol — pass the chosen split and index to `reset()` instead. See the - [Task API guide](https://huggingface.co/docs/openenv/guides/task-api). + [Task API guide](https://openenv.github.io/OpenEnv/main/guides/task-api). Examples: @@ -223,7 +223,7 @@ class Transform(ABC, Generic[ObsT]): class Environment(ABC, Generic[ActT, ObsT, StateT]): """Base class for all environment servers following Gym/Gymnasium API. - See [rfcs/004-rubrics.md](https://github.com/huggingface/OpenEnv/blob/main/rfcs/004-rubrics.md) for rubric design details. + See [rfcs/004-rubrics.md](https://github.com/openenv/OpenEnv/blob/main/rfcs/004-rubrics.md) for rubric design details. Args: transform (`Transform`, *optional*): diff --git a/src/openenv/core/env_server/mcp_environment.py b/src/openenv/core/env_server/mcp_environment.py index 9d9ad564b9f965194ac6d3edb3766f99a42cbd2e..7d683fab84072bceca4841ffda213b2e86b6bb93 100644 --- a/src/openenv/core/env_server/mcp_environment.py +++ b/src/openenv/core/env_server/mcp_environment.py @@ -86,17 +86,17 @@ VALID_MODES = {"production", "simulation"} def get_server_tools(mcp_server: Any) -> Dict[str, Any]: """ - Get tools from a FastMCP server, compatible with both 2.x and 3.x. + Get tools from a FastMCP server. Returns: Dictionary mapping tool names to tool objects. """ - # FastMCP 2.x: get_tools() returns dict {name: Tool} + # FastMCP server tools are exposed as a name-to-tool mapping. if hasattr(mcp_server, "get_tools"): result = run_async_safely(mcp_server.get_tools()) if isinstance(result, dict): return result - # FastMCP 3.x: list_tools() returns list of Tool objects + # Some server adapters expose the tools as a list instead. if hasattr(mcp_server, "list_tools"): tools_list = run_async_safely(mcp_server.list_tools()) return {t.name: t for t in tools_list} @@ -108,7 +108,7 @@ def _tool_from_server_tool(tool: Any) -> Tool: return Tool( name=tool.name, description=tool.description or "", - input_schema=tool.inputSchema if hasattr(tool, "inputSchema") else {}, + input_schema=tool.input_schema, ) @@ -187,7 +187,9 @@ class MCPEnvironment(Environment): self._validate_tool_names(mcp_server) self.mcp_server = mcp_server - self.mcp_client = Client(mcp_server) + # OpenEnv sessions keep MCP state across tool calls. FastMCP 4's default + # modern protocol is sessionless, so use its supported legacy handshake. + self.mcp_client = Client(mcp_server, mode="legacy") # Track mode-specific tools: {tool_name: {mode: func}} # mode can be "production", "simulation", or None (available in all modes) @@ -195,6 +197,11 @@ class MCPEnvironment(Environment): # Track tool schemas for list_tools: {tool_name: {mode: schema}} self._mode_tool_schemas = defaultdict(dict) + self._mode: Optional[str] = None + + def set_mode(self, mode: Optional[str]) -> None: + """Set the active mode ('production' or 'simulation') for mode-aware tools.""" + self._mode = mode def _require_mcp_client(self) -> Any: """Return MCP client or raise if environment has been closed.""" @@ -249,7 +256,7 @@ class MCPEnvironment(Environment): def _get_server_tools(self, mcp_server: Any) -> Dict[str, Any]: """ - Get tools from a FastMCP server, compatible with both 2.x and 3.x. + Get tools from a FastMCP server. Returns: Dictionary mapping tool names to tool objects. @@ -496,7 +503,8 @@ class MCPEnvironment(Environment): tools_result = await self._async_list_tools() tools = [] for tool in tools_result: - if tool.name not in self._mode_tool_schemas: + mode_schemas = self._mode_tool_schemas.get(tool.name, {}) + if _schema_for_mode(mode_schemas, current_mode) is None: tools.append(_tool_from_server_tool(tool)) for mode_schemas in self._mode_tool_schemas.values(): schema = _schema_for_mode(mode_schemas, current_mode) @@ -519,21 +527,12 @@ class MCPEnvironment(Environment): tool_name = action.tool_name current_mode = getattr(self, "_mode", None) - if tool_name in self._mode_tools: - mode_info = self._mode_tools[tool_name] + mode_info = self._mode_tools.get(tool_name, {}) + if None in mode_info or current_mode in mode_info: if None in mode_info: func = mode_info[None] elif current_mode in mode_info: func = mode_info[current_mode] - else: - return CallToolObservation( - tool_name=tool_name, - result=None, - error=ToolError( - error_type=ToolErrorType.TOOL_NOT_FOUND, - message=f"Tool '{tool_name}' not available in {current_mode} mode", - ), - ) try: if inspect.iscoroutinefunction(func): result = await func(**action.arguments) diff --git a/src/openenv/core/env_server/security.py b/src/openenv/core/env_server/security.py new file mode 100644 index 0000000000000000000000000000000000000000..6757585d753abc843f2d94e12677f0308cd59202 --- /dev/null +++ b/src/openenv/core/env_server/security.py @@ -0,0 +1,192 @@ +# SPDX-License-Identifier: BSD-3-Clause + +"""Optional fastapi-guard security middleware for environment servers. + +Opt-in via the `OPENENV_GUARD_*` environment variables. When disabled (the +default), `attach_guard` is a no-op and environment servers behave exactly as +before. + +Install the extra with `pip install "openenv[security]"` and enable with +`OPENENV_GUARD_ENABLED=1` to get IP block/allow lists, rate limiting, +user-agent blocking, penetration-attempt detection with auto-ban, and optional +Redis-backed distributed state (fastapi-guard). + +Health and schema endpoints are excluded from detection checks so +orchestrators can probe the server; global IP allow/block lists are still +enforced on those paths. + +WebSocket connections (`/ws`, `/mcp`, `/harness`, `/ws/ui`) get the same +checks on the handshake: ban, IP lists, a separate rate-limit bucket and +penetration detection on the path, query and headers. A refused handshake is +closed before `accept()`, so the client gets HTTP 403 on the upgrade and no +socket. Messages on an accepted connection are not screened, for the same +reason request bodies are not. With Redis configured, the guard initializes at +startup; while Redis is unreachable a handshake is closed with 1013 and HTTP +requests are refused. +""" + +from __future__ import annotations + +import os +from contextlib import asynccontextmanager +from typing import Any + +from starlette import status +from starlette.exceptions import WebSocketException +from starlette.websockets import WebSocket + +DEFAULT_EXCLUDED_PATHS = [ + "/health", + "/schema", + "/metadata", + "/docs", + "/redoc", + "/openapi.json", +] +# Empty by default on purpose: trusting private-range peers would let +# any of them spoof X-Forwarded-For past the blocklist and rate limits. +# Behind a reverse proxy, list the proxy's addresses in +# OPENENV_GUARD_TRUSTED_PROXIES. +DEFAULT_TRUSTED_PROXIES = "" + + +def _env_list(name: str, default: str = "") -> list[str]: + raw = os.environ.get(name, default) + return [item.strip() for item in raw.split(",") if item.strip()] + + +def _env_bool(name: str) -> bool: + raw = os.environ.get(name) + if raw is None or not raw.strip(): + return False + normalized = raw.strip().lower() + if normalized in ("1", "true", "yes", "on"): + return True + if normalized in ("0", "false", "no", "off"): + return False + msg = f"{name} must be a boolean (1/true/yes/on or 0/false/no/off), got {raw!r}" + raise ValueError(msg) + + +def _build_security_config() -> Any: + from guard import SecurityConfig + + kwargs: dict[str, Any] = { + "enable_rate_limiting": True, + "rate_limit": int(os.environ.get("OPENENV_GUARD_RATE_LIMIT", "100")), + "rate_limit_window": int( + os.environ.get("OPENENV_GUARD_RATE_LIMIT_WINDOW", "60") + ), + "enable_ip_banning": True, + "auto_ban_threshold": int( + os.environ.get("OPENENV_GUARD_AUTO_BAN_THRESHOLD", "10") + ), + "auto_ban_duration": int( + os.environ.get("OPENENV_GUARD_AUTO_BAN_DURATION", "300") + ), + # Environment/request bodies are model input (observations, prompts, + # completions), not commands this server executes: signature-scanning + # them false-positives on ordinary content. URL, query, and header + # screening stay on. + "detection_scan_body": False, + "enable_penetration_detection": True, + # In-memory state unless a Redis URL is configured: never implicitly + # depend on a Redis server being reachable at localhost. + "enable_redis": False, + "blacklist": tuple(_env_list("OPENENV_GUARD_BLOCKED_IPS")), + "blocked_user_agents": _env_list("OPENENV_GUARD_BLOCKED_USER_AGENTS"), + "trusted_proxies": tuple( + _env_list("OPENENV_GUARD_TRUSTED_PROXIES", DEFAULT_TRUSTED_PROXIES) + ), + "trusted_proxy_depth": int( + os.environ.get("OPENENV_GUARD_TRUSTED_PROXY_DEPTH", "1") + ), + "exclude_paths": DEFAULT_EXCLUDED_PATHS, + # fastapi-guard sends security headers unless this is None, and its + # X-Frame-Options: SAMEORIGIN stops a Space page from framing the app. + "security_headers": None, + } + + allowed_ips = _env_list("OPENENV_GUARD_ALLOWED_IPS") + if allowed_ips: + kwargs["whitelist"] = tuple(allowed_ips) + + redis_url = os.environ.get("OPENENV_GUARD_REDIS_URL") + if redis_url: + kwargs["enable_redis"] = True + kwargs["redis_url"] = redis_url + + return SecurityConfig(**kwargs) + + +class _WebSocketGuardMiddleware: + # SecurityMiddleware is a BaseHTTPMiddleware, which never sees websocket + # scopes, so every handshake goes through fastapi-guard's guard_websocket. + def __init__(self, app: Any, config: Any) -> None: + from guard import guard_websocket + from guard.lifespan import _find_security_redis_handler, guard_startup + + self.app = app + self.config = config + self.guard_websocket = guard_websocket + # guard_websocket reads Redis through this; None means not connected. + self.find_redis = _find_security_redis_handler + self.guard_startup = guard_startup + + async def __call__(self, scope: Any, receive: Any, send: Any) -> None: + if scope["type"] == "websocket": + websocket = WebSocket(scope, receive, send) + try: + if not await self._redis_ready(scope["app"]): + # The HTTP side refuses too until Redis is reachable. + raise WebSocketException( + code=status.WS_1013_TRY_AGAIN_LATER, + reason="Service temporarily unavailable", + ) + await self.guard_websocket(websocket) + except WebSocketException as exc: + await websocket.close(code=exc.code, reason=exc.reason) + return + await self.app(scope, receive, send) + + async def _redis_ready(self, app: Any) -> bool: + if not self.config.enable_redis or self.find_redis(app) is not None: + return True + # Retry on each handshake, like the HTTP side's first request. + await self.guard_startup(app) + return self.find_redis(app) is not None + + +def attach_guard(app: Any) -> None: + """Add the fastapi-guard middleware to `app` when enabled via env. + + No-op unless OPENENV_GUARD_ENABLED is set to 1/true/yes/on. + """ + if not _env_bool("OPENENV_GUARD_ENABLED"): + return + if getattr(app.state, "guard_attached", False): + return + try: + from guard import SecurityMiddleware + from guard.lifespan import guard_lifespan + except ImportError as exc: + raise ImportError( + "OPENENV_GUARD_ENABLED requires fastapi-guard. " + 'Install it with: pip install "openenv[security]"' + ) from exc + + config = _build_security_config() + app.add_middleware(SecurityMiddleware, config=config) + app.add_middleware(_WebSocketGuardMiddleware, config=config) + # Initialize the guard (Redis included) at startup, so a WebSocket-only + # worker never runs on in-memory state. + existing_lifespan = app.router.lifespan_context + + @asynccontextmanager + async def lifespan(app: Any): + async with guard_lifespan(app): + async with existing_lifespan(app) as state: + yield state + + app.router.lifespan_context = lifespan + app.state.guard_attached = True diff --git a/src/openenv/core/env_server/session_telemetry.py b/src/openenv/core/env_server/session_telemetry.py new file mode 100644 index 0000000000000000000000000000000000000000..fe9c3eb0f45b3777856491c4bd0c738077a21630 --- /dev/null +++ b/src/openenv/core/env_server/session_telemetry.py @@ -0,0 +1,241 @@ +# SPDX-License-Identifier: BSD-3-Clause + +"""Bounded, opt-in evidence emitted by the subject's replay session.""" + +import json +import secrets +from typing import Any, Literal + +from openenv.core.rubrics.base import Rubric +from openenv.core.rubrics.containers import Gate, Sequential, WeightedSum +from pydantic import BaseModel, ConfigDict, Field, SecretStr + +MAX_TELEMETRY_BYTES = 8 * 1024 * 1024 +MAX_TRAJECTORY_ACTIONS = 100 +MAX_TRAJECTORY_RECORDS = 202 +MAX_RUBRIC_NODES = 128 + + +class _WireModel(BaseModel): + model_config = ConfigDict(extra="forbid", strict=True) + + +class ValidationOpenData(_WireModel): + schema_version: Literal[1] + token: SecretStr = Field(min_length=32, max_length=256) + + +class ValidationOpenMessage(_WireModel): + type: Literal["validation_open"] + data: ValidationOpenData + + +class ValidationReadData(_WireModel): + schema_version: Literal[1] + capability: SecretStr = Field(min_length=32, max_length=256) + + +class ValidationReadMessage(_WireModel): + type: Literal["validation_read"] + data: ValidationReadData + + +class ValidationOpenedData(_WireModel): + schema_version: Literal[1] = 1 + capability: str + + +class ValidationOpenedResponse(_WireModel): + type: Literal["validation_open"] = "validation_open" + data: ValidationOpenedData + + +class SeedAcceptance(_WireModel): + requested: bool + value: Any = None + accepted: bool + + +class RubricNode(_WireModel): + name: str + class_name: str + children: list[str] + aggregation: Literal["weighted_sum", "sequential", "gate", "leaf", "unknown"] + config: dict[str, Any] + config_available: bool + score: Any = None + evaluated: bool = False + + +class StepAttribution(_WireModel): + step_index: int + rubric: list[RubricNode] + + +class TrajectoryRecord(_WireModel): + operation: Literal["reset", "step", "state"] + request: dict[str, Any] + response: dict[str, Any] + + +class SubjectTrajectory(_WireModel): + schema_version: Literal[1] = 1 + source: Literal["openenv-server"] = "openenv-server" + records: list[TrajectoryRecord] = Field(default_factory=list) + complete: bool = True + reason: str | None = None + + +class ValidationSnapshot(_WireModel): + schema_version: Literal[1] = 1 + seed: SeedAcceptance | None = None + rubric: list[RubricNode] = Field(default_factory=list) + rubric_error: str | None = None + attribution: list[StepAttribution] = Field(default_factory=list) + trajectory: SubjectTrajectory = Field(default_factory=SubjectTrajectory) + + +class ValidationResponse(_WireModel): + type: Literal["validation"] = "validation" + data: ValidationSnapshot + + +def _rubrics(root: Rubric | None) -> list[tuple[str, Rubric]]: + """Visit the named tree with finite size, rejecting cycles and aliases.""" + if root is None: + return [] + result, pending, seen = [], [("root", root)], set() + while pending: + name, rubric = pending.pop() + if id(rubric) in seen or len(result) >= MAX_RUBRIC_NODES: + raise ValueError("Rubric tree is cyclic, shared, or exceeds 128 nodes") + seen.add(id(rubric)) + result.append((name, rubric)) + children = list(rubric.named_children()) + if any(not key or "." in key for key, _ in children): + raise ValueError("Rubric child names must be nonempty path segments") + pending.extend((f"{name}.{key}", child) for key, child in reversed(children)) + return result + + +def rubric_counts(root: Rubric | None) -> dict[int, int]: + return {id(r): r._evaluation_count for _, r in _rubrics(root)} + + +def rubric_snapshot( + root: Rubric | None, before: dict[int, int] | None = None +) -> list[RubricNode]: + nodes = [] + for name, rubric in _rubrics(root): + children = [f"{name}.{key}" for key, _ in rubric.named_children()] + aggregation = "unknown" if children else "leaf" + config = None + # Exact types: a subclass can override scoring, so its semantics are unknown. + if type(rubric) is WeightedSum: + aggregation, config = "weighted_sum", {"weights": list(rubric._weights)} + elif type(rubric) is Sequential: + aggregation, config = "sequential", {} + elif type(rubric) is Gate: + aggregation, config = "gate", {"threshold": rubric.threshold} + else: + config = rubric.validation_config() + evaluated = before is not None and rubric._evaluation_count > before.get( + id(rubric), 0 + ) + nodes.append( + RubricNode( + name=name, + class_name=f"{type(rubric).__module__}.{type(rubric).__qualname__}", + children=children, + aggregation=aggregation, + config={} if config is None else config, + config_available=config is not None, + score=rubric.last_score if evaluated else None, + evaluated=evaluated, + ) + ) + json.dumps([node.model_dump() for node in nodes], allow_nan=False) + return nodes + + +class SessionTelemetry: + """Own one socket's capability and a detached record of completed operations.""" + + def __init__(self): + self.capability = secrets.token_urlsafe(32) + self.snapshot = ValidationSnapshot() + self._bytes = 0 + self._steps = 0 + + def authorized(self, capability: str) -> bool: + return secrets.compare_digest(self.capability.encode(), capability.encode()) + + def append( + self, + operation: Literal["reset", "step", "state"], + request: dict[str, Any], + response: dict[str, Any], + *, + seed: SeedAcceptance | None = None, + rubric: list[RubricNode] | None = None, + ) -> None: + if not self.snapshot.trajectory.complete: + return + try: + # JSON round-trip detaches mutable observations/actions from the record. + record = TrajectoryRecord.model_validate( + json.loads( + json.dumps( + { + "operation": operation, + "request": request, + "response": response, + }, + allow_nan=False, + ) + ) + ) + attribution = ( + StepAttribution(step_index=self._steps, rubric=rubric or []) + if operation == "step" + else None + ) + byte_count = len(record.model_dump_json().encode()) + if attribution is not None: + byte_count += len(attribution.model_dump_json().encode()) + byte_count += ( + len(seed.model_dump_json().encode()) if seed is not None else 0 + ) + # Reserve room for the current rubric, envelope, and seed metadata. + current_bytes = len( + json.dumps( + [ + node.model_dump() + for node in (self.snapshot.rubric if rubric is None else rubric) + ], + allow_nan=False, + ).encode() + ) + if ( + len(self.snapshot.trajectory.records) >= MAX_TRAJECTORY_RECORDS + or operation == "step" + and self._steps >= MAX_TRAJECTORY_ACTIONS + or self._bytes + byte_count + current_bytes + 4096 > MAX_TELEMETRY_BYTES + ): + self.incomplete("Session telemetry budget exceeded") + return + self._bytes += byte_count + self.snapshot.trajectory.records.append(record) + if seed is not None: + self.snapshot.seed = seed.model_copy(deep=True) + if rubric is not None: + self.snapshot.rubric = [node.model_copy(deep=True) for node in rubric] + if attribution is not None: + self.snapshot.attribution.append(attribution.model_copy(deep=True)) + self._steps += 1 + except (TypeError, ValueError): + self.incomplete("Session telemetry contains non-JSON data") + + def incomplete(self, reason: str) -> None: + self.snapshot.trajectory.complete = False + self.snapshot.trajectory.reason = reason diff --git a/src/openenv/core/env_server/types.py b/src/openenv/core/env_server/types.py index 3ccc69bcb59ea814bc934bcadb8b9399fe009f33..c81c4e8e721e4cdba6559f78ee4196e165c930c8 100644 --- a/src/openenv/core/env_server/types.py +++ b/src/openenv/core/env_server/types.py @@ -236,6 +236,10 @@ class SchemaResponse(BaseMessage): state: Dict[str, Any] = Field( description="JSON schema for environment state objects" ) + reset: Optional[Dict[str, Any]] = Field( + default=None, + description="JSON schema for reset parameters accepted by this environment", + ) reset_observation: Optional[Dict[str, Any]] = Field( default=None, description="JSON schema for observations returned by reset" ) @@ -243,6 +247,8 @@ class SchemaResponse(BaseMessage): @model_serializer(mode="wrap") def _omit_undeclared_reset_schema(self, handler): data = handler(self) + if self.reset is None: + data.pop("reset", None) if self.reset_observation is None: data.pop("reset_observation", None) return data diff --git a/src/openenv/core/env_server/web_interface.py b/src/openenv/core/env_server/web_interface.py index b0366aefe38077bc0df050294d1913f1163ffaae..449b90f99dc133ab475eff66bf5bda4958487232 100644 --- a/src/openenv/core/env_server/web_interface.py +++ b/src/openenv/core/env_server/web_interface.py @@ -28,7 +28,7 @@ from .gradio_theme import OPENENV_GRADIO_CSS, OPENENV_GRADIO_THEME from .gradio_ui import build_gradio_app, get_gradio_display_title from .interfaces import Environment from .serialization import deserialize_action_with_preprocessing, serialize_observation -from .types import Action, EnvironmentMetadata, Observation, State +from .types import Action, EnvironmentMetadata, Observation, ResetRequest, State _CLIENT_BASES = {"EnvClient", "MCPClientBase", "MCPToolClient"} @@ -169,7 +169,7 @@ def get_quick_start_markdown( lines += ["", after] lines += [ "", - "More in the [OpenEnv documentation](https://huggingface.co/docs/openenv).", + "More in the [OpenEnv documentation](https://openenv.github.io/OpenEnv/).", ] return "\n".join(lines) @@ -485,6 +485,7 @@ def create_web_interface_app( *, mode: Optional[Any] = None, reset_observation_cls: Optional[Type[Observation]] = None, + reset_cls: Type[ResetRequest] = ResetRequest, ) -> FastAPI: """ Create a FastAPI application with web interface for the given environment. @@ -519,6 +520,9 @@ def create_web_interface_app( title instead of the default ``"OpenEnv Agentic Environment: {name}"``. state_cls: The State subclass this environment reports. Used for the /state response model and the state entry of /schema. Defaults to State. + reset_cls: The ResetRequest subclass describing reset parameters. Published + as the reset entry of /schema; not used for validation. Defaults to + ResetRequest. mode: Server mode (``ServerMode`` or string). When ``None``, resolved from the ``OPENENV_MODE`` environment variable, defaulting to simulation. @@ -537,6 +541,7 @@ def create_web_interface_app( concurrency_config, env_name=env_name, state_cls=state_cls, + reset_cls=reset_cls, reset_observation_cls=reset_observation_cls, mode=mode, ) @@ -638,6 +643,8 @@ def create_web_interface_app( css=OPENENV_GRADIO_CSS, ) + # Security middleware is attached inside create_fastapi_app, before the + # gradio mount at /web; it is app-level middleware, so it covers the mount. return app diff --git a/src/openenv/core/harness/bridge.py b/src/openenv/core/harness/bridge.py index 7167690ac56b926e05644771bc66591aafde2263..badf965571c2f1e096dddbcb87fe178dc86e08f7 100644 --- a/src/openenv/core/harness/bridge.py +++ b/src/openenv/core/harness/bridge.py @@ -14,7 +14,7 @@ from .adapter import HarnessError async def _source_tools(mcp_server: Any) -> dict[str, Any]: - """Return {name: FastMCP tool}, compatible with FastMCP 2.x and 3.x. + """Return {name: FastMCP tool}. Async twin of [`~openenv.core.env_server.mcp_environment.get_server_tools`], which wraps the same calls in `run_async_safely`; awaiting directly avoids @@ -52,9 +52,11 @@ async def build_bridge_server(mcp_server: Any, renames: dict[str, str]) -> Any: return mcp_server from fastmcp import Client + from fastmcp.server.dependencies import get_context from fastmcp.server.providers.proxy import FastMCPProxy, StatefulProxyClient from fastmcp.server.transforms import ToolTransform from fastmcp.tools.tool_transform import ToolTransformConfig + from mcp_types.version import MODERN_PROTOCOL_VERSIONS source_tools = await _source_tools(mcp_server) missing = sorted(set(renames.values()) - set(source_tools)) @@ -71,12 +73,20 @@ async def build_bridge_server(mcp_server: Any, renames: dict[str, str]) -> Any: async with Client(mcp_server): yield {} - # Forward callbacks in the current request context. Each harness MCP - # connection gets its own source session, closed on disconnect. + # Keep one backend client per front connection, and mirror its protocol era. + # StatefulProxyClient defaults to legacy, which cannot carry sampling guards. client = StatefulProxyClient(mcp_server) + + def client_factory(): + backend = client.new_stateful() + if not backend.is_connected(): + version = get_context().request_context.protocol_version + backend.mode = version if version in MODERN_PROTOCOL_VERSIONS else "legacy" + return backend + view = FastMCPProxy( name=f"{getattr(mcp_server, 'name', 'openenv')}-harness-view", - client_factory=client.new_stateful, + client_factory=client_factory, lifespan=lifespan, ) view.add_transform( diff --git a/src/openenv/core/harness/capture/forwarding.py b/src/openenv/core/harness/capture/forwarding.py index 1c8e841452f86aaaf16107395813f5c408fb0b54..83aa1bb834d720c6e2cafd42e1c8564492990852 100644 --- a/src/openenv/core/harness/capture/forwarding.py +++ b/src/openenv/core/harness/capture/forwarding.py @@ -33,6 +33,7 @@ why `SessionRegistry.require_registered` defaults to True. from __future__ import annotations +import importlib import logging import re import secrets @@ -42,6 +43,12 @@ import subprocess import threading import time from abc import ABC, abstractmethod +from pathlib import Path + +try: + import fcntl +except ImportError: # Windows: no advisory locks, keep gradio's unlocked download. + fcntl = None logger = logging.getLogger(__name__) @@ -147,6 +154,25 @@ class GradioForwarder(PortForwarder): f"gradio is required for GradioForwarder: {exc}" ) from exc + @staticmethod + def _ensure_frpc_binary() -> None: + """ + Download gradio's frpc binary once, under a cross-process lock. + + Gradio checks `Path(BINARY_PATH).exists()` and then writes the binary in place. A second + process that starts while the first is still writing sees the file, skips the download and + executes a half-written binary, which fails with `Text file busy` (ETXTBSY) or a corrupt + executable. Holding an exclusive lock next to the binary makes every other process wait + until the first download has finished, after which gradio's own check skips the download. + """ + tunneling = importlib.import_module("gradio.tunneling") + binary = Path(tunneling.BINARY_PATH) + binary.parent.mkdir(parents=True, exist_ok=True) + with open(binary.with_name(binary.name + ".lock"), "a") as lock_file: + if fcntl is not None: + fcntl.flock(lock_file, fcntl.LOCK_EX) + tunneling.Tunnel.download_binary() + def start(self, local_port: int, *, local_host: str = "127.0.0.1") -> str: from gradio.networking import setup_tunnel from gradio.tunneling import CURRENT_TUNNELS @@ -154,6 +180,7 @@ class GradioForwarder(PortForwarder): self.stop() share_token = secrets.token_hex(16) try: + self._ensure_frpc_binary() url = setup_tunnel( local_host=local_host, local_port=local_port, diff --git a/src/openenv/core/harness/capture/graph.py b/src/openenv/core/harness/capture/graph.py index 61cc88bf2dc54662e9fa55d643ae4468d9e0a808..820689b54d21c97bd57172b06493f1871c5a466c 100644 --- a/src/openenv/core/harness/capture/graph.py +++ b/src/openenv/core/harness/capture/graph.py @@ -248,9 +248,25 @@ class RolloutGraph: self._nodes: dict[str, TurnNode] = {} self._order: list[str] = [] self._children: dict[str, list[str]] = {} + # Every request re-sends the whole history, so each turn decodes a fresh copy of every + # earlier image and long text. Keep one copy per graph. Only immutable strings are shared; + # message dicts and lists stay per turn. + self._shared_text: dict[str, str] = {} + + def _share_text(self, value: Any) -> Any: + if isinstance(value, str) and len(value) >= 1024: + return self._shared_text.setdefault(value, value) + if isinstance(value, list): + return [self._share_text(item) for item in value] + if isinstance(value, dict): + return {key: self._share_text(item) for key, item in value.items()} + return value # --- construction -------------------------------------------------- def add_turn(self, node: TurnNode) -> TurnNode: + node.request_messages = self._share_text(node.request_messages) + node.request_tools = self._share_text(node.request_tools) + node.response_message = self._share_text(node.response_message) node.index = len(self._order) node.parent_id = self._find_parent(node) self._nodes[node.node_id] = node diff --git a/src/openenv/core/harness/capture/server.py b/src/openenv/core/harness/capture/server.py index 32b9dad48bf7934f1c67c0f91dd36d748d4315c3..9d9f956c55b37c29143266e1bd7da747afbb26b7 100644 --- a/src/openenv/core/harness/capture/server.py +++ b/src/openenv/core/harness/capture/server.py @@ -266,6 +266,41 @@ def clamp_output_tokens(chat_request: dict[str, Any], cap: int | None) -> int | return replaced +def context_window_ran_out( + chat_request: dict[str, Any], response: dict[str, Any] +) -> bool: + """Whether the engine cut the completion short because the context window was full. + + Older vLLM rejects a request whose prompt plus `max_tokens` exceeds the context window with a 400 + ("maximum context length"), which the proxy turns into a budget stop. Newer vLLM (seen with 0.34) + serves it and stops generating when the window is full instead: the completion ends with + `finish_reason="length"` before reaching `max_tokens`. Forwarded as is, that truncated turn reaches + the harness, and pi answers it by compacting its context, in a summarisation call capture cannot + tie to the rest of the rollout: every such rollout fails validation with `turn_mismatch`. It is the + same event as the 400, so it ends the rollout the same way. + """ + # The limit the engine applies, in its order: vLLM (like OpenAI) takes `max_completion_tokens` and + # falls back to `max_tokens`. A harness that sends both with different values would otherwise turn + # an output-cap stop into a context stop, or hide a real one. + requested = next( + ( + chat_request[key] + for key in ("max_completion_tokens", "max_tokens") + if isinstance(chat_request.get(key), int) + ), + None, + ) + choices = response.get("choices") or [] + completion_tokens = (response.get("usage") or {}).get("completion_tokens") + return ( + requested is not None + and isinstance(completion_tokens, int) + and bool(choices) + and choices[0].get("finish_reason") == "length" + and completion_tokens < requested + ) + + def normalise_for_capture(chat_request: dict[str, Any]) -> None: """Force the upstream call into the one shape that yields complete, capturable responses. @@ -1199,6 +1234,23 @@ def create_app( for key in SAMPLING_KEYS: chat_request.pop(key, None) chat_request.update(effective_sampling) + if context_window_ran_out(chat_request, response): + # Like the 400 above: a stop the harness ends on, and the truncated turn is never ingested + session.findings.append( + "[WARN] context_budget_exhausted: the engine stopped at the context window, " + "before max_tokens" + ) + session.budget_stop_count += 1 + stop = _budget_stop_response(_model_of(session) or app.state.model) + if client_wants_stream: + return StreamingResponse( + sse.replay(api_type, transformer, stop, original_request), + media_type="text/event-stream", + headers=sse.SSE_HEADERS, + ) + payload = transformer.transform_response(stop, original_request) + normalise_client_payload(payload, api_type) + return JSONResponse(payload) normalise_response(response) _ingest( session, diff --git a/src/openenv/core/harness/capture/validate_llm.py b/src/openenv/core/harness/capture/validate_llm.py index 41028e4a6b389aeff73511fff1508cb4c5facec3..4c96a4798c4cebb49b74e3e067fa65be2ac49d9b 100644 --- a/src/openenv/core/harness/capture/validate_llm.py +++ b/src/openenv/core/harness/capture/validate_llm.py @@ -44,11 +44,13 @@ from __future__ import annotations import json import os +import time import urllib.error import urllib.request from dataclasses import dataclass, field +from urllib.parse import urlsplit -from .compat import behaviour_warnings, diagnose, MAX_FIXES +from .compat import behaviour_warnings, diagnose, MAX_FIXES, ParamFix from .upstream import ( auth_headers, normalise_engine_base, @@ -70,6 +72,25 @@ ENGINE_HINT = ( ) +# How many times the probe repeats the SAME request after an error that names nothing it can fix. +# Hosted routers occasionally answer a valid request with a 400 or 5xx that a resend clears: observed +# as one task in ~150 aborting before it ran, against an endpoint that served the other 149. +PROBE_RETRIES = 2 +PROBE_RETRY_DELAY = 1.0 +# Errors no resend or rewrite can fix: bad credentials, no access, no such route or model. Retrying +# these only delays a message the user needs now. +_FATAL_HTTP = frozenset({401, 403, 404}) +# Statuses with which a provider rejects a request it doesn't accept, e.g. unsupported capture params. +_PARAM_REJECTION_HTTP = frozenset({400, 422}) +# What the eval fallback drops. `logprobs` also takes `top_logprobs` with it (see `ParamFix.apply`). +_CAPTURE_PARAMS = ("return_token_ids", "logprobs") + + +def _is_timeout(exc: BaseException) -> bool: + reason = getattr(exc, "reason", None) + return isinstance(exc, TimeoutError) or isinstance(reason, TimeoutError) + + @dataclass class LLMReport: """Outcome of the probe. `ok` means trainable; `reachable` means usable at all.""" @@ -574,7 +595,10 @@ def validate_llm( # or gate it behind different scopes than inference, and refusing there would reject an endpoint # that serves completions perfectly well. The completion probe below is the real test; a missing # list only costs us the model-name check. - listed_model = model.rsplit(":", 1)[0] if provider == "hf" else model + # The HF router lists bare ids but routes `:` (also `:fastest`, `:cheapest`). The + # CLI reaches it with the default provider, so recognise the router by its host as well. + hf_router = urlsplit(base).hostname == "router.huggingface.co" + listed_model = model.rsplit(":", 1)[0] if provider == "hf" or hf_router else model if served and model not in served and listed_model not in served: # Worth failing on rather than warning: a mismatched name is silently accepted by some # servers and then every request 404s at rollout time instead of at startup. @@ -603,6 +627,7 @@ def validate_llm( applied: list = [] payload: dict | None = None failure = "" + retries_left = PROBE_RETRIES # Negotiate down. Each 400 that names a parameter costs one retry and removes one obstacle; the # capture params are the ones most likely to go, and losing them is what decides the level. @@ -630,13 +655,40 @@ def validate_llm( fix = diagnose(json.loads(detail)) except json.JSONDecodeError: fix = diagnose(detail) - if fix is None or not fix.apply(body): - failure = f"probe failed: HTTP {exc.code}: {detail[:300]}" + if fix is not None and fix.apply(body): + fixes.append(str(fix)) + applied.append(fix) + continue + failure = f"probe failed: HTTP {exc.code}: {detail[:300]}" + if exc.code in _FATAL_HTTP: break - fixes.append(str(fix)) - applied.append(fix) + # An error that names no parameter is first treated as transient: the same request again. + if retries_left: + retries_left -= 1 + time.sleep(PROBE_RETRY_DELAY) + continue + # Still failing. Some providers reject the capture params with a bare 400 that names + # nothing, so ask once more without them. If that answers, the endpoint is an eval + # backend (the level is graded from what comes back), which is what `ENGINE_HINT` + # promises. A `purpose="train"` rollout still refuses it, since the level is not `tokens`. + # Only a request error can be about the params: a 5xx or a 429 that outlasts the retries + # is reported, rather than grading a busy token-capable engine as `text`. + if exc.code not in _PARAM_REJECTION_HTTP: + break + dropped = [ParamFix(param=p) for p in _CAPTURE_PARAMS] + dropped = [f for f in dropped if f.apply(body)] + if not dropped: + break + for f in dropped: + fixes.append(f"{f} (eval fallback after HTTP {exc.code})") + applied.append(f) except Exception as exc: # noqa: BLE001 failure = f"probe failed: {type(exc).__name__}: {str(exc)[:300]}" + # A timeout is worth repeating. Anything else here (connection refused, DNS) is not. + if _is_timeout(exc) and retries_left: + retries_left -= 1 + time.sleep(PROBE_RETRY_DELAY) + continue break if payload is None: diff --git a/src/openenv/core/harness/collect.py b/src/openenv/core/harness/collect.py index 946ce5d54b98fc66ed8ed2e8821b38683a6f86ba..82d0a5fb14485cb871c44878961b15235f6d526d 100644 --- a/src/openenv/core/harness/collect.py +++ b/src/openenv/core/harness/collect.py @@ -23,10 +23,11 @@ import warnings from dataclasses import asdict, dataclass, field from datetime import datetime, timezone from pathlib import Path -from typing import Any, BinaryIO, Callable, Iterable, Iterator +from typing import Any, BinaryIO, Callable, Iterable from ..env_server.mcp_types import Tool from ..llm_client import LLMClient +from ..utils import redact_secrets from .rollout import ( _resolve_env_reward, HarnessAdapter, @@ -237,9 +238,10 @@ class CollectResult: class CollectRunner: """Drive repeated rollouts into an append-only JSONL dataset. - The runner is stateless across ``run()`` calls — resume state lives on - disk via the ``RolloutSerializer``. A single runner instance can be - reused across runs targeting different output dirs. + Resume state lives on disk via the ``RolloutSerializer``. Repeatable task + iterables, such as lists and tuples, restart at the first task on each + ``run()`` so tasks stay aligned with episode ids. One-shot iterators work + for one run; reusing them raises ``ValueError`` before accessing results. """ def __init__( @@ -254,17 +256,10 @@ class CollectRunner: self._session_factory = session_factory self._harness_adapter = harness_adapter self._serializer = serializer - self._tasks: Iterator[Any] | None = iter(tasks) if tasks is not None else None + self._tasks = tasks + self._tasks_used = False self._limits = limits - def _next_task(self) -> Any: - if self._tasks is None: - return None - try: - return next(self._tasks) - except StopIteration: - return None - def run( self, *, @@ -274,6 +269,16 @@ class CollectRunner: resume: bool = True, should_keep: Callable[[EpisodeRecord], bool] | None = None, ) -> CollectResult: + task_iterator = iter(self._tasks) if self._tasks is not None else None + if ( + task_iterator is not None + and task_iterator is self._tasks + and self._tasks_used + ): + raise ValueError( + "Cannot reuse a one-shot task iterator; pass a repeatable iterable " + "or create a new CollectRunner with a fresh iterator." + ) planned_ids = [f"{episode_id_prefix}-{i:06d}" for i in range(num_episodes)] if resume: @@ -312,7 +317,8 @@ class CollectRunner: with progress: for episode_id in planned_ids: # Preserve task-to-episode alignment even when resume skips ids. - task = self._next_task() + self._tasks_used = True + task = next(task_iterator, None) if task_iterator is not None else None if episode_id in already: num_skipped += 1 progress.advance(task_id) @@ -513,7 +519,7 @@ def build_dataset_readme(output_dir: Path) -> str: "", "# OpenEnv rollouts", "", - "Collected with [OpenEnv](https://github.com/huggingface/OpenEnv) " + "Collected with [OpenEnv](https://github.com/openenv/OpenEnv) " "(`openenv collect`).", "", f"- **Episodes:** {_count_episodes(results_path)}", @@ -594,6 +600,19 @@ def push_to_hf_hub( readme_path = output_dir / README_FILENAME readme_path.write_text(build_dataset_readme(output_dir), encoding="utf-8") + # Episodes hold what the agent saw and printed, which can include credentials. + redacted = 0 + for path in output_dir.iterdir(): + if path.suffix in {".jsonl", ".json", ".md"}: + text, count = redact_secrets(path.read_text(encoding="utf-8")) + if count: + path.write_text(text, encoding="utf-8") + redacted += count + if redacted: + warnings.warn( + f"Redacted {redacted} secret(s) from {output_dir} before the upload" + ) + num_episodes = _count_episodes(results_path) message = commit_message or f"Add {num_episodes} collected episode(s)" diff --git a/src/openenv/core/mcp_client.py b/src/openenv/core/mcp_client.py index 9002fabf9bcafc743660cb6cf04e364976c45391..c7967a926291691a58e79fddb647e5ff7a214272 100644 --- a/src/openenv/core/mcp_client.py +++ b/src/openenv/core/mcp_client.py @@ -255,6 +255,12 @@ class MCPClientBase(EnvClient[Any, Observation, State]): return await super()._connect_async() + def _raise_if_session_lost(self) -> None: + # In production mode a reconnect attaches to the same HTTP MCP session, + # which outlives the WebSocket, so the episode carries over. + if not getattr(self, "use_production_mode", False): + super()._raise_if_session_lost() + async def _ensure_production_session(self) -> str: """Create and cache a persistent HTTP MCP session id if needed.""" async with self._production_session_lock: diff --git a/src/openenv/core/rubrics/base.py b/src/openenv/core/rubrics/base.py index 0e2753047f755f2fcd1a5f263f3f25d5cd67b55d..276de7b3c456ed1d0c0f8b7e5831bd9bc9e1eb40 100644 --- a/src/openenv/core/rubrics/base.py +++ b/src/openenv/core/rubrics/base.py @@ -46,6 +46,7 @@ class Rubric(ABC): object.__setattr__(self, "_forward_hooks", []) object.__setattr__(self, "_forward_pre_hooks", []) object.__setattr__(self, "last_score", None) + object.__setattr__(self, "_evaluation_count", 0) def __setattr__(self, name: str, value: Any) -> None: # Auto-register child rubrics when assigned as attributes @@ -118,6 +119,7 @@ class Rubric(ABC): def _finish_forward(self, action: Any, observation: Any, result: float) -> float: """Store the result and run post-forward hooks synchronously.""" self.last_score = result + self._evaluation_count += 1 # Post-forward hooks for hook in self._forward_hooks: @@ -130,6 +132,7 @@ class Rubric(ABC): ) -> float: """Store the result and run post-forward hooks from an async call path.""" self.last_score = result + self._evaluation_count += 1 # Post-forward hooks for hook in self._forward_hooks: @@ -234,8 +237,22 @@ class Rubric(ABC): return current def reset(self) -> None: - """Reset any internal state. Override in subclasses if needed.""" - pass + """Reset internal state, including every child rubric. + + Override to clear your own state and call `super().reset()` so child + rubrics are reset too. + """ + for child in self.children(): + child.reset() + + def validation_config(self) -> Optional[Dict[str, Any]]: + """Return explicitly public configuration for authorized validation. + + Override to expose JSON configuration without credentials or runtime state. + ``None`` means configuration introspection is unavailable. Stock aggregation + containers expose their weights/threshold directly through the server. + """ + return None def state_dict(self) -> Dict[str, Any]: """Serialize rubric configuration for checkpointing.""" diff --git a/src/openenv/core/rubrics/containers.py b/src/openenv/core/rubrics/containers.py index ed796aaa1d64a425f2d1d1cf3e0206bf5e695750..17d88a8dbe934e551fef52df0f67b4e65a30d3f2 100644 --- a/src/openenv/core/rubrics/containers.py +++ b/src/openenv/core/rubrics/containers.py @@ -76,6 +76,8 @@ class Sequential(Rubric): # Pre-hooks run before any child is evaluated ran = self._run_leading_sync_pre_hooks(action, observation) + if ran < len(self._forward_pre_hooks): + return self._call_async_detected(action, observation, None, ran) # Call first rubric to see if it's async first_result = self._rubric_list[0](action, observation) @@ -85,8 +87,7 @@ class Sequential(Rubric): else: # Continue with sync path if first_result == 0.0: - self._run_forward_pre_hooks(action, observation, start=ran) - return self._finish_forward(action, observation, 0.0) + return self._finish_sync(action, observation, 0.0, ran) final_result = first_result for i, rubric in enumerate(self._rubric_list[1:], start=1): @@ -102,16 +103,21 @@ class Sequential(Rubric): ran, ) if score == 0.0: - self._run_forward_pre_hooks(action, observation, start=ran) - return self._finish_forward(action, observation, 0.0) + return self._finish_sync(action, observation, 0.0, ran) final_result = score - # All sync - check if in async context - if _in_async_context(): - return self._wrap_sync_result(action, observation, final_result, ran) - else: - self._run_forward_pre_hooks(action, observation, start=ran) - return self._finish_forward(action, observation, final_result) + return self._finish_sync(action, observation, final_result, ran) + + def _finish_sync(self, action, observation, result, ran=0): + """Finish a run where every evaluated child was sync. + + In an async context, return an awaitable even when a child stopped + the chain, so callers can always ``await`` the result. + """ + if _in_async_context(): + return self._wrap_sync_result(action, observation, result, ran) + self._run_forward_pre_hooks(action, observation, start=ran) + return self._finish_forward(action, observation, result) async def _empty_async(self, action, observation): """Async path for empty sequential.""" @@ -124,10 +130,16 @@ class Sequential(Rubric): return await self._finish_forward_async(action, observation, result) async def _call_async_detected(self, action, observation, first_coro, ran=0): - """Async path when first child is async.""" + """Async path for an async first child or pending pre-hooks.""" await self._run_forward_pre_hooks_async(action, observation, start=ran) - result = await first_coro + result = ( + self._rubric_list[0](action, observation) + if first_coro is None + else first_coro + ) + if inspect.iscoroutine(result): + result = await result if result == 0.0: return await self._finish_forward_async(action, observation, result) @@ -207,6 +219,8 @@ class Gate(Rubric): """Override to handle async child.""" # Pre-hooks run before the child is evaluated ran = self._run_leading_sync_pre_hooks(action, observation) + if ran < len(self._forward_pre_hooks): + return self._call_async(action, observation, None, ran) # Call child score = self.rubric(action, observation) @@ -224,7 +238,9 @@ class Gate(Rubric): """Async path.""" await self._run_forward_pre_hooks_async(action, observation, start=ran) - score = await score_coro + score = self.rubric(action, observation) if score_coro is None else score_coro + if inspect.iscoroutine(score): + score = await score result = 0.0 if score < self.threshold else score return await self._finish_forward_async(action, observation, result) @@ -282,6 +298,8 @@ class WeightedSum(Rubric): """Override to handle async children with parallel execution.""" # Pre-hooks run before any child is evaluated ran = self._run_leading_sync_pre_hooks(action, observation) + if ran < len(self._forward_pre_hooks): + return self._call_async(action, observation, None, ran) # Call all rubrics results = [rubric(action, observation) for rubric in self._rubric_list] @@ -304,6 +322,9 @@ class WeightedSum(Rubric): """Async path with parallel execution.""" await self._run_forward_pre_hooks_async(action, observation, start=ran) + if results is None: + results = [rubric(action, observation) for rubric in self._rubric_list] + # Separate sync and async results async_tasks = [] async_indices = [] diff --git a/src/openenv/core/rubrics/trajectory.py b/src/openenv/core/rubrics/trajectory.py index 6a62aceb5a19df77fe007d950266a58c2c3f8434..db94ee10bb4026ecc5d8caf3ab45be84bfb64c4a 100644 --- a/src/openenv/core/rubrics/trajectory.py +++ b/src/openenv/core/rubrics/trajectory.py @@ -118,6 +118,7 @@ class TrajectoryRubric(Rubric): def reset(self) -> None: """Clear accumulated trajectory. Call on env.reset().""" + super().reset() self._trajectory = [] @property diff --git a/src/openenv/core/sync_client.py b/src/openenv/core/sync_client.py index 0de088a095c6f8382bc10d6accc842ecc2350c51..4c94ce5732af67b5e405df6162a6d977e3e4c784 100644 --- a/src/openenv/core/sync_client.py +++ b/src/openenv/core/sync_client.py @@ -243,8 +243,15 @@ class SyncEnvClient(Generic[ActT, ObsT, StateT]): WebSocket can fail and is surfaced as a connection error. """ async_client = self._async._create_session_client() - client = SyncEnvClient(async_client) - client.connect() + client = async_client.sync() + try: + client.connect() + except Exception: + # No caller receives this child on failure. Release its loop here + # while preserving the connection error if cleanup also fails. + with suppress(Exception): + client.close() + raise self._child_clients.append(client) return client diff --git a/src/openenv/core/tools/git_server_client.py b/src/openenv/core/tools/git_server_client.py index b0100a444e7835784eec48478184b855feba5c7e..ea20134e225c62c86f66e0b49be11621ac0a2d50 100644 --- a/src/openenv/core/tools/git_server_client.py +++ b/src/openenv/core/tools/git_server_client.py @@ -10,6 +10,7 @@ instances share the same Gitea server but have isolated workspaces. import atexit import json import os +import re import shlex import shutil import subprocess @@ -17,7 +18,82 @@ import tempfile import time from dataclasses import dataclass from pathlib import Path -from urllib.parse import urlparse +from urllib.parse import quote, urlparse + +# Git subcommands an agent may run. Left out: those that run other programs (submodule, bisect, +# difftool, filter-branch) or read files outside the repository (hash-object, apply, am), and +# global options before the subcommand (`-c`, `-C`, `--git-dir`). +_AGENT_SUBCOMMANDS = frozenset( + { + "add", + "blame", + "branch", + "checkout", + "cherry-pick", + "commit", + "config", + "describe", + "diff", + "fetch", + "grep", + "init", + "log", + "ls-files", + "merge", + "mv", + "pull", + "push", + "rebase", + "remote", + "reset", + "restore", + "rev-parse", + "revert", + "rm", + "shortlog", + "show", + "stash", + "status", + "switch", + "tag", + } +) +# Options that run a program or read or write a path outside the repository. Git also accepts any +# unambiguous prefix of a long option, so prefixes are refused too. +_BLOCKED_LONG_OPTIONS = ( + "--config", + "--exec", + "--ext-diff", + "--extcmd", + "--file", + "--no-index", + "--open-files-in-pager", + "--output", + "--pathspec-from-file", + "--receive-pack", + "--template", + "--upload-pack", +) +_BLOCKED_SHORT_OPTIONS = "FOx" # -F , grep -O , rebase -x +_SECRET_ENV_NAME = re.compile(r"(^|_)(TOKEN|KEY|SECRET|PASSWORD)(_|$)", re.IGNORECASE) + + +def _refusal(args: list[str]) -> str | None: + """Why an agent's git arguments are refused, or `None` when they may run.""" + if not args or args[0] not in _AGENT_SUBCOMMANDS: + return f"git {args[0] if args else ''} is not available here" + if args[0] == "config" and ( + len(args) > 3 or args[1:2] not in (["--get"], ["--get-all"], ["--list"]) + ): + return "git config is not available here, except --get , --get-all and --list" + for arg in args[1:]: + name = arg.split("=", 1)[0] + if name.startswith("--") and len(name) > 2: + if any(option.startswith(name) for option in _BLOCKED_LONG_OPTIONS): + return f"{name} is not available here" + elif name.startswith("-") and set(name[1:]) & set(_BLOCKED_SHORT_OPTIONS): + return f"{name} is not available here" + return None @dataclass @@ -101,10 +177,13 @@ class GitServerClient: config_dir = Path(tempfile.mkdtemp(prefix="openenv-git-")) atexit.register(shutil.rmtree, config_dir, ignore_errors=True) - # Git credentials - git_credentials = ( - f"http://{self.username}:{self.password}@{self.domain}:{self.port}\n" - ) + # Git credentials. The entry must match the URL git is given (scheme and + # host[:port]), and the user name and password must be percent-encoded + # so characters such as "@", ":", "/" or "#" do not break the URL. + parsed = urlparse(self.gitea_url) + user = quote(self.username, safe="") + password = quote(self.password, safe="") + git_credentials = f"{parsed.scheme}://{user}:{password}@{parsed.netloc}\n" gitcreds_path = config_dir / "git-credentials" gitcreds_path.write_text(git_credentials) gitcreds_path.chmod(0o600) @@ -121,7 +200,12 @@ class GitServerClient: gitconfig_path = config_dir / "gitconfig" gitconfig_path.write_text(git_config) - self._git_env = {**os.environ, "GIT_CONFIG_GLOBAL": str(gitconfig_path)} + # Agents run git in this environment, so it carries no credentials of the server. + self._git_env = { + **{k: v for k, v in os.environ.items() if not _SECRET_ENV_NAME.search(k)}, + "GIT_CONFIG_GLOBAL": str(gitconfig_path), + "GIT_ALLOW_PROTOCOL": "http:https", + } def wait_for_ready(self, timeout: int = 30) -> bool: """ @@ -219,7 +303,10 @@ class GitServerClient: raise RuntimeError("Gitea server is not ready") target_dir = target_dir or repo_name - target_path = self.workspace_dir / target_dir + workspace = self.workspace_dir.resolve() + target_path = (workspace / target_dir).resolve() + if target_path == workspace or not target_path.is_relative_to(workspace): + raise ValueError(f"target_dir {target_dir!r} is outside the workspace") # Remove existing directory if present if target_path.exists(): @@ -349,14 +436,19 @@ class GitServerClient: Returns: `tuple` of (exit_code, stdout, stderr). """ - work_path = ( - self.workspace_dir / working_dir if working_dir else self.workspace_dir - ) + workspace = self.workspace_dir.resolve() + work_path = (workspace / working_dir).resolve() + if not work_path.is_relative_to(workspace): + return (1, "", f"working_dir {working_dir!r} is outside the workspace") if not work_path.exists(): return (1, "", f"Working directory does not exist: {work_path}") - cmd_parts = ["git"] + shlex.split(command) + args = shlex.split(command) + refusal = _refusal(args) + if refusal: + return (1, "", refusal) + cmd_parts = ["git"] + args result = subprocess.run( cmd_parts, diff --git a/src/openenv/core/tools/local_python_executor.py b/src/openenv/core/tools/local_python_executor.py index ac73730da739f2f042bf184b5452f9ef2bfa4a97..0d5e5762e826482acb8acbcaf4ade12fd0b192f1 100644 --- a/src/openenv/core/tools/local_python_executor.py +++ b/src/openenv/core/tools/local_python_executor.py @@ -35,6 +35,12 @@ class PyExecutor: LocalPythonExecutor that can be used by the executed code to format exceptions and to safely stringify results for improved error reporting. + + LocalPythonExecutor is an interpreter that restricts imports and + attributes, not a sandbox: the code runs in the current process and can + reach what that process holds. Run model code with it in a separate + process that has no secrets (environment variables, tokens in memory), + as `coding_env` does with one worker process per session. """ def __init__(self, additional_imports: list[str] | None = None): diff --git a/src/openenv/core/utils.py b/src/openenv/core/utils.py index 70c14ae7a49299d111ad97d74a91524361ff5c9f..9dd72c4a5bd5e3e3b0f29e588905f90182fb41a8 100644 --- a/src/openenv/core/utils.py +++ b/src/openenv/core/utils.py @@ -4,6 +4,8 @@ import asyncio import concurrent.futures +import json +import os import re @@ -71,3 +73,43 @@ def hf_space_subdomain(repo_id: str) -> str: The Space subdomain. """ return re.sub(r"[^a-z0-9]", "-", repo_id.lower()) + + +_SECRET_PATTERN = re.compile( + r"hf_[A-Za-z0-9]{30,}" + r"|sk-[A-Za-z0-9_-]{20,}" + r"|gh[pousr]_[A-Za-z0-9]{30,}|github_pat_[A-Za-z0-9_]{30,}" + r"|(?:AKIA|ASIA)[A-Z0-9]{16}" + r"|-----BEGIN [A-Z ]*PRIVATE KEY-----.*?-----END [A-Z ]*PRIVATE KEY-----", + re.DOTALL, +) +_SECRET_ENV_NAME = re.compile(r"(^|_)(TOKEN|KEY|SECRET|PASSWORD)(_|$)", re.IGNORECASE) + + +def redact_secrets(text: str) -> tuple[str, int]: + """ + Replace credentials in `text` with ``. + + Covers Hugging Face, OpenAI/Anthropic, GitHub and AWS keys, private key blocks, and the value of + every environment variable of this process with `TOKEN`, `KEY`, `SECRET` or `PASSWORD` as a part + of its name (`HF_TOKEN`, `OPENAI_API_KEY`), also in its JSON-escaped form. Agent traces can hold + any of them: a model that runs `env` or reads a config file puts the value in its own output. + + Args: + text (`str`): + Text to scan. + + Returns: + `tuple[str, int]`: The redacted text and the number of secrets replaced. + """ + count = 0 + for name, value in os.environ.items(): + if not _SECRET_ENV_NAME.search(name) or len(value) < 8: + continue + # Traces are JSON, where quotes, backslashes and non-ASCII characters are escaped. The + # escaped form goes first: it can contain the raw one (a value ending in a backslash). + for form in (json.dumps(value)[1:-1], value): + count += text.count(form) + text = text.replace(form, "") + text, matches = _SECRET_PATTERN.subn("", text) + return text, count + matches diff --git a/src/openenv/discovery/schemas/0.1-draft/catalog.schema.json b/src/openenv/discovery/schemas/0.1-draft/catalog.schema.json index 40d4b356862a88fbcd81151027cc899e6b0432b5..4863c0501bb0f2cc3f96bad371d96627f40eac30 100644 --- a/src/openenv/discovery/schemas/0.1-draft/catalog.schema.json +++ b/src/openenv/discovery/schemas/0.1-draft/catalog.schema.json @@ -652,7 +652,7 @@ "type": "object" } }, - "$id": "https://raw.githubusercontent.com/huggingface/OpenEnv/main/src/openenv/discovery/schemas/0.1-draft/catalog.schema.json", + "$id": "https://raw.githubusercontent.com/openenv/OpenEnv/main/src/openenv/discovery/schemas/0.1-draft/catalog.schema.json", "$schema": "https://json-schema.org/draft/2020-12/schema", "additionalProperties": false, "properties": { diff --git a/src/openenv/discovery/schemas/0.1-draft/declaration.schema.json b/src/openenv/discovery/schemas/0.1-draft/declaration.schema.json index fb7422a1c8d3d9a34cc55429d1f742271e363239..f57d3d2cd4f15802851e4932b7b05e41c6826e09 100644 --- a/src/openenv/discovery/schemas/0.1-draft/declaration.schema.json +++ b/src/openenv/discovery/schemas/0.1-draft/declaration.schema.json @@ -49,7 +49,7 @@ "type": "object" } }, - "$id": "https://raw.githubusercontent.com/huggingface/OpenEnv/main/src/openenv/discovery/schemas/0.1-draft/declaration.schema.json", + "$id": "https://raw.githubusercontent.com/openenv/OpenEnv/main/src/openenv/discovery/schemas/0.1-draft/declaration.schema.json", "$schema": "https://json-schema.org/draft/2020-12/schema", "additionalProperties": false, "properties": { diff --git a/src/openenv/discovery/schemas/0.1-draft/environment-card.schema.json b/src/openenv/discovery/schemas/0.1-draft/environment-card.schema.json index f8980e004eb07000628f2e1e9f467dbeda3dad5a..cf0a2ecfe9b034b9c76519de718a5d453ecb28c3 100644 --- a/src/openenv/discovery/schemas/0.1-draft/environment-card.schema.json +++ b/src/openenv/discovery/schemas/0.1-draft/environment-card.schema.json @@ -186,7 +186,7 @@ "type": "object" } }, - "$id": "https://raw.githubusercontent.com/huggingface/OpenEnv/main/src/openenv/discovery/schemas/0.1-draft/environment-card.schema.json", + "$id": "https://raw.githubusercontent.com/openenv/OpenEnv/main/src/openenv/discovery/schemas/0.1-draft/environment-card.schema.json", "$schema": "https://json-schema.org/draft/2020-12/schema", "additionalProperties": false, "allOf": [ diff --git a/src/openenv/harbor/atif.py b/src/openenv/harbor/atif.py index 2a67ab640deeffc47ab7b86b3b6e8cbeb5683005..eb9c43edf15d00228e1ac5a682968f4868ade901 100644 --- a/src/openenv/harbor/atif.py +++ b/src/openenv/harbor/atif.py @@ -52,12 +52,16 @@ def load_atif(trial_dir: str | Path) -> dict[str, Any] | None: def _pi_session_as_atif(trial_dir: Path) -> dict[str, Any] | None: - """pi's own session log, reshaped into the two ATIF fields reconciliation reads. + """pi's own session log, reshaped into the ATIF fields reconciliation reads. pi writes no `trajectory.json`, but it does write `agent/pi/sessions/*.jsonl`, and every assistant record there carries `usage.output`: the completion-token count for that call, which is exactly what `metrics.completion_tokens` provides in ATIF. So the cross-check is available for pi after all, just under a different name and shape. + + The text and tool calls are kept too. pi logs the proxy's budget stop like any other reply, + and `reconcile` can only tell it apart by its text; without it, every pi rollout that hits a + step or context limit fails reconciliation and cannot be trained on. """ sessions = sorted((trial_dir / "agent" / "pi" / "sessions").glob("*.jsonl")) if not sessions: @@ -72,9 +76,26 @@ def _pi_session_as_atif(trial_dir: Path) -> dict[str, Any] | None: if record.get("type") != "message" or message.get("role") != "assistant": continue usage = message.get("usage") or {} + content = message.get("content") or [] + if isinstance(content, str): + content = [{"type": "text", "text": content}] steps.append( { "source": "agent", + "message": "".join( + part.get("text") or "" + for part in content + if part.get("type") == "text" + ), + "tool_calls": [ + { + "tool_call_id": part.get("id"), + "function_name": part.get("name"), + "arguments": part.get("arguments"), + } + for part in content + if part.get("type") == "toolCall" + ], "metrics": {"completion_tokens": int(usage.get("output") or 0)}, } ) @@ -325,6 +346,26 @@ def reconcile(document: dict[str, Any], atif: dict[str, Any] | None) -> Report: ) return report + subagents = atif.get("subagent_trajectories") or [] + if subagents: + # FATAL, not WARN. The old text said subagent turns "must not be trained with the parent + # rollout's reward" and then did nothing to stop it: no node ids were collected, no role was + # changed, so if a subagent's calls landed in the same session as `agent` roots they shipped as + # trainable carrying the parent's reward — the exact outcome the sentence forbade. The aux path + # below demotes; this one only complained. + # + # Refusing rather than guessing which roots belong to the subagent: ATIF gives trajectories, + # not the node ids that would let us demote precisely, and picking roots by shape here would be + # inventing an attribution. A rollout whose reward cannot be attributed is not trainable. + report.add( + FATAL, + "atif_subagents", + f"ATIF reports {len(subagents)} subagent trajectory(ies) and the graph has " + f"{document['stats']['n_roots']} root(s). Subagent turns must not be trained with the " + "parent rollout's reward, and ATIF does not say which captured calls are theirs, so " + "this rollout cannot be attributed. Run this harness without subagents to train on it.", + ) + # Compare against EVERY call the agent made, in arrival order, across ALL agent roots. # # Two reasons this is the right comparison rather than the surviving training path: @@ -473,25 +514,6 @@ def reconcile(document: dict[str, Any], atif: dict[str, Any] | None) -> Report: f"Graph found {document['stats']['n_discarded']} discarded turn(s).", ) - subagents = atif.get("subagent_trajectories") or [] - if subagents: - # FATAL, not WARN. The old text said subagent turns "must not be trained with the parent - # rollout's reward" and then did nothing to stop it: no node ids were collected, no role was - # changed, so if a subagent's calls landed in the same session as `agent` roots they shipped as - # trainable carrying the parent's reward — the exact outcome the sentence forbade. The aux path - # right above demotes; this one only complained. - # - # Refusing rather than guessing which roots belong to the subagent: ATIF gives trajectories, - # not the node ids that would let us demote precisely, and picking roots by shape here would be - # inventing an attribution. A rollout whose reward cannot be attributed is not trainable. - report.add( - FATAL, - "atif_subagents", - f"ATIF reports {len(subagents)} subagent trajectory(ies) and the graph has " - f"{document['stats']['n_roots']} root(s). Subagent turns must not be trained with the " - "parent rollout's reward, and ATIF does not say which captured calls are theirs, so " - "this rollout cannot be attributed. Run this harness without subagents to train on it.", - ) return report diff --git a/src/openenv/harbor/capabilities.py b/src/openenv/harbor/capabilities.py index 2c0981d7ba488593fd3f0ba607d538b1b337d6aa..7da90b98bdf5248298e731870376b57e261c4b49 100644 --- a/src/openenv/harbor/capabilities.py +++ b/src/openenv/harbor/capabilities.py @@ -21,11 +21,6 @@ from typing import Any from . import seams -# Harbor agents that run HOST-SIDE, in this server's process, rather than being installed into the -# sandbox. The distinction is not cosmetic: their LLM traffic never leaves the host, so they reach -# the capture proxy on localhost and need no public URL at all. -HOST_SIDE_AGENTS = frozenset({"terminus-2", "computer-1", "oracle", "nop", "dspy-rlm"}) - # Backends worth advertising. Harbor registers 23; these are the ones with a credential story we # check and have exercised. Others still work via `--sandbox `, just unadvertised. KNOWN_SANDBOXES = ("docker", "e2b", "modal", "daytona", "hf-sandbox") @@ -288,7 +283,7 @@ def list_harnesses() -> list[HarnessStatus]: HarnessStatus( name=name, dialect=seam.dialect, - kind="base" if name in HOST_SIDE_AGENTS else "installed", + kind="base" if seam.host_side else "installed", status=seam.status, needs_subclass=seam.import_path is not None, notes=seam.notes, diff --git a/src/openenv/harbor/environment.py b/src/openenv/harbor/environment.py index 50e6963c53da175691a875e786d07b17116e74aa..64f40233231a07298eb0943d1db2a0e0f03b1c23 100644 --- a/src/openenv/harbor/environment.py +++ b/src/openenv/harbor/environment.py @@ -249,6 +249,22 @@ class HarborEnvironment(MCPEnvironment): from .models import HarborRolloutResult from .rollout import run_rollout as _run + # The client names the harness, and a `module:Class` name makes this server import that + # module. Only the import paths the operator allowed at startup are accepted. + allowed = { + entry.strip() + for entry in os.environ.get("OPENENV_HARBOR_ALLOW_HARNESS", "").split(",") + if entry.strip() + } + if ":" in harness and harness not in allowed: + return HarborRolloutResult( + ok=False, + error=f"harness {harness!r} is not allowed on this server: start it with " + f"`openenv harbor serve --allow-harness {harness}`", + harness=harness, + sandbox=sandbox, + ).model_dump_json() + service = self._service() if service is None: return HarborRolloutResult( @@ -266,6 +282,20 @@ class HarborEnvironment(MCPEnvironment): ok=False, error=str(exc)[:400], harness=harness, sandbox=sandbox ).model_dump_json() + # Same rule as the web UI: a task that gets this server's environment variables or files + # runs only on the server's own endpoint, since the caller's model would see the secrets. + if llm_url: + from .ui_data import reads_environment + + if reads_environment(split, int(task_index)): + return HarborRolloutResult( + ok=False, + error="this task passes the server's environment variables or files into " + "the sandbox, so it runs only on the server's own endpoint, not with llm_url", + harness=harness, + sandbox=sandbox, + ).model_dump_json() + # This tool is `async` on purpose. FastMCP dispatches a SYNC tool body through # `anyio.to_thread.run_sync` with no limiter (`fastmcp/utilities/async_utils.py`), which # uses anyio's default `CapacityLimiter(40)` — and the body holds that worker thread for the @@ -310,6 +340,7 @@ class HarborEnvironment(MCPEnvironment): sandbox=sandbox, registry=service.capture.registry, intercept_url=service.public_url, + local_intercept_url=service.local_url, model=served, trials_dir=_trials_dir(), dataset=split, diff --git a/src/openenv/harbor/rollout.py b/src/openenv/harbor/rollout.py index 9a9ae3b67b12ba1835646096f6c8f9e8f5806ea1..2037fd23db00a44158d52a368fd686352ece3640 100644 --- a/src/openenv/harbor/rollout.py +++ b/src/openenv/harbor/rollout.py @@ -43,6 +43,7 @@ from .models import ( HarborTurn, turns_from_document, ) +from .supervisor import get_supervisor # Harbor's own retry is deliberately off. A Harbor-level retry re-runs the agent against the SAME # capture session, so two attempts merge into one graph and the trace cross-check compares a @@ -150,6 +151,48 @@ def _finite_reward(key: str, value: Any) -> float: return number +def _graded_nonzero_exit(info: Any, reward: float | None) -> bool: + """Whether a trial's exception is only the agent's exit code, after the verifier graded the run. + + `opencode run` has been seen to exit 1 on runs that finished normally: the stream ends on a + `step_finish` with `reason: "stop"`, it carries no `error` event and stderr is empty. Harbor runs + the command under `set -o pipefail` and turns any non-zero status into + `NonZeroAgentExitCodeError` (agents/installed/base.py `_exec`), records it on the trial, and + still runs the verifier. Treating that record as the outcome failed solved and unsolved rollouts + alike. + + Only the plain exit code qualifies. Harbor's own classifications of the same failure (`ApiError` + and its subclasses, refusals) keep failing, and so does an opencode stream that carries an + `error` event, since that run was cut short by the provider rather than finished. + + Args: + info (`Any`): + The trial's `exception_info` (Harbor's `ExceptionInfo`). + reward (`float`, *optional*): + The headline reward already picked from the verifier, `None` when there is none. + + Returns: + `bool`: `True` when the exception should be kept as a warning rather than a failure. + """ + if reward is None: + return False + if getattr(info, "exception_type", None) != "NonZeroAgentExitCodeError": + return False + message = str(getattr(info, "exception_message", "") or "") + return ( + message.startswith("Command failed (exit ") and '"type":"error"' not in message + ) + + +def _first_line(info: Any) -> str: + """The exception's type and the first line of its message, for a one-line finding.""" + message = str(getattr(info, "exception_message", "") or "") + first = message.splitlines()[0] if message else "" + if len(first) > 200: + first = first[:200] + "..." + return f"{getattr(info, 'exception_type', None)}: {first}" + + def _pick_reward( rewards: dict[str, float], reward_key: str = "" ) -> tuple[float | None, str]: @@ -209,12 +252,15 @@ def build_trial_config( force_build: bool = False, training: bool = False, harness_profile: str | None = None, + environment_kwargs: dict[str, Any] | None = None, ) -> Any: """Assemble Harbor's `TrialConfig` for one rollout. The seam decides how this particular agent learns about the proxy — an env var, a constructor kwarg, or a config file written by a subclass. That is the only per-agent knowledge involved; everything downstream is identical. + + Backend kwargs in `environment_kwargs` pass to Harbor. `None` keeps Harbor's defaults. """ from harbor.models.trial.config import ( AgentConfig, @@ -270,6 +316,9 @@ def build_trial_config( ), delete=not keep_sandbox, force_build=force_build, + **( + {"kwargs": environment_kwargs} if environment_kwargs is not None else {} + ), ), verifier=VerifierConfig(), trial_name=trial_name, @@ -277,6 +326,17 @@ def build_trial_config( ) +async def _run_trial(trial: Any, on_trial_created: Callable[[Any], None] | None) -> Any: + """Close Harbor's trial log when a trusted hook prevents execution.""" + if on_trial_created is not None: + try: + on_trial_created(trial) + except BaseException: + trial._close_logger_handler() + raise + return await trial.run() + + async def run_rollout( *, task_dir: Path | str, @@ -288,6 +348,7 @@ async def run_rollout( trials_dir: Path | str, dataset: str = "", reward_key: str = "", + local_intercept_url: str = "", require_reward: bool = True, keep_sandbox: bool = False, agent_timeout_sec: float | None = None, @@ -302,6 +363,8 @@ async def run_rollout( eval_sampling: dict[str, Any] | None = None, harness_profile: str | None = None, on_session_created: Callable[[str], None] | None = None, + on_trial_created: Callable[[Any], None] | None = None, + environment_kwargs: dict[str, Any] | None = None, ) -> HarborRolloutResult: """Run one rollout end to end. Never raises. @@ -316,6 +379,10 @@ async def run_rollout( The live capture registry; a session is minted here and its id becomes the agent's key. intercept_url (`str`): Public URL of the capture proxy, as the sandbox must reach it. + local_intercept_url (`str`, *optional*): + The proxy's loopback URL. A host-side agent (`Seam.host_side`) is handed this instead of + `intercept_url`: it calls the model from this process, and every public hop is one more + place a long completion can be cut. Empty keeps `intercept_url` for every agent. model (`str`): Served model id. Normalised per harness by the seam. trials_dir (`Path` or `str`): @@ -344,6 +411,11 @@ async def run_rollout( on_session_created (`Callable[[str], None]`, *optional*): Receive this rollout's capture session ID before the agent starts. Live views must follow this ID rather than discover unrelated sessions from the shared registry. + on_trial_created (`Callable[[Any], None]`, *optional*): + Trusted infrastructure callback invoked with the native Harbor trial before it runs. + Exceptions fail the rollout and prevent trial execution. Not exposed through MCP. + environment_kwargs (`dict[str, Any]`, *optional*): + Backend kwargs passed to Harbor. `None` keeps Harbor's defaults. Returns: [`HarborRolloutResult`]: Reward, per-turn token ids and logprobs, and validation findings. @@ -431,6 +503,14 @@ async def run_rollout( enable_shared_templates() + # A host-side agent calls the model from this process, so it takes the loopback URL. A + # public forward is one more hop that can cut a long completion: a gradio share link + # answers 502 after about a minute while the upstream is still generating, the agent + # retries, and the capture records the same prompt again as a new root. + seam = seams.get(harness, profile=harness_profile) + if local_intercept_url and seam.host_side: + intercept_url = local_intercept_url + config_kwargs = dict( task_dir=task_dir, harness=harness, @@ -446,6 +526,7 @@ async def run_rollout( force_build=force_build, training=sampling is not None, harness_profile=harness_profile, + environment_kwargs=environment_kwargs, ) # Held across construction because Harbor's wrappers read `os.environ` while building the @@ -454,14 +535,14 @@ async def run_rollout( # I/O worth speaking of: the sandbox is booted later, by `trial.run()`, outside the lock. # Harbor's wrappers read `os.environ` while constructing the agent, so the seam's # process-level vars have to be in place across `Trial.create` and are put back after. - seam = seams.get(harness, profile=harness_profile) *_, proc_env = seam.resolve( base_url=intercept_url, session=session.session_id, model=model ) if not proc_env: config = build_trial_config(**config_kwargs) trial = await Trial.create(config) - trial_result = await trial.run() + get_supervisor().adopt(trial) + trial_result = await _run_trial(trial, on_trial_created) else: # The override has to span `run()`, not just construction. Harbor's goose wrapper reads # `os.environ["OPENAI_API_KEY"]` inside its own `run` (goose.py:653), long after @@ -493,7 +574,8 @@ async def run_rollout( with ctx_env_overlay(proc_env): config = build_trial_config(**config_kwargs) trial = await Trial.create(config) - trial_result = await trial.run() + get_supervisor().adopt(trial) + trial_result = await _run_trial(trial, on_trial_created) else: # Fallback: mutate the real environment under a lock, one rollout at a time. await _acquire_proc_env() @@ -501,7 +583,8 @@ async def run_rollout( with process_env(seam.name, proc_env): config = build_trial_config(**config_kwargs) trial = await Trial.create(config) - trial_result = await trial.run() + get_supervisor().adopt(trial) + trial_result = await _run_trial(trial, on_trial_created) finally: _PROC_ENV_LOCK.release() except Exception as exc: # noqa: BLE001 - a rollout failure is a RESULT, never an exception @@ -574,9 +657,17 @@ async def run_rollout( ) info = getattr(trial_result, "exception_info", None) if info is not None and result.error is None: - result.ok = False - result.exception_type = getattr(info, "exception_type", None) - result.error = str(getattr(info, "exception_message", ""))[:600] + if _graded_nonzero_exit(info, result.reward): + # The agent's exit status is not the outcome when the verifier graded the run. + # The capture checks below still decide `ok`, so an empty or broken capture fails. + result.findings.append( + "[WARN] agent exited non-zero after a graded run: " + + _first_line(info) + ) + else: + result.ok = False + result.exception_type = getattr(info, "exception_type", None) + result.error = str(getattr(info, "exception_message", ""))[:600] # --- capture -------------------------------------------------------- try: diff --git a/src/openenv/harbor/runner.py b/src/openenv/harbor/runner.py index f9853a7ad151b9fc3ef8972cf9e43e6615809a7c..fcf1672d28921d16b6bafb01ce07b89f92bdc871 100644 --- a/src/openenv/harbor/runner.py +++ b/src/openenv/harbor/runner.py @@ -11,6 +11,7 @@ from __future__ import annotations import os import secrets from pathlib import Path +from typing import Any, Callable from openenv.core.harness.capture import CaptureServer @@ -44,6 +45,10 @@ async def run_batch( auth_header: str = "Authorization", provider: str = "openai", admin_key: str | None = None, + agent_timeout_sec: float | None = None, + agent_step_limit: int | None = None, + on_trial_created: Callable[[Any], None] | None = None, + environment_kwargs: dict[str, Any] | None = None, ) -> list[HarborRolloutResult]: """Run `task_indices` from `dataset` and print a per-rollout report. @@ -64,6 +69,15 @@ async def run_batch( Key the capture proxy's session-management routes require. Defaults to `$OPENENV_CAPTURE_ADMIN_KEY`, else a random one minted for this batch. The proxy is published on a public URL, so these routes are never left open. + agent_timeout_sec (`float`, *optional*): + Override each agent's execution timeout in seconds. + agent_step_limit (`int`, *optional*): + Limit each rollout's agent steps and captured model calls. + on_trial_created (`Callable[[Any], None]`, *optional*): + Trusted infrastructure callback invoked with each native Harbor trial before it runs. + Exceptions fail that rollout and prevent trial execution. Not exposed through MCP. + environment_kwargs (`dict[str, Any]`, *optional*): + Backend kwargs passed to Harbor. `None` keeps Harbor's defaults. Returns: `list[HarborRolloutResult]`: One per index, in order. @@ -153,14 +167,24 @@ async def run_batch( sandbox=sandbox, registry=capture.registry, intercept_url=public_url, + local_intercept_url=f"http://127.0.0.1:{port}", model=model, trials_dir=trials_dir, dataset=dataset, reward_key=reward_key, + # A rollout to look at, not to train on: when the verifier wrote several rewards and + # `reward_key` names none of them, the capture is still usable and every reward stays + # in `rewards`. Failing it would report a graded rollout as an infra error. The + # training path (`run_rollout`'s default) still refuses to pick a signal. + require_reward=False, keep_sandbox=keep_sandbox, + agent_timeout_sec=agent_timeout_sec, + agent_step_limit=agent_step_limit, force_build=force_build, capture_level=capture_level, inference=capture.inference, + on_trial_created=on_trial_created, + environment_kwargs=environment_kwargs, ) results.append(result) print(" " + _summarise(result)) @@ -193,6 +217,12 @@ def _summarise(r: HarborRolloutResult) -> str: f"{status:<26} reward={reward:<6} turns={r.n_turns:<3} roots={r.n_roots:<3} " f"{mode:<11} {detail} atif={r.atif:<9} {r.wall_s:.0f}s" + (f"\n {r.error[:180]}" if r.error else "") + + ( + f"\n verifier wrote {r.rewards} but none is the headline reward: " + "pass --reward-key (a comma-separated preference order is accepted)" + if r.reward is None and r.rewards + else "" + ) ) @@ -202,15 +232,24 @@ def _report(results: list[HarborRolloutResult]) -> str: ok = sum(1 for r in results if r.ok) graded = [r for r in results if r.reward is not None] solved = sum(1 for r in graded if r.reward and r.reward > 0) + # Two different reasons for no reward. Only an empty `rewards` means the verifier never ran: + # with keys present it did run, and no key was chosen as the headline one. + no_headline = [r for r in results if r.reward is None and r.rewards] + never_ran = len(results) - len(graded) - len(no_headline) + ungraded = [] + if no_headline: + keys = sorted({key for r in no_headline for key in r.rewards}) + ungraded.append( + f"{len(no_headline)} ungraded: the verifier ran but no headline reward among " + f"{keys}, pass --reward-key" + ) + if never_ran: + ungraded.append(f"{never_ran} ungraded: the verifier never ran") lines = [ "=" * 78, f"capture {ok}/{len(results)} usable", f"solved {solved}/{len(graded)} graded" - + ( - f" ({len(results) - len(graded)} ungraded — the verifier never ran)" - if len(graded) != len(results) - else "" - ), + + "".join(f" ({reason})" for reason in ungraded), ] if all(r.rollout_type == "eval" for r in results): lines.append( diff --git a/src/openenv/harbor/seams.py b/src/openenv/harbor/seams.py index b31d22bf03c1b54e4a8469a00af949d403230007..4936ee3194481b29fa6068412d1a2acca8676601 100644 --- a/src/openenv/harbor/seams.py +++ b/src/openenv/harbor/seams.py @@ -109,6 +109,10 @@ def _pi(base_url: str, session: str, model: str) -> dict[str, Any]: logger = logging.getLogger(__name__) +# Harnesses already warned about an inexpressible step limit, in this process. The warning is a fact +# about the harness, not the rollout: repeating it for every rollout of a training run buries it. +_STEP_LIMIT_WARNED: set[str] = set() + @dataclass(frozen=True) class Seam: @@ -153,6 +157,9 @@ class Seam: # the loss step while every log line looks healthy. Harbor itself has no step cap — only a # timeout — and an earlier Qwen3-4B run micro-stepped to 451 turns and 10.1M prompt tokens. step_limit: Callable[[int], dict[str, Any]] | None = None + # The agent runs in OUR process (terminus-2, computer-1, a host-side agent of your own) and makes + # its model calls from here, so the proxy's loopback address reaches it: no public forward needed. + host_side: bool = False status: str = "untested" notes: str = "" @@ -183,11 +190,14 @@ class Seam: extra = _deep_merge(extra, self.training_kwargs) if step_limit: if self.step_limit is None: - logger.warning( - "%s has no native step-limit setting; the capture proxy enforces the " - "model-call budget and the agent timeout still applies", - self.name, - ) + if self.name not in _STEP_LIMIT_WARNED: + _STEP_LIMIT_WARNED.add(self.name) + logger.warning( + "%s has no native step-limit setting; the capture proxy enforces the " + "model-call budget and the agent timeout still applies (said once per " + "harness)", + self.name, + ) else: extra = _deep_merge(extra, self.step_limit(step_limit)) return self.model_fmt.format(model=model), extra, agent_env, proc_env @@ -430,6 +440,7 @@ SEAMS: dict[str, Seam] = { # --- second wave -------------------------------------------------------- "terminus-2": Seam( name="terminus-2", + host_side=True, status="validated", dialect="openai_chat", model_fmt="hosted_vllm/{model}", @@ -690,6 +701,7 @@ SEAMS: dict[str, Seam] = { # reason is RECORDED rather than assumed. "computer-1": Seam( name="computer-1", + host_side=True, dialect="openai_chat", model_fmt="hosted_vllm/{model}", # Host-side like terminus-2: drives litellm from our process with an `api_base` kwarg, so @@ -930,7 +942,103 @@ PRIORITY = [ ] +def _custom_kwargs(base_url: str, session: str, model: str) -> dict[str, Any]: + """A host-side agent of your own reaches the proxy through two constructor kwargs. + + The names are terminus-2's (`api_base`) and the OpenAI SDK's (`api_key`): an agent declares both + in its options and hands them to whatever client it uses. + """ + return {"api_base": f"{base_url}/v1", "api_key": session} + + +def custom(import_path: str) -> Seam: + """The seam for `--harness module:Class`, an agent Harbor builds from its import path. + + Harbor already constructs agents from an import path. What it cannot know is how to point one + at the capture proxy, and that depends only on what the class is: + + * a subclass of an agent with a seam (its `name()` is in `SEAMS`, e.g. your own opencode + subclass) is wired exactly like that agent. Where the seam's wiring lives in an OpenEnv + subclass (pi's `InterceptPi` writes models.json), yours must subclass that class; + * a host-side agent (a plain `BaseAgent`, like terminus-2) makes its model calls from THIS + process, so it gets `api_base` (the proxy's `/v1` URL) and `api_key` (the capture session + id) as constructor kwargs. Nothing reaches the sandbox or the verifier; + * any other agent installed into the sandbox is refused: there is no way to tell which env + var or config file it reads, and guessed wiring fails as a rollout with no model calls. + + The status is "untested" in every case: OpenEnv has no evidence about an agent it has not run. + """ + import importlib + import inspect + from dataclasses import replace + + from harbor.agents.base import BaseAgent + from harbor.agents.installed.base import BaseInstalledAgent + + module, _, attr = import_path.partition(":") + try: + cls = getattr(importlib.import_module(module), attr) + if not isinstance(cls, type): + raise TypeError(f"{attr} is not a class") + if not issubclass(cls, BaseAgent): + raise TypeError(f"{import_path} must subclass harbor.agents.base.BaseAgent") + except Exception as exc: # noqa: BLE001 - surface why, whatever the import raised + raise KeyError( + f"cannot import harness {import_path!r}: {type(exc).__name__}: {exc}" + ) from exc + try: + parent = cls.name() + except Exception: # noqa: BLE001 - a name() that needs an instance is not a known agent + parent = None + if parent in SEAMS: + wired_by = SEAMS[parent].import_path + if wired_by: + wired_module, _, wired_attr = wired_by.partition(":") + if not issubclass( + cls, getattr(importlib.import_module(wired_module), wired_attr) + ): + raise ValueError( + f"{import_path} subclasses {parent}, which OpenEnv points at the capture " + f"proxy through {wired_by}. Subclass {wired_by} instead." + ) + return replace( + SEAMS[parent], + name=import_path, + import_path=import_path, + status="untested", + notes=f"{import_path} is a {parent} subclass, wired like {parent}.", + ) + if issubclass(cls, BaseInstalledAgent): + raise ValueError( + f"{import_path} is installed into the sandbox, and OpenEnv cannot tell how to point it " + "at the capture proxy. Subclass an agent that has a seam, or add a Seam for it to " + f"openenv.harbor.seams.SEAMS. Known: {sorted(SEAMS)}" + ) + accepted = set(inspect.signature(cls.__init__).parameters) + # Harbor 0.22 predates options models; constructor parameters still work. + options_model = getattr(cls, "options_model", None) + if options_model is not None: + accepted.update(options_model.model_fields) + missing = {"api_base", "api_key"} - accepted + if missing: + raise ValueError( + f"{import_path} must declare {', '.join(sorted(missing))} as constructor " + "parameters or options fields; Harbor can silently ignore these kwargs." + ) + return Seam( + name=import_path, + dialect="openai_chat", + import_path=import_path, + kwargs=_custom_kwargs, + host_side=True, + status="untested", + notes="Host-side agent of your own: gets the proxy as api_base/api_key kwargs.", + ) + + def get(name: str, *, profile: str | None = None) -> Seam: + if name not in SEAMS and ":" in name and profile is None: + return custom(name) if name not in SEAMS: raise KeyError(f"no seam for {name!r}. Known: {sorted(SEAMS)}") if profile is None: diff --git a/src/openenv/harbor/serving.py b/src/openenv/harbor/serving.py index 6c73e9936d694cf650391c9e731bdad1b0d146a4..46d3dd967df456bdae7ff7139aeacec592025c60 100644 --- a/src/openenv/harbor/serving.py +++ b/src/openenv/harbor/serving.py @@ -25,6 +25,8 @@ from typing import Any from openenv.core.harness.capture import CaptureServer +from .supervisor import get_supervisor + # Where the capture app is mounted when the env server hosts it directly. CAPTURE_MOUNT = "/capture" @@ -139,6 +141,12 @@ class HarborService: raise return self.public_url + @property + def local_url(self) -> str: + """The proxy's loopback URL, for agents running in this process. Empty when it is mounted on a + Space's app, whose port this service does not own.""" + return "" if self.mounted else f"http://127.0.0.1:{self.capture.port}" + def stop(self) -> None: """Tear both halves down, even if the first half refuses to go. @@ -332,6 +340,10 @@ def build_app( # their browser start rollouts on this server's endpoint, or reach a server on their own machine # that the page itself cannot. Nothing a real visitor does is cross-site. app.add_middleware(SameOrigin) + # The UI runs each rollout under `asyncio.run` in a worker thread, where a sandbox start cannot + # install signal handlers. Startup runs on the main thread inside uvicorn's own signal capture, + # so the supervisor wraps uvicorn's handlers and a signal stops those sandboxes on their loops. + app.router.on_startup.append(lambda: get_supervisor().install_signal_handlers()) return app diff --git a/src/openenv/harbor/sft.py b/src/openenv/harbor/sft.py new file mode 100644 index 0000000000000000000000000000000000000000..9d168dd6d13778cc144f8f78b9a0ad5e0c96fb06 --- /dev/null +++ b/src/openenv/harbor/sft.py @@ -0,0 +1,285 @@ +# SPDX-License-Identifier: BSD-3-Clause + +"""Turn Harbor rollouts into supervised fine-tuning rows. + +An evaluation rollout against a hosted model carries no token ids, so it can't feed RL training, but its trace is +supervised data as it stands. The agent's last model call holds the whole conversation as the harness sent it +(system prompt, task, every earlier assistant turn with its tool calls, every tool output), and that call plus its +reply is one SFT row. This is the text-level export: it works on `eval` and `train` rollouts alike, and never goes +through the token-level training contract of `openenv.harbor.contract`. + +Rows are in the conversational format with a `tools` column, which TRL's `SFTTrainer` and chat templates read +directly. Each row keeps its reward. Filtering is the caller's choice (`min_reward`), since a recorder shouldn't +decide a training policy. + +Examples: + +```python +from openenv.harbor.sft import export_sft + +rows, stats = export_sft(results, min_reward=1.0) +``` +""" + +from __future__ import annotations + +import json +from collections.abc import Iterable +from dataclasses import dataclass, field +from typing import Any + +from .models import HarborRolloutResult + + +@dataclass +class SFTExportStats: + """ + What `export_sft` did with each rollout. + + Attributes: + rollouts (`int`): + Rollouts read. + rows (`int`): + Rows written. + below_min_reward (`int`): + Rollouts graded below `min_reward`. + ungraded (`int`): + Rollouts with no reward, dropped when `min_reward` is set. + no_agent_turn (`int`): + Rollouts with no agent call to the model. + capture_failed (`int`): + Rollouts whose capture is unusable (a `[FATAL]` finding, a trace that doesn't match the capture, or a + failed export), never exported. + empty_reply (`int`): + Rollouts whose last reply has neither text nor tool calls. + malformed_tool_call (`int`): + Rollouts with a tool call whose arguments aren't a JSON object. + ended_on_tool_call (`list[str]`): + Tasks whose agent stopped right after a tool call, worth running again. + """ + + rollouts: int = 0 + rows: int = 0 + below_min_reward: int = 0 + ungraded: int = 0 + no_agent_turn: int = 0 + capture_failed: int = 0 + empty_reply: int = 0 + malformed_tool_call: int = 0 + ended_on_tool_call: list[str] = field(default_factory=list) + + +def rollout_reward(result: HarborRolloutResult, reward_key: str = "") -> float | None: + """ + The reward a rollout was graded with. + + `result.reward` when it's set. Otherwise the verifier reported several named rewards and none was picked as the + training signal: `reward_key` names it, and a single named reward is used as it is. + + Args: + result ([`HarborRolloutResult`]): + One rollout. + reward_key (`str`, *optional*, defaults to `""`): + Key of `result.rewards` to fall back to, or a comma-separated preference order. + + Returns: + `float` or `None`: the reward, or `None` when the rollout was not graded. + """ + if result.reward is not None: + return result.reward + if reward_key: + # A literal key first, then a comma-separated preference order, as `openenv harbor rollout --reward-key`. + for key in [reward_key] + [k.strip() for k in reward_key.split(",")]: + if key in result.rewards: + return result.rewards[key] + return None # a key was named and isn't there: another reward would be a different signal + if len(result.rewards) == 1: + return next(iter(result.rewards.values())) + return None + + +def _normalize_tool_calls( + calls: Iterable[dict[str, Any]], +) -> list[dict[str, Any]] | None: + """OpenAI-style tool calls with `arguments` as a dict, or `None` if a call's arguments aren't a JSON object. + + Captured replies carry flat `{name, arguments}` and request messages nest them under `function`, and providers + send `arguments` as a JSON string. Chat templates such as Qwen3.5's iterate over the arguments, so they're parsed. + A call whose arguments don't parse to an object would teach the student a malformed call, so the row is dropped. + """ + out = [] + for call in calls: + fn = call.get("function", call) + args = fn.get("arguments") + if isinstance(args, str): + try: + args = json.loads(args) if args.strip() else {} + except json.JSONDecodeError: + return None + if args is None: + args = {} + if not isinstance(args, dict): + return None + normalized = { + "type": "function", + "function": {"name": fn.get("name", ""), "arguments": args}, + } + if call.get("id"): + normalized["id"] = call["id"] + out.append(normalized) + return out + + +def _capture_unusable(result: HarborRolloutResult) -> bool: + """The capture itself is broken, as opposed to the agent or the grading. + + Not `result.ok`: it is also false for a graded rollout whose agent exited non-zero, or whose verifier wrote + several rewards with none picked, and those conversations are sound. + """ + return ( + any("[FATAL" in finding for finding in result.findings) + or result.atif == "MISMATCH" + or (result.error or "").startswith(("capture failed", "capture export failed")) + ) + + +def _last_agent_turn(result: HarborRolloutResult): + turns = [ + t + for t in result.turns + if t.role == "agent" and not t.discarded and t.request_messages + ] + return turns[-1] if turns else None + + +def ended_on_tool_call(result: HarborRolloutResult) -> bool: + """ + Whether the agent stopped right after a tool call, with no final reply. + + It usually means a model call failed and the harness gave up, so the task is worth running again rather than + counting as a wrong answer. + + Args: + result ([`HarborRolloutResult`]): + One rollout. + + Returns: + `bool`: whether the last agent turn finished on a tool call. + """ + turn = _last_agent_turn(result) + return turn is not None and turn.finish_reason == "tool_calls" + + +def to_sft_row( + result: HarborRolloutResult, reward_key: str = "" +) -> dict[str, Any] | None: + """ + One conversational SFT row from a rollout, or `None` if it has no agent turn or a malformed tool call. + + The row is the agent's last request to the model plus the reply to it. Discarded retries are not part of it, and + neither are auxiliary calls the capture gives a sequence of their own (session titles, summaries). + + Args: + result ([`HarborRolloutResult`]): + One rollout. + reward_key (`str`, *optional*, defaults to `""`): + Passed to [`rollout_reward`]. + + Returns: + `dict` with keys: + - `messages` (`list[dict]`): the conversation, ending with the agent's last reply. + - `tools` (`list[dict]`): the tools the harness offered. + - `reward` (`float` or `None`): the rollout's reward. + - `rewards` (`dict[str, float]`): every reward the verifier reported. + - `task_name`, `dataset`, `harness`, `rollout_type` (`str`): where the row comes from. + - `n_turns` (`int`): model calls in the rollout. + """ + turn = _last_agent_turn(result) + if turn is None: + return None + reply: dict[str, Any] = {"role": "assistant", "content": turn.text or ""} + if turn.tool_calls: + reply["tool_calls"] = turn.tool_calls + messages = [dict(m) for m in turn.request_messages] + [reply] + for message in messages: + if message.get("role") == "assistant" and message.get("tool_calls"): + message["tool_calls"] = _normalize_tool_calls(message["tool_calls"]) + if message["tool_calls"] is None: + return None + return { + "messages": messages, + "tools": list(turn.request_tools or []), + "reward": rollout_reward(result, reward_key), + "rewards": dict(result.rewards), + "task_name": result.task_name, + "dataset": result.dataset, + "harness": result.harness, + "rollout_type": result.rollout_type, + "n_turns": result.n_turns, + } + + +def export_sft( + results: Iterable[HarborRolloutResult | dict[str, Any]], + min_reward: float | None = None, + reward_key: str = "", +) -> tuple[list[dict[str, Any]], SFTExportStats]: + """ + SFT rows from Harbor rollouts. + + Args: + results (`Iterable` of [`HarborRolloutResult`] or `dict`): + Rollouts, as returned by `run_batch` or read back from `openenv harbor rollout --out`. + min_reward (`float`, *optional*): + Keep only rollouts graded at least this. Ungraded rollouts are dropped too. Unset, every usable rollout + becomes a row, with its reward on it. Rollouts whose capture is unusable, whose last reply is empty + or that hold a malformed tool call are never exported, and [`SFTExportStats`] counts them. + reward_key (`str`, *optional*, defaults to `""`): + Passed to [`rollout_reward`]. + + Returns: + `tuple` of the rows and an [`SFTExportStats`]. + + Examples: + + ```python + import json + from openenv.harbor.sft import export_sft + + rows, stats = export_sft(json.load(open("result.json")), min_reward=1.0) + ``` + """ + rows, stats = [], SFTExportStats() + for item in results: + result = ( + item + if isinstance(item, HarborRolloutResult) + else HarborRolloutResult.model_validate(item) + ) + stats.rollouts += 1 + if ended_on_tool_call(result): + stats.ended_on_tool_call.append(result.task_name) + if _capture_unusable(result): + stats.capture_failed += 1 + continue + turn = _last_agent_turn(result) + if turn is None: + stats.no_agent_turn += 1 + continue + if not turn.text and not turn.tool_calls: + stats.empty_reply += 1 + continue + row = to_sft_row(result, reward_key) + if row is None: + stats.malformed_tool_call += 1 + continue + if min_reward is not None: + if row["reward"] is None: + stats.ungraded += 1 + continue + if row["reward"] < min_reward: + stats.below_min_reward += 1 + continue + rows.append(row) + stats.rows = len(rows) + return rows, stats diff --git a/src/openenv/harbor/supervisor.py b/src/openenv/harbor/supervisor.py new file mode 100644 index 0000000000000000000000000000000000000000..dc8be7f892f39ab70ef708b61214fec7ff47ccaf --- /dev/null +++ b/src/openenv/harbor/supervisor.py @@ -0,0 +1,364 @@ +"""Own the sandboxes this process starts: cap how many start at once, stop them on SIGINT/SIGTERM. + +Harbor already tears a sandbox down at the end of every trial: `Trial._finalize` shields +`agent_environment.stop()`. Three gaps remain once a run is large enough: + +- SIGTERM's default action kills the process before any `finally` runs, so every live sandbox is + stranded. SIGINT cancels, but `asyncio.run` closes its loop right after, which cancels the shielded + stop as well. +- Nothing caps how many sandboxes are being created at once. Providers throttle creation well below + the rollout concurrency a trainer wants, and a throttled create reads as a failed rollout. +- Cancelling a rollout while its sandbox is starting abandons the start mid-flight, and teardown + then races it. Harbor's docker backend leaves `docker compose up` running when `communicate()` is + cancelled (only its timeout path terminates the child); a remote backend can finish a create + request whose handle was dropped. Either way the sandbox can appear after `stop()` has run. + +`SandboxSupervisor.adopt(trial)` wraps the trial's own `agent_environment.start/stop`, so Harbor's +lifecycle is unchanged and the supervisor only sees sandboxes this process created. +""" + +from __future__ import annotations + +import asyncio +import collections +import os +import signal +import threading +from typing import Any + +# How long `stop()` waits for a start that is still in flight. Stopping first is what leaks, so it +# waits; but a start that never returns must not hold teardown forever. +_START_GRACE_S = 120.0 + +# How long a cleanup triggered by a signal may take before the signal is passed on anyway. A wedged +# backend must not turn Ctrl-C into a hang; a second signal skips the wait entirely. It covers a stop +# that first waits out an in-flight start, or a signal during creation would end the process with +# the start still running and nothing deleted. +_CLEANUP_TIMEOUT_S = _START_GRACE_S + 60.0 + +_SIGNALS = (signal.SIGINT, signal.SIGTERM) + + +class _StartLimit: + """At most `limit` concurrent starts across every event loop in the process. + + Not an `asyncio.Semaphore`: rollouts run on several loops (the UI runs each one under its own + `asyncio.run` in a worker thread), and an asyncio primitive binds to the first loop that waits on + it. Waiters queue FIFO and are woken on their own loop. + """ + + def __init__(self, limit: int): + self._limit = limit + self._active = 0 + self._waiters: collections.deque[asyncio.Future] = collections.deque() + self._lock = threading.Lock() + + async def acquire(self) -> None: + with self._lock: + if self._active < self._limit and not self._waiters: + self._active += 1 + return + waiter = asyncio.get_running_loop().create_future() + self._waiters.append(waiter) + try: + await waiter + except asyncio.CancelledError: + with self._lock: + if waiter in self._waiters: + self._waiters.remove(waiter) + raise + # The permit was handed over just as this waiter was cancelled: pass it on. + self.release() + raise + + def release(self) -> None: + with self._lock: + if not self._waiters: + self._active -= 1 + return + waiter = self._waiters.popleft() + waiter.get_loop().call_soon_threadsafe(self._grant, waiter) + + def _grant(self, waiter: asyncio.Future) -> None: + # A waiter cancelled after it was dequeued releases the permit itself, in `acquire`. + if not waiter.done(): + waiter.set_result(None) + + +class _Sandbox: + """One adopted agent environment and the loop its handles belong to.""" + + def __init__(self, env: Any, delete: bool): + self.env = env + self.delete = delete + self.loop: asyncio.AbstractEventLoop | None = None + self.start_task: asyncio.Future | None = None + self.stop_task: asyncio.Future | None = None + + +class _LoopHandler: + """A signal callback that was registered on an event loop with `add_signal_handler`.""" + + def __init__(self, loop: asyncio.AbstractEventLoop, callback: Any, args: tuple): + self.loop = loop + self.callback = callback + self.args = args + + +class SandboxSupervisor: + """Track the sandboxes this process starts and tear them down on request or on a signal. + + Args: + max_starts (`int`, *optional*): + How many sandboxes may be starting at once. `None` or `0` means no limit. This bounds + creation only; how many rollouts run at once is still `MAX_CONCURRENT_ENVS`, so a + rollout that has its sandbox no longer counts against it. + """ + + def __init__(self, max_starts: int | None = None): + self._limit = _StartLimit(max_starts) if max_starts else None + self._owned: set[_Sandbox] = set() + self._lock = threading.Lock() + self._previous: dict[int, Any] = {} + # Signals whose previous handler the event loop delivers by itself; see `install_signal_handlers`. + self._loop_delivers: set[int] = set() + self._handling = False + self._cleanup: asyncio.Future | None = None + # Set by `aclose` under `_lock`. A start that has not registered yet must not open a sandbox + # cleanup will never see, so it fails instead. + self._closing = False + + @property + def owned(self) -> int: + """How many sandboxes this supervisor started and has not yet stopped.""" + with self._lock: + return len(self._owned) + + def adopt(self, trial: Any) -> Any: + """Route `trial.agent_environment`'s start and stop through this supervisor. + + Call after `Trial.create` and before `trial.run()`. Harbor's own calls are unchanged; they + now pass through the creation limit, and `stop()` waits for a pending start. Concurrent + callers share cleanup; successful cleanup is cached and failed cleanup can be retried. + """ + # `getattr`, because callers and tests pass their own trial objects; one without an agent + # environment has no sandbox to supervise. + env = getattr(trial, "agent_environment", None) + if env is None or getattr(env, "_openenv_sandbox", None) is not None: + return trial + box = _Sandbox(env, delete=trial.config.environment.delete) + real_start, real_stop = env.start, env.stop + + async def start(force_build: bool) -> None: + box.loop = asyncio.get_running_loop() + self.install_signal_handlers() + if self._limit is not None: + await self._limit.acquire() + with self._lock: + closing = self._closing + if not closing: + self._owned.add(box) + if closing: + if self._limit is not None: + self._limit.release() + raise RuntimeError( + "sandbox supervisor is shutting down; not starting a new sandbox" + ) + # Shielded: a caller cancelled mid-start gets its CancelledError, but the start itself + # runs to completion so that `stop()` has a whole sandbox to delete, not half of one. + box.start_task = asyncio.ensure_future(real_start(force_build=force_build)) + if self._limit is not None: + box.start_task.add_done_callback(lambda _: self._limit.release()) + await asyncio.shield(box.start_task) + + async def stop(delete: bool) -> None: + # Share an in-flight stop and cache success, but allow failed cleanup to retry. + if box.stop_task is None or ( + box.stop_task.done() + and (box.stop_task.cancelled() or box.stop_task.exception() is not None) + ): + box.stop_task = asyncio.ensure_future(_stop_once(delete)) + await asyncio.shield(box.stop_task) + + async def _stop_once(delete: bool) -> None: + if box.start_task is not None: + await asyncio.wait({box.start_task}, timeout=_START_GRACE_S) + if not box.start_task.done(): + box.start_task.cancel() + # The backend can finish creating the sandbox while the start unwinds. + await asyncio.wait({box.start_task}) + if not box.start_task.cancelled(): + # A start failure is the trial's to report; retrieved so asyncio stays quiet. + box.start_task.exception() + await real_stop(delete=delete) + with self._lock: + self._owned.discard(box) + + env.start, env.stop = start, stop + env._openenv_sandbox = box + return trial + + async def aclose(self, timeout: float | None = None) -> None: + """Stop every sandbox this supervisor owns. Safe to call more than once, and concurrently. + + From the first call on, new starts are refused, so a rollout still queued for a creation + permit cannot open a sandbox while cleanup is running. + + Each stop runs on the loop that started the sandbox, since backends hold loop-bound handles + (docker's are asyncio subprocesses). A sandbox whose loop has already closed cannot be + reached from here and is left alone. `timeout` defaults to `_CLEANUP_TIMEOUT_S`. + """ + with self._lock: + # Same lock as the registration in `start`, so every sandbox is either in this snapshot + # or refused: none can be created after cleanup has looked. + self._closing = True + boxes = list(self._owned) + here = asyncio.get_running_loop() + pending = [] + for box in boxes: + if box.loop is here: + pending.append(asyncio.ensure_future(box.env.stop(delete=box.delete))) + elif box.loop is not None and box.loop.is_running(): + future = asyncio.run_coroutine_threadsafe( + box.env.stop(delete=box.delete), box.loop + ) + pending.append(asyncio.wrap_future(future)) + if not pending: + return + done, _ = await asyncio.wait( + pending, timeout=_CLEANUP_TIMEOUT_S if timeout is None else timeout + ) + for task in done: + if not task.cancelled(): + task.exception() # stop failures belong to the trial + + def install_signal_handlers(self, signals: tuple[int, ...] = _SIGNALS) -> bool: + """Stop owned sandboxes on these signals, then hand the signal to the previous handler. + + Called automatically when the first sandbox starts. Only the main thread can install signal + handlers, so this returns `False` elsewhere; a process that starts every sandbox from worker + threads should call it once from the main thread. The Harbor server does, at app startup + (`serving.build_app`), because the UI runs each rollout in a worker thread. Installing late + is deliberate: a server such as uvicorn replaces handlers when it starts serving, and this + one has to wrap its. + + A handler registered with `loop.add_signal_handler` (uvicorn before 0.29) is delivered by + the loop through the wakeup fd, whatever `signal.signal` holds, so wrapping that would let + the server start shutting down while cleanup is still running and then see the signal a + second time. On an asyncio loop the supervisor takes the loop's slot instead and puts the + callback back when cleanup is done. A loop that does not expose its callbacks (uvloop) + cannot be wrapped: cleanup then runs alongside the server's shutdown, and the signal is not + delivered again. + """ + if self._closing or threading.current_thread() is not threading.main_thread(): + return False + try: + loop = asyncio.get_running_loop() + except RuntimeError: + loop = None + for sig in signals: + current = signal.getsignal(sig) + # Private, but unchanged since asyncio was added: the public API can replace a loop's + # signal callback, not read it back. + handle = getattr(loop, "_signal_handlers", {}).get(sig) + if current == self._on_signal or ( + handle is not None and handle._callback == self._on_loop_signal + ): + continue + if handle is not None: + self._previous[sig] = _LoopHandler(loop, handle._callback, handle._args) + loop.add_signal_handler(sig, self._on_loop_signal, sig) + continue + if isinstance( + getattr(current, "__self__", None), asyncio.AbstractEventLoop + ): + self._loop_delivers.add(sig) + self._previous[sig] = current + signal.signal(sig, self._on_signal) + return True + + def _on_loop_signal(self, sig: int) -> None: + # Runs as an ordinary loop callback, so unlike `_on_signal` it may start the cleanup itself. + if self._handling: + self._chain(sig) + return + self._handling = True + self._start_cleanup(sig) + + def _on_signal(self, sig: int, frame: Any) -> None: + if self._handling: + # A second signal means "stop waiting". + self._chain(sig) + return + self._handling = True + try: + loop = asyncio.get_running_loop() + except RuntimeError: + loop = None + if loop is not None: + # The handler interrupts the loop mid-callback; scheduling is all it may do safely. + loop.call_soon_threadsafe(self._start_cleanup, sig) + return + # No loop on the main thread, so the sandboxes live on other threads' loops and waiting + # for them here cannot deadlock. + worker = threading.Thread( + target=asyncio.run, args=(self.aclose(),), daemon=True + ) + worker.start() + worker.join(_CLEANUP_TIMEOUT_S + 5) + self._chain(sig) + + def _start_cleanup(self, sig: int) -> None: + async def cleanup_then_chain() -> None: + try: + await self.aclose() + finally: + if self._handling: + self._chain(sig) + + self._cleanup = asyncio.ensure_future(cleanup_then_chain()) + + def _chain(self, sig: int) -> None: + """Put the previous handler back and re-deliver the signal to it. + + Re-raising rather than calling it keeps its semantics exactly: SIG_DFL still terminates, + the default SIGINT handler still raises KeyboardInterrupt, uvicorn still shuts down. + """ + self._handling = False + previous = self._previous.pop(sig, signal.SIG_DFL) + if isinstance(previous, _LoopHandler): + if previous.loop.is_closed(): + return + previous.loop.add_signal_handler(sig, previous.callback, *previous.args) + else: + signal.signal(sig, signal.SIG_DFL if previous is None else previous) + if sig in self._loop_delivers: + # The loop already ran its callback for this signal. + self._loop_delivers.discard(sig) + return + signal.raise_signal(sig) + + +_supervisor: SandboxSupervisor | None = None +_supervisor_lock = threading.Lock() + + +def get_supervisor() -> SandboxSupervisor: + """The process-wide supervisor that `run_rollout` adopts every trial into. + + `OPENENV_HARBOR_MAX_SANDBOX_STARTS` caps concurrent sandbox creation; unset or `0` leaves it + uncapped. It is read once, on first use. + """ + global _supervisor + with _supervisor_lock: + if _supervisor is None: + raw = os.environ.get("OPENENV_HARBOR_MAX_SANDBOX_STARTS", "0") or "0" + if not raw.isdigit(): + raise ValueError( + f"OPENENV_HARBOR_MAX_SANDBOX_STARTS must be a non-negative integer, got {raw!r}" + ) + _supervisor = SandboxSupervisor(max_starts=int(raw)) + return _supervisor + + +__all__ = ["SandboxSupervisor", "get_supervisor"] diff --git a/src/openenv/harbor/ui_pages.py b/src/openenv/harbor/ui_pages.py index 69bdcc7697237562a9077bb17bff003ee90b732c..bad6cb755f547d2e6638ed70776aba4765ab1a3e 100644 --- a/src/openenv/harbor/ui_pages.py +++ b/src/openenv/harbor/ui_pages.py @@ -128,7 +128,7 @@ def granted(token: str) -> str | None: # ── header ─────────────────────────────────────────────────────────────────────────────────────── -DOCS_URL = "https://huggingface.co/docs/openenv/environments/harbor" +DOCS_URL = "https://openenv.github.io/OpenEnv/main/environments/harbor" def header_html( diff --git a/src/openenv/harbor/ui_runs.py b/src/openenv/harbor/ui_runs.py index 679f09306a0b9ace60127fb2aac66f141c493c4c..3a6c1879cd25798458d16403108fea31a3f7cb93 100644 --- a/src/openenv/harbor/ui_runs.py +++ b/src/openenv/harbor/ui_runs.py @@ -437,6 +437,7 @@ async def _rollout( sandbox=sandbox, registry=service.capture.registry, intercept_url=service.public_url, + local_intercept_url=service.local_url, model=served, trials_dir=Path( os.environ.get("OPENENV_HARBOR_TRIALS_DIR", "/tmp/openenv-harbor-trials") diff --git a/src/openenv/validation/graders/__init__.py b/src/openenv/validation/graders/__init__.py index 03dda9811369b4c93ae61db843c233ad5fd611e3..88bbd02225fd66fde08bc645175656dae099e20c 100644 --- a/src/openenv/validation/graders/__init__.py +++ b/src/openenv/validation/graders/__init__.py @@ -13,7 +13,12 @@ from typing import Protocol, runtime_checkable from ..manifest import CapabilitiesSpec, NormalizedManifest from ..providers import RunningSubject from ..report import CheckResult -from ..runtime.contracts import RuntimeEvidence +from ..runtime.contracts import ( + HttpProbe, + IsolationEvidence, + OracleEvidence, + RuntimeEvidence, +) from ..types import Level, ProviderCapability ENTRY_POINT_GROUP = "openenv.validation.graders" @@ -38,6 +43,16 @@ class Subject: Where trajectory records and replay artifacts are written. network_evidence_json (`str`, *optional*): Provider-measured [`~openenv.validation.runtime.contracts.NetworkEvidence`]. + containment_evidence_json (`str`, *optional*): + Provider-measured [`~openenv.validation.runtime.contracts.ContainmentEvidence`]. + resource_evidence_json (`str`, *optional*): + Provider-measured [`~openenv.validation.runtime.contracts.ResourceEvidence`]. + isolation_evidence ([`~openenv.validation.runtime.contracts.IsolationEvidence`], *optional*): + Same-session and fresh episodes on the running subject. + oracle_http (`tuple[HttpProbe, ...]`): + GET probes for the declared oracle path on the control endpoint. + oracle_evidence ([`~openenv.validation.runtime.contracts.OracleEvidence`], *optional*): + Oracle, do-nothing and canary rewards for the Level 3 checks. """ root: Path @@ -47,6 +62,11 @@ class Subject: outputs_dir: Path runtime_evidence: RuntimeEvidence | None = None network_evidence_json: str | None = None + containment_evidence_json: str | None = None + resource_evidence_json: str | None = None + isolation_evidence: IsolationEvidence | None = None + oracle_http: tuple[HttpProbe, ...] = () + oracle_evidence: OracleEvidence | None = None @runtime_checkable diff --git a/src/openenv/validation/graders/runtime/__init__.py b/src/openenv/validation/graders/runtime/__init__.py index a667df64fc0a62ed8312bc726c82de1274b78c99..28766a0de7c67d1517ddcc71748c3d3a4a90aac2 100644 --- a/src/openenv/validation/graders/runtime/__init__.py +++ b/src/openenv/validation/graders/runtime/__init__.py @@ -1,11 +1,19 @@ -"""Runtime graders: raw reward, observation, state and network-policy contracts.""" +"""Runtime graders: raw reward, observation, state, network, containment, resource, isolation and oracle contracts.""" from .basic import ObservationSchemaGrader, RewardWellFormedGrader, StateContractGrader +from .containment import HostContainmentGrader +from .isolation import EpisodeIsolationGrader from .network import NetworkPolicyGrader +from .oracle import OracleContainmentGrader +from .resources import ResourceBoundsGrader __all__ = [ + "EpisodeIsolationGrader", + "HostContainmentGrader", "NetworkPolicyGrader", "ObservationSchemaGrader", + "OracleContainmentGrader", + "ResourceBoundsGrader", "RewardWellFormedGrader", "StateContractGrader", ] diff --git a/src/openenv/validation/graders/runtime/containment.py b/src/openenv/validation/graders/runtime/containment.py new file mode 100644 index 0000000000000000000000000000000000000000..b9b65f2c3f6ce357a67b7d7d7aaa9abcd5474472 --- /dev/null +++ b/src/openenv/validation/graders/runtime/containment.py @@ -0,0 +1,183 @@ +"""`runtime.host_containment`: judge measured isolation, never provider claims.""" + +import time + +from ...report import CheckResult +from ...runtime.contracts import ContainmentEvidence +from ...types import CheckStatus, Level, ProviderCapability + +# Mounts every container runtime adds. Anything else could expose host state. +_RUNTIME_MOUNTS = { + "/", + "/etc/hosts", + "/etc/hostname", + "/etc/resolv.conf", + # Docker binds its init at /sbin/docker-init, which resolves to + # /usr/sbin/docker-init in images where /sbin links to /usr/sbin. + "/sbin/docker-init", + "/usr/sbin/docker-init", + "/run/podman-init", +} +_PSEUDO_ROOTS = ("/proc", "/sys", "/dev") +_PSEUDO_FS = {"proc", "sysfs", "tmpfs", "devpts", "mqueue", "cgroup", "cgroup2"} +# Read-write filesystems of a hardened Docker launch that hold no subject files. +_NOT_STORAGE = { + # Kernel interfaces; Docker makes the sensitive entries read-only or masks them. + ("/proc", "proc"), + # Pseudo-terminal device nodes. + ("/dev/pts", "devpts"), + # POSIX message queues, bounded by the subject's own IPC namespace limits. + ("/dev/mqueue", "mqueue"), +} + + +class HostContainmentGrader: + """Check that the API-boundary subject cannot reach host state or privileges.""" + + check_id = "runtime.host_containment" + level = Level.RUNTIME + requires_capabilities = frozenset() + requires_provider = frozenset({ProviderCapability.INSPECTED_ISOLATION}) + depends_on = ("runtime.startup",) + + def applies_to(self, manifest) -> bool: + return True + + def run(self, subject) -> CheckResult: + started = time.monotonic() + status, problems, measured = self._grade(subject) + return CheckResult( + check_id=self.check_id, + status=status, + evidence=problems or ["measured isolation matches the agent boundary"], + measured=measured, + remediation=( + "Run the subject unprivileged from a read-only image, without host " + "namespaces, mounts or devices, and with writes confined to its " + "allotted roots." + if status is CheckStatus.FAIL + else None + ), + duration_s=time.monotonic() - started, + ) + + @staticmethod + def _grade(subject): + if subject.containment_evidence_json is None: + return CheckStatus.SKIP, ["containment evidence is unavailable"], {} + try: + evidence = ContainmentEvidence.model_validate_json( + subject.containment_evidence_json + ) + except ValueError: # includes pydantic's ValidationError + return CheckStatus.FAIL, ["malformed containment evidence"], {} + + launch = evidence.launch + problems = [] + if launch.privileged: + problems.append("subject runs privileged") + problems += [ + f"subject shares the host {ns} namespace" for ns in launch.host_namespaces + ] + problems += [f"capability added: {cap}" for cap in launch.cap_add] + problems += [f"host device passed in: {device}" for device in launch.devices] + problems += [f"confinement disabled: {option}" for option in launch.unconfined] + for process in evidence.processes: + label = f"process {process.pid} ({process.name})" + if 0 in process.uids: + problems.append(f"{label} runs as root") + if process.cap_eff: + problems.append(f"{label} holds capabilities {process.cap_eff:#x}") + if not process.no_new_privs: + problems.append(f"{label} can gain privileges") + if process.seccomp == 0: + problems.append(f"{label} runs without seccomp") + for mount in evidence.mounts: + pseudo = mount.fstype in _PSEUDO_FS and any( + mount.mount_point == root or mount.mount_point.startswith(root + "/") + for root in _PSEUDO_ROOTS + ) + allotted = ( + mount.mount_point in evidence.allotted and mount.fstype == "tmpfs" + ) + if mount.mount_point not in _RUNTIME_MOUNTS and not allotted and not pseudo: + problems.append( + f"unexpected mount at {mount.mount_point} ({mount.fstype})" + ) + # The read-write mounts are every filesystem the subject could store data in. + if any(m.mount_point == "/" and not m.read_only for m in evidence.mounts): + problems.append("the image root is writable") + # Docker's /dev tmpfs is also bound as /dev/null over masked /proc files. + # Only a complete subtree inventory can establish storage denial. + dev = { + m.device + for m in evidence.mounts + if (m.mount_point, m.fstype) == ("/dev", "tmpfs") + } + for mount in evidence.mounts: + if ( + mount.read_only + or mount.mount_point in ("/", *evidence.allotted) + or (mount.mount_point, mount.fstype) in _NOT_STORAGE + or mount.device in dev + ): + continue + problems.append( + "writable filesystem outside the allotted roots: " + f"{mount.mount_point} ({mount.fstype})" + ) + not_storage = { + m.mount_point + for m in evidence.mounts + if (m.mount_point, m.fstype) in _NOT_STORAGE + } + problems += [ + f"subject can write outside its allotted roots: {path}" + for path in evidence.writable + if path not in not_storage + ] + problems += [ + f"device filesystem {device} permits subject storage" + for device in dev + if device in evidence.device_storage + and evidence.device_storage[device].writable + ] + measured = { + "processes": len(evidence.processes), + "mounts": len(evidence.mounts), + "allotted_writable": evidence.allotted_writable, + "device_storage": { + device: reading.model_dump() + for device, reading in evidence.device_storage.items() + }, + } + # A failed control cannot erase an independently proven violation. + if problems: + return CheckStatus.FAIL, problems, measured + if not evidence.processes: + return CheckStatus.SKIP, ["no subject process could be measured"], measured + if not any(m.mount_point == "/" for m in evidence.mounts): + return ( + CheckStatus.SKIP, + ["the subject's mount table could not be read in full"], + measured, + ) + if sorted(evidence.allotted_writable) != sorted(evidence.allotted): + return ( + CheckStatus.SKIP, + [ + "the probe could not write an allotted root, so write denial is unproven" + ], + measured, + ) + if any( + device not in evidence.device_storage + or not evidence.device_storage[device].complete + for device in dev + ): + return ( + CheckStatus.SKIP, + ["the device filesystem storage inventory is incomplete"], + measured, + ) + return CheckStatus.PASS, [], measured diff --git a/src/openenv/validation/graders/runtime/discovery.py b/src/openenv/validation/graders/runtime/discovery.py new file mode 100644 index 0000000000000000000000000000000000000000..ac1801ee9654e8c04a2d6f5053c7d08f6d23b101 --- /dev/null +++ b/src/openenv/validation/graders/runtime/discovery.py @@ -0,0 +1,367 @@ +"""Declaration and rubric checks over bounded, independently collected evidence.""" + +import json +import math +import time +from decimal import Decimal + +from ...report import CheckResult +from ...types import CheckStatus +from .basic import _RuntimeGrader +from .repeatability import _difference + + +def _finite(value): + try: + return type(value) in (int, float, Decimal) and math.isfinite(value) + except OverflowError: + return False + + +def _json_decimal(value): + number = float(value) + if not math.isfinite(number): + raise ValueError("runtime JSON numbers must be finite") + # Retain the original token for configuration equality. + return Decimal(value) + + +def _arithmetic_value(value): + return float(value) if isinstance(value, Decimal) else value + + +class _EvidenceGrader(_RuntimeGrader): + """Discovery can be measured without an episode step; missing evidence cannot pass.""" + + unavailable_field = None + + def run(self, subject): + started = time.monotonic() + problems, incomplete = [], None + evidence = subject.runtime_evidence + if not self.applies_to(subject.manifest): + incomplete = "declared capability does not apply" + elif evidence is None: + incomplete = "runtime evidence is unavailable" + elif getattr(evidence, self.error_field): + problems = [f"{self.label} collection failed"] + elif self.unavailable_field and getattr(evidence, self.unavailable_field): + incomplete = getattr(evidence, self.unavailable_field) + elif getattr(evidence, self.field) is None: + incomplete = f"missing prerequisite: {self.label} evidence" + else: + try: + payload = json.loads( + getattr(evidence, self.field), + parse_float=_json_decimal, + parse_constant=_json_decimal, + ) + if not isinstance(payload, dict): + raise ValueError("evidence must be an object") + problems, incomplete = self.check(subject, payload) + except (ValueError, TypeError, KeyError, RecursionError, OverflowError): + problems = [f"malformed {self.label} evidence"] + status = ( + CheckStatus.FAIL + if problems + else CheckStatus.SKIP + if incomplete + else CheckStatus.PASS + ) + return CheckResult( + check_id=self.check_id, + status=status, + evidence=problems[:20] + or [incomplete or f"observed {self.label} contract holds"], + duration_s=time.monotonic() - started, + ) + + +class ToolDeclarationAccuracyGrader(_EvidenceGrader): + check_id = "runtime.tool_declaration_accuracy" + depends_on = () + field, error_field, label = "tools_json", "tools_error", "tool discovery" + unavailable_field = "tools_unavailable" + + def applies_to(self, manifest): + return "declared_tools" in manifest.capabilities.model_fields_set + + def check(self, subject, payload): + tools = payload["tools"] + if not isinstance(tools, list): + raise ValueError("tools must be a list") + names = [tool["name"] for tool in tools] + if any(not isinstance(name, str) or not name for name in names): + raise ValueError("invalid tool name") + cursor = payload.get("nextCursor") + if cursor is not None and not isinstance(cursor, str): + raise ValueError("invalid tool pagination cursor") + declared = subject.manifest.capabilities.declared_tools + problems = [] + if len(set(names)) != len(names): + problems.append("discovery contains duplicate tool names") + if len(set(declared)) != len(declared): + problems.append("declaration contains duplicate tool names") + missing = set(declared) - set(names) + extra = set(names) - set(declared) + if missing and cursor is None: + problems.append(f"{len(missing)} declared tools are missing from discovery") + if extra: + problems.append(f"{len(extra)} discovered tools are undeclared") + return problems, ( + "tool inventory is incomplete: pagination was not collected" + if cursor is not None + else None + ) + + +class TaskDeclarationAccuracyGrader(_EvidenceGrader): + check_id = "runtime.task_declaration_accuracy" + depends_on = () + field, error_field, label = "tasks_json", "tasks_error", "task discovery" + + def applies_to(self, manifest): + return manifest.capabilities.task_api or ( + "declared_task_count" in manifest.capabilities.model_fields_set + ) + + def check(self, subject, payload): + splits, counts, previews = ( + payload["splits"], + payload["counts"], + payload["previews"], + ) + if ( + not isinstance(splits, list) + or not isinstance(counts, dict) + or not isinstance(previews, dict) + ): + raise ValueError("invalid task discovery") + names = [split["name"] for split in splits] + if any(not isinstance(name, str) or not name for name in names) or len( + set(names) + ) != len(names): + raise ValueError("invalid split names") + if set(names) != counts.keys() or set(names) != previews.keys(): + raise ValueError("incomplete split discovery") + problems = [] + declared = subject.manifest.capabilities.declared_task_count + has_counts = ( + "declared_task_count" in subject.manifest.capabilities.model_fields_set + ) + if has_counts and set(names) != declared.keys(): + problems.append("discovered splits differ from declared task counts") + for name in names: + count, preview = counts[name], previews[name] + if type(count) is not int or count < 0: + raise ValueError("invalid task count") + if not isinstance(preview, list): + raise ValueError("invalid task preview") + if len(preview) > count or (count > 0 and not preview): + problems.append( + "task preview is inconsistent with the advertised count" + ) + if name in declared and count != declared[name]: + problems.append("advertised task count differs from the declaration") + return problems, None if has_counts else "task counts were not declared" + + +def _rubric_nodes(payload): + if not isinstance(payload, list) or not payload: + raise ValueError("missing rubric tree") + nodes = {} + for node in payload: + name = node["name"] + if not isinstance(name, str) or not all(name.split(".")) or name in nodes: + raise ValueError("invalid rubric name") + if not isinstance(node["class_name"], str) or not node["class_name"]: + raise ValueError("missing rubric class") + children = node["children"] + if not isinstance(children, list) or any( + not isinstance(child, str) for child in children + ): + raise ValueError("invalid rubric children") + if len(set(children)) != len(children): + raise ValueError("duplicate rubric children") + if type(node["config_available"]) is not bool or not isinstance( + node["config"], dict + ): + raise ValueError("invalid rubric configuration") + if type(node["evaluated"]) is not bool: + raise ValueError("invalid evaluation marker") + if node["evaluated"] and not _finite(node["score"]): + raise ValueError("evaluated score is not finite") + if not node["evaluated"] and node["score"] is not None: + raise ValueError("unevaluated score must be absent") + aggregation = node["aggregation"] + if aggregation not in {"weighted_sum", "sequential", "gate", "leaf", "unknown"}: + raise ValueError("invalid aggregation") + if aggregation == "leaf" and children: + raise ValueError("leaf has children") + if aggregation == "weighted_sum": + weights = node["config"]["weights"] + if ( + not isinstance(weights, list) + or len(weights) != len(children) + or not all(_finite(weight) for weight in weights) + ): + raise ValueError("invalid rubric weights") + if not math.isclose( + sum(_arithmetic_value(weight) for weight in weights), + 1, + rel_tol=0, + abs_tol=1e-6, + ): + raise ValueError("rubric weights do not sum to one") + if aggregation == "gate" and ( + len(children) != 1 or not _finite(node["config"]["threshold"]) + ): + raise ValueError("invalid rubric gate") + nodes[name] = node + if "root" not in nodes: + raise ValueError("missing rubric root") + linked = set() + for name, node in nodes.items(): + for child in node["children"]: + if ( + child not in nodes + or child in linked + or child.rsplit(".", 1)[0] != name + or child == name + ): + raise ValueError("invalid rubric edge") + linked.add(child) + if linked != nodes.keys() - {"root"}: + raise ValueError("disconnected rubric tree") + return nodes + + +class RubricIntrospectableGrader(_EvidenceGrader): + check_id = "runtime.rubric_introspectable" + requires_capabilities = frozenset({"rubric_tree"}) + field, error_field, label = "telemetry_json", "telemetry_error", "rubric telemetry" + unavailable_field = "telemetry_unavailable" + + def applies_to(self, manifest): + return manifest.capabilities.rubric_tree + + def check(self, subject, payload): + if type(payload["schema_version"]) is not int or payload["schema_version"] != 1: + raise ValueError("unsupported telemetry version") + if payload.get("rubric_error") is not None: + return ["subject reported unavailable rubric introspection"], None + nodes = _rubric_nodes(payload["rubric"]) + return ( + ["rubric configuration is unavailable"] + if any(not node["config_available"] for node in nodes.values()) + else [] + ), None + + +class RewardAttributionGrader(RubricIntrospectableGrader): + check_id = "runtime.reward_attribution" + depends_on = ("runtime.startup", "runtime.rubric_introspectable") + + def check(self, subject, payload): + problems, _ = super().check(subject, payload) + if subject.runtime_evidence.failure_reason: + problems.append("wire replay is incomplete") + if problems: + return problems, None + baseline = _rubric_nodes(payload["rubric"]) + steps = [ + row for row in subject.runtime_evidence.exchanges if row.operation == "step" + ] + records = payload["attribution"] + if not isinstance(records, list): + raise ValueError("invalid attribution") + if not steps: + return problems, "missing prerequisite: an observed step reward" + if len(records) != len(steps): + return problems + ["attribution does not cover every observed step"], None + + def definition(tree): + return { + name: { + key: value + for key, value in node.items() + if key not in {"score", "evaluated"} + } + for name, node in tree.items() + } + + unsupported = False + scored_steps = 0 + for index, (record, step) in enumerate(zip(records, steps, strict=True)): + if type(record["step_index"]) is not int or record["step_index"] != index: + problems.append( + f"step {index}: attribution identity differs from the wire" + ) + nodes = _rubric_nodes(record["rubric"]) + if _difference(definition(nodes), definition(baseline)): + problems.append(f"step {index}: rubric configuration changed") + data = json.loads(step.response_json)["data"] + reward = data["reward"] + root = nodes["root"] + unscored = reward is None and data.get("done") is False + scored_steps += not unscored + if not unscored and ( + not root["evaluated"] + or not _finite(reward) + or not math.isclose(root["score"], reward, rel_tol=1e-9, abs_tol=1e-9) + ): + problems.append( + f"step {index}: fresh root score differs from emitted reward" + ) + for node in nodes.values(): + if not node["evaluated"]: + continue + children = [nodes[name] for name in node["children"]] + aggregation = node["aggregation"] + if aggregation == "unknown": + unsupported = True + continue + if aggregation == "leaf": + continue + expected = 1.0 if aggregation == "sequential" else 0.0 + visited = 0 + for child in children: + if not child["evaluated"]: + problems.append( + f"step {index}: required child score was not evaluated" + ) + break + visited += 1 + score = _arithmetic_value(child["score"]) + if aggregation == "weighted_sum": + expected += score * _arithmetic_value( + node["config"]["weights"][visited - 1] + ) + elif aggregation == "gate": + expected = ( + 0.0 + if score < _arithmetic_value(node["config"]["threshold"]) + else score + ) + else: + expected = score + if score == 0: + break + if aggregation == "sequential" and any( + child["evaluated"] for child in children[visited:] + ): + problems.append( + f"step {index}: sequential evaluated children after its gate" + ) + if not _finite(expected) or not math.isclose( + node["score"], expected, rel_tol=1e-9, abs_tol=1e-9 + ): + problems.append( + f"step {index}: child attribution does not match the parent score" + ) + incomplete = ( + "unsupported custom rubric aggregation semantics" if unsupported else None + ) + if not scored_steps: + incomplete = "missing prerequisite: an observed numeric step reward" + return problems, incomplete diff --git a/src/openenv/validation/graders/runtime/isolation.py b/src/openenv/validation/graders/runtime/isolation.py new file mode 100644 index 0000000000000000000000000000000000000000..856799a64a96d1597d9457ceba3e6019d1f87def --- /dev/null +++ b/src/openenv/validation/graders/runtime/isolation.py @@ -0,0 +1,193 @@ +"""`runtime.episode_isolation`: a reset must leave no trace of the previous episode.""" + +import time +from json import JSONDecodeError + +from ...report import CheckResult +from ...runtime.json_values import loads, typed_json +from ...types import CheckStatus, Level + + +def _canonical(text): + """Compare exact decoded values while preserving JSON types and malformed text.""" + try: + value = loads(text) + except JSONDecodeError: + return text + try: + return typed_json(value) + except ValueError: + return text # Malformed text is compared exactly as it was sent. + + +def _trace(evidence): + trace, problems = [], [] + for x in evidence.exchanges: + values = [x.operation] + for text in (x.request_json, x.response_json): + try: + values.append(_canonical(text)) + except (RecursionError, ArithmeticError, ValueError) as exc: + # Unknown values are neither equal nor different, even when + # their raw bytes match. Keep the supported fields comparable. + values.append(None) + if isinstance(exc, RecursionError): + problem = "JSON nesting exceeds the parser depth" + elif isinstance(exc, ArithmeticError): + problem = "JSON numeric range exceeds Decimal support" + else: + problem = "JSON integer range exceeds parser support" + if problem not in problems: + problems.append(problem) + trace.append(tuple(values)) + return trace, problems + + +def _divergence(left, right, complete=True, controls=()): + """ + Describe the first supported difference, or `None` when none is established. + + When `left` is an incomplete recording, only its recorded exchanges count. + Unknown values cannot establish equality or a difference. A leak also + requires supported fresh controls at the differing position. + """ + fixed_inputs = True + for index, (a, b) in enumerate(zip(left, right)): + if controls: + fixed_inputs = ( + fixed_inputs + and None not in a[:2] + and None not in b[:2] + and a[:2] == b[:2] + and all( + index < len(control) and control[index][:2] == b[:2] + for control in controls + ) + ) + if controls and ( + not fixed_inputs + or None in a + or None in b + or any(index >= len(control) or control[index] != b for control in controls) + ): + continue + if any(x is not None and y is not None and x != y for x, y in zip(a, b)): + return f"exchange {index} ({a[0]})" + if complete and fixed_inputs and len(left) != len(right): + return f"exchange {min(len(left), len(right))} (trace length)" + return None + + +class EpisodeIsolationGrader: + """Compare an episode that follows a same-session reset with a fresh episode.""" + + check_id = "runtime.episode_isolation" + level = Level.RUNTIME + requires_capabilities = frozenset() + requires_provider = frozenset() + depends_on = ("runtime.startup",) + + def applies_to(self, manifest) -> bool: + return True + + def run(self, subject) -> CheckResult: + started = time.monotonic() + status, problems, measured = self._grade(subject) + return CheckResult( + check_id=self.check_id, + status=status, + evidence=problems or ["an episode after reset matches a fresh episode"], + measured=measured, + remediation=( + "Reset all episode state, including files, caches and rubric " + "state, at the start of every episode." + if status is CheckStatus.FAIL + else None + ), + duration_s=time.monotonic() - started, + ) + + @staticmethod + def _grade(subject): + isolation = subject.isolation_evidence + reference = subject.runtime_evidence + if isolation is None or reference is None: + return CheckStatus.SKIP, ["isolation evidence is unavailable"], {} + failure = isolation.sequential.failure_reason + fresh_failure = isolation.fresh.failure_reason + sequential, sequential_problems = _trace(isolation.sequential) + fresh, fresh_problems = _trace(isolation.fresh) + baseline, baseline_problems = _trace(reference) + problems = sequential_problems + fresh_problems + baseline_problems + if fresh_failure and not fresh_problems: + return ( + CheckStatus.SKIP, + ["the fresh reference episode failed: " + fresh_failure], + {}, + ) + resets = [ + i + for i, x in enumerate(isolation.sequential.exchanges) + if x.operation == "reset" + ] + if len(resets) < 2 and not failure: + return CheckStatus.SKIP, ["no second episode was recorded"], {} + split = resets[1] if len(resets) > 1 else len(sequential) + first, after_reset = sequential[:split], sequential[split:] + measured = {"exchanges": len(after_reset)} + # Isolation is only observable when fixed inputs give a fixed trace, so + # the first episode of every session must agree. + # A validator limit may leave a usable fresh prefix, but never proves + # equality with the unrecorded tail of a complete reference. + drift = _divergence(baseline, fresh, complete=not fresh_failure) or _divergence( + first, baseline, complete=not failure + ) + if drift: + return ( + CheckStatus.SKIP, + [f"two fresh episodes differ at {drift}, so isolation is unproven"], + measured, + ) + leak = _divergence( + after_reset, + fresh, + complete=not failure and not problems, + controls=(baseline, first), + ) + if leak: + return ( + CheckStatus.FAIL, + [ + f"the episode after a same-session reset differs from a fresh one at {leak}" + ], + measured, + ) + inputs = _divergence( + [x[:2] for x in after_reset], [x[:2] for x in fresh], complete=False + ) + if inputs: + return ( + CheckStatus.SKIP, + [ + f"the episode after reset used different inputs at {inputs}, so isolation is unproven" + ], + measured, + ) + if problems: + return ( + CheckStatus.SKIP, + [ + problem + ", so isolation is unproven" + for problem in dict.fromkeys(problems) + ], + measured, + ) + if failure: + # A deadline, size bound or transport failure that left no + # differing response is a gap in the experiment, not a leak. + return ( + CheckStatus.SKIP, + [f"the same-session episodes did not complete: {failure}"], + measured, + ) + return CheckStatus.PASS, [], measured diff --git a/src/openenv/validation/graders/runtime/oracle.py b/src/openenv/validation/graders/runtime/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..bc7f6ab4761e790968e8353aeac4b0394e9e2f13 --- /dev/null +++ b/src/openenv/validation/graders/runtime/oracle.py @@ -0,0 +1,277 @@ +"""`runtime.oracle_containment`: trace declared artifacts through collected responses.""" + +import os +import time +from dataclasses import dataclass +from pathlib import Path + +from ...report import CheckResult +from ...runtime.json_values import loads, typed_json +from ...types import CheckStatus, Level + +MAX_ORACLE_BYTES = 1024 * 1024 +MAX_ORACLE_FILES = 64 +_MIN_FINGERPRINT = 16 + + +@dataclass(frozen=True) +class OracleInventory: + """Bounded file content and explicit coverage of the declared artifact.""" + + files: tuple[tuple[str, str | None], ...] + bytes_read: int + omitted_files: int + omitted_bytes: int + errors: tuple[str, ...] = () + + +def oracle_inventory(root: Path, location: str) -> OracleInventory: + """Read bounded regular files inside the package; never trace truncated content.""" + package = root.resolve() + target = package / location + if not target.resolve().is_relative_to(package) or target.is_symlink(): + raise OSError("oracle is outside the package or is a symlink") + if not target.exists(): + raise OSError("oracle does not exist") + errors = [] + if target.is_dir(): + paths = [] + for directory, dirs, names in os.walk( + target, onerror=lambda exc: errors.append("oracle directory is unreadable") + ): + parent = Path(directory) + paths.extend(parent / name for name in names) + paths.extend(parent / name for name in dirs if (parent / name).is_symlink()) + paths.sort() + else: + paths = [target] + files, total, omitted_files, omitted_bytes = [], 0, 0, 0 + for index, path in enumerate(paths): + try: + if path.is_symlink() or not path.is_file(): + raise OSError("oracle entry is not a regular file") + size = path.stat().st_size + if index >= MAX_ORACLE_FILES or total >= MAX_ORACLE_BYTES: + omitted_files += 1 + omitted_bytes += size + continue + with path.open("rb") as stream: + data = stream.read(min(size, MAX_ORACLE_BYTES - total)) + total += len(data) + complete = len(data) == size + if not complete: + omitted_files += 1 + omitted_bytes += size - len(data) + files.append( + ( + path.relative_to(package).as_posix(), + data.decode("utf-8") if complete else None, + ) + ) + except (OSError, UnicodeError): + errors.append("oracle entry is unreadable or is not UTF-8 regular content") + return OracleInventory( + tuple(files), total, omitted_files, omitted_bytes, tuple(errors) + ) + + +def _json_values(text): + """Walk JSON values iteratively, retaining raw text for non-JSON responses.""" + try: + pending = [loads(text)] + except ValueError: + return + while pending: + value = pending.pop() + yield value + if isinstance(value, dict): + pending.extend(value.values()) + elif isinstance(value, list): + pending.extend(value) + + +def _appears(artifacts, strings, structured, text): + # Whole artifacts avoid conclusive failures from ordinary source-code lines. + if any(artifact in text for artifact in artifacts): + return True, True + parsed, complete = False, True + try: + for value in _json_values(text): + parsed = True + if isinstance(value, str) and any( + artifact in value for artifact in strings + ): + return True, complete + if structured and isinstance(value, (dict, list)): + try: + if typed_json(value) in structured: + return True, complete + except ValueError: + complete = False + except (ArithmeticError, RecursionError): + complete = False + return not parsed and any(artifact in text for artifact in strings), complete + + +class OracleContainmentGrader: + """Check for complete declared artifacts in the measured response surfaces.""" + + check_id = "runtime.oracle_containment" + level = Level.RUNTIME + requires_capabilities = frozenset({"oracle"}) + requires_provider = frozenset() + depends_on = ("runtime.startup",) + + def applies_to(self, manifest) -> bool: + return True + + def run(self, subject) -> CheckResult: + started = time.monotonic() + status, problems, measured = self._grade(subject) + return CheckResult( + check_id=self.check_id, + status=status, + evidence=problems + or [ + "no complete oracle artifact matched collected reset/step/state responses, " + "complete /schema responses or bounded same-origin HTTP file probes; " + "MCP tool access and reward-artifact writes were not tested" + ], + measured=measured, + remediation=( + "Keep oracle and reward artifacts out of observations, state and served files." + if status is CheckStatus.FAIL + else None + ), + duration_s=time.monotonic() - started, + ) + + @staticmethod + def _grade(subject): + if subject.runtime_evidence is None: + return CheckStatus.SKIP, ["runtime evidence is unavailable"], {} + location = subject.manifest.capabilities.oracle.location + try: + inventory = oracle_inventory(subject.root, location) + except (OSError, UnicodeError): + return ( + CheckStatus.SKIP, + [f"oracle artifact {location} is not readable inside the package"], + {}, + ) + artifacts = { + text.strip() + for _, text in inventory.files + if text and len(text.strip()) >= _MIN_FINGERPRINT + } + untraceable = sum( + text is not None and len(text.strip()) < _MIN_FINGERPRINT + for _, text in inventory.files + ) + # Structured artifacts are independent of indentation, key order and escaping. + structured = set() + strings = set(artifacts) + comparison_complete = True + for text in tuple(artifacts): + try: + value = loads(text) + except ValueError: + continue # Scripts and other plain text use whole-content matching. + except (ArithmeticError, RecursionError): + comparison_complete = False + continue + if isinstance(value, str) and len(value.strip()) >= _MIN_FINGERPRINT: + strings.add(value.strip()) + elif isinstance(value, (dict, list)): + try: + structured.add(typed_json(value)) + except ValueError: + comparison_complete = False + runs = [subject.runtime_evidence] + if subject.isolation_evidence: + runs += [ + subject.isolation_evidence.sequential, + subject.isolation_evidence.fresh, + ] + sources = [ + (f"{x.operation} response", x.response_json) + for run in runs + for x in run.exchanges + ] + sources += [ + ("schema response", run.schema_response_json) + for run in runs + if run.schema_response_json is not None + ] + sources += [ + (f"GET {probe.path}", body.decode("utf-8", "replace")) + for probe in subject.oracle_http + for body in (*probe.redirect_bodies, probe.body) + ] + leaks = set() + for label, text in sources: + matched, complete = _appears(artifacts, strings, structured, text) + comparison_complete &= complete + if matched: + leaks.add(label) + measured = { + "artifacts": len(inventory.files), + "bytes_read": inventory.bytes_read, + "omitted_files": inventory.omitted_files, + "omitted_bytes": inventory.omitted_bytes, + "inventory_errors": len(inventory.errors), + "untraceable_files": untraceable, + "json_comparison_complete": comparison_complete, + "sources": len(sources), + "http_probes": len(subject.oracle_http), + "mcp_tool_access_tested": False, + "reward_artifact_writes_tested": False, + } + if leaks: + return ( + CheckStatus.FAIL, + [ + f"oracle content is readable through the API: {label}" + for label in sorted(leaks) + ], + measured, + ) + incomplete = list(inventory.errors) + if not comparison_complete: + incomplete.append( + "structured oracle JSON exceeds supported comparison limits" + ) + if inventory.omitted_files: + incomplete.append("oracle inventory exceeds the file or byte bound") + if untraceable: + incomplete.append( + "some oracle files have no distinctive complete content to trace" + ) + if not artifacts: + incomplete.append( + "the oracle artifact has no distinctive complete content to trace" + ) + if any( + run.failure_reason or not run.exchanges or run.schema_response_json is None + for run in runs + ): + incomplete.append( + "runtime transcript or complete /schema response is unavailable or incomplete" + ) + required = {"/" + path for path, _ in inventory.files} + if ( + not required + or not required.issubset({probe.path for probe in subject.oracle_http}) + or any( + probe.status is None + or probe.failure + or probe.status >= 500 + or probe.status == 206 + or 300 <= probe.status < 400 + for probe in subject.oracle_http + ) + ): + incomplete.append("required oracle HTTP probes are missing or incomplete") + if incomplete: + return CheckStatus.SKIP, incomplete, measured + return CheckStatus.PASS, [], measured diff --git a/src/openenv/validation/graders/runtime/repeatability.py b/src/openenv/validation/graders/runtime/repeatability.py new file mode 100644 index 0000000000000000000000000000000000000000..7788015386291bb039d78e447e6e7499889c13fc --- /dev/null +++ b/src/openenv/validation/graders/runtime/repeatability.py @@ -0,0 +1,417 @@ +"""Seed forwarding, independent records and bounded fresh replay comparisons.""" + +import math +import statistics +import time +from decimal import Decimal, DecimalException +from fractions import Fraction + +from ...report import CheckResult +from ...runtime.json_values import dumps, loads +from ...types import CheckStatus +from .basic import _RuntimeGrader + +JUDGED_REPLAYS = 20 +MAX_JUDGED_NUMBER_DIGITS = 10_000 + + +def _json(text): + try: + return loads(text) + except DecimalException as error: + raise ValueError("unsupported JSON number") from error + + +def _trace(evidence, *, operation=None): + trace = [ + { + "operation": row.operation, + "request": _json(row.request_json), + "response": _json(row.response_json), + } + for row in evidence.exchanges + if operation is None or row.operation == operation + ] + for row in trace: + dumps(row) + operation, request, response = ( + row["operation"], + row["request"], + row["response"], + ) + if ( + operation not in {"reset", "step", "state"} + or not isinstance(request, dict) + or request.get("type") != operation + or not isinstance(response, dict) + or response.get("type") + != ("state" if operation == "state" else "observation") + or not isinstance(response.get("data"), dict) + ): + raise ValueError("malformed trace envelope") + return trace + + +def _difference(expected, observed, path="$"): + """First differing location, exposing indices and key ordinals only.""" + if type(expected) is not type(observed): + return path + if isinstance(expected, dict): + for index, key in enumerate(sorted(expected.keys() | observed.keys())): + child = f"{path}." + if key not in expected or key not in observed: + return child + mismatch = _difference(expected[key], observed[key], child) + if mismatch: + return mismatch + elif isinstance(expected, list): + for index, (left, right) in enumerate(zip(expected, observed)): + mismatch = _difference(left, right, f"{path}[{index}]") + if mismatch: + return mismatch + if len(expected) != len(observed): + return f"{path}[{min(len(expected), len(observed))}]" + elif expected != observed: + return path + return None + + +def _telemetry(evidence): + value = _json(evidence.telemetry_json) + if not isinstance(value, dict) or type(value.get("schema_version")) is not int: + raise ValueError("malformed telemetry") + if value["schema_version"] != 1: + raise ValueError("unsupported telemetry version") + return value + + +def _missing_telemetry(grader, evidence): + if evidence is not None and evidence.failure_reason: + # The shared runtime dependency reports incomplete primary collection. + return None + if evidence is not None and evidence.telemetry_json is None: + failure = evidence.telemetry_error + return CheckResult( + check_id=grader.check_id, + status=CheckStatus.FAIL if failure else CheckStatus.SKIP, + evidence=[ + failure + or evidence.telemetry_unavailable + or "session telemetry is unavailable" + ], + duration_s=0, + ) + return None + + +class SeedControlGrader(_RuntimeGrader): + """Require observed seed forwarding for the original and scheduled resets.""" + + check_id = "runtime.seed_control" + + def run(self, subject): + evidence = subject.runtime_evidence + result = _missing_telemetry(self, evidence) or super().run(subject) + if result.status is CheckStatus.PASS: + seed_replays = [ + replay.evidence for replay in evidence.replays if replay.scope == "seed" + ] + if not seed_replays: + return result.model_copy( + update={ + "status": CheckStatus.SKIP, + "evidence": [ + evidence.replay_failure_reason + or "different-seed reset experiment is unavailable" + ], + } + ) + unavailable = [ + sample.telemetry_unavailable + for sample in seed_replays + if sample.telemetry_unavailable + ] + if unavailable: + return result.model_copy( + update={"status": CheckStatus.SKIP, "evidence": unavailable} + ) + if any( + sample.failure_reason and sample.telemetry_json is None + for sample in seed_replays + ): + return result.model_copy( + update={ + "status": CheckStatus.SKIP, + "evidence": [ + "different-seed reset experiment did not produce seed telemetry" + ], + } + ) + if result.status is CheckStatus.PASS: + return result.model_copy( + update={ + "evidence": ["requested seeds were observed as forwarded to reset"] + } + ) + return result + + def check(self, subject, evidence): + problems = [] + original_seed = None + for index, sample in enumerate( + [evidence] + + [replay.evidence for replay in evidence.replays if replay.scope == "seed"] + ): + if sample.telemetry_error: + problems.append(f"replay {index}: telemetry collection failed") + continue + if sample.telemetry_unavailable: + continue + incomplete = sample.failure_reason and sample.telemetry_json is None + if incomplete: + # Failed later actions leave seed forwarding unproven; an + # observed reset rejection remains a seed experiment failure. + _trace(sample, operation="reset") + resets = [row for row in sample.exchanges if row.operation == "reset"] + if incomplete and not resets: + continue + if len(resets) != 1: + problems.append(f"replay {index}: expected one measured reset") + continue + seed = _json(resets[0].request_json)["data"]["seed"] + if type(seed) is not int: + problems.append(f"replay {index}: requested seed is not an integer") + continue + if index == 0: + original_seed = seed + elif seed == original_seed: + problems.append(f"replay {index}: scheduled seed was not changed") + if incomplete: + continue + if sample.telemetry_json is None: + problems.append(f"replay {index}: seed telemetry unavailable") + continue + observed = _telemetry(sample).get("seed") + if ( + not isinstance(observed, dict) + or observed.get("requested") is not True + or observed.get("accepted") is not True + or type(observed.get("value")) is not int + or observed["value"] != seed + ): + problems.append(f"replay {index}: seed was not observed as forwarded") + return problems + + +class TrajectoryRecordGrader(_RuntimeGrader): + """Compare a subject-emitted record with the independent collector transcript.""" + + check_id = "runtime.trajectory_record" + + def run(self, subject): + return _missing_telemetry(self, subject.runtime_evidence) or super().run( + subject + ) + + def check(self, subject, evidence): + if evidence.telemetry_error: + return [evidence.telemetry_error] + record = _telemetry(evidence).get("trajectory") + if not isinstance(record, dict): + return ["subject-emitted trajectory record is missing"] + if ( + type(record.get("schema_version")) is not int + or record["schema_version"] != 1 + or record.get("source") != "openenv-server" + ): + return ["subject-emitted trajectory record metadata is invalid"] + if record.get("complete") is not True: + return ["subject-emitted trajectory record is incomplete"] + if not isinstance(record.get("records"), list): + return ["subject-emitted trajectory records are malformed"] + mismatch = _difference(_trace(evidence), record["records"]) + return [f"subject record differs at {mismatch}"] if mismatch else [] + + +class EpisodeDeterminismGrader(_RuntimeGrader): + """Compare full traces, or per-step reward population variance for a judge.""" + + check_id = "runtime.episode_determinism" + + def run(self, subject): + started = time.monotonic() + evidence = subject.runtime_evidence + if evidence is None: + return super().run(subject) + measured = {} + try: + status, messages, measured = self._grade(subject, evidence) + except (ValueError, TypeError, KeyError, RecursionError, OverflowError): + status, messages = CheckStatus.FAIL, ["malformed replay evidence"] + return CheckResult( + check_id=self.check_id, + status=status, + evidence=messages, + measured=measured, + duration_s=time.monotonic() - started, + ) + + def _grade(self, subject, evidence): + if any( + row.scope not in {"session", "container", "seed"} + for row in evidence.replays + ): + return CheckStatus.FAIL, ["invalid replay scope"], {} + replays = [row for row in evidence.replays if row.scope != "seed"] + samples = [evidence] + [row.evidence for row in replays] + completed = [ + not row.failure_reason + and not row.failure_phase + and any(exchange.operation == "step" for exchange in row.exchanges) + for row in samples + ] + measured = {"completed_replays": sum(completed)} + judged = subject.manifest.capabilities.llm_judged + required = JUDGED_REPLAYS if judged else 3 + # Inspect retained content before reporting an incomplete schedule: a + # timeout cannot conceal malformed wire data or an observed divergence. + traces = [_trace(sample) for sample in samples] + rewards = [] + for trace in traces: + sample_rewards = [] + for row in trace: + if row["operation"] != "step": + continue + if judged: + data = row["response"]["data"] + reward = data["reward"] + if reward is None and data.get("done") is False: + sample_rewards.append(None) + continue + low, high = subject.manifest.reward.range + if ( + type(reward) not in (int, Decimal) + or not Decimal(reward).is_finite() + or not Decimal(str(low)) <= reward <= Decimal(str(high)) + ): + return ( + CheckStatus.FAIL, + ["invalid judged replay reward"], + measured, + ) + sample_rewards.append(Decimal(reward)) + # Keep null versus numeric positions visible to trace comparison. + data["reward"] = 0.0 + rewards.append(sample_rewards) + # Policy-owned volatile exclusions are deliberately empty. All replays + # use the same episode identity; no author field can suppress a difference. + for index, trace in enumerate(traces[1:], 1): + if completed[0] and completed[index]: + mismatch = _difference(traces[0], trace) + else: + shared = min(len(traces[0]), len(trace)) + mismatch = _difference(traces[0][:shared], trace[:shared]) + if mismatch: + return ( + CheckStatus.FAIL, + [f"replay {index}: first divergence at {mismatch}"], + measured, + ) + if ( + not all(completed) + or len(samples) < required + or {row.scope for row in replays} != {"session", "container"} + ): + return ( + CheckStatus.SKIP, + [ + evidence.replay_failure_reason + or f"requires {required} completed replays across fresh sessions and containers" + ], + measured, + ) + if judged and len(samples) != JUDGED_REPLAYS: + return ( + CheckStatus.FAIL, + ["judged procedure requires exactly 20 samples"], + measured, + ) + if judged: + bound = subject.manifest.reward.variance_tolerance + if type(bound) not in (int, float) or not math.isfinite(bound) or bound < 0: + return CheckStatus.FAIL, ["invalid declared variance bound"], measured + variances, unsupported = [], [] + for index, values in enumerate(zip(*rewards)): + if values[0] is None: + variance = None + # A short exponent token must not allocate an unbounded rational. + elif any( + len(value.as_tuple().digits) + abs(value.as_tuple().exponent) + > MAX_JUDGED_NUMBER_DIGITS + for value in values + ): + unsupported.append(index) + variance = None + else: + # Rational variance avoids float and Decimal-context rounding. + variance = statistics.pvariance(map(Fraction, values)) + variances.append(variance) + failure = next( + ( + index + for index, variance in enumerate(variances) + if variance is not None and variance > Decimal(str(bound)) + ), + None, + ) + if unsupported and failure is None: + return ( + CheckStatus.SKIP, + ["judged reward precision exceeds supported arithmetic bounds"], + measured, + ) + display = [] + unavailable = { + str(index): "exceeds supported arithmetic bounds" + for index in unsupported + } + for index, variance in enumerate(variances): + try: + display.append(None if variance is None else float(variance)) + except OverflowError: + display.append(None) + unavailable[str(index)] = "exceeds finite float display range" + measured.update( + reward_population_variance=display, + variance_units="reward_squared", + ) + if unavailable: + measured["reward_population_variance_unavailable"] = unavailable + if failure is not None: + return ( + CheckStatus.FAIL, + [ + f"step {failure}: reward population variance exceeds declared bound" + ], + measured, + ) + if not any(variance is not None for variance in variances): + return ( + CheckStatus.SKIP, + ["missing prerequisite: an observed numeric step reward"], + measured, + ) + if any( + row.scope == "container" and row.cleanup_complete is not True + for row in replays + ): + return ( + CheckStatus.SKIP, + ["fresh container cleanup was not confirmed"], + measured, + ) + return ( + CheckStatus.PASS, + ["fresh-session and fresh-container replays agree"], + measured, + ) diff --git a/src/openenv/validation/graders/runtime/resources.py b/src/openenv/validation/graders/runtime/resources.py new file mode 100644 index 0000000000000000000000000000000000000000..a69bbfd641150dc098ca6fb5f1fa45961cc72345 --- /dev/null +++ b/src/openenv/validation/graders/runtime/resources.py @@ -0,0 +1,199 @@ +"""`runtime.resource_bounds`: measured limits and enforcement against the declared budget.""" + +import time + +from ...report import CheckResult +from ...runtime.contracts import ResourceEvidence +from ...types import CheckStatus, Level, ProviderCapability + +_MIB = 1024 * 1024 +_PROBES = { + "memory": "cgroup_oom_kill", + "pids": "cgroup_pids_max", + "disk": "filesystem_full", + "exec_timeout": "exec_timeout", +} + + +class ResourceBoundsGrader: + """Check measured resource ceilings and Docker exec descendant cleanup.""" + + check_id = "runtime.resource_bounds" + level = Level.RUNTIME + requires_capabilities = frozenset() + requires_provider = frozenset({ProviderCapability.RESOURCE_ENFORCEMENT}) + depends_on = ("runtime.startup",) + + def applies_to(self, manifest) -> bool: + return True + + def run(self, subject) -> CheckResult: + started = time.monotonic() + status, problems, measured = self._grade(subject) + return CheckResult( + check_id=self.check_id, + status=status, + evidence=problems + or [ + "measured CPU, memory, PID and storage ceilings match the declaration; " + "Docker exec timeout removes descendants; episode deadline is not qualified" + ], + measured=measured, + remediation=( + "Run the subject under finite CPU, memory, swap, process and " + "writable-storage limits within its declared budget." + if status is CheckStatus.FAIL + else None + ), + duration_s=time.monotonic() - started, + ) + + @staticmethod + def _grade(subject): + if subject.resource_evidence_json is None: + return CheckStatus.SKIP, ["resource evidence is unavailable"], {} + try: + evidence = ResourceEvidence.model_validate_json( + subject.resource_evidence_json + ) + except ValueError: # includes pydantic's ValidationError + return CheckStatus.FAIL, ["malformed resource evidence"], {} + + declared = subject.manifest.resources + cgroup = evidence.cgroup + problems = [] + if cgroup is not None: + if "memory_max" in cgroup.unavailable: + pass + elif cgroup.memory_max is None: + problems.append("memory is unlimited") + elif cgroup.memory_max > declared.memory_mb * _MIB: + problems.append( + f"memory limit {cgroup.memory_max} B exceeds {declared.memory_mb} MiB" + ) + if "swap_max" not in cgroup.unavailable and cgroup.swap_max != 0: + problems.append("swap is not disabled") + if {"cpu_quota", "cpu_period"} & set(cgroup.unavailable): + pass + elif cgroup.cpu_quota is None: + problems.append("CPU is unlimited") + elif cgroup.cpu_period is None: + problems.append("CPU period is unavailable") + elif cgroup.cpu_quota / cgroup.cpu_period > declared.cpu + 1e-9: + problems.append( + f"CPU limit {cgroup.cpu_quota / cgroup.cpu_period:g} exceeds {declared.cpu:g}" + ) + if "pids_max" not in cgroup.unavailable and cgroup.pids_max is None: + problems.append("process count is unlimited") + inventory = evidence.containment + storage_unknown = inventory is None or not any( + mount.mount_point == "/" for mount in inventory.mounts + ) + filesystems = {} + if inventory is not None: + # Docker's device tmpfs is also bound over masked /proc files. Denial + # at /dev alone says nothing about nested directories or regular files. + dev = { + mount.device + for mount in inventory.mounts + if (mount.mount_point, mount.fstype) == ("/dev", "tmpfs") + } + if any( + device not in inventory.device_storage + or not inventory.device_storage[device].complete + for device in dev + ): + storage_unknown = True + for mount in inventory.mounts: + if mount.mount_point == "/" and not mount.read_only: + problems.append("the image root is writable") + if mount.read_only or (mount.mount_point, mount.fstype) in { + ("/proc", "proc"), + ("/dev/pts", "devpts"), + ("/dev/mqueue", "mqueue"), + }: + continue + if mount.device in dev and mount.mount_point not in inventory.allotted: + access = inventory.device_storage.get(mount.device) + if access is None or not access.writable: + continue + if mount.size_bytes is None: + storage_unknown = True + else: + filesystems[mount.device] = mount.size_bytes + if sorted(inventory.allotted_writable) != sorted(inventory.allotted): + storage_unknown = True + writable = sum(filesystems.values()) + if writable > declared.disk_mb * _MIB: + problems.append( + f"writable storage {writable} B exceeds {declared.disk_mb} MiB" + ) + results = {probe.kind: probe.result for probe in evidence.qualification} + problems += [ + f"the {kind} probe escaped its limit" + for kind, result in results.items() + if result == "escaped" + ] + measured = { + "cgroup": cgroup.model_dump() if cgroup else None, + "writable_bytes": writable, + "qualification": results, + } + # A failed control cannot erase an independently proven violation. + if problems: + return CheckStatus.FAIL, problems, measured + if cgroup is None: + return CheckStatus.SKIP, ["cgroup v2 limits could not be read"], measured + if cgroup.unavailable: + return ( + CheckStatus.SKIP, + ["unreadable cgroup limits: " + ", ".join(cgroup.unavailable)], + measured, + ) + if storage_unknown: + return ( + CheckStatus.SKIP, + ["complete writable-filesystem inventory is unavailable"], + measured, + ) + qualified = {probe.kind: probe for probe in evidence.qualification} + unproven = [] + for kind, reason in _PROBES.items(): + probe = qualified.get(kind) + if ( + probe is None + or not probe.started + or probe.result != "contained" + or probe.reason != reason + ): + unproven.append(kind) + continue + increased = ( + probe.counter_before is not None + and probe.counter_after is not None + and probe.counter_after > probe.counter_before + ) + corroborated = { + "memory": probe.oom_killed or increased, + "pids": increased, + "disk": all( + probe.free_bytes.get(path) == 0 + and (probe.free_bytes_before.get(path) or 0) > 0 + for path in inventory.allotted + ), + "exec_timeout": ( + probe.removed + and probe.parent_pid is not None + and probe.descendant_pid is not None + and probe.parent_pid != probe.descendant_pid + ), + }[kind] + if not corroborated: + unproven.append(kind) + if unproven: + return ( + CheckStatus.SKIP, + [f"enforcement not proven for {', '.join(unproven)}"], + measured, + ) + return CheckStatus.PASS, [], measured diff --git a/src/openenv/validation/graders/semantic/__init__.py b/src/openenv/validation/graders/semantic/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..08aadc2e4ddaaaf35cccfe4a4475e9c0df48d150 --- /dev/null +++ b/src/openenv/validation/graders/semantic/__init__.py @@ -0,0 +1,5 @@ +"""Semantic-level graders.""" + +from .oracle import CanaryFloorGrader, FloorGapGrader, OracleMaxGrader + +__all__ = ["CanaryFloorGrader", "FloorGapGrader", "OracleMaxGrader"] diff --git a/src/openenv/validation/graders/semantic/oracle.py b/src/openenv/validation/graders/semantic/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..9dd8a8d9f39e948b6207ce16b6c778ba16ba5b39 --- /dev/null +++ b/src/openenv/validation/graders/semantic/oracle.py @@ -0,0 +1,145 @@ +"""Verifier sanity over oracle, do-nothing and canary rewards (#778 tests #25, #28). + +The execution binding measures the rewards; these graders only compare them with the +manifest's declared range, tolerance and margin. Comparisons use exact rationals so a +tiny floor cannot round into the margin. +""" + +import time +from fractions import Fraction + +from ...report import CheckResult +from ...types import CheckStatus, Level + + +class _SemanticGrader: + level = Level.SEMANTIC + requires_capabilities = frozenset() + requires_provider = frozenset() + # RFC 008: episode determinism is a precondition of every semantic check. + depends_on = ("runtime.episode_determinism",) + remediation = "" + + def applies_to(self, manifest) -> bool: + return True + + def run(self, subject) -> CheckResult: + started = time.monotonic() + evidence = subject.oracle_evidence + if evidence is None: + return CheckResult( + check_id=self.check_id, + status=CheckStatus.ERROR, + evidence=["oracle evidence is unavailable"], + duration_s=0, + ) + reward = subject.manifest.reward + low, high = (Fraction(str(value)) for value in reward.range) + problems, measured = self.check( + evidence, + maximum=high, + width=high - low, + tolerance=Fraction(str(reward.oracle_tolerance)), + margin=Fraction(str(reward.floor_margin)), + ) + return CheckResult( + check_id=self.check_id, + status=CheckStatus.FAIL if problems else CheckStatus.PASS, + measured=measured, + evidence=problems or [self.passed], + remediation=self.remediation if problems else None, + duration_s=time.monotonic() - started, + ) + + +class OracleMaxGrader(_SemanticGrader): + """Every oracle run exits cleanly and meets the range-normalized tolerance.""" + + check_id = "semantic.oracle_max" + passed = "every oracle run reached the declared maximum within tolerance" + remediation = ( + "Fix the oracle or the verifier so a correct solution exits cleanly and " + "earns the declared maximum reward." + ) + + def check(self, evidence, *, maximum, width, tolerance, margin): + threshold = maximum - tolerance * width + problems = [] + for run, (reward, code) in enumerate( + zip(evidence.oracle, evidence.oracle_exit_codes, strict=True), start=1 + ): + if code != 0: + problems.append(f"oracle run {run} exited with code {code}") + if reward < threshold: + problems.append( + f"oracle run {run} earned {float(reward)}, below {float(threshold)}" + ) + return problems, { + "oracle_rewards": [float(reward) for reward in evidence.oracle], + "oracle_exit_codes": list(evidence.oracle_exit_codes), + "declared_max": float(maximum), + "oracle_tolerance": float(tolerance), + } + + +class FloorGapGrader(_SemanticGrader): + """ + The do-nothing reward sits at least `floor_margin` of the declared range below + the maximum and every oracle run. The oracle may sit up to the tolerance below + the maximum, so both gaps are required. + """ + + check_id = "semantic.floor_gap" + passed = "the do-nothing reward leaves the declared margin" + remediation = ( + "The verifier rewards doing nothing. Check for vacuous success conditions, " + "such as comparisons against empty output." + ) + + def check(self, evidence, *, maximum, width, tolerance, margin): + floor = evidence.floor + required_gap = margin * width + problems = [] + if maximum - floor < required_gap: + problems.append( + f"do-nothing reward {float(floor)} is within {float(maximum - floor)} " + f"of the maximum, below the required gap {float(required_gap)}" + ) + lowest = min(evidence.oracle) + if lowest - floor < required_gap: + problems.append( + f"oracle reward {float(lowest)} is within {float(lowest - floor)} " + f"of the do-nothing reward, below the required gap {float(required_gap)}" + ) + return problems, { + "measured_floor": float(floor), + "oracle_reward": float(lowest), + "declared_max": float(maximum), + "declared_margin": float(margin), + } + + +class CanaryFloorGrader(_SemanticGrader): + """Every declared canary, a known-wrong solution, earns no more than doing nothing.""" + + check_id = "semantic.canary_floor" + requires_capabilities = frozenset({"canaries"}) + passed = "every canary stayed at the do-nothing reward" + remediation = ( + "The verifier rewards a known-wrong solution. Tighten the tests so each " + "canary earns no more than doing nothing." + ) + + def check(self, evidence, *, maximum, width, tolerance, margin): + problems = [ + f"canary {name} earned {float(reward)}, above the do-nothing reward " + f"{float(evidence.floor)}" + for name, reward in evidence.canaries + if reward > evidence.floor + ] + return problems, { + "measured_floor": float(evidence.floor), + "canary_rewards": { + name: float(reward) for name, reward in evidence.canaries + }, + } diff --git a/src/openenv/validation/harbor.py b/src/openenv/validation/harbor.py new file mode 100644 index 0000000000000000000000000000000000000000..6932562ecbd917051e2257d81d86911b36e14252 --- /dev/null +++ b/src/openenv/validation/harbor.py @@ -0,0 +1,1549 @@ +"""Native Harbor execution: fresh trials graded through RFC 008 check ids. + +No served-protocol evidence is synthesized. On local Docker, a do-nothing trial +builds the image, or pulls the task's digest-pinned one, and the oracle, its replay +and any canaries run pinned to that image. On `hf-sandbox`, every trial starts at +once from the task's digest-pinned image, each in its own Hugging Face Job. +""" + +import asyncio +import hashlib +import json +import math +import os +import re +import shutil +import signal +import stat +import subprocess +import tempfile +import time +import uuid +from concurrent.futures import ThreadPoolExecutor +from dataclasses import replace +from decimal import Decimal +from fractions import Fraction +from functools import partial +from importlib.metadata import distribution +from pathlib import Path + +from .graders import GraderRegistry +from .graders.semantic import CanaryFloorGrader, FloorGapGrader, OracleMaxGrader +from .parsers.harbor_toml import ( + _unique_object, + canary_scripts, + HARBOR_PROFILE, + read_harbor_contract, + read_harbor_task, +) +from .policy import apply_policy +from .report import CheckResult, ValidationReportV2 +from .runtime.artifacts import write_runtime_bundle +from .runtime.contracts import OracleEvidence +from .runtime.json_values import dumps +from .runtime.scheduler import execute_graders +from .types import CheckStatus, Lane, Level + +_IMAGE_ID = re.compile(r"sha256:[0-9a-f]{64}\Z") +# A tag can move between validation and training; a digest cannot. +_PINNED_IMAGE = re.compile(r"[^@\s]+@sha256:[0-9a-f]{64}\Z") +_RESOURCE_ID = re.compile(r"[a-zA-Z0-9][a-zA-Z0-9_.-]*\Z") +_PROJECT = re.compile( + r"openenv-validation-[a-f0-9]+-(nop|oracle|oracle-replay|canary-[1-8])__env" +) +_MAX_REWARD_BYTES = 1024 * 1024 +# Failures the trial's teardown records over any earlier one. +_HOST_FAILURES = { + "HarborTeardownError", + "CleanupNotVerified", + "RewardArtifactDrift", + "UnsafeRewardArtifact", + "RetainedImageDrift", + "RetainedImageUnverified", +} +_TERMINAL_STAGES = {"COMPLETED", "CANCELED", "ERROR", "DELETED"} +_JOB_STOP_TIMEOUT_S = 60 +# Readiness budget inside the 600-second start budget; allocation can take longer. +_SANDBOX_START_TIMEOUT_S = 540 +# Checks this binding measures; every other local check is a named SKIP. +_IMPLEMENTED = { + "runtime.startup", + "runtime.reward_well_formed", + "runtime.episode_determinism", + "semantic.oracle_max", + "semantic.floor_gap", + "semantic.canary_floor", +} + + +class NativeEvidenceError(ValueError): + """A credential-safe diagnostic written by the trusted native collector.""" + + +def _digest(value): + return hashlib.sha256( + json.dumps(value, sort_keys=True, allow_nan=False).encode() + ).hexdigest() + + +class DockerInspector: + """Trusted host inspection and removal limited to run-owned resources.""" + + def __init__(self): + self._owned_volumes = {} + self._retained_image = None + + def _docker(self, *args): + result = subprocess.run( + ["docker", *args], capture_output=True, timeout=30, check=True + ) + if len(result.stdout) > 4 * 1024 * 1024: + raise NativeEvidenceError("Docker inspection exceeded its output limit") + return result.stdout.decode() + + def preflight(self): + info = json.loads(self._docker("info", "--format", "{{json .}}")) + if info["OSType"] != "linux": + raise NativeEvidenceError("Harbor requires a Linux Docker daemon") + self._docker("compose", "version") + return { + "os": info["OSType"], + "daemon_id": info["ID"], + "server_version": info["ServerVersion"], + } + + def inventory(self, project): + if not _PROJECT.fullmatch(project): + raise NativeEvidenceError("not a run-owned Harbor project") + label = f"label=com.docker.compose.project={project}" + inventory = {} + for kind, args in ( + ("containers", ("ps", "-aq", "--no-trunc")), + ("networks", ("network", "ls", "-q", "--no-trunc")), + ("volumes", ("volume", "ls", "-q")), + ): + ids = self._docker(*args, "--filter", label).split() + if any(not _RESOURCE_ID.fullmatch(item) for item in ids): + raise NativeEvidenceError("invalid Docker resource identity") + inventory[kind] = ids + images = self._docker( + "image", "ls", "-q", "--no-trunc", project + "-main:latest" + ).split() + if len(images) > 1 or any(not _IMAGE_ID.fullmatch(image) for image in images): + raise NativeEvidenceError("invalid Compose image identity") + inventory["images"] = images + return inventory + + def capture(self, project, retained_tag, *, retain=True): + inventory = self.inventory(project) + if retained_tag != "openenv-validation:" + project.split("-", 3)[2]: + raise NativeEvidenceError( + "retained image tag differs from its run-owned project" + ) + if len(inventory["containers"]) != 1: + raise NativeEvidenceError("Harbor requires exactly one main container") + item = json.loads(self._docker("inspect", inventory["containers"][0]))[0] + labels = item["Config"]["Labels"] + if ( + labels.get("com.docker.compose.project") != project + or labels.get("com.docker.compose.service") != "main" + ): + raise NativeEvidenceError( + "container does not match the native main service" + ) + if not item["State"]["Running"] or not _IMAGE_ID.fullmatch(item["Image"]): + raise NativeEvidenceError( + "native container is not running with an immutable image" + ) + if retain: + self._retained_image = (retained_tag, item["Image"]) + self._docker("image", "tag", item["Image"], retained_tag) + retained = json.loads(self._docker("image", "inspect", retained_tag))[0] + if (retain and retained["Id"] != item["Image"]) or retained["Os"] != "linux": + raise NativeEvidenceError("retained image binding changed") + host = item["HostConfig"] + # Dockerfile VOLUME creates anonymous volumes without Compose labels. + volumes = [ + mount["Name"] for mount in item["Mounts"] if mount["Type"] == "volume" + ] + if any(not _RESOURCE_ID.fullmatch(name) for name in volumes): + raise NativeEvidenceError("invalid mounted volume identity") + self._owned_volumes[project] = volumes + configuration = { + "image_ref": item["Image"], + "user": item["Config"]["User"], + "workdir": item["Config"]["WorkingDir"], + "environment_digest": _digest(sorted(item["Config"].get("Env") or [])), + "entrypoint": item["Config"].get("Entrypoint"), + "command": item["Config"].get("Cmd"), + "host": { + key: host.get(key) + for key in ( + "NanoCpus", + "Memory", + "MemorySwap", + "PidsLimit", + "ReadonlyRootfs", + "Privileged", + "CapAdd", + "CapDrop", + "SecurityOpt", + "Devices", + ) + }, + "network_mode": "compose-default" + if host["NetworkMode"] == project + "_default" + else host["NetworkMode"], + "mounts": sorted( + [ + { + "type": mount["Type"], + "destination": mount["Destination"], + "rw": mount["RW"], + } + for mount in item["Mounts"] + ], + key=lambda mount: mount["destination"], + ), + } + return { + "container_id": item["Id"], + "project": project, + "image_ref": item["Image"], + "retained_image_tag": retained_tag, + "configuration": configuration, + "configuration_digest": _digest(configuration), + "owned_volumes": volumes, + } + + def cleanup(self, project): + before = self.inventory(project) + for container in before["containers"]: + item = json.loads(self._docker("inspect", container))[0] + if item["Config"]["Labels"].get("com.docker.compose.project") != project: + raise NativeEvidenceError("cleanup container ownership changed") + volumes = [ + mount["Name"] for mount in item["Mounts"] if mount["Type"] == "volume" + ] + if any(not _RESOURCE_ID.fullmatch(name) for name in volumes): + raise NativeEvidenceError("invalid cleanup volume identity") + self._owned_volumes.setdefault(project, []).extend(volumes) + # Even a successful docker rm -v can leave an anonymous volume behind. + registered = self._owned_volumes.get(project, []) + existing = ( + set(self._docker("volume", "ls", "-q").split()) if registered else set() + ) + before["volumes"] = sorted( + set(before["volumes"]) | (set(registered) & existing) + ) + for key, args in ( + ("containers", ("rm", "-f", "-v")), + ("networks", ("network", "rm")), + ("volumes", ("volume", "rm")), + ): + remaining = before[key] + if key == "volumes" and remaining: + existing = set(self._docker("volume", "ls", "-q").split()) + remaining = [name for name in remaining if name in existing] + if remaining: + self._docker(*args, *remaining) + for image_ref in before["images"]: + tag = project + "-main:latest" + image = json.loads(self._docker("image", "inspect", tag))[0] + labels = image["Config"]["Labels"] + if ( + image["Id"] != image_ref + or labels.get("com.docker.compose.project") != project + or labels.get("com.docker.compose.service") != "main" + ): + raise NativeEvidenceError( + "Compose image ownership changed before removal" + ) + self._docker("image", "rm", "--no-prune", tag) + after = self.inventory(project) + if registered: + existing = set(self._docker("volume", "ls", "-q").split()) + after["volumes"] = sorted( + set(after["volumes"]) | (set(registered) & existing) + ) + return {"verified": not any(after.values()), "before": before, "after": after} + + def verify_image(self, tag, image_ref): + image = json.loads(self._docker("image", "inspect", tag))[0] + return image["Id"] == image_ref + + def remove_image(self): + if self._retained_image is not None: + tag, image_ref = self._retained_image + if not self.verify_image(tag, image_ref): + raise NativeEvidenceError( + "retained image ownership changed before removal" + ) + self._docker("image", "rm", "--no-prune", tag) + self._retained_image = None + + +def _job_labels(trial_name): + # openenv-validation-- + run_id, role = trial_name.split("-", 3)[2:] + return {"openenv-validation-run": run_id, "openenv-validation-role": role} + + +class HFJobsInspector: + """ + Trusted HF Jobs checks limited to sandbox jobs labelled with this run. + + The image identity is the digest requested from HF Jobs and read back from the + job; no runtime digest is measured inside the sandbox. + """ + + def __init__(self, image, flavor, namespace, resources): + self.image = image + self.flavor = flavor + self.namespace = namespace + self._resources = resources + self._api = None + self._observed_jobs = {} + + def preflight(self): + from huggingface_hub import HfApi + + self._api = HfApi() + if self.namespace is None: + self.namespace = self._api.whoami()["name"] + hardware = {item.name: item for item in self._api.list_jobs_hardware()} + if self.flavor not in hardware: + raise NativeEvidenceError(f"unknown HF Jobs flavor {self.flavor}") + item = hardware[self.flavor] + # The Hub lists specs as "2 vCPU", "16 GB" and "50 GB". + cpu, memory_gb, disk_gb = ( + int(spec.split()[0]) + for spec in (item.cpu, item.ram, item.ephemeral_storage) + ) + if ( + cpu < self._resources.cpu + or memory_gb * 1024 < self._resources.memory_mb + or disk_gb * 1024 < self._resources.disk_mb + ): + raise NativeEvidenceError( + f"HF Jobs flavor {self.flavor} ({item.cpu}, {item.ram} RAM, " + + f"{item.ephemeral_storage} disk) is smaller than the contract resources" + ) + return { + "flavor": self.flavor, + "namespace": self.namespace, + "hardware": { + "cpu": item.cpu, + "ram": item.ram, + "disk": item.ephemeral_storage, + }, + } + + def register_job(self, project, job_id): + # The Sandbox handle is authoritative even before AGENT_START or listing. + self._observed_jobs.setdefault(project, set()).add(job_id) + + def _jobs(self, project): + if not _PROJECT.fullmatch(project): + raise NativeEvidenceError("not a run-owned Harbor project") + labels = _job_labels(project.removesuffix("__env")) + jobs = list(self._api.list_jobs(labels=labels, namespace=self.namespace)) + # A listing omission does not prove a previously observed job terminated. + listed_ids = {job.id for job in jobs} + known_ids = self._observed_jobs.get(project, set()) + jobs.extend( + self._api.inspect_job(job_id=job_id, namespace=self.namespace) + for job_id in sorted(known_ids - listed_ids) + ) + # Cleanup cancels what this returns, so recheck the server-side filter. + if any( + not labels.items() <= (job.labels or {}).items() + or job.owner.name != self.namespace + for job in jobs + ): + raise NativeEvidenceError("HF Jobs returned a job outside this run") + self._observed_jobs[project] = known_ids | listed_ids + return jobs + + def inventory(self, project): + return {"jobs": sorted(job.id for job in self._jobs(project))} + + def capture(self, project, retained_tag, *, retain=True): + jobs = self._jobs(project) + if len(jobs) != 1: + raise NativeEvidenceError("HF Sandbox trial requires exactly one job") + job = jobs[0] + if ( + job.status.stage != "RUNNING" + or job.docker_image != self.image + or job.flavor != self.flavor + ): + raise NativeEvidenceError( + "HF Sandbox job is not running the pinned image on the requested flavor" + ) + configuration = { + "image_ref": job.docker_image, + "flavor": self.flavor, + "namespace": self.namespace, + } + return { + "container_id": job.id, + "project": project, + "image_ref": job.docker_image, + "configuration": configuration, + "configuration_digest": _digest(configuration), + } + + def cleanup(self, project): + # Startup settles allocation before teardown; inspect until each job ends. + deadline = time.monotonic() + _JOB_STOP_TIMEOUT_S + cancelled = set() + while True: + stages = {job.id: job.status.stage for job in self._jobs(project)} + running = { + job_id + for job_id, stage in stages.items() + if stage not in _TERMINAL_STAGES + } + for job_id in running - cancelled: + self._api.cancel_job(job_id=job_id, namespace=self.namespace) + cancelled.add(job_id) + if not running or time.monotonic() > deadline: + return { + "verified": not running, + "jobs": stages, + "cancelled": sorted(cancelled), + } + time.sleep(2) + + def verify_image(self, tag, image_ref): + return image_ref == self.image + + def remove_image(self): + pass # Nothing is pulled or tagged on this host. + + +def _unsupported(task, contract, sandbox): + config = task.config + env = config.environment + verifier_env = config.verifier.environment + environments = (env,) if verifier_env is None else (env, verifier_env) + if task.has_steps: + return "multi-step Harbor tasks" + if any(environment.os.value != "linux" for environment in environments): + return "non-Linux Harbor tasks" + if env.docker_image is not None and not _PINNED_IMAGE.fullmatch(env.docker_image): + return "task-declared environment.docker_image without a sha256 digest pin" + separate = verifier_env is not None or ( + config.verifier.environment_mode is not None + and config.verifier.environment_mode.value != "shared" + ) + if separate and sandbox != "hf-sandbox": + return "separate Harbor verifier environments outside hf-sandbox" + if ( + env.docker_image is None + and not (task.task_dir / "environment/Dockerfile").is_file() + ) or any( + path.name.lower() + in {"docker-compose.yaml", "docker-compose.yml", "compose.yaml", "compose.yml"} + for path in (task.task_dir / "environment").rglob("*") + ): + return "tasks without one Dockerfile or pinned image, or with task-authored Compose" + if contract.resources.gpus or any( + environment.gpus or environment.tpu or environment.mcp_servers + for environment in environments + ): + return "GPU/TPU or external MCP requirements" + if contract.requires_credentials: + return "external credential requirements" + if env.network_mode.value != "public" or any( + phase.network_mode is not None and phase.network_mode.value != "public" + for phase in (config.agent, config.verifier, verifier_env) + if phase is not None + ): + return "non-public or differing phase network policies" + if ( + any(environment.env for environment in environments) + or config.verifier.env + or config.solution.env + ): + return "task environment variables (including host credential substitutions)" + if ( + any( + environment.healthcheck or environment.skills_dir + for environment in environments + ) + or config.verifier.collect + ): + return "healthcheck, skills or collect extensions" + if config.artifacts and sandbox != "hf-sandbox": + return "artifact extensions outside hf-sandbox" + if sandbox == "hf-sandbox": + if env.docker_image is None: + return ( + "hf-sandbox tasks without environment.docker_image; build and push " + + "the image, then pin it as name@sha256:" + ) + if config.agent.user is not None or config.verifier.user is not None: + return "agent or verifier users on hf-sandbox, which cannot switch users" + # Harbor runs a separate verifier from verifier.environment.docker_image, + # else a tests/ Dockerfile, else the task image with tests/ uploaded. + if separate and ( + (verifier_env is not None and verifier_env.docker_image is not None) + or any( + (task.task_dir / "tests" / name).is_file() + for name in ("Dockerfile", "docker-compose.yaml") + ) + ): + return ( + "separate verifiers on hf-sandbox that use their own image; " + + "the verifier must reuse the task's pinned image" + ) + return None + + +async def _create_trial(config, register_job=None): + from harbor.environments.hf_sandbox import HFSandboxEnvironment + from harbor.trial.trial import Trial + + trial = await Trial.create(config) + environment = trial.agent_environment + trial._openenv_cancelled_compose = [] + if isinstance(environment, HFSandboxEnvironment): + start = partial( + _start_sandbox, + labels=_job_labels(config.trial_name), + namespace=config.environment.kwargs["namespace"], + ) + environment.start = partial(start, environment) + # Harbor checks a separate verifier's environment just before starting + # it, so its job gets the same labels and is registered for cleanup. + check_verifier = trial._validate_separate_verifier_env_policies + + def label_verifier(verifier, *, plan): + check_verifier(verifier, plan=plan) + + async def start_verifier(*, force_build): + try: + await start(verifier, force_build=force_build) + finally: + if verifier._sandbox is not None: + register_job(verifier._sandbox.id) + + verifier.start = start_verifier + + trial._validate_separate_verifier_env_policies = label_verifier + else: + environment._run_docker_compose_command = partial( + _run_compose, environment, cancelled=trial._openenv_cancelled_compose + ) + return trial + + +async def _start_sandbox(environment, *, force_build, labels, namespace): + # Harbor's hf-sandbox start, plus labels that let cleanup find every run-owned job. + from huggingface_hub import Sandbox + + creating = asyncio.create_task( + asyncio.to_thread( + Sandbox.create, + image=environment.task_env_config.docker_image, + flavor=environment._flavor, + idle_timeout=environment._idle_timeout, + namespace=namespace, + # The default job name is derived from the image, and a digest-pinned + # registry image makes it longer than the 100 characters HF Jobs allows. + labels={**labels, "name": environment.session_id}, + start_timeout=_SANDBOX_START_TIMEOUT_S, + ) + ) + try: + environment._sandbox = await asyncio.shield(creating) + except asyncio.CancelledError: + # A cancelled worker can still allocate a job. Settle it and preserve its + # handle before Harbor teardown and the final ownership/terminal checks. + # Both Harbor and the validator can cancel the same start at its deadline. + while not creating.done(): + try: + await asyncio.shield(creating) + except asyncio.CancelledError: + continue + environment._sandbox = creating.result() + raise + if workdir := environment.task_env_config.workdir: + await asyncio.to_thread(environment._sandbox.files.mkdir, workdir) + await environment.ensure_dirs(environment._mount_targets(writable_only=True)) + await environment._upload_environment_dir_after_start() + + +async def _run_compose( + environment, + command, + check=True, + timeout_sec=None, + stdin_data=None, + on_output=None, + *, + cancelled, +): + # Harbor's Compose collector does not reap the client on outer cancellation. + runtime = type(environment).runtime() + argv = [*runtime.compose, "--project-name", environment.session_id] + if runtime.supports_compose_project_directory: + argv.extend(["--project-directory", str(environment.environment_dir.resolve())]) + for path in environment._docker_compose_paths: + argv.extend(["-f", str(path.resolve())]) + spawn = asyncio.create_task( + asyncio.create_subprocess_exec( + *argv, + *command, + env=environment._compose_env_vars(include_os_env=True), + # A task with a prebuilt image may ship no environment directory. + cwd=str(environment.environment_dir.resolve()) + if environment.environment_dir.is_dir() + else None, + stdin=asyncio.subprocess.PIPE + if stdin_data is not None + else asyncio.subprocess.DEVNULL, + stdout=asyncio.subprocess.PIPE, + stderr=asyncio.subprocess.STDOUT, + start_new_session=True, + ) + ) + try: + process = await asyncio.shield(spawn) + if on_output is not None: + result = await environment._collect_streamed_output( + process, + timeout_sec=timeout_sec, + stdin_data=stdin_data, + on_output=on_output, + ) + else: + result = await environment._collect_buffered_output( + process, timeout_sec=timeout_sec, stdin_data=stdin_data + ) + if check and result.return_code != 0: + raise RuntimeError("Harbor Compose command failed") + return result + except BaseException as exc: + # Finish spawning before cleanup, even if cancellation raced with exec. + process = await spawn + try: + os.killpg(process.pid, signal.SIGKILL) + except ProcessLookupError: + pass + await process.wait() + if isinstance(exc, asyncio.CancelledError) and command[0] in { + "build", + "pull", + "up", + }: + cancelled.append( + { + "command": command[0], + "project": environment.session_id, + "client_group_killed": True, + "client_reaped": True, + "daemon_completion_verified": False, + } + ) + raise + + +def _read_output(path, root): + relative = path.relative_to(root) + current = root + for part in relative.parts: + current = current / part + if current.is_symlink(): + raise NativeEvidenceError("native output may not contain symbolic links") + try: + fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK) + except FileNotFoundError: + return None + with os.fdopen(fd, "rb") as stream: + info = os.fstat(stream.fileno()) + if not stat.S_ISREG(info.st_mode) or info.st_size > _MAX_REWARD_BYTES: + raise NativeEvidenceError( + "native reward output must be a bounded regular file" + ) + raw = stream.read(_MAX_REWARD_BYTES + 1) + if len(raw) > _MAX_REWARD_BYTES: + raise NativeEvidenceError("native reward output exceeded its size bound") + return raw + + +def _reward(raw_files, parsed, contract): + if "reward.json" in raw_files: + raw = json.loads( + raw_files["reward.json"], + object_pairs_hook=_unique_object, + parse_float=Decimal, + ) + elif "reward.txt" in raw_files: + raw = {"reward": Decimal(raw_files["reward.txt"].decode().strip())} + else: + raise NativeEvidenceError("verifier produced no raw reward file") + if not isinstance(raw, dict) or not raw or contract.reward_key not in raw: + raise NativeEvidenceError( + "verifier reward map is empty or lacks the declared key" + ) + low, high = (Decimal(str(value)) for value in contract.reward.range) + for value in raw.values(): + if ( + isinstance(value, bool) + or not isinstance(value, (int, Decimal)) + or not Decimal(value).is_finite() + or not low <= value <= high + ): + raise NativeEvidenceError( + "every reward must be finite, nonboolean and within the declared range" + ) + if ( + not isinstance(parsed, dict) + or any(isinstance(value, bool) for value in parsed.values()) + or raw != {key: Decimal(str(value)) for key, value in parsed.items()} + ): + raise NativeEvidenceError("raw verifier rewards differ from the Harbor result") + return raw + + +async def _trial( + root, + role, + agent, + work, + contract, + inspector, + run_id, + source_binding, + expected=None, + canary=None, +): + from harbor.models.environment_type import EnvironmentType + from harbor.models.trial.config import ( + AgentConfig, + EnvironmentConfig, + TaskConfig, + TrialConfig, + VerifierConfig, + ) + from harbor.trial.hooks import TrialEvent + + from .providers.docker import DockerValidationProvider + from .runner import _DIGEST_EXCLUDED_DIRS, source_digest + + name = f"openenv-validation-{run_id}-{role}" + project = name + "__env" + retained_tag = f"openenv-validation:{run_id}" + record = { + "role": role, + "agent": agent, + "project": project, + "raw_rewards": {}, + "cleanup": {"verified": False}, + } + raw_files = {} + trial = None + phase = "trial creation" + registered = False + hf = isinstance(inspector, HFJobsInspector) + try: + # Verify ownership before Trial.create can allocate anything. + record["pre_allocation_inventory"] = await asyncio.to_thread( + inspector.inventory, project + ) + if any(record["pre_allocation_inventory"].values()): + raise NativeEvidenceError( + "run-owned project was not empty before allocation" + ) + registered = True + task_copy = work / role / "task" + shutil.copytree( + root, + task_copy, + symlinks=True, + ignore=shutil.ignore_patterns(*_DIGEST_EXCLUDED_DIRS), + ) + copied_digest = source_digest(task_copy) + record["unmodified_task_digest"] = copied_digest + if copied_digest != source_binding: + raise NativeEvidenceError( + "private execution task differs from the validated source digest" + ) + overlay = {} + if expected: + task = read_harbor_task(task_copy) + task.config.environment.docker_image = retained_tag + (task_copy / "task.toml").write_text(task.config.model_dump_toml()) + overlay["environment.docker_image"] = retained_tag + if canary is not None: + # The oracle agent runs the canary in place of the reference solution. + script = (task_copy / canary).read_bytes() + (task_copy / "solution/solve.sh").write_bytes(script) + overlay["solution/solve.sh"] = { + "canary": canary, + "sha256": hashlib.sha256(script).hexdigest(), + } + digest_before = source_digest(task_copy) + record["execution_task_digest"] = digest_before + record["task_overlay"] = overlay + budget = contract.resources.episode_timeout_s + build_budget = ( + DockerValidationProvider().build_timeout_s if not expected else budget + ) + config = TrialConfig( + task=TaskConfig(path=task_copy.resolve()), + agent=AgentConfig( + name=agent, + override_timeout_sec=budget, + override_setup_timeout_sec=budget, + ), + environment=EnvironmentConfig( + type=EnvironmentType.HF_SANDBOX, + delete=True, + kwargs={ + "flavor": inspector.flavor, + "namespace": inspector.namespace, + # Idle shutdown must outlast the longest single command. + "job_timeout": math.ceil(budget) + 600, + }, + ) + if hf + else EnvironmentConfig( + type=EnvironmentType.DOCKER, + delete=False, + force_build=False, + override_cpus=contract.resources.cpu, + override_memory_mb=contract.resources.memory_mb, + override_storage_mb=contract.resources.disk_mb, + kwargs={"auto_mounting": False, "keep_containers": True}, + ), + verifier=VerifierConfig(override_timeout_sec=budget), + trial_name=name, + trials_dir=(work / role / "trials").resolve(), + ) + effective_config = config.model_dump(mode="json") + effective_config["task"]["path"] = "" + effective_config["trials_dir"] = "" + effective_config.pop("trial_name") + record["trial_config_digest"] = _digest(effective_config) + record["resources"] = contract.resources.model_dump() + trial = await _create_trial( + config, + register_job=partial(inspector.register_job, project) if hf else None, + ) + record["harbor_build_timeout_s"] = trial._environment_build_timeout_sec + trial._environment_build_timeout_sec = build_budget + if not expected: + record["build_timeout_s"] = build_budget + start_environment = trial.agent_environment.start + + async def build_and_start(*, force_build): + nonlocal phase + try: + async with asyncio.timeout(build_budget): + await start_environment(force_build=force_build) + finally: + if hf: + sandbox = trial.agent_environment._sandbox + record["job_handle_missing_after_start"] = sandbox is None + if sandbox is not None: + inspector.register_job(project, sandbox.id) + phase = "agent setup" + + trial.agent_environment.start = build_and_start + + async def environment_start(_event): + nonlocal phase + phase = "environment build/start" + + async def capture(_event): + nonlocal phase + phase = "agent" + if trial.agent_environment.session_id != project: + raise NativeEvidenceError( + "Harbor sandbox identity differs from the registered project" + ) + identity = await asyncio.to_thread( + inspector.capture, project, retained_tag, retain=not expected + ) + record.update(identity) + if expected and ( + identity["image_ref"] != expected["image_ref"] + or identity["configuration_digest"] != expected["configuration_digest"] + ): + raise NativeEvidenceError( + "fresh native trial image or effective container configuration drifted" + ) + + async def capture_exit(_event): + # Harbor writes the marker only for a nonzero exit. Later sandbox + # log synchronization can overwrite it, so this reading is trusted. + if agent == "oracle": + marker = _read_output( + trial.paths.agent_dir / "exit-code.txt", trial.paths.trial_dir + ) + record["oracle_exit_observed_at_agent_end"] = True + record["oracle_exit_code"] = int(marker) if marker is not None else 0 + if marker is not None: + raw_files["oracle-exit-code.txt"] = marker + + async def verification_start(_event): + nonlocal phase + phase = "verifier" + + trial.add_hook(TrialEvent.ENVIRONMENT_START, environment_start) + trial.add_hook(TrialEvent.AGENT_START, capture) + trial.add_hook(TrialEvent.AGENT_END, capture_exit) + trial.add_hook(TrialEvent.VERIFICATION_START, verification_start) + result = await trial.run() + if source_digest(task_copy) != digest_before: + raise NativeEvidenceError( + "private execution task changed during validation" + ) + if result.exception_info is not None: + failure = result.exception_info.exception_type + if failure in { + "RewardFileNotFoundError", + "RewardFileEmptyError", + "VerifierOutputParseError", + }: + if "container_id" not in record: + raise NativeEvidenceError( + "Harbor reward failure has no container identity" + ) + record["reward_error"] = True + raise NativeEvidenceError(f"Harbor verifier reward failed ({failure})") + if failure == "EnvironmentStartTimeoutError": + raise NativeEvidenceError( + f"validator build/start exceeded its {build_budget:g}-second budget" + ) + subject_phase = { + "SandboxBuildFailedError": "environment build/start", + "AgentSetupTimeoutError": "agent setup", + "AgentTimeoutError": "agent", + "VerifierTimeoutError": "verifier", + }.get(failure) + if failure == "RuntimeError" and phase == "environment build/start": + subject_phase = phase + if subject_phase: + record["subject_error"] = subject_phase + raise NativeEvidenceError( + f"Harbor subject failed during {subject_phase} ({failure})" + ) + raise NativeEvidenceError("Harbor Trial returned exception_info") + if "container_id" not in record: + raise NativeEvidenceError("Harbor Trial has no actual AGENT_START identity") + for filename, path in ( + ("reward.json", trial.paths.reward_json_path), + ("reward.txt", trial.paths.reward_text_path), + ): + raw = _read_output(path, trial.paths.trial_dir) + if raw is not None: + raw_files[filename] = raw + if agent == "oracle": + if not record.get("oracle_exit_observed_at_agent_end"): + raise NativeEvidenceError( + "oracle has no trusted AGENT_END exit observation" + ) + marker = _read_output( + trial.paths.agent_dir / "exit-code.txt", trial.paths.trial_dir + ) + if marker is not None and int(marker) != record["oracle_exit_code"]: + raise NativeEvidenceError("oracle exit marker changed after AGENT_END") + parsed = result.verifier_result.rewards if result.verifier_result else None + record["reward_error"] = True + record["rewards"] = _reward(raw_files, parsed, contract) + record.pop("reward_error") + except (Exception, KeyboardInterrupt) as exc: + record["failure"] = type(exc).__name__ + if isinstance(exc, TimeoutError): + record["reason"] = ( + f"validator build/start exceeded its {build_budget:g}-second budget" + if phase == "environment build/start" + else f"unexpected Harbor timeout during {phase}" + ) + # Error categories are safe; task-authored exception messages/logs are not. + if isinstance(exc, NativeEvidenceError): + record["reason"] = str(exc) + finally: + if trial is not None: + try: + async with asyncio.timeout(30): + await trial.agent_environment.stop(delete=hf) + except (Exception, KeyboardInterrupt): + record["failure"] = "HarborTeardownError" + if registered: + try: + record["cleanup"] = await asyncio.to_thread(inspector.cleanup, project) + if ( + hf + and record.get("job_handle_missing_after_start") + and not record["cleanup"]["jobs"] + ): + # Sandbox.create can fail after allocation and swallow a failed + # cancellation. An empty listing cannot prove no job was created. + record["cleanup"].update( + verified=False, + reason="sandbox creation returned no handle and no labelled job was recovered", + ) + if trial is not None and trial._openenv_cancelled_compose: + record["cleanup"].update( + { + "verified": False, + "pending_operations": trial._openenv_cancelled_compose, + } + ) + record["reason"] = ( + "Docker daemon completion after cancelled Compose allocation is unverified" + ) + if not record["cleanup"]["verified"]: + record["failure"] = "CleanupNotVerified" + except (Exception, KeyboardInterrupt) as exc: + record["cleanup"] = {"verified": False, "failure": type(exc).__name__} + record["failure"] = "CleanupNotVerified" + else: + record["cleanup"] = { + "verified": False, + "reason": "project ownership was not verified before allocation", + } + if trial is not None: + # Preserve raw verifier files even when Harbor rejects their values. + for filename, path in ( + ("reward.json", trial.paths.reward_json_path), + ("reward.txt", trial.paths.reward_text_path), + ("oracle-exit-code.txt", trial.paths.agent_dir / "exit-code.txt"), + ): + try: + raw = _read_output(path, trial.paths.trial_dir) + if raw is not None: + if filename in raw_files and raw_files[filename] != raw: + record["failure"] = "RewardArtifactDrift" + if filename == "oracle-exit-code.txt" and filename in raw_files: + continue + raw_files[filename] = raw + except (ValueError, OSError): + record["failure"] = "UnsafeRewardArtifact" + return record, raw_files + + +async def _collect(root, contract, work, inspector, source_binding, canaries=()): + run_id = uuid.uuid4().hex + # The replay makes episode determinism measurable before any semantic check. + plan = [ + ("nop", "nop", None), + ("oracle", "oracle", None), + ("oracle-replay", "oracle", None), + *( + (f"canary-{index}", "oracle", canary) + for index, canary in enumerate(canaries, start=1) + ), + ] + if isinstance(inspector, HFJobsInspector): + # Each running trial blocks a worker thread for every sandbox command, and + # a trial waiting for a free thread would spend its own phase budget. + asyncio.get_running_loop().set_default_executor( + ThreadPoolExecutor(max_workers=len(plan) + 4) + ) + host = await asyncio.to_thread(inspector.preflight) + run_trial = partial( + _trial, + root, + work=work, + contract=contract, + inspector=inspector, + run_id=run_id, + source_binding=source_binding, + ) + if isinstance(inspector, HFJobsInspector): + # A pinned image needs no build, so every trial starts at once. + outcomes = await asyncio.gather( + *(run_trial(role, agent, canary=canary) for role, agent, canary in plan) + ) + else: + outcomes = [] + for role, agent, canary in plan: + expected = outcomes[0][0] if outcomes else None + outcomes.append( + await run_trial(role, agent, expected=expected, canary=canary) + ) + if "failure" in outcomes[-1][0]: + break + trials, files = [], {} + for trial, raw in outcomes: + trials.append(trial) + for name, value in raw.items(): + relative = f"harbor-trials/{trial['role']}/{name}" + files[relative] = value + trial["raw_rewards"][name] = { + "path": relative, + "sha256": hashlib.sha256(value).hexdigest(), + } + if trials and "image_ref" in trials[0]: + try: + if not inspector.verify_image( + f"openenv-validation:{run_id}", trials[0]["image_ref"] + ): + trials[-1]["failure"] = "RetainedImageDrift" + except Exception: + trials[-1]["failure"] = "RetainedImageUnverified" + return host, trials, files + + +def _result(check_id, status, reason, measured=None): + return CheckResult( + check_id=check_id, + status=status, + evidence=[reason], + measured=measured or {}, + duration_s=0, + ) + + +def _reward_only(trial): + # `reward_error` marks a failure raised while parsing the verifier's reward: + # the package's defect, unless teardown or cleanup later found a host problem. + return trial.get("reward_error") and trial.get("failure") not in _HOST_FAILURES + + +def _skip_reason(entry, contract): + if entry.check_id not in _IMPLEMENTED: + if entry.level is Level.STATIC: + return "grader not implemented in this build" + return f"not implemented for the harbor_task binding ({HARBOR_PROFILE})" + if entry.check_id == "semantic.canary_floor" and contract.canaries is None: + return "no canaries declared in validation/openenv.json" + return "unmet dependency: native Harbor trials" + + +def validate_harbor( + subject, + *, + max_level, + policy, + results, + digest_before, + artifacts_dir, + report_target=None, + skip_build=False, + provider=None, + sandbox="docker", + flavor="cpu-basic", + namespace=None, +): + """Run fresh native Harbor trials and grade them up to the requested level.""" + from .runner import source_digest + + started = time.monotonic() + contract = read_harbor_contract(subject.root) + semantic = max_level >= Level.SEMANTIC + canaries = ( + canary_scripts(subject.root, contract.canaries) + if semantic and contract.canaries is not None + else [] + ) + record = { + "schema_version": "2", + "profile": HARBOR_PROFILE, + "sandbox": sandbox, + "task_effective_digest": digest_before, + "original_source_digest": contract.original_source_digest, + "contract_digest": _digest(contract.model_dump(mode="json")), + "reward_key": contract.reward_key, + "cleanup": {"verified": False}, + "trials": [], + } + harbor_dist = distribution("harbor") + record["harbor"] = {"version": harbor_dist.version} + direct_url = harbor_dist.read_text("direct_url.json") + if direct_url: + installed = json.loads(direct_url) + record["harbor"]["commit_id"] = installed.get("vcs_info", {}).get("commit_id") + files = {} + inspector = DockerInspector() + try: + attempted = False + task = read_harbor_task(subject.root) + problem = _unsupported(task, contract, sandbox) + if sandbox == "hf-sandbox": + inspector = HFJobsInspector( + task.config.environment.docker_image, + flavor, + namespace, + contract.resources, + ) + if skip_build: + problem = "image build skipped by --skip-build" + if provider is not None: + problem = ( + "served-package providers, including --space; " + + "run Harbor trials on HF Jobs with --sandbox hf-sandbox" + ) + if any(result.status is not CheckStatus.PASS for result in results): + problem = "unmet dependency: static.manifest" + startup = _result( + "runtime.startup", + CheckStatus.SKIP, + f"unsupported by {HARBOR_PROFILE}: {problem}", + ) + reward_result = _result( + "runtime.reward_well_formed", + CheckStatus.SKIP, + "unmet dependency: native Harbor trials", + ) + determinism = _result( + "runtime.episode_determinism", + CheckStatus.SKIP, + "unmet dependency: native Harbor trials", + ) + evidence = None + checks = [] + semantic_graded = False + if ( + semantic + and subject.manifest.capabilities.oracle is None + and all(result.status is CheckStatus.PASS for result in results) + ): + # RFC 008: a missing oracle is a graded FAIL, never a SKIP. + semantic_graded = True + checks.append( + CheckResult( + check_id="semantic.oracle_max", + status=CheckStatus.FAIL, + evidence=["the task has no oracle (solution/solve.sh)"], + remediation=( + "Add solution/solve.sh that drives the task to a correct solution." + ), + duration_s=0, + ) + ) + if not problem: + if subject.manifest.capabilities.oracle is None: + startup = _result( + "runtime.startup", + CheckStatus.SKIP, + "native Harbor trials need solution/solve.sh", + ) + else: + attempted = True + try: + with tempfile.TemporaryDirectory( + prefix="openenv-harbor-validation-" + ) as temp: + host, trials, files = asyncio.run( + _collect( + subject.root, + contract, + Path(temp), + inspector, + digest_before, + canaries, + ) + ) + record["trials"] = trials + if sandbox == "hf-sandbox": + record["hf_jobs"] = host + record["limitations"] = [ + "The image is the digest requested from HF Jobs and read " + + "back from each job, not a digest measured at runtime.", + "HF Sandbox cannot turn the network off or switch users, " + + "so every phase runs with public networking as the " + + "image's default user.", + ] + else: + record["daemon"] = host + record["cleanup"] = { + "verified": bool(trials) + and all(trial["cleanup"]["verified"] for trial in trials) + } + broken = [ + trial + for trial in trials + if "failure" in trial and not _reward_only(trial) + ] + malformed = any(_reward_only(trial) for trial in trials) + containers = [trial.get("container_id") for trial in trials] + if ( + broken + or (not malformed and len(trials) != 3 + len(canaries)) + or len(set(containers)) != len(containers) + ): + subject_failures = broken and all( + trial.get("subject_error") + and trial["failure"] not in _HOST_FAILURES + for trial in broken + ) + startup = _result( + "runtime.startup", + CheckStatus.FAIL if subject_failures else CheckStatus.ERROR, + "native Harbor subject failed during " + + ", ".join( + sorted({trial["subject_error"] for trial in broken}) + ) + if subject_failures + else "native Harbor trial, binding or cleanup failed", + { + "failures": [ + trial.get("reason", trial.get("failure")) + for trial in broken + ] + }, + ) + startup.evidence.extend( + trial["reason"] for trial in broken if "reason" in trial + ) + if malformed: + reward_result = _result( + "runtime.reward_well_formed", + CheckStatus.FAIL, + "native verifier reward violates the explicit contract", + ) + else: + record["image_ref"] = trials[0]["image_ref"] + startup = _result( + "runtime.startup", + CheckStatus.PASS, + "fresh native Harbor trials ran from one immutable image " + "with verified cleanup", + { + "profile": HARBOR_PROFILE, + "image_ref": trials[0]["image_ref"], + "roles": [trial["role"] for trial in trials], + "task_effective_digest": digest_before, + }, + ) + source_image = task.config.environment.docker_image + if source_image is not None: + record["source_image"] = source_image + startup.measured["source_image"] = source_image + if sandbox == "hf-sandbox": + startup.measured.update( + sandbox=sandbox, + flavor=host["flavor"], + namespace=host["namespace"], + job_ids=containers, + ) + if malformed: + reward_result = _result( + "runtime.reward_well_formed", + CheckStatus.FAIL, + "native verifier reward violates the explicit contract", + ) + determinism = _result( + "runtime.episode_determinism", + CheckStatus.SKIP, + "unmet dependency: runtime.reward_well_formed", + ) + else: + reward_result = _result( + "runtime.reward_well_formed", + CheckStatus.PASS, + "every raw verifier reward map matches Harbor and " + "satisfies the declared key/range", + { + "profile": HARBOR_PROFILE, + "reward_key": contract.reward_key, + }, + ) + complete_baseline = ( + len(trials) >= 3 + and all( + "failure" not in trial and trial["cleanup"]["verified"] + for trial in trials[:3] + ) + and len(set(containers[:3])) == 3 + ) + if complete_baseline: + nop, oracle, replay, *canary_trials = trials + same = ( + oracle["rewards"] == replay["rewards"] + and oracle["oracle_exit_code"] == replay["oracle_exit_code"] + ) + determinism = _result( + "runtime.episode_determinism", + CheckStatus.PASS if same else CheckStatus.FAIL, + "the oracle replay in a fresh container " + + ( + "reproduced every reward and the exit code" + if same + else "produced different rewards or a different exit code" + ), + { + "rewards": [ + json.loads(dumps(trial["rewards"])) + for trial in (oracle, replay) + ], + "exit_codes": [ + trial["oracle_exit_code"] + for trial in (oracle, replay) + ], + }, + ) + key = contract.reward_key + record.update( + { + "floor_reward": nop["rewards"][key], + "oracle_reward": oracle["rewards"][key], + } + ) + evidence = OracleEvidence( + floor=Fraction(nop["rewards"][key]), + oracle=tuple( + Fraction(trial["rewards"][key]) + for trial in (oracle, replay) + ), + oracle_exit_codes=tuple( + trial["oracle_exit_code"] for trial in (oracle, replay) + ), + canaries=tuple( + ( + trial["task_overlay"]["solution/solve.sh"][ + "canary" + ], + Fraction(trial["rewards"][key]), + ) + for trial in canary_trials + if "failure" not in trial + and trial["cleanup"]["verified"] + ), + ) + except (Exception, KeyboardInterrupt) as exc: + record["failure"] = type(exc).__name__ + reason = f"native Harbor collection failed ({type(exc).__name__})" + if isinstance(exc, NativeEvidenceError): + record["reason"] = str(exc) + reason += ": " + str(exc) + startup = _result( + "runtime.startup", + CheckStatus.ERROR, + reason, + ) + if semantic: + registry = GraderRegistry() + for grader in ( + OracleMaxGrader(), + FloorGapGrader(), + CanaryFloorGrader(), + ): + registry.register(grader) + selected = registry.select(subject.manifest, max_level) + if evidence is not None and len(evidence.canaries) != len(canaries): + selected = [ + grader + for grader in selected + if grader.check_id != "semantic.canary_floor" + ] + checks.append( + _result( + "semantic.canary_floor", + CheckStatus.SKIP, + "unmet dependency: complete canary trials with verified cleanup", + ) + ) + checks.extend( + execute_graders( + selected, + replace(subject, oracle_evidence=evidence), + prior=[startup, reward_result, determinism], + ) + ) + try: + unchanged = source_digest(subject.root) == digest_before + except (ValueError, OSError): + unchanged = False + if not unchanged: + record["failure"] = "SourceDrift" + startup = _result( + "runtime.startup", + CheckStatus.ERROR, + "task source changed during native validation", + ) + reward_result, determinism, *checks = ( + _result( + check.check_id, + CheckStatus.SKIP, + "unmet dependency: unchanged native task source", + ) + for check in (reward_result, determinism, *checks) + ) + startup.duration_s = time.monotonic() - started + record["cleanup"].update( + {"required": attempted, "completed": record["cleanup"]["verified"]} + ) + results = [*results, startup, reward_result, determinism, *checks] + present = {result.check_id for result in results} + for entry in policy.entries_for_lane(Lane.LOCAL).values(): + if entry.level <= max_level and entry.check_id not in present: + results.append( + _result( + entry.check_id, + CheckStatus.SKIP, + _skip_reason(entry, contract), + ) + ) + if any( + check.status in {CheckStatus.FAIL, CheckStatus.ERROR} for check in results + ): + try: + inspector.remove_image() + except (Exception, KeyboardInterrupt) as exc: + startup.status = CheckStatus.ERROR + startup.evidence.append( + f"retained image removal failed ({type(exc).__name__})" + ) + record["cleanup"].update(verified=False, completed=False) + elif "image_ref" in record and sandbox == "docker": + tag = trials[0]["retained_image_tag"] + startup.measured["retained_image_tag"] = tag + record["retained_image_tag"] = tag + levels = [Level.STATIC] + if attempted: + levels.append(Level.RUNTIME) + if semantic and (attempted or semantic_graded): + levels.append(Level.SEMANTIC) + report = ValidationReportV2( + report_schema_version="2", + target=str(subject.root) if report_target is None else report_target, + source_digest=digest_before, + signature=subject.manifest.signature, + manifest=subject.manifest, + policy_version=policy.policy_version, + lane=Lane.LOCAL, + levels_run=levels, + results=results, + verdict=apply_policy(results, policy, Lane.LOCAL), + ) + if artifacts_dir is not None: + write_runtime_bundle( + artifacts_dir, + report, + cleanup=record["cleanup"], + provider={ + "binding": "harbor_task", + "profile": HARBOR_PROFILE, + "sandbox": sandbox, + }, + ) + files["harbor-evidence.json"] = (dumps(record) + "\n").encode() + checksums = (artifacts_dir / "SHA256SUMS").read_text() + for name, raw in sorted(files.items()): + path = artifacts_dir / name + path.parent.mkdir(parents=True, exist_ok=True) + path.write_bytes(raw) + path.chmod(0o600) + checksums += f"{hashlib.sha256(raw).hexdigest()} {name}\n" + (artifacts_dir / "SHA256SUMS").write_text(checksums) + return report + except BaseException as original: + try: + inspector.remove_image() + except (Exception, KeyboardInterrupt) as exc: + record["cleanup"].update( + verified=False, completed=False, failure=type(exc).__name__ + ) + original.add_note( + f"retained image removal failed ({type(exc).__name__}); cleanup incomplete" + ) + raise diff --git a/src/openenv/validation/manifest.py b/src/openenv/validation/manifest.py index a4623da3b65c840540053d46ba6635c8abd0c1bb..f54c7546240ca47c24057a291340936499b7aaf8 100644 --- a/src/openenv/validation/manifest.py +++ b/src/openenv/validation/manifest.py @@ -9,7 +9,14 @@ import math from pathlib import PurePosixPath from typing import Annotated, Any, Literal -from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator +from pydantic import ( + BaseModel, + ConfigDict, + Field, + field_validator, + model_serializer, + model_validator, +) from .types import SignatureKind @@ -47,9 +54,13 @@ class RewardDeclaration(BaseModel): range (`tuple[float, float]`): Declared reward range, defaults to `(0.0, 1.0)`. Must be strictly increasing. oracle_tolerance (`float`): - The oracle check passes when `reward(oracle) >= max - oracle_tolerance`. + Fraction of the declared range allowed below the maximum. + The oracle check requires `reward(oracle) >= max - oracle_tolerance * width`, + where `width = max - min`. floor_margin (`float`): - The gap check requires `max - measured_floor >= floor_margin`. + Fraction of the declared range required below the maximum and every oracle. + Both `max - measured_floor` and `reward(oracle) - measured_floor` must be + at least `floor_margin * width`. variance_tolerance (`float`, *optional*): Required iff the environment declares `llm_judged`; bounds reward variance for variance-mode determinism checks. @@ -241,6 +252,14 @@ class CapabilitiesSpec(BaseModel): declared_tools: list[str] = Field(default_factory=list) declared_task_count: dict[str, int] = Field(default_factory=dict) + @model_serializer(mode="wrap") + def _preserve_declaration_presence(self, serialize): + data = serialize(self) + for field in ("declared_tools", "declared_task_count"): + if field not in self.model_fields_set: + data.pop(field, None) + return data + @model_validator(mode="after") def _injected_state_requires_set_state(self) -> "CapabilitiesSpec": if ( @@ -365,6 +384,18 @@ class ExecutionDeclaration(BaseModel): return value +class HarborExecutionDeclaration(BaseModel): + """Native process execution of a Harbor task through fresh Docker trials.""" + + model_config = ConfigDict(extra="forbid", frozen=True) + + kind: Literal["harbor_task"] + agent_boundary: Literal["process"] = "process" + profile: Literal["harbor-semantic-v1"] = "harbor-semantic-v1" + contract_path: Literal["validation/openenv.json"] = "validation/openenv.json" + requires_credentials: bool = Field(default=False, strict=True) + + class NormalizedManifestV2(NormalizedManifest): """ Version 2 adds the runtime execution declaration without changing schema 1. @@ -375,7 +406,7 @@ class NormalizedManifestV2(NormalizedManifest): """ manifest_schema_version: Literal["2"] - execution: ExecutionDeclaration + execution: ExecutionDeclaration | HarborExecutionDeclaration @model_validator(mode="after") def _finite_declarations(self) -> "NormalizedManifestV2": diff --git a/src/openenv/validation/parsers/harbor_toml.py b/src/openenv/validation/parsers/harbor_toml.py new file mode 100644 index 0000000000000000000000000000000000000000..39bce5d73f3c5570b20af50caecf65ea54819b36 --- /dev/null +++ b/src/openenv/validation/parsers/harbor_toml.py @@ -0,0 +1,226 @@ +"""Pure Harbor task parsing and the explicit, operator-supplied semantic contract.""" + +import json +import math +import stat +from decimal import Decimal +from importlib.metadata import PackageNotFoundError, version +from pathlib import Path, PurePosixPath +from typing import Literal + +from pydantic import BaseModel, ConfigDict, Field, field_validator, ValidationError + +from ..manifest import ( + ManifestError, + NormalizedManifestV2, + ResourceDeclaration, + RewardDeclaration, + TypeSpec, +) +from ..types import SignatureKind + +HARBOR_PROFILE = "harbor-semantic-v1" +MAX_CANARIES = 8 + + +class HarborContract(BaseModel): + """Trusted declarations absent from Harbor's task format; never inferred.""" + + model_config = ConfigDict(extra="forbid") + + profile: Literal["harbor-semantic-v1"] + reward_key: str = Field(min_length=1) + reward: RewardDeclaration + resources: ResourceDeclaration + types: TypeSpec + original_source_digest: str | None = Field(default=None, pattern="^[0-9a-f]{64}$") + requires_credentials: bool = Field(default=False, strict=True) + # Directory of known-wrong `solve.sh` replacements for `semantic.canary_floor`. + canaries: str | None = None + + @field_validator("canaries") + @classmethod + def _package_relative(cls, value): + path = PurePosixPath(value) + if ( + "\\" in value + or ":" in value + or "\x00" in value + or path.is_absolute() + or ".." in path.parts + or path == PurePosixPath(".") + ): + raise ValueError("canaries must be a portable package-relative directory") + return value + + +def _unique_object(pairs): + result = {} + for key, value in pairs: + if key in result: + raise ValueError("duplicate JSON object key") + result[key] = value + return result + + +def read_harbor_contract(package_root: Path) -> HarborContract: + """Read `validation/openenv.json` without importing or executing task code.""" + try: + raw = json.loads( + (package_root / "validation/openenv.json").read_text(), + object_pairs_hook=_unique_object, + parse_float=Decimal, + ) + if not isinstance(raw, dict): + raise ValueError("contract must be an object") + if ( + not {"range", "oracle_tolerance", "floor_margin"} + <= raw.get("reward", {}).keys() + ): + raise ValueError( + "reward range, oracle_tolerance and floor_margin must be explicit" + ) + for section, fields in ( + ("reward", RewardDeclaration.model_fields), + ("resources", ("cpu", "memory_mb", "disk_mb", "episode_timeout_s", "gpus")), + ): + pending = [raw.get(section, {}).get(field) for field in fields] + while pending: + item = pending.pop() + if isinstance(item, dict): + pending.extend(item.values()) + elif isinstance(item, list): + pending.extend(item) + elif isinstance(item, (bool, str)) or ( + isinstance(item, float) and not math.isfinite(item) + ): + raise ValueError( + "numeric declarations must be finite, nonboolean JSON numbers" + ) + # Graders compare against the stored float, so it must keep the + # declared value exactly: 0.100000000000000001 would become 0.1. + elif isinstance(item, (int, Decimal)) and Decimal( + repr(float(item)) + ) != Decimal(item): + raise ValueError( + "numeric declarations must keep their exact value as floats" + ) + return HarborContract.model_validate(raw) + except ( + OSError, + ValueError, + TypeError, + AttributeError, + OverflowError, + RecursionError, + ) as exc: + raise ManifestError( + [f"invalid trusted Harbor contract ({type(exc).__name__})"], + remediation="supply explicit reward/resources in validation/openenv.json", + ) from exc + + +def canary_scripts(package_root: Path, directory: str) -> list[str]: + """ + List the declared canary scripts without reading or running them. + + Args: + package_root (`Path`): + The task directory. + directory (`str`): + Package-relative directory holding one `*.sh` file per canary. + + Returns: + `list[str]`: package-relative script paths, sorted by name. + """ + root = package_root / directory + if root.is_symlink() or not root.is_dir(): + raise ValueError("the canaries directory does not exist") + scripts = [] + for path in sorted(root.iterdir()): + info = path.lstat() + if path.suffix != ".sh" or not stat.S_ISREG(info.st_mode): + raise ValueError("the canaries directory may hold only regular *.sh files") + scripts.append((PurePosixPath(directory) / path.name).as_posix()) + if not 1 <= len(scripts) <= MAX_CANARIES: + raise ValueError(f"declare between 1 and {MAX_CANARIES} canaries") + return scripts + + +def read_harbor_task(package_root: Path): + """Use the pinned Harbor data loader; constructing a Trial is runtime-only.""" + try: + installed = version("harbor") + except PackageNotFoundError as exc: + raise RuntimeError( + "Harbor task validation requires harbor==0.25.0; Harbor is not installed" + ) from exc + if installed != "0.25.0": + raise RuntimeError( + f"Harbor task validation requires harbor==0.25.0; installed {installed}" + ) + try: + from harbor.models.task.task import Task + + return Task(package_root) + except ( + ImportError, + OSError, + ValueError, + RuntimeError, + ) as exc: + raise ManifestError( + [f"invalid Harbor 0.25.0 task ({type(exc).__name__})"], + remediation="install Harbor 0.25.0 and supply a valid task.toml/task layout", + ) from exc + + +class HarborTaskParser: + """Normalize declarations only; no environment, Trial, build or subprocess.""" + + signature = SignatureKind.HARBOR_TASK + + def parse(self, package_root: Path) -> NormalizedManifestV2: + contract = read_harbor_contract(package_root) + task = read_harbor_task(package_root) + if contract.canaries is not None: + try: + canary_scripts(package_root, contract.canaries) + except (OSError, ValueError) as exc: + raise ManifestError( + [f"invalid canaries declaration ({exc})"], + remediation="declare a directory of 1 to 8 *.sh canary scripts", + ) from exc + oracle = ( + {"form": "script", "location": "solution/solve.sh"} + if (package_root / "solution/solve.sh").is_file() + else None + ) + try: + return NormalizedManifestV2.model_validate( + { + "manifest_schema_version": "2", + "signature": self.signature, + "name": task.name, + "version": task.config.task.version if task.config.task else None, + "reward": contract.reward.model_dump(), + "resources": contract.resources.model_dump(), + "types": contract.types.model_dump(), + "network": {"mode": task.config.environment.network_mode.value}, + "capabilities": { + "verifier": {"kind": "script", "entry": "tests/test.sh"}, + "oracle": oracle, + "canaries": contract.canaries, + }, + "execution": { + "kind": "harbor_task", + "agent_boundary": "process", + "profile": contract.profile, + "requires_credentials": contract.requires_credentials, + }, + } + ) + except ValidationError as exc: + raise ManifestError( + ["Harbor declarations do not match the manifest schema"] + ) from exc diff --git a/src/openenv/validation/parsers/openenv_yaml.py b/src/openenv/validation/parsers/openenv_yaml.py index 6d82d3cacc9287a94966c1e7e1409cc34f56b7e1..90722125c18552437e006a1033af6698e7081321 100644 --- a/src/openenv/validation/parsers/openenv_yaml.py +++ b/src/openenv/validation/parsers/openenv_yaml.py @@ -5,7 +5,12 @@ from pathlib import Path import yaml from pydantic import ValidationError -from ..manifest import ManifestError, NormalizedManifest, NormalizedManifestV2 +from ..manifest import ( + ExecutionDeclaration, + ManifestError, + NormalizedManifest, + NormalizedManifestV2, +) from ..types import SignatureKind VALIDATION_BLOCK_REMEDIATION = ( @@ -89,7 +94,15 @@ class OpenEnvYamlParser: data[key] = value if has_execution: - data["execution"] = validation["execution"] + try: + data["execution"] = ExecutionDeclaration.model_validate( + validation["execution"] + ) + except ValidationError as exc: + raise ManifestError( + [f"execution: {error}" for error in _format_validation_error(exc)], + remediation=SCHEMA_REMEDIATION, + ) from exc try: model = NormalizedManifestV2 if has_execution else NormalizedManifest diff --git a/src/openenv/validation/providers/__init__.py b/src/openenv/validation/providers/__init__.py index b81f382e76fb58e73d3978fee5aed1d6778cc739..66fccb5e57b116c9b96ef890c174b66e61c7e55a 100644 --- a/src/openenv/validation/providers/__init__.py +++ b/src/openenv/validation/providers/__init__.py @@ -25,6 +25,10 @@ class ProviderError(RuntimeError): """A bounded, sanitized provider operation failed.""" +class CleanupError(ProviderError): + """Run-owned resources remain or their removal could not be verified.""" + + class StartupError(ProviderError): """A subject did not become healthy within its startup deadline.""" diff --git a/src/openenv/validation/providers/_netns.py b/src/openenv/validation/providers/_netns.py index dc5e0312d8ab50abec6837e1cb160b7a85de1526..6bcde3e8695ca182e4533ec5a07ce25125248e0d 100644 --- a/src/openenv/validation/providers/_netns.py +++ b/src/openenv/validation/providers/_netns.py @@ -83,6 +83,13 @@ def icmp(): deadline = time.monotonic() + wait while time.monotonic() < deadline and outcome(tcp)["result"] != "reachable": time.sleep(0.2) +def up(name): + # Kernels add down fallback tunnels (gre0, sit0, ...) to every namespace, and + # /sys/class/net can hold regular files such as bonding_masters. Only up links + # carry traffic. Any other read error leaves link state unknown and fails the probe. + try: + with open(f"/sys/class/net/{{name}}/flags") as f: return int(f.read(), 16) & 1 + except NotADirectoryError: return False def lines(path): try: with open(path) as f: return f.read().splitlines() @@ -94,7 +101,7 @@ listening = sorted({{int(f[1].split(":")[1], 16) if len(f) > 3 and f[3] == "0A"}}) print(json.dumps({{ "namespace": {{ - "interfaces": sorted(os.listdir("/sys/class/net")), + "interfaces": sorted(n for n in os.listdir("/sys/class/net") if up(n)), "default_route": any(len(r) > 1 and r[1] == "00000000" for r in routes), "ipv6_non_loopback": sum(1 for f in v6 if f and f[-1] != "lo"), "listening_ports": listening, diff --git a/src/openenv/validation/providers/_pidns.py b/src/openenv/validation/providers/_pidns.py new file mode 100644 index 0000000000000000000000000000000000000000..a8a4a753efc029b9af73ed9fb3af830cd90ff6f4 --- /dev/null +++ b/src/openenv/validation/providers/_pidns.py @@ -0,0 +1,320 @@ +"""Trusted PID-namespace probe for the Docker-local provider. + +The probe runs from the validator's own digest-pinned image and joins only the +subject's PID namespace, so it never executes code from the subject's image. It reads +each subject process from `/proc` and reaches the subject's mount namespace through +`/proc/1/root`, as the subject's own user. +""" + +# Measures process identity, the mount table and writable mounts. argv: allotted roots. +PROBE_SCRIPT = """ +import errno, json, os, re, stat, sys, uuid +me = os.getpid() +allotted = sys.argv[1:] +processes = [] +for entry in sorted(os.listdir("/proc"), key=lambda e: (len(e), e)): + if not entry.isdigit() or int(entry) == me: + continue + try: + with open(f"/proc/{entry}/status") as f: + status = dict(l.rstrip("\\n").split(":", 1) for l in f if ":" in l) + except OSError: + continue + processes.append({ + "pid": int(entry), + "name": status["Name"].strip()[:64], + "uids": [int(u) for u in status["Uid"].split()], + "cap_eff": int(status["CapEff"], 16), + "no_new_privs": status.get("NoNewPrivs", "0").strip() == "1", + "seccomp": int(status.get("Seccomp", "0")), + }) +root = "/proc/1/root" +def size(path): + try: + info = os.statvfs(root + path) + except OSError: + return None + return info.f_blocks * info.f_frsize or None +try: + mounts = [] + with open("/proc/1/mountinfo") as f: + for line in f: + fields = line.split() + separator = fields.index("-") + mount_point = re.sub(r"\\\\([0-7]{3})", lambda m: chr(int(m[1], 8)), fields[4]) + mounts.append({ + "mount_point": mount_point, + "fstype": fields[separator + 1], + "device": fields[2], + # Writes need both the mount and its filesystem to be read-write. + "read_only": "ro" in fields[5].split(",") + fields[separator + 3].split(","), + "size_bytes": size(mount_point), + }) +except (OSError, ValueError, IndexError): + # A partial table could omit a writable filesystem. + mounts = [] +def writable(path): + target = os.path.join(root + path, ".openenv-containment-" + uuid.uuid4().hex) + try: + fd = os.open(target, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o600) + except OSError: + return False + os.close(fd) + os.unlink(target) + return True +# Every writable filesystem is a mount, so try each one outside the allotted roots. +candidates = { + m["mount_point"] for m in mounts if not m["read_only"] and m["mount_point"] not in allotted +} +writable_paths = {p for p in candidates if writable(p)} +# Only /dev's otherwise exempt tmpfs needs a subtree inventory. Separate mounts +# (including allotted /dev/shm), symlinks and device nodes are never traversed. +devices = {m["device"] for m in mounts if (m["mount_point"], m["fstype"]) == ("/dev", "tmpfs")} +device_storage = {d: {"complete": True, "writable": False} for d in devices} +boundaries = {m["mount_point"] for m in mounts} +remaining = 1024 +def scan(path, device, parent_fd, depth=0): + global remaining + reading = device_storage[device] + if depth and path in boundaries: + return + remaining -= 1 + if remaining < 0 or depth > 32: + reading["complete"] = False + return + target = path.rsplit("/", 1)[-1] + try: + info = os.stat(target, dir_fd=parent_fd, follow_symlinks=False) + directory = stat.S_ISDIR(info.st_mode) + if depth == 0 and stat.S_ISLNK(info.st_mode): + reading["complete"] = False + return + if not directory and not stat.S_ISREG(info.st_mode): + return + if directory and any(path == p or path.startswith(p + "/") for p in ("/proc", "/sys")): + reading["complete"] = False + return + if f"{os.major(info.st_dev)}:{os.minor(info.st_dev)}" != device: + reading["complete"] = False + return + # An owner can restore write permission without changing the launch. + flags = os.O_RDONLY | os.O_DIRECTORY if directory else os.O_WRONLY | os.O_APPEND | os.O_NONBLOCK + try: + fd = os.open(target, flags | os.O_NOFOLLOW, dir_fd=parent_fd) + except OSError as error: + if (directory or error.errno not in (errno.EACCES, errno.EPERM, errno.EROFS) + or (info.st_uid == os.geteuid() and error.errno in (errno.EACCES, errno.EPERM))): + reading["complete"] = False + return + try: + opened = os.fstat(fd) + if (opened.st_dev, opened.st_ino) != (info.st_dev, info.st_ino): + reading["complete"] = False + return + if directory: + name = ".openenv-containment-" + uuid.uuid4().hex + try: + probe = os.open(name, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o600, dir_fd=fd) + except OSError as error: + if (error.errno not in (errno.EACCES, errno.EPERM, errno.EROFS) + or (opened.st_uid == os.geteuid() and error.errno in (errno.EACCES, errno.EPERM))): + reading["complete"] = False + else: + reading["writable"] = True + writable_paths.add(path) + os.close(probe) + os.unlink(name, dir_fd=fd) + with os.scandir(fd) as entries: + for entry in entries: + if remaining <= 0: + reading["complete"] = False + break + scan(path + "/" + entry.name, device, fd, depth + 1) + else: + # Opening without truncation proves access without changing data. + reading["writable"] = True + writable_paths.add(path) + finally: + os.close(fd) + except OSError: + reading["complete"] = False +for mount in mounts: + if mount["device"] in devices and not mount["read_only"] and mount["mount_point"] not in allotted: + parent_fd = None + try: + parent_fd = os.open(root, os.O_RDONLY | os.O_DIRECTORY) + for part in mount["mount_point"].strip("/").split("/")[:-1]: + child_fd = os.open(part, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW, dir_fd=parent_fd) + os.close(parent_fd) + parent_fd = child_fd + scan(mount["mount_point"], mount["device"], parent_fd) + except OSError: + device_storage[mount["device"]]["complete"] = False + finally: + if parent_fd is not None: + os.close(parent_fd) +print(json.dumps({ + "processes": processes, + "mounts": mounts, + "allotted_writable": [a for a in allotted if writable(a)], + "writable": sorted(p for p in writable_paths if len(p) <= 1024)[:8], + "device_storage": device_storage, +})) +""" + +# Read limits independently: an unavailable file must not erase known violations. +LIMITS_SCRIPT = """ +import json +root = "/proc/1/root/sys/fs/cgroup/" +cgroup = {} +unavailable = [] +for filename, keys in [ + ("memory.max", ["memory_max"]), + ("memory.swap.max", ["swap_max"]), + ("cpu.max", ["cpu_quota", "cpu_period"]), + ("pids.max", ["pids_max"]), +]: + try: + with open(root + filename) as f: + values = f.read().split() + if len(values) != len(keys): + raise ValueError() + parsed = [None if value == "max" else int(value) for value in values] + if any(value is not None and value < 0 for value in parsed): + raise ValueError() + if "cpu_period" in keys and (parsed[1] is None or parsed[1] == 0): + raise ValueError() + except (OSError, ValueError): + parsed = [None] * len(keys) + unavailable.extend(keys) + cgroup.update(zip(keys, parsed)) +cgroup["unavailable"] = unavailable +print(json.dumps({"cgroup": cgroup})) +""" + +# Trusted pre/post stress evidence from the subject's cgroup and filesystem. +COUNTERS_SCRIPT = """ +import json, os, sys +root = "/proc/1/root" +result = {} +for filename, key, counter in [ + ("memory.events", "oom_kill", "oom_kill"), + ("pids.events", "pids_max", "max"), +]: + try: + with open(root + "/sys/fs/cgroup/" + filename) as f: + result[key] = int(dict(line.split() for line in f)[counter]) + except (OSError, ValueError, KeyError): + result[key] = None +result["free_bytes"] = {} +for path in sys.argv[1:]: + try: + info = os.statvfs(root + path) + result["free_bytes"][path] = info.f_bavail * info.f_frsize + except OSError: + result["free_bytes"][path] = None +print(json.dumps(result)) +""" + +# Observe a live fork from the nonce-correlated stimulus using the trusted image. +DESCENDANTS_SCRIPT = """ +import json, os, sys, time +proc = "/proc" +nonce, duration = sys.argv[1], float(sys.argv[2]) +expected = [b"exec_timeout", b"1", nonce.encode(), b"/tmp", b"/dev/shm"] +me = os.getpid() +def process(pid): + if pid == me: + return None + try: + with open(f"{proc}/{pid}/stat") as f: + before = f.read().rsplit(") ", 1)[1].split() + with open(f"{proc}/{pid}/cmdline", "rb") as f: + argv = f.read().rstrip(b"\\0").split(b"\\0") + with open(f"{proc}/{pid}/stat") as f: + after = f.read().rsplit(") ", 1)[1].split() + if (argv[-5:] != expected or before[0] in ("Z", "X") + or after[0] in ("Z", "X") or before[1] != after[1] + or before[19] != after[19]): + return None + return (pid, int(after[1]), int(after[19])) + except (OSError, ValueError, IndexError): + return None +witness = {} +deadline = time.monotonic() + duration +while time.monotonic() < deadline: + try: + entries = os.listdir(proc) + except OSError: + break + if len(entries) > 4096: + break + processes = {} + for entry in entries: + if entry.isdigit(): + reading = process(int(entry)) + if reading is not None: + processes[reading[0]] = reading + for child in processes.values(): + parent = processes.get(child[1]) + if (parent is not None and child[0] != parent[0] + and process(parent[0]) == parent and process(child[0]) == child): + witness = {"parent_pid": parent[0], "descendant_pid": child[0]} + break + if witness: + break + time.sleep(0.02) +print(json.dumps(witness), flush=True) +""" + +# Subject-image code is only a stimulus. Trusted counters corroborate its result. +QUALIFY_SCRIPT = """ +import errno, os, sys, time +kind, budget, nonce = sys.argv[1], int(sys.argv[2]), sys.argv[3] +print("openenv-probe-start:" + nonce, flush=True) +mib = 1 << 20 +if kind == "memory": + with open("/proc/self/oom_score_adj", "w") as f: + f.write("1000") + held = [] + while len(held) * 16 * mib < budget + 64 * mib: + held.append(b"\\x01" * (16 * mib)) + print("escaped", flush=True) +elif kind == "pids": + children = [] + try: + for _ in range(budget + 16): + pid = os.fork() + if pid == 0: + time.sleep(30) + os._exit(0) + children.append(pid) + print("escaped", flush=True) + except BlockingIOError: + print("contained", flush=True) + finally: + for pid in children: + os.kill(pid, 9) + os.waitpid(pid, 0) +elif kind == "disk": + written = 0 + for index, path in enumerate(sys.argv[4:]): + try: + with open(os.path.join(path, f"openenv-fill-{index}"), "wb") as f: + while written <= budget + 16 * mib: + f.write(b"\\x01" * mib) + f.flush() + written += mib + except OSError as exc: + if exc.errno not in (errno.ENOSPC, errno.EDQUOT): + print("inconclusive", flush=True) + sys.exit() + # Leave the files for trusted statvfs verification; this subject is disposable. + print("escaped" if written > budget else "contained", flush=True) +elif kind == "exec_timeout": + if os.fork() == 0: + time.sleep(300) + os._exit(0) + print("openenv-probe-descendant:" + nonce, flush=True) + time.sleep(300) +""" diff --git a/src/openenv/validation/providers/docker.py b/src/openenv/validation/providers/docker.py index e9fd81b8d1602b274a27ccd9979007e8dab7cfdb..2c51b587be12eaa0619318ffb3cc835e244f4e24 100644 --- a/src/openenv/validation/providers/docker.py +++ b/src/openenv/validation/providers/docker.py @@ -2,7 +2,8 @@ Public and no-network modes are enforced; allowlists are refused. No-network subjects are reached through a trusted helper sharing only their network namespace. Runtime -hardening is an execution baseline; it does not certify containment. +hardening is an execution baseline; `runtime.host_containment` judges its measured +effect. """ import json @@ -18,12 +19,24 @@ import time import urllib.error import urllib.request import uuid +from concurrent.futures import ThreadPoolExecutor from pathlib import Path from ..manifest import ExecutionDeclaration -from ..runtime.contracts import LaunchSpec, NetworkEvidence +from ..runtime.contracts import ( + ContainmentEvidence, + LaunchSpec, + NetworkEvidence, + ResourceEvidence, +) from ..types import ProviderCapability -from . import ExecResult, ProviderError, StartupError, UnsupportedCapability +from . import ( + CleanupError, + ExecResult, + ProviderError, + StartupError, + UnsupportedCapability, +) from ._netns import ( ExecRelayBridge, HARDENING, @@ -32,9 +45,18 @@ from ._netns import ( SINK_SCRIPT, WAIT_READY_SCRIPT, ) +from ._pidns import ( + COUNTERS_SCRIPT, + DESCENDANTS_SCRIPT, + LIMITS_SCRIPT, + PROBE_SCRIPT as PIDNS_PROBE_SCRIPT, + QUALIFY_SCRIPT, +) _LABEL = "org.openenv.validation.run" +# Writable roots granted to every subject; everything else is read-only. +_ALLOTTED = ("/tmp", "/dev/shm") _MAX_OUTPUT = 65536 _EXCLUDED = { ".git", @@ -76,6 +98,12 @@ def _safe_text(value: str, secrets: tuple[str, ...] = ()) -> str: ) +class _OperationTimeout(ProviderError): + def __init__(self, stdout: str): + super().__init__("Docker operation exceeded its deadline") + self.stdout = stdout + + def _command( argv: list[str], timeout_s: float, max_bytes: int = _MAX_OUTPUT ) -> tuple[int, str, str]: @@ -118,7 +146,9 @@ def _command( # The process group can exit between wait() and killpg(). pass process.wait() - raise ProviderError("Docker operation exceeded its deadline") from None + for thread in threads: + thread.join(timeout=1) + raise _OperationTimeout(buffers[0].decode("utf-8", "replace")) from None except BaseException: try: os.killpg(process.pid, signal.SIGKILL) @@ -250,7 +280,10 @@ class DockerValidationProvider: { ProviderCapability.IMAGE_BUILD, ProviderCapability.EXEC, + ProviderCapability.FRESH_CONTAINER, ProviderCapability.NETWORK_POLICY, + ProviderCapability.INSPECTED_ISOLATION, + ProviderCapability.RESOURCE_ENFORCEMENT, } ) supported_network_modes = frozenset({"public", "no-network"}) @@ -261,6 +294,7 @@ class DockerValidationProvider: build_timeout_s: float = 600, max_context_bytes: int = 2**30, helper_image: str = HELPER_IMAGE, + cleanup_subjects: list["DockerRunningSubject"] | None = None, ): if not math.isfinite(build_timeout_s) or build_timeout_s <= 0: raise ValueError("build_timeout_s must be positive and finite") @@ -271,6 +305,7 @@ class DockerValidationProvider: self.build_timeout_s = build_timeout_s self.max_context_bytes = max_context_bytes self.helper_image = helper_image + self._cleanup_subjects = cleanup_subjects def build(self, root: Path, execution: ExecutionDeclaration) -> str: deadline = time.monotonic() + self.build_timeout_s @@ -327,6 +362,8 @@ class DockerValidationProvider: _ensure_image(self.helper_image) name = f"openenv-validation-{spec.run_id}-{uuid.uuid4().hex[:12]}" subject = DockerRunningSubject(name, spec, helper_image=self.helper_image) + if self._cleanup_subjects is not None: + self._cleanup_subjects.append(subject) # tmpfs and /dev/shm share the declared aggregate writable-byte allowance. budget = spec.resources.disk_mb * 1024 * 1024 shm_bytes = min(64 * 1024 * 1024, budget // 2) @@ -342,6 +379,9 @@ class DockerValidationProvider: "--stop-timeout", "0", "--init", + # cgroup v1 daemons default to the host cgroup namespace. + "--cgroupns", + "private", "--user", "65532:65532", "--read-only", @@ -433,6 +473,10 @@ class DockerValidationProvider: try: subject.stop() except ProviderError as cleanup: + if self._cleanup_subjects is not None: + raise CleanupError( + "Disposable startup and teardown failed" + ) from cleanup raise StartupError( f"Startup failed; cleanup also failed: {cleanup}" ) from None @@ -450,12 +494,14 @@ class DockerRunningSubject: self.base_url = "" self._stopped = False self._secrets = tuple(spec.env_vars.values()) + self._spec = spec self._mode = spec.network.mode self._helper_image = helper_image self._helper: str | None = None self._bridge: ExecRelayBridge | None = None # Run-owned helper, sink and control containers, removed before the subject. self._auxiliary: list[str] = [] + self._disposables: list[DockerRunningSubject] = [] def _owned_create(self, name: str, argv: list[str], timeout_s: float) -> None: self._auxiliary.append(name) @@ -581,6 +627,338 @@ class DockerRunningSubject: self._remove_owned(sink) return evidence.model_dump(mode="json") + def _pidns_probe( + self, suffix: str, script: str, args: list[str], user: str, timeout_s: float + ) -> str: + """Run a validator-image probe joined only to the subject's PID namespace.""" + probe = f"{self.name}-{suffix}" + self._auxiliary.append(probe) + code, out, _ = _command( + [ + "docker", + "run", + "--rm", + "--name", + probe, + "--label", + f"{_LABEL}={self.run_id}", + "--pid", + f"container:{self.name}", + "--network", + "none", + *HARDENING, + # The last --user wins: probes act as the subject's own user. + "--user", + user, + self._helper_image, + "python3", + "-c", + script, + *args, + ], + timeout_s, + ) + if code: + raise ProviderError(f"The {suffix} probe failed") + return out + + def _measure_exec_timeout( + self, argv: list[str], nonce: str, user: str, timeout_s: float + ) -> dict: + """Witness the stimulus's fork before timing out and removing its container.""" + deadline = time.monotonic() + min(2.0, timeout_s) + witness = {} + with ThreadPoolExecutor(max_workers=1) as executor: + # The caller must latch the witness before removal can destroy /proc. + stimulus = executor.submit( + _command, + ["docker", "exec", "--", self.name, *argv], + deadline - time.monotonic(), + ) + try: + reading = json.loads( + self._pidns_probe( + "descendants", + DESCENDANTS_SCRIPT, + [nonce, "1"], + user, + deadline - time.monotonic(), + ) + ) + if not stimulus.done() and isinstance(reading, dict): + witness = reading + except CleanupError: + raise + except (ProviderError, ValueError): + # Witness collection is best effort; preserve timeout and cleanup. + pass + try: + stimulus.result() + except _OperationTimeout as exc: + try: + self.stop() + except ProviderError as cleanup: + raise CleanupError( + "Subject exec teardown failed: " + str(cleanup) + ) from exc + parent, child = witness.get("parent_pid"), witness.get("descendant_pid") + if ( + isinstance(parent, int) + and isinstance(child, int) + and parent > 0 + and child > 0 + and parent != child + ): + return dict( + started=True, + result="contained", + reason="exec_timeout", + removed=True, + parent_pid=parent, + descendant_pid=child, + ) + return {"removed": True} + return {} + + def measure_containment(self, timeout_s: float = 60) -> dict: + """ + Measure the subject's isolation from its inspected launch and its processes. + + A probe from the validator's image joins only the subject's PID namespace and + runs as the subject's user, so its writes stand for what the subject can write. + + Args: + timeout_s (`float`, *optional*, defaults to `60`): + Budget for inspection and the probe. + + Returns: + `dict`: a validated [`~openenv.validation.runtime.contracts.ContainmentEvidence`]. + """ + _ensure_image(self._helper_image) + deadline = time.monotonic() + timeout_s + details = self._raw_inspect(deadline - time.monotonic()) + host = details.get("HostConfig", {}) + out = self._pidns_probe( + "containment", + PIDNS_PROBE_SCRIPT, + list(_ALLOTTED), + details["Config"].get("User") or "0", + deadline - time.monotonic(), + ) + namespaces = { + "pid": "PidMode", + "ipc": "IpcMode", + "network": "NetworkMode", + "uts": "UTSMode", + "user": "UsernsMode", + "cgroup": "CgroupnsMode", + } + try: + evidence = ContainmentEvidence.model_validate( + { + **json.loads(out), + "allotted": list(_ALLOTTED), + "launch": { + "privileged": bool(host.get("Privileged")), + "host_namespaces": [ + ns + for ns, key in namespaces.items() + if host.get(key) == "host" + ], + "cap_add": host.get("CapAdd") or [], + "devices": [ + device.get("PathOnHost", "") + for device in host.get("Devices") or [] + ], + "unconfined": [ + option + for option in host.get("SecurityOpt") or [] + if option.replace(":", "=") + in { + "seccomp=unconfined", + "apparmor=unconfined", + "label=disable", + } + ], + }, + } + ) + except (ValueError, TypeError, AttributeError) as exc: + raise ProviderError("Containment probe returned invalid evidence") from exc + return evidence.model_dump(mode="json") + + def measure_resources(self, timeout_s: float = 180) -> dict: + """ + Read effective limits and qualify storage, memory, PIDs and exec cleanup. + + Each destructive probe has a fresh disposable subject registered for outer + cleanup. Exec cleanup does not qualify the declared episode deadline. + + Args: + timeout_s (`float`, *optional*, defaults to `180`): + Budget for measurement, disposable launches and probes. + + Returns: + `dict`: validated resource evidence with complete storage inventory. + """ + _ensure_image(self._helper_image) + deadline = time.monotonic() + timeout_s + + def remaining(): + return deadline - time.monotonic() + + user = self._raw_inspect(remaining())["Config"].get("User") or "0" + try: + measured = json.loads( + self._pidns_probe("limits", LIMITS_SCRIPT, [], user, remaining()) + ) + except ValueError as exc: + raise ProviderError("Limits probe returned invalid evidence") from exc + try: + containment = self.measure_containment(remaining()) + except CleanupError: + raise + except ProviderError: + containment = None + # Keep the original capacities and the full inventory that establishes coverage. + measured["containment"] = containment + measured["writable"] = [ + {"path": mount["mount_point"], "size_bytes": mount["size_bytes"]} + for mount in (containment["mounts"] if containment is not None else []) + if mount["mount_point"] in _ALLOTTED and mount["size_bytes"] is not None + ] + resources = self._spec.resources + budgets = { + "pids": (measured.get("cgroup") or {}).get("pids_max") or 0, + "disk": resources.disk_mb * 1024 * 1024, + "memory": resources.memory_mb * 1024 * 1024, + "exec_timeout": 1, + } + qualification = [] + for kind, budget in budgets.items(): + probe = {"kind": kind, "result": "inconclusive", "started": False} + qualification.append(probe) + if not budget: + continue + sibling = None + try: + sibling = DockerValidationProvider( + helper_image=self._helper_image, cleanup_subjects=self._disposables + ).start( + self._spec.model_copy( + update={ + "startup_timeout_s": min( + self._spec.startup_timeout_s, remaining() + ) + } + ) + ) + python = next( + ( + name + for name in ("python3", "python") + if sibling.exec([name, "-c", "pass"], remaining()).exit_code + == 0 + ), + None, + ) + if python is None: + continue + + def counters(): + return json.loads( + sibling._pidns_probe( + "counters", + COUNTERS_SCRIPT, + list(_ALLOTTED), + user, + remaining(), + ) + ) + + nonce = uuid.uuid4().hex + argv = [ + python, + "-c", + QUALIFY_SCRIPT, + kind, + str(budget), + nonce, + *_ALLOTTED, + ] + if kind == "exec_timeout": + probe.update( + sibling._measure_exec_timeout(argv, nonce, user, remaining()) + ) + continue + before = counters() + result = sibling.exec(argv, remaining()) + probe["started"] = ( + "openenv-probe-start:" + nonce in result.stdout.splitlines() + ) + if not probe["started"]: + continue + state = sibling._raw_inspect(remaining())["State"] + after = counters() if state["Running"] else {} + if kind == "memory": + previous, current = before.get("oom_kill"), after.get("oom_kill") + probe.update( + counter_before=previous, + counter_after=current, + oom_killed=bool(state.get("OOMKilled")), + ) + if state.get("OOMKilled") or ( + previous is not None + and current is not None + and current > previous + ): + probe.update(result="contained", reason="cgroup_oom_kill") + elif kind == "pids": + previous, current = before.get("pids_max"), after.get("pids_max") + probe.update(counter_before=previous, counter_after=current) + if ( + result.exit_code == 0 + and result.stdout.splitlines()[-1:] == ["contained"] + and previous is not None + and current is not None + and current > previous + ): + probe.update(result="contained", reason="cgroup_pids_max") + elif kind == "disk": + free = after.get("free_bytes", {}) + probe["free_bytes"] = free + probe["free_bytes_before"] = before.get("free_bytes", {}) + if ( + result.exit_code == 0 + and result.stdout.splitlines()[-1:] == ["contained"] + and all( + free.get(path) == 0 + and (probe["free_bytes_before"].get(path) or 0) > 0 + for path in _ALLOTTED + ) + ): + probe.update(result="contained", reason="filesystem_full") + except CleanupError: + raise + except (ProviderError, ValueError): + # A failed stimulus cannot establish enforcement, or erase other probes. + pass + finally: + try: + if sibling is not None: + sibling.stop() + except ProviderError as exc: + raise CleanupError( + "Disposable resource subject teardown failed" + ) from exc + try: + evidence = ResourceEvidence.model_validate( + {**measured, "qualification": qualification} + ) + except ValueError as exc: + raise ProviderError("Resource probes returned invalid evidence") from exc + return evidence.model_dump(mode="json") + def _run(self, argv: list[str], timeout_s: float, max_bytes: int = _MAX_OUTPUT): code, stdout, stderr = _command(argv, timeout_s, max_bytes) if code: @@ -666,7 +1044,9 @@ class DockerRunningSubject: try: self.stop() except ProviderError as cleanup: - raise cleanup from exc + raise CleanupError( + "Subject exec teardown failed: " + str(cleanup) + ) from exc raise return ExecResult( code, @@ -720,6 +1100,12 @@ class DockerRunningSubject: def stop(self) -> None: if self._stopped: return + disposable_cleanup_failed = False + for disposable in reversed(self._disposables): + try: + disposable.stop() + except ProviderError: + disposable_cleanup_failed = True if self._bridge is not None: self._bridge.close() self._bridge = None @@ -761,5 +1147,7 @@ class DockerRunningSubject: "Container removal could not be independently verified" ) if auxiliary_cleanup_failed: - raise ProviderError("Could not verify network helper cleanup") + raise CleanupError("Could not verify network helper cleanup") + if disposable_cleanup_failed: + raise CleanupError("Could not verify disposable resource subject cleanup") self._stopped = True diff --git a/src/openenv/validation/providers/hf_sandbox.py b/src/openenv/validation/providers/hf_sandbox.py new file mode 100644 index 0000000000000000000000000000000000000000..e0c232284a43e5e89818a43c68b0e2277f092aba --- /dev/null +++ b/src/openenv/validation/providers/hf_sandbox.py @@ -0,0 +1,303 @@ +"""Run a Hugging Face Space as a validation subject in a dedicated HF Sandbox. + +A Space revision pins the downloaded source, not the image selected by HF Jobs. +This integration has no supported source-to-image digest resolver, so runtime +startup reports the missing immutable_image capability before creating a job. +The sandbox subject below retains bounded serving, exec and cleanup support for +provider qualification once that binding is available. +""" + +import json +import re +import shlex +import time +from pathlib import Path + +import httpx + +from ...core.containers.runtime.hf_sandbox_provider import _LocalAuthProxy +from ..manifest import ExecutionDeclaration +from ..runtime.contracts import LaunchSpec +from ..types import ProviderCapability +from . import ExecResult, ProviderError, StartupError, UnsupportedCapability + +_TERMINAL_STAGES = {"COMPLETED", "CANCELED", "ERROR", "DELETED"} +_MAX_OUTPUT = 65536 + + +def _server_command(dockerfile: str) -> list[str]: + """The effective `CMD` of a Dockerfile, which a Sandbox job does not run itself.""" + if re.search(r"(?im)^#\s*escape\s*=\s*`\s*$", dockerfile): + raise UnsupportedCapability("hf-sandbox requires backslash Dockerfile escapes") + stages = {} + stage = {} + stage_number = 0 + lines = "\n".join( + line for line in dockerfile.splitlines() if not line.lstrip().startswith("#") + ) + # Docker continues only an unescaped backslash, allowing trailing spaces/tabs. + lines = re.sub(r"(? int: + """`app_port` from the Space card front matter; the Hub default is 7860.""" + front = readme.split("---", 2)[1] if readme.startswith("---") else "" + match = re.search(r"^app_port:\s*(\d+)\s*$", front, re.M) + return int(match.group(1)) if match else 7860 + + +class HFSandboxValidationProvider: + """ + Inspect a Hub Space for validation on HF Jobs hardware, including GPU flavors. + + Args: + space_id (`str`): + The Space to run, e.g. `"openenv/echo_env"`. + revision (`str`): + The full commit hash of the validated Space files; resolve a branch or + tag first. Runtime remains unsupported until an immutable image can + be bound to this source commit. + flavor (`str`, *optional*, defaults to `"cpu-basic"`): + HF Jobs hardware flavor, as listed by `hf jobs hardware`. + token (`str`, *optional*): + Hugging Face token; defaults to the locally saved one. + """ + + name = "hf-sandbox" + supported_network_modes = frozenset({"public"}) + + def __init__( + self, + space_id: str, + revision: str, + *, + flavor: str = "cpu-basic", + token: str | None = None, + ): + from huggingface_hub import HfApi + + if not re.fullmatch(r"[0-9a-f]{40}", revision): + raise ValueError(f"revision must be a full commit hash, not {revision!r}") + self.space_id = space_id + self.revision = revision + self.flavor = flavor + self._api = HfApi(token=token) + hardware = {h.name: h for h in self._api.list_jobs_hardware()} + if flavor not in hardware: + raise ValueError(f"unknown HF Jobs flavor {flavor!r}") + accelerator = hardware[flavor].accelerator + self.gpus = int(accelerator.quantity) if accelerator else 0 + self.capabilities = frozenset( + { + ProviderCapability.IMAGE_BUILD, + ProviderCapability.EXEC, + ProviderCapability.REMOTE, + *([ProviderCapability.GPU] if self.gpus else []), + } + ) + self._command: list[str] = [] + self._port = 7860 + + def _check_space(self) -> None: + """Compare source and reported runtime metadata without claiming image provenance.""" + try: + info = self._api.space_info(self.space_id) + except Exception as exc: + raise ProviderError(f"Could not read Space {self.space_id}") from exc + if info.sha != self.revision: + raise ProviderError( + f"Space {self.space_id} is at revision {info.sha}, not the " + + f"validated revision {self.revision}" + ) + # Raw runtime metadata is not provenance for a separately launched Job. + runtime = info.runtime.raw if info.runtime else {} + stage, runtime_revision = runtime.get("stage"), runtime.get("sha") + if stage not in (None, "RUNNING") or runtime_revision not in ( + None, + self.revision, + ): + raise ProviderError( + f"Space {self.space_id} reports stage {stage}, runtime revision " + + f"{runtime_revision}; expected RUNNING at source revision {self.revision}; " + + "job image identity remains unverified" + ) + if stage is None or runtime_revision is None: + raise UnsupportedCapability( + "missing provider capability: space_runtime_metadata; " + + "Space runtime stage or revision is unavailable; " + + "job image identity remains unverified; no job launched" + ) + + def build(self, root: Path, execution: ExecutionDeclaration) -> str: + """Read the server command and port from the validated Space files.""" + try: + dockerfile = (root / execution.dockerfile).read_text() + except OSError: + raise StartupError( + f"The Space has no Dockerfile at {execution.dockerfile}" + ) from None + self._command = _server_command(dockerfile) + readme = root / "README.md" + self._port = _app_port(readme.read_text() if readme.is_file() else "") + self._check_space() + raise UnsupportedCapability( + "missing provider capability: immutable_image; " + + f"Space source revision {self.revision} matches the Hub runtime revision, " + + "but no verified source-to-image digest binding is available; no job launched" + ) + + def start(self, spec: LaunchSpec) -> "HFSandboxSubject": + if spec.network.mode not in self.supported_network_modes: + raise UnsupportedCapability( + f"hf-sandbox does not enforce {spec.network.mode}" + ) + if spec.resources.gpus > self.gpus: + raise UnsupportedCapability( + f"flavor {self.flavor} has {self.gpus} GPUs, " + + f"{spec.resources.gpus} declared" + ) + self._check_space() + raise UnsupportedCapability( + "missing provider capability: immutable_image; " + + f"no verified image digest for Space source revision {self.revision}; " + + "no job launched" + ) + + +class HFSandboxSubject: + """A dedicated sandbox job serving one Space; stopping cancels the job.""" + + def __init__(self, sandbox, provider: HFSandboxValidationProvider): + self.base_url = "" + self._sandbox = sandbox + self._provider = provider + self._proxy: _LocalAuthProxy | None = None + self._stopped = False + + def _serve(self, command: list[str], port: int, timeout_s: float) -> None: + self._sandbox.run( + shlex.join(command) + + f" 2>&1 | {{ head -c {_MAX_OUTPUT} > /tmp/openenv-server.log; " + "cat > /dev/null; }", + shell=True, + background=True, + ) + target = self._sandbox.proxy_url_for(port, "/") + headers = self._sandbox.proxy_headers + deadline = time.monotonic() + timeout_s + # Until the subject binds its port, the sandbox's own server answers the + # proxy, including a healthy /health; wait for the subject's listener first. + listening = f"grep -qi ':{port:04X} 0\\+:0000 0A' /proc/net/tcp /proc/net/tcp6" + with httpx.Client(trust_env=False, follow_redirects=False) as client: + while time.monotonic() < deadline: + try: + check = self._sandbox.run( + listening, shell=True, check=False, timeout=5 + ) + if check.exit_code == 0: + response = client.get( + target + "health", headers=headers, timeout=5 + ) + if response.status_code == 200: + break + except httpx.HTTPError: + pass # The server is still starting. + time.sleep(1) + else: + raise StartupError( + "Subject did not return HTTP 200 from /health before its deadline" + ) + self._proxy = _LocalAuthProxy(target_url=target, headers=headers) + self.base_url = self._proxy.start() + + def inspect(self) -> dict: + return { + "job_id": self._sandbox.id, + "image": f"hf.co/spaces/{self._provider.space_id}", + # No source-bound image digest has been verified. + "image_verified": False, + "space_revision": self._provider.revision, + "built_revision": None, + "flavor": self._provider.flavor, + } + + def logs(self, max_bytes: int = _MAX_OUTPUT) -> str: + result = self._sandbox.run( + ["tail", "-c", str(max_bytes), "/tmp/openenv-server.log"], check=False + ) + return result.stdout[-max_bytes:] + + def exec(self, argv: list[str], timeout_s: float) -> ExecResult: + if self._stopped: + raise ProviderError("Subject has stopped") + started = time.monotonic() + result = self._sandbox.run(argv, shell=False, timeout=timeout_s, check=False) + return ExecResult( + result.exit_code, + result.stdout[-_MAX_OUTPUT:], + result.stderr[-_MAX_OUTPUT:], + time.monotonic() - started, + ) + + def stop(self) -> None: + if self._stopped: + return + try: + if self._proxy is not None: + self._proxy.stop() + self._proxy = None + finally: + self._sandbox.kill() + # kill() logs rather than raises on failure, so confirm with the Jobs API. + deadline = time.monotonic() + 60 + while time.monotonic() < deadline: + stage = self._provider._api.inspect_job( + job_id=self._sandbox.id + ).status.stage + if stage in _TERMINAL_STAGES: + break + time.sleep(2) + else: + raise ProviderError(f"HF Sandbox job {self._sandbox.id} did not stop") + self._stopped = True diff --git a/src/openenv/validation/runner.py b/src/openenv/validation/runner.py index e66856042da590fd05106df90736cecf3a8d42b7..4fd19388f7a785274de0c97aa158e6dcc2ea2c81 100644 --- a/src/openenv/validation/runner.py +++ b/src/openenv/validation/runner.py @@ -3,30 +3,64 @@ import hashlib import json import os +import secrets import stat import time import uuid from dataclasses import replace -from pathlib import Path +from pathlib import Path, PurePosixPath +from urllib.parse import quote + +import httpx from .graders import GraderRegistry, Subject from .graders.runtime import ( + EpisodeIsolationGrader, + HostContainmentGrader, NetworkPolicyGrader, ObservationSchemaGrader, + OracleContainmentGrader, + ResourceBoundsGrader, RewardWellFormedGrader, StateContractGrader, ) +from .graders.runtime.discovery import ( + RewardAttributionGrader, + RubricIntrospectableGrader, + TaskDeclarationAccuracyGrader, + ToolDeclarationAccuracyGrader, +) +from .graders.runtime.oracle import oracle_inventory +from .graders.runtime.repeatability import ( + EpisodeDeterminismGrader, + SeedControlGrader, + TrajectoryRecordGrader, +) from .graders.static import StaticManifestGrader from .manifest import ManifestError, NormalizedManifest, NormalizedManifestV2 from .parsers import ParserRegistry +from .parsers.harbor_toml import HarborTaskParser from .parsers.openenv_yaml import OpenEnvYamlParser from .policy import apply_policy, load_policy, PolicyError, SeverityPolicy -from .providers import ProviderError, StartupError, UnsupportedCapability +from .providers import CleanupError, ProviderError, StartupError, UnsupportedCapability from .report import CheckResult, ValidationReport, ValidationReportV2 from .runtime.artifacts import write_runtime_bundle -from .runtime.collector import collect_runtime_evidence, RuntimeCollectionInterrupted -from .runtime.contracts import LaunchSpec, load_runtime_plan, RuntimePlanError +from .runtime.collector import ( + collect_runtime_evidence, + RuntimeCollectionInterrupted, + RuntimeCollectionUnsupported, +) +from .runtime.contracts import ( + HttpProbe, + IsolationEvidence, + LaunchSpec, + load_runtime_plan, + RuntimeEvidence, + RuntimePlanError, +) +from .runtime.replay import collect_replays, REPLAY_BUDGET_SECONDS from .runtime.scheduler import execute_graders, order_graders +from .runtime.transport import http_deadline from .signature import detect_signature from .types import CheckStatus, Lane, Level, ProviderCapability @@ -34,6 +68,11 @@ REPORT_SCHEMA_VERSION = "1" _DIGEST_EXCLUDED_DIRS = {".git", "__pycache__", ".venv", ".worktrees", "outputs"} +# One deadline and one body budget cover the oracle's HTTP probes. +ORACLE_PROBE_TIMEOUT_S = 10.0 +MAX_ORACLE_PROBE_BYTES = 1024 * 1024 +MAX_REDIRECTS = 3 + def source_digest(package_root: Path) -> str: """ @@ -83,6 +122,7 @@ def default_parser_registry() -> ParserRegistry: """The parsers shipped in this build.""" registry = ParserRegistry() registry.register(OpenEnvYamlParser()) + registry.register(HarborTaskParser()) return registry @@ -93,7 +133,19 @@ def default_grader_registry(policy: SeverityPolicy) -> GraderRegistry: registry.register(RewardWellFormedGrader()) registry.register(ObservationSchemaGrader()) registry.register(StateContractGrader()) + registry.register(SeedControlGrader()) + registry.register(EpisodeDeterminismGrader()) + registry.register(TrajectoryRecordGrader()) + registry.register(ToolDeclarationAccuracyGrader()) + registry.register(TaskDeclarationAccuracyGrader()) + registry.register(RubricIntrospectableGrader()) + registry.register(RewardAttributionGrader()) + registry.register(NetworkPolicyGrader()) + registry.register(HostContainmentGrader()) + registry.register(ResourceBoundsGrader()) + registry.register(EpisodeIsolationGrader()) + registry.register(OracleContainmentGrader()) return registry @@ -107,23 +159,128 @@ def _outcome(check_id, status, reason, *, started=None, measured=None): ) +class _OracleCollectionInterrupted(KeyboardInterrupt): + """Cancellation carrying the bounded HTTP evidence already received.""" + + def __init__(self, probes): + super().__init__("oracle collection interrupted") + self.probes = tuple(probes) + + +def _get(base_url, location, deadline, max_bytes=MAX_ORACLE_PROBE_BYTES): + """ + GET a package-relative path from the control endpoint, unproxied and bounded. + + Same-origin redirects are followed up to `MAX_REDIRECTS` times. Every request + and body read ends at `deadline`, a `time.monotonic()` value. The probe keeps + bounded bodies from every redirect hop and names any incomplete response. + """ + path = "/" + PurePosixPath(location).as_posix() + url = httpx.URL(base_url.rstrip("/") + quote(path)) + origin = (url.scheme, url.host, url.port) + status, body = None, bytearray() + redirects = [] + retained = 0 + + def probe(failure=None): + return HttpProbe(path, status, bytes(body), failure, tuple(redirects)) + + try: + # Without keep-alive, every request opens a socket the deadline can abort. + with httpx.Client( + trust_env=False, + follow_redirects=False, + limits=httpx.Limits(max_keepalive_connections=0), + ) as client: + for hop in range(MAX_REDIRECTS + 1): + timeout = deadline - time.monotonic() + with ( + http_deadline(timeout) as extensions, + client.stream( + "GET", + url, + timeout=timeout, + headers={"Accept-Encoding": "identity"}, + extensions=extensions, + ) as response, + ): + status = response.status_code + # iter_bytes() would decompress before the byte bound applies. + encoding = response.headers.get("Content-Encoding", "identity") + if encoding.strip().lower() != "identity": + return probe("compressed response") + for chunk in response.iter_raw(): + if retained + len(body) + len(chunk) > max_bytes: + body.extend(chunk[: max_bytes - retained - len(body)]) + return probe("body exceeds the byte bound") + body.extend(chunk) + if not response.has_redirect_location: + return probe() + if hop == MAX_REDIRECTS: + return probe("too many redirects") + if retained + len(body) >= max_bytes: + return probe("body exceeds the byte bound") + url = url.join(response.headers["Location"]) + if (url.scheme, url.host, url.port) != origin: + return probe("cross-origin redirect") + redirects.append(bytes(body)) + retained += len(body) + body.clear() + status = None + except KeyboardInterrupt: + raise _OracleCollectionInterrupted((probe("KeyboardInterrupt"),)) from None + except (httpx.HTTPError, httpx.InvalidURL, TimeoutError) as exc: + # Exception text may include subject-controlled URLs. + return probe(type(exc).__name__) + return probe("too many redirects") + + +def _oracle_probes(base_url, root, location): + """Share one deadline and body budget across the bounded file inventory.""" + try: + inventory = oracle_inventory(root, location) + except (OSError, UnicodeError): + return () + deadline = time.monotonic() + ORACLE_PROBE_TIMEOUT_S + remaining = MAX_ORACLE_PROBE_BYTES + probes = [] + for path, _ in inventory.files: + if remaining <= 0 or time.monotonic() >= deadline: + probe = HttpProbe("/" + path, None, failure="oracle probe budget exhausted") + else: + try: + probe = _get(base_url, path, deadline, remaining) + except KeyboardInterrupt as exc: + interrupted = ( + exc.probes + if isinstance(exc, _OracleCollectionInterrupted) + else (HttpProbe("/" + path, None, failure="KeyboardInterrupt"),) + ) + raise _OracleCollectionInterrupted((*probes, *interrupted)) from None + probes.append(probe) + remaining -= len(probe.body) + sum(map(len, probe.redirect_bodies)) + return tuple(probes) + + def _applicable(check_id, manifest): if manifest is None: return True if check_id in {"runtime.rubric_introspectable", "runtime.reward_attribution"}: return manifest.capabilities.rubric_tree if check_id == "runtime.task_declaration_accuracy": - return manifest.capabilities.task_api or bool( - manifest.capabilities.declared_task_count - ) + return TaskDeclarationAccuracyGrader().applies_to(manifest) + if check_id == "runtime.tool_declaration_accuracy": + return ToolDeclarationAccuracyGrader().applies_to(manifest) return True -def _runtime(subject, graders, *, skip_build, provider): +def _runtime(subject, graders, *, skip_build, provider, sandbox): """Own build/start/collection/stop and retain failure evidence through teardown.""" manifest = subject.manifest plan = None evidence = None + isolation = None + oracle_http = () running = None inspection = {} cleanup = {"required": False, "completed": True} @@ -136,6 +293,11 @@ def _runtime(subject, graders, *, skip_build, provider): raise UnsupportedCapability( "--skip-build: build-dependent runtime checks skipped" ) + if sandbox != "docker": + raise UnsupportedCapability( + f"{sandbox} runs native Harbor tasks only; " + + "validate a served Space with --space" + ) if not isinstance(manifest, NormalizedManifestV2): raise UnsupportedCapability( "missing validation.execution declaration and runtime plan" @@ -166,12 +328,12 @@ def _runtime(subject, graders, *, skip_build, provider): resources=manifest.resources, network=manifest.network, run_id="validation-" + uuid.uuid4().hex, + env_vars={"OPENENV_VALIDATION_TOKEN": secrets.token_urlsafe(32)}, ) attempted = True image_ref = provider.build(subject.root, manifest.execution) - running = provider.start( - LaunchSpec.model_validate({**spec.model_dump(), "image_ref": image_ref}) - ) + spec = LaunchSpec.model_validate({**spec.model_dump(), "image_ref": image_ref}) + running = provider.start(spec) cleanup = {"required": True, "completed": False} inspection = running.inspect() result = _outcome( @@ -181,11 +343,19 @@ def _runtime(subject, graders, *, skip_build, provider): started=started, measured={"provider": provider.name, "image_ref": image_ref}, ) + replay_deadline = time.monotonic() + REPLAY_BUDGET_SECONDS evidence = collect_runtime_evidence( running.base_url, plan, - episode_timeout_s=manifest.resources.episode_timeout_s, + episode_timeout_s=min( + manifest.resources.episode_timeout_s, REPLAY_BUDGET_SECONDS + ), + validation_token=spec.env_vars["OPENENV_VALIDATION_TOKEN"], + collect_tools=_applicable("runtime.tool_declaration_accuracy", manifest), + collect_tasks=_applicable("runtime.task_declaration_accuracy", manifest), ) + # Independent isolation and oracle probes do not spend the replay budget. + replay_remaining_s = max(0.0, replay_deadline - time.monotonic()) # Protocol collection must finish before its dependent contract checks run. if evidence.failure_reason: result = _outcome( @@ -194,6 +364,59 @@ def _runtime(subject, graders, *, skip_build, provider): evidence.failure_reason, started=started, ) + if result.status is CheckStatus.PASS: + not_started = RuntimeEvidence( + failure_phase="not_started", + failure_reason="validation interrupted before the fresh episode", + ) + try: + # Later JSON limits leave primary contracts and other probes measurable. + try: + sequential = collect_runtime_evidence( + running.base_url, + plan, + episode_timeout_s=manifest.resources.episode_timeout_s, + episodes=2, + validation_token=spec.env_vars["OPENENV_VALIDATION_TOKEN"], + request_telemetry=False, + ) + except RuntimeCollectionUnsupported as exc: + sequential = exc.evidence + isolation = IsolationEvidence(sequential=sequential, fresh=not_started) + try: + fresh = collect_runtime_evidence( + running.base_url, + plan, + episode_timeout_s=manifest.resources.episode_timeout_s, + validation_token=spec.env_vars["OPENENV_VALIDATION_TOKEN"], + request_telemetry=False, + ) + except RuntimeCollectionUnsupported as exc: + fresh = exc.evidence + isolation = replace(isolation, fresh=fresh) + except RuntimeCollectionInterrupted as exc: + isolation = ( + IsolationEvidence(sequential=exc.evidence, fresh=not_started) + if isolation is None + else replace(isolation, fresh=exc.evidence) + ) + raise KeyboardInterrupt from None + if manifest.capabilities.oracle is not None: + oracle_http = _oracle_probes( + running.base_url, + subject.root, + manifest.capabilities.oracle.location, + ) + evidence = collect_replays( + provider, + running, + spec, + plan, + evidence, + capabilities=manifest.capabilities, + deadline=time.monotonic() + replay_remaining_s, + ) + network_json = None if ( result.status is CheckStatus.PASS @@ -207,18 +430,58 @@ def _runtime(subject, graders, *, skip_build, provider): inspection = {**inspection, "network": network} except ProviderError as exc: inspection = {**inspection, "network_error": str(exc)[:1024]} + containment_json = None + if ( + result.status is CheckStatus.PASS + and ProviderCapability.INSPECTED_ISOLATION in provider.capabilities + ): + try: + containment = running.measure_containment() + containment_json = json.dumps(containment, allow_nan=False) + inspection = {**inspection, "containment": containment} + except ProviderError as exc: + inspection = {**inspection, "containment_error": str(exc)[:1024]} + resource_json = None + if ( + result.status is CheckStatus.PASS + and ProviderCapability.RESOURCE_ENFORCEMENT in provider.capabilities + ): + try: + resources = running.measure_resources() + resource_json = json.dumps(resources, allow_nan=False) + inspection = {**inspection, "resources": resources} + except CleanupError: + raise + except ProviderError as exc: + inspection = {**inspection, "resources_error": str(exc)[:1024]} subject = replace( subject, image_ref=image_ref, running=running, runtime_evidence=evidence, network_evidence_json=network_json, + containment_evidence_json=containment_json, + resource_evidence_json=resource_json, + isolation_evidence=isolation, + oracle_http=oracle_http, ) - checks = execute_graders( - graders, - subject, - provider_capabilities=provider.capabilities, - prior=[result], + checks.extend( + execute_graders( + graders, + subject, + provider_capabilities=provider.capabilities, + prior=[result], + ) + ) + # Cleanup failure cannot invalidate evidence already collected from a + # healthy subject. Preserve its findings before failing the run closed. + if any(replay.cleanup_complete is False for replay in evidence.replays): + result.status = CheckStatus.ERROR + result.evidence.append("replay subject teardown failed") + except RuntimeCollectionUnsupported as exc: + evidence = exc.evidence + result = _outcome( + "runtime.startup", CheckStatus.SKIP, str(exc), started=started ) except UnsupportedCapability as exc: result = _outcome( @@ -241,6 +504,8 @@ def _runtime(subject, graders, *, skip_build, provider): except KeyboardInterrupt as exc: if isinstance(exc, RuntimeCollectionInterrupted): evidence = exc.evidence + elif isinstance(exc, _OracleCollectionInterrupted): + oracle_http = exc.probes result = _outcome( "runtime.startup", CheckStatus.ERROR, @@ -255,25 +520,66 @@ def _runtime(subject, graders, *, skip_build, provider): started=started, ) finally: - if running is not None: - try: - running.stop() - cleanup["completed"] = True - except (Exception, KeyboardInterrupt) as exc: - cleanup["completed"] = False - cleanup["reason"] = f"subject teardown failed ({type(exc).__name__})" - if result is None: + try: + # Discovery precedes the episode; its completed evidence remains usable + # when collection is unsupported or interrupted before normal grading. + graded = {check.check_id for check in checks} + independent = [ + grader + for grader in graders + if not grader.depends_on and grader.check_id not in graded + ] + if independent: + try: + checks.extend( + execute_graders( + independent, replace(subject, runtime_evidence=evidence) + ) + ) + except KeyboardInterrupt: result = _outcome( "runtime.startup", CheckStatus.ERROR, - "subject teardown failed", + "validation interrupted", started=started, ) - else: - result.status = CheckStatus.ERROR - result.evidence.append("subject teardown failed") - result.duration_s = time.monotonic() - started - return [result, *checks], attempted, plan, evidence, inspection, cleanup + finally: + if running is not None: + try: + running.stop() + cleanup["completed"] = not ( + evidence + and any( + replay.cleanup_complete is False + for replay in evidence.replays + ) + ) + except (Exception, KeyboardInterrupt) as exc: + cleanup["completed"] = False + cleanup["reason"] = ( + f"subject teardown failed ({type(exc).__name__})" + ) + if result is None: + result = _outcome( + "runtime.startup", + CheckStatus.ERROR, + "subject teardown failed", + started=started, + ) + else: + result.status = CheckStatus.ERROR + result.evidence.append("subject teardown failed") + result.duration_s = time.monotonic() - started + return ( + [result, *checks], + attempted, + plan, + evidence, + inspection, + cleanup, + isolation, + oracle_http, + ) def run_validation( @@ -284,6 +590,10 @@ def run_validation( policy: SeverityPolicy | None = None, provider=None, artifacts_dir: Path | None = None, + report_target: str | None = None, + sandbox: str = "docker", + flavor: str = "cpu-basic", + namespace: str | None = None, ) -> ValidationReport | ValidationReportV2: """ Validate a package end to end and return the report. @@ -293,7 +603,7 @@ def run_validation( [`~openenv.validation.signature.UnsupportedPackageError`] for recognized-but-unsupported ones (CLI exit code 2). A package whose declarations fail the manifest schema yields a normal report with a `static.manifest` FAIL - (exit code 1). + (exit code 1). An unknown `sandbox` raises `ValueError` before validation. Args: target (`Path`): @@ -308,10 +618,24 @@ def run_validation( Validation-only provider; defaults to Docker-local for runtime runs. artifacts_dir (`Path`, *optional*): Write a redacted reproduction bundle to this directory. + report_target (`str`, *optional*): + Durable source identity for the report; defaults to the package path. + sandbox (`str`, *optional*, defaults to `"docker"`): + Where native Harbor trials run: `"docker"` on the local daemon or + `"hf-sandbox"`, one Hugging Face Job per trial. Served packages run + on `"docker"` or `provider` only. + flavor (`str`, *optional*, defaults to `"cpu-basic"`): + HF Jobs hardware flavor for `"hf-sandbox"` trials, as listed by + `hf jobs hardware`. + namespace (`str`, *optional*): + User or organization that owns the `"hf-sandbox"` jobs; defaults to + the token's user. Returns: [`~openenv.validation.report.ValidationReport`]: the completed report. """ + if sandbox not in ("docker", "hf-sandbox"): + raise ValueError(f"unknown sandbox {sandbox!r}; expected docker or hf-sandbox") target = Path(target) wants_runtime = max_level >= Level.RUNTIME policy = policy or load_policy("v2" if wants_runtime else "v1") @@ -357,7 +681,8 @@ def run_validation( ) levels = [Level.STATIC] - plan = evidence = None + plan = evidence = isolation = None + oracle_http = () inspection = {} cleanup = {"required": False, "completed": True} if manifest is not None: @@ -382,7 +707,36 @@ def run_validation( ) ) if wants_runtime: - runtime_results, attempted, plan, evidence, inspection, cleanup = _runtime( + if ( + isinstance(manifest, NormalizedManifestV2) + and manifest.execution.kind == "harbor_task" + ): + from .harbor import validate_harbor + + return validate_harbor( + subject, + max_level=max_level, + policy=policy, + results=results, + digest_before=digest_before, + artifacts_dir=artifacts_dir, + report_target=report_target, + skip_build=skip_build, + provider=provider, + sandbox=sandbox, + flavor=flavor, + namespace=namespace, + ) + ( + runtime_results, + attempted, + plan, + evidence, + inspection, + cleanup, + isolation, + oracle_http, + ) = _runtime( subject, [ grader @@ -391,34 +745,35 @@ def run_validation( ], skip_build=skip_build, provider=provider, + sandbox=sandbox, ) results.extend(runtime_results) if attempted: levels.append(Level.RUNTIME) + # Policy IDs are an inventory, not evidence that a grader exists. Name every + # requested check that did not run, so a PASS never hides missing coverage. + present = {result.check_id for result in results} + for entry in policy.entries_for_lane(Lane.LOCAL).values(): + grader = graders.get(entry.check_id) + applicable = ( + manifest is None + or entry.check_id in selected + or (grader is None and _applicable(entry.check_id, manifest)) + ) + if entry.level <= max_level and entry.check_id not in present and applicable: + reason = "grader not implemented in this build" + if manifest is None: + reason = "unmet dependency: valid manifest" + elif entry.level is Level.SEMANTIC: + reason = "oracle execution is not implemented for served packages" + elif grader is not None and grader.depends_on: + reason = "unmet dependency: " + ", ".join(grader.depends_on) + elif grader is not None: + reason = "grader did not complete" + results.append(_outcome(entry.check_id, CheckStatus.SKIP, reason)) + if wants_runtime: - # Policy IDs are an inventory, not evidence that a grader exists. Keep the - # incomplete surface explicit throughout the staged implementation. - present = {result.check_id for result in results} - for entry in policy.entries_for_lane(Lane.LOCAL).values(): - grader = graders.get(entry.check_id) - applicable = ( - manifest is None - or entry.check_id in selected - or (grader is None and _applicable(entry.check_id, manifest)) - ) - if ( - entry.level in {Level.RUNTIME, Level.SEMANTIC} - and entry.level <= max_level - and entry.check_id not in present - and applicable - ): - reason = "grader not implemented in this build" - if manifest is None: - reason = "unmet dependency: valid manifest" - elif grader is not None and grader.depends_on: - reason = "unmet dependency: " + ", ".join(grader.depends_on) - results.append(_outcome(entry.check_id, CheckStatus.SKIP, reason)) source_problem = None if not digest_before: source_problem = "package source could not be verified before validation" @@ -435,6 +790,12 @@ def run_validation( ) if source_problem is not None: invalidated = {"runtime.startup"} + # Independent discovery also depends on the verified package source. + invalidated.update( + grader.check_id + for grader in selected.values() + if grader.level is Level.RUNTIME + ) for grader in order_graders(list(selected.values())): if invalidated.intersection(grader.depends_on): invalidated.add(grader.check_id) @@ -466,7 +827,7 @@ def run_validation( report_schema_version="2" if report_type is ValidationReportV2 else REPORT_SCHEMA_VERSION, - target=str(target), + target=str(target) if report_target is None else report_target, source_digest=digest_before, signature=signature, manifest=manifest, @@ -484,5 +845,7 @@ def run_validation( evidence=evidence, provider=inspection, cleanup=cleanup, + isolation=isolation, + oracle_http=oracle_http, ) return report diff --git a/src/openenv/validation/runtime/artifacts.py b/src/openenv/validation/runtime/artifacts.py index e69f9fcfd2adb9d0dcf717748fa65a6392a888d0..205ab4d26bd3b33e466ed753e42c28bb3e3a815e 100644 --- a/src/openenv/validation/runtime/artifacts.py +++ b/src/openenv/validation/runtime/artifacts.py @@ -1,13 +1,15 @@ """Small, bounded reproduction bundles; reports remain the public result contract.""" import hashlib -import json import math import platform import re from dataclasses import asdict +from decimal import Decimal from pathlib import Path +from .json_values import dumps, loads + _SECRET_KEY = re.compile(r"(?i)(password|secret|token|authorization|api[_-]?key)") _TOKEN_METADATA_KEYS = {"max_tokens", "prompt_token_ids"} _TOKEN = re.compile( @@ -16,6 +18,14 @@ _TOKEN = re.compile( _MAX_ARTIFACT_DEPTH = 64 +def _unique_object(pairs): + # A dict cannot retain earlier duplicate values for redaction or replay. + value = dict(pairs) + if len(value) != len(pairs): + raise ValueError("duplicate JSON object members") + return value + + def _redact(value, *, depth=0): if depth >= _MAX_ARTIFACT_DEPTH and isinstance(value, (dict, list)): return {"omitted": "artifact nesting limit exceeded"} @@ -32,45 +42,13 @@ def _redact(value, *, depth=0): return _TOKEN.sub("[REDACTED]", value) if isinstance(value, float) and not math.isfinite(value): return {"invalid_number": str(value)} + if isinstance(value, Decimal) and not value.is_finite(): + return {"invalid_number": str(value).lower()} return value -def write_runtime_bundle( - directory: Path, report, *, plan=None, evidence=None, provider=None, cleanup=None -): - """Write a credential-filtered trace, source/policy/plan provenance and coverage.""" - directory.mkdir(parents=True, exist_ok=True) - files = {} - coverage = { - "requested_runtime_checks": [ - r.check_id for r in report.results if r.check_id.startswith("runtime.") - ], - "executed": [r.check_id for r in report.results if r.status.value != "skip"], - "incomplete": [r.check_id for r in report.results if r.status.value == "skip"], - } - files["coverage.json"] = coverage - files["report.json"] = report.model_dump(mode="json") - files["cleanup.json"] = cleanup or {"required": False} - if plan: - files["runtime-plan.json"] = plan.model_dump(mode="json") - files["run-manifest.json"] = { - "bundle_schema_version": "1", - "source_digest": report.source_digest, - "policy_version": report.policy_version, - "manifest_schema_version": report.manifest.manifest_schema_version - if report.manifest - else None, - "plan_digest": hashlib.sha256(plan.model_dump_json().encode()).hexdigest() - if plan - else None, - "plan_redacted": bool( - plan - and _redact(plan.model_dump(mode="json")) != plan.model_dump(mode="json") - ), - "platform": platform.platform(), - "python": platform.python_version(), - "provider": provider or {}, - } +def _recording(evidence, trace_file): + """Use the same redaction and completion metadata for every session.""" trace = [] collector_metadata = None if evidence: @@ -79,28 +57,42 @@ def write_runtime_bundle( row = asdict(exchange) for key in ("request_json", "response_json"): try: - row[key] = json.loads(row[key]) - except (ValueError, RecursionError): - row[key] = "[malformed response omitted]" + row[key] = loads(row[key], object_pairs_hook=_unique_object) + except (ValueError, ArithmeticError, RecursionError): + row[key] = "[malformed or unsupported response omitted]" omitted_fields.append({"exchange_index": index, "field": key}) trace.append(row) schema = None schema_parse_failed = False if evidence.observation_schema_json is not None: try: - schema = json.loads(evidence.observation_schema_json) - except (ValueError, RecursionError): + schema = loads( + evidence.observation_schema_json, object_pairs_hook=_unique_object + ) + except (ValueError, ArithmeticError, RecursionError): schema_parse_failed = True reset_schema = None reset_schema_parse_failed = False if evidence.reset_observation_schema_json is not None: try: - reset_schema = json.loads(evidence.reset_observation_schema_json) - except (ValueError, RecursionError): + reset_schema = loads( + evidence.reset_observation_schema_json, + object_pairs_hook=_unique_object, + ) + except (ValueError, ArithmeticError, RecursionError): reset_schema_parse_failed = True + schema_response = None + schema_response_parse_failed = False + if evidence.schema_response_json is not None: + try: + schema_response = loads( + evidence.schema_response_json, object_pairs_hook=_unique_object + ) + except (ValueError, ArithmeticError, RecursionError): + schema_response_parse_failed = True collector_metadata = { "evidence_schema_version": "1", - "trace_file": "collector-trace.json", + "trace_file": trace_file, "observation_schema": schema, "schema_available": evidence.observation_schema_json is not None, "schema_parse_failed": schema_parse_failed, @@ -108,9 +100,14 @@ def write_runtime_bundle( "reset_schema_available": evidence.reset_observation_schema_json is not None, "reset_schema_parse_failed": reset_schema_parse_failed, + "schema_response": schema_response, + "schema_response_available": evidence.schema_response_json is not None, + "schema_response_parse_failed": schema_response_parse_failed, "omitted_trace_fields": omitted_fields, "failure_phase": evidence.failure_phase, "failure_reason": evidence.failure_reason, + "telemetry_error": evidence.telemetry_error, + "telemetry_unavailable": evidence.telemetry_unavailable, "complete": evidence.failure_phase is None and evidence.failure_reason is None, } @@ -118,16 +115,221 @@ def write_runtime_bundle( bool(omitted_fields) or schema_parse_failed or reset_schema_parse_failed + or schema_response_parse_failed or _redact(trace) != trace or _redact(collector_metadata) != collector_metadata ) - files["collector-trace.json"] = trace - files["collector-evidence.json"] = collector_metadata + return trace, collector_metadata + + +def _http_body(body): + text = body.decode("utf-8", errors="replace") + omitted = False + try: + value = loads(text.lstrip("\ufeff"), object_pairs_hook=_unique_object) + except (ValueError, ArithmeticError, RecursionError): + value = text + # Unparseable JSON loses the key context used by the structured redactor. + omitted = text.lstrip("\ufeff \t\r\n").startswith(("{", "[", '"')) + pending = [value] + while pending and not omitted: + child = pending.pop() + if isinstance(child, dict): + pending.extend(child.values()) + elif isinstance(child, list): + pending.extend(child) + elif isinstance(child, str) and _SECRET_KEY.search(child): + omitted = True + if omitted: + value = "[unstructured body omitted]" + return { + "body": value, + "body_sha256": hashlib.sha256(body).hexdigest(), + "retained_bytes": len(body), + "body_omitted": omitted, + "redacted": omitted or _redact(value) != value or text.encode("utf-8") != body, + } + + +def write_runtime_bundle( + directory: Path, + report, + *, + plan=None, + evidence=None, + provider=None, + cleanup=None, + isolation=None, + oracle_http=(), +): + """Write a credential-filtered trace, source/policy/plan provenance and coverage.""" + directory.mkdir(parents=True, exist_ok=True) + files = {} + coverage = { + "requested_runtime_checks": [ + r.check_id for r in report.results if r.check_id.startswith("runtime.") + ], + "executed": [r.check_id for r in report.results if r.status.value != "skip"], + "incomplete": [r.check_id for r in report.results if r.status.value == "skip"], + } + files["coverage.json"] = coverage + files["report.json"] = report.model_dump(mode="json") + files["cleanup.json"] = cleanup or {"required": False} + if plan: + files["runtime-plan.json"] = plan.model_dump(mode="json") + files["run-manifest.json"] = { + "bundle_schema_version": "1", + "json_numbers": "exact integer and decimal tokens; decode with Decimal", + "source_digest": report.source_digest, + "policy_version": report.policy_version, + "manifest_schema_version": report.manifest.manifest_schema_version + if report.manifest + else None, + "plan_digest": hashlib.sha256(plan.model_dump_json().encode()).hexdigest() + if plan + else None, + "plan_redacted": bool( + plan + and _redact(plan.model_dump(mode="json")) != plan.model_dump(mode="json") + ), + "platform": platform.platform(), + "python": platform.python_version(), + "provider": provider or {}, + } + recordings = [("collector", evidence)] + if isolation is not None: + recordings.extend( + [ + ("isolation-sequential", isolation.sequential), + ("isolation-fresh", isolation.fresh), + ] + ) + for session, recording in recordings: + trace_file = f"{session}-trace.json" + trace, metadata = _recording(recording, trace_file) + if metadata is not None: + metadata["session"] = session + if recording.telemetry_json is not None: + try: + telemetry = loads( + recording.telemetry_json, object_pairs_hook=_unique_object + ) + telemetry_file = ( + "session-telemetry.json" + if session == "collector" + else f"{session}-telemetry.json" + ) + files[telemetry_file] = telemetry + metadata["redacted"] |= _redact(telemetry) != telemetry + except (ValueError, ArithmeticError, RecursionError): + metadata["telemetry_error"] = "malformed telemetry omitted" + metadata["redacted"] = True + files[trace_file] = trace + files[f"{session}-evidence.json"] = metadata + probes = [] + for probe in oracle_http: + row = asdict(probe) + row.update(_http_body(row.pop("body"))) + row["redirect_bodies"] = [_http_body(body) for body in row["redirect_bodies"]] + row["redacted"] |= any(body["redacted"] for body in row["redirect_bodies"]) + probes.append(row) + retained_probes = _redact(probes) + # Evaluate modification flags at their actual depth in the saved document. + for original, retained in zip(probes, retained_probes): + retained["redacted"] |= original["body"] != retained["body"] + for before, after in zip( + original["redirect_bodies"], retained["redirect_bodies"] + ): + after["redacted"] |= before["body"] != after["body"] + retained["redacted"] |= after["redacted"] + files["oracle-http.json"] = retained_probes + if evidence: + discovery = {} + omitted = [] + for name in ("tools", "tasks"): + raw = getattr(evidence, name + "_json") + discovery[name + "_available"] = raw is not None + discovery[name + "_error"] = getattr(evidence, name + "_error") + if name == "tools": + discovery["tools_unavailable"] = evidence.tools_unavailable + try: + discovery[name] = ( + loads(raw, object_pairs_hook=_unique_object) + if raw is not None + else None + ) + except (ValueError, ArithmeticError, RecursionError): + discovery[name] = "[malformed evidence omitted]" + omitted.append(name) + discovery["omitted_fields"] = omitted + discovery["redacted"] = bool(omitted) or _redact(discovery) != discovery + files["discovery.json"] = discovery + if evidence and (evidence.replays or evidence.replay_failure_reason): + samples = [] + for replay in evidence.replays: + sample = replay.evidence + row = { + "scope": replay.scope, + "cleanup_complete": replay.cleanup_complete, + "failure_phase": sample.failure_phase, + "failure_reason": sample.failure_reason, + "telemetry_error": sample.telemetry_error, + "telemetry_unavailable": sample.telemetry_unavailable, + "trace": [], + "omitted_trace_fields": [], + "omitted_evidence_fields": [], + } + for index, exchange in enumerate(sample.exchanges): + item = {"operation": exchange.operation} + for key in ("request_json", "response_json"): + try: + item[key] = loads( + getattr(exchange, key), object_pairs_hook=_unique_object + ) + except (ValueError, ArithmeticError, RecursionError): + item[key] = "[malformed response omitted]" + row["omitted_trace_fields"].append( + {"exchange_index": index, "field": key} + ) + row["trace"].append(item) + for key, raw in ( + ("telemetry", sample.telemetry_json), + ("schema", sample.observation_schema_json), + ("reset_schema", sample.reset_observation_schema_json), + ("provider", replay.provider_json), + ): + row[f"{key}_available"] = raw is not None + try: + row[key] = ( + loads(raw, object_pairs_hook=_unique_object) + if raw is not None + else None + ) + except (ValueError, ArithmeticError, RecursionError): + row[key] = "[malformed evidence omitted]" + row["omitted_evidence_fields"].append(key) + row["redacted"] = ( + bool(row["omitted_trace_fields"]) + or bool(row["omitted_evidence_fields"]) + or _redact(row) != row + ) + samples.append(row) + files["replays.json"] = { + "schema_version": "1", + "failure_reason": evidence.replay_failure_reason, + "samples": samples, + } + for name in ( + "runtime-plan.json", + "session-telemetry.json", + "replays.json", + "discovery.json", + ): + if name not in files: + (directory / name).unlink(missing_ok=True) digests = [] for name, value in files.items(): - payload = ( - json.dumps(_redact(value), indent=2, sort_keys=True, allow_nan=False) + "\n" - ).encode() + payload = (dumps(_redact(value)) + "\n").encode() (directory / name).write_bytes(payload) digests.append(f"{hashlib.sha256(payload).hexdigest()} {name}\n") (directory / "SHA256SUMS").write_text("".join(digests)) diff --git a/src/openenv/validation/runtime/collector.py b/src/openenv/validation/runtime/collector.py index 4fd853094f729f8cff46de5cc46962b87e33bcdd..60290ba1599fb1e13a4c322a94d9f821933110e5 100644 --- a/src/openenv/validation/runtime/collector.py +++ b/src/openenv/validation/runtime/collector.py @@ -6,16 +6,29 @@ import time from urllib.parse import urlsplit, urlunsplit import httpx +from websockets.exceptions import ConnectionClosed from websockets.sync.client import connect from ...core.env_server.types import WSErrorCode from .contracts import RuntimeEvidence, RuntimePlan, WireExchange +from .discovery import collect_task_evidence +from .json_values import dumps, loads from .transport import abort_socket, http_deadline MAX_MESSAGE_BYTES = 1024 * 1024 MAX_TRACE_BYTES = 8 * 1024 * 1024 +def _server_error_code(response): + if isinstance(response, dict) and response.get("type") == "error": + data = response.get("data") + code = data.get("code") if isinstance(data, dict) else None + # Only protocol constants are safe diagnostics, never subject error text. + if isinstance(code, str) and code in {item.value for item in WSErrorCode}: + return code + return None + + def _bounded_call(connection, operation, timeout_s): if timeout_s <= 0: raise TimeoutError("episode deadline exceeded") @@ -54,12 +67,25 @@ class RuntimeCollectionInterrupted(KeyboardInterrupt): self.evidence = evidence +class RuntimeCollectionUnsupported(RuntimeError): + """A validator JSON limit carrying the retained collection prefix.""" + + def __init__(self, evidence: RuntimeEvidence, *, capability="json_numeric_range"): + super().__init__(f"{capability}: runtime JSON exceeds validator support") + self.evidence = evidence + + def collect_runtime_evidence( base_url: str, plan: RuntimePlan, *, episode_timeout_s: float, request_timeout_s: float | None = None, + episodes: int = 1, + validation_token: str | None = None, + collect_tools: bool = False, + collect_tasks: bool = False, + request_telemetry: bool = True, ) -> RuntimeEvidence: """ Preserve schema and reset/step/state responses without model coercion. @@ -74,19 +100,40 @@ def collect_runtime_evidence( plan ([`~openenv.validation.runtime.contracts.RuntimePlan`]): Validated, bounded reset and action inputs. episode_timeout_s (`float`): - Deadline for the complete collection, including schema retrieval. + Deadline for each episode. The first episode's budget also covers + schema retrieval and connecting. request_timeout_s (`float`, *optional*): Optional per-operation cap. By default, each operation may use the remaining declared episode budget. + episodes (`int`, *optional*, defaults to `1`): + Run the plan this many times on the same session, resetting between + episodes. Each later episode gets a fresh deadline and trace budget + at its reset, so one episode never spends what another saved and the + collection is bounded by `episodes` single-episode budgets. + validation_token (`str`, *optional*): + Run-scoped credential to omit from evidence; also authorizes optional + telemetry when `request_telemetry` is enabled. + collect_tools (`bool`, *optional*, defaults to `False`): + Discover tools on the measured WebSocket before reset. + collect_tasks (`bool`, *optional*, defaults to `False`): + Discover the server's environment namespace and sample its task metadata. + request_telemetry (`bool`, *optional*, defaults to `True`): + Request session telemetry with the provided authorization. Disable + for scrub-only collection with the ordinary protocol byte limits. Returns: [`~openenv.validation.runtime.contracts.RuntimeEvidence`]: raw evidence. """ deadline = time.monotonic() + episode_timeout_s exchanges = [] - schema_json = reset_schema_json = None + schema_json = reset_schema_json = schema_response_json = None phase = "schema" trace_bytes = 0 + telemetry_json = None + telemetry_error = None + tools_json = tools_error = tasks_json = tasks_error = None + tools_unavailable = None + telemetry_unavailable = None server_code = None def remaining() -> float: @@ -124,23 +171,25 @@ def collect_runtime_evidence( if len(payload) + len(chunk) > MAX_MESSAGE_BYTES: raise ValueError("schema exceeds size bound") payload.extend(chunk) - schema = json.loads(payload) + raw_schema = payload.decode("utf-8") + if not validation_token: + schema_response_json = raw_schema + # Only retain credential-aware schemas after both scans and parsing + # succeed. The raw body can include values lost to duplicate keys. + if validation_token and validation_token in raw_schema: + raise ValueError("schema contains validation credentials") + schema = loads(payload) + if validation_token and validation_token in dumps(schema): + raise ValueError("schema contains validation credentials") + schema_response_json = raw_schema if not isinstance(schema, dict) or "observation" not in schema: raise ValueError("missing observation schema") - schema_json = json.dumps( - schema["observation"], - allow_nan=False, - ensure_ascii=False, - separators=(",", ":"), - ) + schema_payload = dumps(schema["observation"]) + schema_json = schema_payload if "reset_observation" in schema: - reset_schema_json = json.dumps( - schema["reset_observation"], - allow_nan=False, - ensure_ascii=False, - separators=(",", ":"), - ) + reset_schema_payload = dumps(schema["reset_observation"]) + reset_schema_json = reset_schema_payload endpoint = urlsplit(base_url) ws_url = urlunsplit( @@ -158,13 +207,182 @@ def collect_runtime_evidence( proxy=None, open_timeout=remaining(), close_timeout=1, - max_size=MAX_MESSAGE_BYTES, + max_size=( + MAX_TRACE_BYTES + if validation_token and request_telemetry + else MAX_MESSAGE_BYTES + ), max_queue=1, compression=None, ) complete = False try: + def receive_response(request): + nonlocal server_code + try: + _bounded_call( + connection, lambda: connection.send(request), remaining() + ) + except ConnectionClosed: + # Session creation can fail before the first send. recv() still + # delivers a queued error, but the failed send cannot succeed. + try: + raw = connection.recv(timeout=remaining()) + if ( + isinstance(raw, str) + and len(raw.encode()) <= MAX_TRACE_BYTES + ): + server_code = _server_error_code(json.loads(raw)) + except Exception: + # Preserve the original ConnectionClosed if diagnostics fail. + pass + raise + return connection.recv(timeout=remaining()) + + def telemetry_request(operation, data, max_bytes=MAX_TRACE_BYTES): + request = json.dumps({"type": operation, "data": data}) + raw = receive_response(request) + if not isinstance(raw, str) or len(raw.encode()) > max_bytes: + raise ValueError("invalid telemetry response") + response = loads(raw) + if not isinstance(response, dict): + raise ValueError("invalid telemetry envelope") + return response + + capability = None + if validation_token and request_telemetry: + phase = "validation_open" + try: + response = telemetry_request( + phase, {"schema_version": 1, "token": validation_token} + ) + except (ValueError, RecursionError) as exc: + # A consumed malformed reply only invalidates optional telemetry. + # Transport failure still aborts this same-session collection. + telemetry_error = f"session telemetry failed ({type(exc).__name__})" + else: + code = _server_error_code(response) + if code in { + WSErrorCode.FACTORY_ERROR, + WSErrorCode.CAPACITY_REACHED, + WSErrorCode.SESSION_ERROR, + }: + server_code = code + raise ValueError("server returned a terminal error") + data = response.get("data") + if ( + response.get("type") == "validation_open" + and isinstance(data, dict) + and data.get("schema_version") == 1 + and isinstance(data.get("capability"), str) + and 16 <= len(data["capability"]) <= 256 + ): + capability = data["capability"] + elif code == WSErrorCode.UNKNOWN_TYPE: + telemetry_unavailable = ( + "unsupported capability: session_telemetry" + ) + else: + telemetry_error = ( + "session telemetry unavailable or authorization refused" + ) + + def contains_credential(value): + pending = [value] + while pending: + child = pending.pop() + if isinstance(child, str): + if any( + secret and secret in child + for secret in (validation_token, capability) + ): + return True + elif isinstance(child, dict): + pending.extend(child.keys()) + pending.extend(child.values()) + elif isinstance(child, list): + pending.extend(child) + return False + + if collect_tools: + phase = "tools/list" + try: + response = telemetry_request( + "mcp", + { + "jsonrpc": "2.0", + "id": 1, + "method": "tools/list", + "params": {}, + }, + MAX_MESSAGE_BYTES, + ) + if contains_credential(response): + raise ValueError("discovery contains validation credentials") + rpc = response.get("data") + if _server_error_code(response) == WSErrorCode.UNKNOWN_TYPE: + tools_unavailable = "unsupported capability: tool_discovery" + else: + if ( + response.get("type") != "mcp" + or not isinstance(rpc, dict) + or rpc.get("jsonrpc") != "2.0" + or type(rpc.get("id")) is not int + or rpc["id"] != 1 + ): + raise ValueError("invalid tool discovery envelope") + error = rpc.get("error") + if ( + isinstance(error, dict) + and type(error.get("code")) is int + and isinstance(error.get("message"), str) + and rpc.get("result") is None + and ( + error["code"] == -32601 + or ( + # Legacy non-MCP tools/list used INTERNAL_ERROR. + error["code"] == -32603 + and error["message"] + == "Environment does not support MCP" + and error.get("data") is None + ) + ) + ): + tools_unavailable = "unsupported capability: tool_discovery" + else: + if ( + error is not None + or not isinstance(rpc.get("result"), dict) + or not isinstance(rpc["result"].get("tools"), list) + ): + raise ValueError("invalid tool discovery response") + discovered = dumps(rpc["result"], ensure_ascii=False) + if len(discovered.encode()) > MAX_MESSAGE_BYTES: + raise ValueError("discovery exceeds size bound") + tools_json = discovered + except Exception as exc: + tools_error = f"tool discovery failed ({type(exc).__name__})" + + if collect_tasks: + phase = "tasks" + try: + discovered, tasks_error = collect_task_evidence( + base_url, + deadline=deadline, + request_timeout_s=request_timeout_s, + ) + if discovered is not None: + if contains_credential(discovered) or contains_credential( + json.loads(discovered) + ): + raise ValueError( + "discovery contains validation credentials" + ) + tasks_json = discovered + except Exception as exc: + tasks_error = f"task discovery failed ({type(exc).__name__})" + def exchange(operation: str, data: dict | None = None) -> dict: nonlocal phase, trace_bytes, server_code phase = operation @@ -172,17 +390,29 @@ def collect_runtime_evidence( if data is not None: request["data"] = data request_json = json.dumps(request, allow_nan=False) - _bounded_call( - connection, lambda: connection.send(request_json), remaining() - ) - raw = connection.recv(timeout=remaining()) + raw = receive_response(request_json) if not isinstance(raw, str): raise ValueError("binary response is not the JSON protocol") + if len(raw.encode("utf-8")) > MAX_MESSAGE_BYTES: + raise ValueError("response exceeds size bound") trace_bytes += len(raw.encode("utf-8")) + len( request_json.encode("utf-8") ) if trace_bytes > MAX_TRACE_BYTES: - raise ValueError("trace exceeds total size bound") + raise ValueError("episode trace exceeds size bound") + # Subjects can echo the authorization into arbitrary JSON fields. + # Check decoded values as well as raw text (which may be malformed). + if contains_credential(raw): + raise ValueError("response contains validation credentials") + try: + parsed = json.loads(raw) + except (ValueError, RecursionError): + # Malformed JSON cannot be checked for escaped credentials. + if validation_token: + raise + parsed = None + if contains_credential(parsed): + raise ValueError("response contains validation credentials") exchanges.append( WireExchange( operation=operation, @@ -192,14 +422,7 @@ def collect_runtime_evidence( ) response = json.loads(raw) if isinstance(response, dict) and response.get("type") == "error": - data = response.get("data") - code = data.get("code") if isinstance(data, dict) else None - # Only protocol constants are safe diagnostics; never echo an - # arbitrary server message or a subject-defined error code. - if isinstance(code, str) and code in { - item.value for item in WSErrorCode - }: - server_code = code + server_code = _server_error_code(response) raise ValueError("server returned an error") expected = "state" if operation == "state" else "observation" if ( @@ -212,13 +435,35 @@ def collect_runtime_evidence( reset = dict(plan.reset.options) reset.update(seed=plan.reset.seed, episode_id=plan.reset.episode_id) - observation = exchange("reset", reset) - exchange("state") - for action in plan.actions: - if observation.get("done") is True: - break - observation = exchange("step", action) + for episode in range(episodes): + if episode: + deadline = time.monotonic() + episode_timeout_s + trace_bytes = 0 + observation = exchange("reset", reset) exchange("state") + for action in plan.actions: + if observation.get("done") is True: + break + observation = exchange("step", action) + exchange("state") + if capability: + phase = "validation_read" + try: + response = telemetry_request( + phase, {"schema_version": 1, "capability": capability} + ) + if response.get("type") != "validation" or not isinstance( + response.get("data"), dict + ): + raise ValueError("invalid telemetry envelope") + if contains_credential(response["data"]): + raise ValueError("telemetry contains validation credentials") + snapshot = dumps(response["data"], ensure_ascii=False) + if len(snapshot.encode("utf-8")) > MAX_TRACE_BYTES: + raise ValueError("telemetry exceeds size bound") + telemetry_json = snapshot + except Exception as exc: + telemetry_error = f"session telemetry failed ({type(exc).__name__})" complete = True finally: # Teardown is best effort and cannot replace an in-episode failure @@ -239,6 +484,15 @@ def collect_runtime_evidence( return RuntimeEvidence( exchanges=tuple(exchanges), observation_schema_json=schema_json, + schema_response_json=schema_response_json, + telemetry_json=telemetry_json, + telemetry_error=telemetry_error, + tools_json=tools_json, + tools_error=tools_error, + tools_unavailable=tools_unavailable, + tasks_json=tasks_json, + tasks_error=tasks_error, + telemetry_unavailable=telemetry_unavailable, reset_observation_schema_json=reset_schema_json, ) except KeyboardInterrupt: @@ -246,17 +500,58 @@ def collect_runtime_evidence( RuntimeEvidence( exchanges=tuple(exchanges), observation_schema_json=schema_json, + schema_response_json=schema_response_json, reset_observation_schema_json=reset_schema_json, failure_phase=phase, failure_reason=f"{phase} failed (KeyboardInterrupt)", + telemetry_json=telemetry_json, + telemetry_error=telemetry_error, + tools_json=tools_json, + tools_error=tools_error, + tools_unavailable=tools_unavailable, + tasks_json=tasks_json, + tasks_error=tasks_error, + telemetry_unavailable=telemetry_unavailable, ) ) from None + except (ArithmeticError, RecursionError) as exc: + capability = ( + "json_numeric_range" if isinstance(exc, ArithmeticError) else "json_depth" + ) + raise RuntimeCollectionUnsupported( + RuntimeEvidence( + exchanges=tuple(exchanges), + observation_schema_json=schema_json, + reset_observation_schema_json=reset_schema_json, + schema_response_json=schema_response_json, + failure_phase=phase, + failure_reason=f"{phase} JSON exceeds validator support ({capability})", + telemetry_json=telemetry_json, + telemetry_error=telemetry_error, + tools_json=tools_json, + tools_error=tools_error, + tools_unavailable=tools_unavailable, + tasks_json=tasks_json, + tasks_error=tasks_error, + telemetry_unavailable=telemetry_unavailable, + ), + capability=capability, + ) from None except Exception as exc: # Exception text may include submitted payloads or URL credentials. return RuntimeEvidence( exchanges=tuple(exchanges), observation_schema_json=schema_json, + schema_response_json=schema_response_json, reset_observation_schema_json=reset_schema_json, failure_phase=phase, failure_reason=f"{phase} failed ({server_code or type(exc).__name__})", + telemetry_json=telemetry_json, + telemetry_error=telemetry_error, + tools_json=tools_json, + tools_error=tools_error, + tools_unavailable=tools_unavailable, + tasks_json=tasks_json, + tasks_error=tasks_error, + telemetry_unavailable=telemetry_unavailable, ) diff --git a/src/openenv/validation/runtime/contracts.py b/src/openenv/validation/runtime/contracts.py index 8f3e6d97a8d54fe9dfb6c0930535bb53f0c9186a..478ba53ace7ca43bde3fc4e588febd431f0594d3 100644 --- a/src/openenv/validation/runtime/contracts.py +++ b/src/openenv/validation/runtime/contracts.py @@ -4,6 +4,7 @@ import json import math import re from dataclasses import dataclass +from fractions import Fraction from pathlib import Path from typing import Any, Literal @@ -265,15 +266,54 @@ class RuntimeEvidence: Collector phase that failed; a truncated transcript cannot pass silently. failure_reason (`str`, *optional*): Credential-safe explanation of the collection failure. + telemetry_json (`str`, *optional*): + Subject-emitted session snapshot, independent of the wire transcript. + telemetry_error (`str`, *optional*): + Bounded telemetry failure without invalidating completed wire evidence. + tools_json (`str`, *optional*): + Raw tools/list result from the measured WebSocket session. + tools_unavailable (`str`, *optional*): + Named capability absent from a subject that explicitly rejects discovery. + tools_error (`str`, *optional*): + Sanitized tool-discovery failure, distinct from a successful empty list. + tasks_json (`str`, *optional*): + Task split descriptors, counts and bounded item samples. + tasks_error (`str`, *optional*): + Sanitized task-discovery failure, independent of tool discovery. + telemetry_unavailable (`str`, *optional*): + Named capability absent from a subject that explicitly rejects telemetry. reset_observation_schema_json (`str`, *optional*): Explicit `/schema` reset_observation value; absent means use the step schema. + schema_response_json (`str`, *optional*): + Complete bounded `/schema` response, including action, state and reset inputs. """ exchanges: tuple[WireExchange, ...] = () observation_schema_json: str | None = None failure_phase: str | None = None failure_reason: str | None = None + telemetry_json: str | None = None + telemetry_error: str | None = None + telemetry_unavailable: str | None = None + replays: tuple["ReplayEvidence", ...] = () + replay_failure_reason: str | None = None + tools_json: str | None = None + tools_error: str | None = None + tools_unavailable: str | None = None + tasks_json: str | None = None + tasks_error: str | None = None reset_observation_schema_json: str | None = None + schema_response_json: str | None = None + + +@dataclass(frozen=True) +class ReplayEvidence: + """A fresh replay and, for containers, inspected identity and cleanup evidence.""" + + scope: Literal["session", "container", "seed"] + evidence: RuntimeEvidence + provider_json: str | None = None + cleanup_complete: bool | None = None class ProbeOutcome(BaseModel): @@ -320,7 +360,7 @@ class NamespaceEvidence(BaseModel): Attributes: interfaces (`list[str]`): - Interface names in the namespace. + Names of the interfaces that are up in the namespace. default_route (`bool`): Whether an IPv4 default route exists. ipv6_non_loopback (`int`): @@ -361,3 +401,340 @@ class NetworkEvidence(BaseModel): subject_network_mode: str namespace: NamespaceEvidence probes: list[NetworkProbe] + + +class LaunchIsolation(BaseModel): + """ + Isolation settings inspected from outside the subject. + + Attributes: + privileged (`bool`): + Whether the subject runs privileged. + host_namespaces (`list[str]`): + Namespaces shared with the host, e.g. `"pid"` or `"network"`. + cap_add (`list[str]`): + Linux capabilities added to the launch. + devices (`list[str]`): + Host devices passed into the subject. + unconfined (`list[str]`): + Security options that disable a confinement profile. + """ + + model_config = ConfigDict(extra="forbid", frozen=True) + + privileged: bool + host_namespaces: list[str] + cap_add: list[str] + devices: list[str] + unconfined: list[str] + + +class ProcessIdentity(BaseModel): + """ + Identity of one subject process, read from `/proc//status`. + + Attributes: + pid (`int`): + Process ID inside the subject's PID namespace. + name (`str`): + Process name, for diagnostics only. + uids (`list[int]`): + Real, effective, saved and filesystem user IDs. + cap_eff (`int`): + Effective capability bit set. + no_new_privs (`bool`): + Whether the process can gain no new privileges. + seccomp (`int`): + Seccomp mode; `0` means disabled. + """ + + model_config = ConfigDict(extra="forbid", frozen=True) + + pid: int = Field(ge=1) + name: str = Field(max_length=64) + uids: list[int] = Field(min_length=1, max_length=4) + cap_eff: int = Field(ge=0) + no_new_privs: bool + seccomp: int = Field(ge=0) + + +class MountRecord(BaseModel): + """ + One mount in the subject's mount namespace. + + The mounts that are not read-only are the subject's complete writable-filesystem + inventory. + + Attributes: + mount_point (`str`): + Path inside the subject. + fstype (`str`): + Filesystem type. + device (`str`): + `major:minor` of the mounted filesystem; bind mounts of one filesystem + share it. + read_only (`bool`): + Whether the mount or its filesystem is read-only. + size_bytes (`int`, *optional*): + Capacity of the mounted filesystem from `statvfs`. `None` when unknown, + including kernel pseudo-filesystems and unbounded tmpfs, which report no + capacity. + """ + + model_config = ConfigDict(extra="forbid", frozen=True) + + mount_point: str = Field(max_length=4096) + fstype: str = Field(max_length=64) + device: str = Field(pattern=r"^\d+:\d+$") + read_only: bool + size_bytes: int | None = Field(ge=1) + + +class DeviceStorage(BaseModel): + """ + Subject storage access on an otherwise exempt device filesystem. + + Attributes: + complete (`bool`): + Whether all accessible directories and regular files were inventoried. + writable (`bool`): + Whether the subject could create a file or open a regular file for writing. + Positive evidence is retained even when enumeration is incomplete. + """ + + model_config = ConfigDict(extra="forbid", frozen=True) + + complete: bool + writable: bool + + +class ContainmentEvidence(BaseModel): + """ + Provider-neutral evidence for `runtime.host_containment`. + + Attributes: + schema_version (`int`): + Evidence format version. + launch ([`~openenv.validation.runtime.contracts.LaunchIsolation`]): + Settings inspected from outside the subject. + processes (`list[ProcessIdentity]`): + Every process measured in the subject's PID namespace. + mounts (`list[MountRecord]`): + The subject's complete mount table; empty if it could not be read. + allotted (`list[str]`): + Writable roots the provider grants the subject. + allotted_writable (`list[str]`): + Allotted roots the probe could write as the subject's identity. + writable (`list[str]`): + Bounded diagnostic sample of paths outside the allotted roots where + the subject could create a file or open a regular file for writing. + device_storage (`dict[str, DeviceStorage]`): + Bounded directory and regular-file inventories keyed by device identity. + Missing or incomplete inventories cannot establish storage denial. + """ + + model_config = ConfigDict(extra="forbid", frozen=True) + + schema_version: Literal[1] = 1 + launch: LaunchIsolation + processes: list[ProcessIdentity] = Field(max_length=1024) + mounts: list[MountRecord] = Field(max_length=1024) + allotted: list[str] + allotted_writable: list[str] + writable: list[str] = Field(max_length=1024) + device_storage: dict[str, DeviceStorage] = Field( + default_factory=dict, max_length=1024 + ) + + +class CgroupLimits(BaseModel): + """ + Effective cgroup v2 limits read from inside the subject. + + `None` means unlimited unless the field is listed in `unavailable`. + + Attributes: + memory_max (`int`, *optional*): + `memory.max` in bytes. + swap_max (`int`, *optional*): + `memory.swap.max` in bytes. + cpu_quota (`int`, *optional*): + CPU time allowed per period, in microseconds. + cpu_period (`int`): + CPU period in microseconds. + pids_max (`int`, *optional*): + `pids.max`. + unavailable (`list[str]`): + Fields whose cgroup files could not be read independently. + """ + + model_config = ConfigDict(extra="forbid", frozen=True) + + memory_max: int | None = Field(ge=0) + swap_max: int | None = Field(ge=0) + cpu_quota: int | None = Field(ge=0) + cpu_period: int | None = Field(gt=0) + pids_max: int | None = Field(ge=0) + unavailable: list[str] = Field(default_factory=list) + + +class WritableRoot(BaseModel): + """ + Capacity of one writable root, from `statvfs` inside the subject. + + Attributes: + path (`str`): + Path inside the subject. + size_bytes (`int`): + Total capacity of the filesystem mounted there. + """ + + model_config = ConfigDict(extra="forbid", frozen=True) + + path: str + size_bytes: int = Field(ge=0) + + +class QualificationProbe(BaseModel): + """ + One bounded stress probe, run in a disposable subject from the same image. + + Attributes: + kind (`str`): + `"memory"`, `"pids"`, `"disk"` or `"exec_timeout"`. + result (`str`): + `"contained"` when the limit stopped the probe, `"escaped"` when it + exceeded its budget, `"inconclusive"` otherwise. + started (`bool`): + Whether the stimulus emitted its fresh start marker, or a trusted observer + witnessed the exec-timeout stimulus with a live descendant. + reason (`str`, *optional*): + Trusted corroboration of the outcome. + counter_before (`int`, *optional*): + Cgroup event count before the stimulus. + counter_after (`int`, *optional*): + Cgroup event count after the stimulus. + oom_killed (`bool`): + Whether Docker recorded a container OOM kill. + free_bytes_before (`dict[str, int or None]`): + Trusted free capacity before the disk stimulus, per allotted root. + free_bytes (`dict[str, int or None]`): + Trusted free capacity after the disk stimulus, per allotted root. + parent_pid (`int`, *optional*): + Stimulus PID observed by the trusted helper before timeout. + descendant_pid (`int`, *optional*): + Live child whose kernel PPID and nonce-bearing command matched the stimulus. + removed (`bool`): + Whether timeout cleanup independently verified container removal. + """ + + model_config = ConfigDict(extra="forbid", frozen=True) + + kind: Literal["memory", "pids", "disk", "exec_timeout"] + result: Literal["contained", "escaped", "inconclusive"] + started: bool = False + reason: str | None = Field(default=None, max_length=256) + counter_before: int | None = Field(default=None, ge=0) + counter_after: int | None = Field(default=None, ge=0) + oom_killed: bool = False + free_bytes_before: dict[str, int | None] = Field(default_factory=dict) + free_bytes: dict[str, int | None] = Field(default_factory=dict) + parent_pid: int | None = Field(default=None, gt=0) + descendant_pid: int | None = Field(default=None, gt=0) + removed: bool = False + + +class ResourceEvidence(BaseModel): + """ + Provider-neutral evidence for `runtime.resource_bounds`. + + Attributes: + schema_version (`int`): + Evidence format version. + cgroup ([`~openenv.validation.runtime.contracts.CgroupLimits`], *optional*): + Limits measured in the subject; `None` if they could not be read. + writable (`list[WritableRoot]`): + Capacity of every writable root. + qualification (`list[QualificationProbe]`): + Enforcement measured by stress probes. + containment ([`~openenv.validation.runtime.contracts.ContainmentEvidence`], *optional*): + Complete filesystem inventory and write controls for storage accounting. + """ + + model_config = ConfigDict(extra="forbid", frozen=True) + + schema_version: Literal[1] = 1 + cgroup: CgroupLimits | None + writable: list[WritableRoot] + qualification: list[QualificationProbe] + containment: ContainmentEvidence | None = None + + +@dataclass(frozen=True) +class IsolationEvidence: + """ + Raw evidence for `runtime.episode_isolation`, collected on the running subject. + + Attributes: + sequential ([`~openenv.validation.runtime.contracts.RuntimeEvidence`]): + The plan run twice on one session: episode A, then a reset into B. + fresh ([`~openenv.validation.runtime.contracts.RuntimeEvidence`]): + The plan run once on a new session, as the reference for B. + """ + + sequential: RuntimeEvidence + fresh: RuntimeEvidence + + +@dataclass(frozen=True) +class OracleEvidence: + """ + Rewards for the Level 3 checks, measured by the execution binding. + + The binding runs every episode in a fresh subject from one immutable image and + selects the graded reward. Values are exact rationals parsed from the raw + verifier output. + + Attributes: + floor (`Fraction`): + Reward of the do-nothing episode. + oracle (`tuple[Fraction, ...]`): + Reward of each oracle run, in run order. + oracle_exit_codes (`tuple[int, ...]`): + Exit code of each oracle run, in run order. + canaries (`tuple[tuple[str, Fraction], ...]`, *optional*): + Name and reward of each declared canary run. + """ + + floor: Fraction + oracle: tuple[Fraction, ...] + oracle_exit_codes: tuple[int, ...] + canaries: tuple[tuple[str, Fraction], ...] = () + + +@dataclass(frozen=True) +class HttpProbe: + """ + One bounded HTTP GET against the subject's control endpoint. + + Attributes: + path (`str`): + Requested path. + status (`int`, *optional*): + Status of the last response, after same-origin redirects; `None` when no + response arrived. + body (`bytes`): + Bounded body of the final response, whatever its status. + failure (`str`, *optional*): + Why the probe is incomplete: a transport error, the deadline, a compressed + or oversized body, or a redirect that was not followed. + redirect_bodies (`tuple[bytes, ...]`): + Prior redirect response bodies, each retained separately for JSON decoding. + All bodies share the probe byte budget. + """ + + path: str + status: int | None + body: bytes = b"" + failure: str | None = None + redirect_bodies: tuple[bytes, ...] = () diff --git a/src/openenv/validation/runtime/discovery.py b/src/openenv/validation/runtime/discovery.py new file mode 100644 index 0000000000000000000000000000000000000000..0b792e07bf09c6554ca6621d4539958791321aa7 --- /dev/null +++ b/src/openenv/validation/runtime/discovery.py @@ -0,0 +1,128 @@ +"""Bounded task metadata sampling through the production task API.""" + +import json +import time +from urllib.parse import quote + +import httpx + +from .transport import http_deadline + +MAX_TASK_SPLITS = 64 +MAX_RESPONSE_BYTES = 1024 * 1024 +MAX_DISCOVERY_BYTES = 8 * 1024 * 1024 + + +def collect_task_evidence(base_url, *, deadline, request_timeout_s=None): + """Return raw counts and at most two task specs per split, never a full listing. + + ``deadline`` is the collector's absolute monotonic episode deadline. Optional + ``request_timeout_s`` may further cap each request. Errors are sanitized; + a failed/unsupported endpoint never becomes an empty success. + Task metadata routes intentionally use independent environment instances. + """ + total_bytes = 0 + + def remaining(): + budget = deadline - time.monotonic() + if request_timeout_s is not None: + budget = min(request_timeout_s, budget) + if budget <= 0: + raise TimeoutError("task discovery deadline exceeded") + return budget + + try: + prefix = base_url.rstrip("/") + with httpx.Client( + trust_env=False, + follow_redirects=False, + limits=httpx.Limits(max_keepalive_connections=0), + ) as client: + + def request(method, route, payload=None): + nonlocal total_bytes + # Each request opens a transport for its deadline watchdog; + # pooled connections do not emit the connection trace event. + with ( + http_deadline(remaining()) as extensions, + client.stream( + method, + prefix + route, + json=payload, + timeout=remaining(), + headers={"Accept-Encoding": "identity"}, + extensions=extensions, + ) as response, + ): + response.raise_for_status() + if ( + response.headers.get("Content-Encoding", "identity") + .strip() + .lower() + != "identity" + ): + raise ValueError("compressed discovery response") + body = bytearray() + for chunk in response.iter_bytes(): + remaining() + total_bytes += len(chunk) + if ( + len(body) + len(chunk) > MAX_RESPONSE_BYTES + or total_bytes > MAX_DISCOVERY_BYTES + ): + raise ValueError("task discovery exceeds byte budget") + body.extend(chunk) + return json.loads(body) + + environments = request("GET", "/list_environments") + if ( + not isinstance(environments, list) + or len(environments) != 1 + or not isinstance(environments[0], str) + or not environments[0] + or environments[0] in {".", ".."} + or "/" in environments[0] + or "\\" in environments[0] + ): + raise ValueError("expected one valid task environment namespace") + prefix += "/" + quote(environments[0], safe="") + splits = request("GET", "/splits") + if not isinstance(splits, list) or len(splits) > MAX_TASK_SPLITS: + raise ValueError("invalid or excessive splits") + counts, previews = {}, {} + for split in splits: + name = split["name"] + if not isinstance(name, str) or not name or name in counts: + raise ValueError("invalid or duplicate split name") + count = request("POST", "/num_tasks", {"split": name})["num_tasks"] + if type(count) is not int or count < 0: + raise ValueError("invalid task count") + counts[name] = count + previews[name] = [ + request("POST", "/task", {"split": name, "index": index})["task"] + for index in range(min(2, count)) + ] + discovered = json.dumps( + { + "environments": environments, + "splits": splits, + "counts": counts, + "previews": previews, + }, + allow_nan=False, + ensure_ascii=False, + separators=(",", ":"), + ) + if len(discovered.encode()) > MAX_DISCOVERY_BYTES: + raise ValueError("task evidence exceeds byte budget") + return discovered, None + except ( + httpx.HTTPError, + httpx.InvalidURL, + OSError, + ValueError, + TypeError, + KeyError, + RecursionError, + ) as error: + return None, f"task discovery failed ({type(error).__name__})" diff --git a/src/openenv/validation/runtime/json_values.py b/src/openenv/validation/runtime/json_values.py new file mode 100644 index 0000000000000000000000000000000000000000..8881ff19d874fa8106f8bd6c3ffd4cdab5c309c9 --- /dev/null +++ b/src/openenv/validation/runtime/json_values.py @@ -0,0 +1,75 @@ +"""Exact JSON values for byte-bounded runtime documents and redacted bundles.""" + +import json +from decimal import Decimal + + +def loads(text, *, object_pairs_hook=None): + # Match the stdlib's BOM handling for bytes after UTF-8 text retention. + if isinstance(text, str): + text = text.removeprefix("\ufeff") + return json.loads( + text, + parse_float=Decimal, + parse_constant=Decimal, + object_pairs_hook=object_pairs_hook, + ) + + +def typed_json(value): + """Flatten values so traversal and equality do not recurse through containers.""" + result, pending = [], [value] + while pending: + child = pending.pop() + if isinstance(child, dict): + result.append((dict, len(child))) + for key in sorted(child, reverse=True): + pending.extend((child[key], key)) + elif isinstance(child, list): + result.append((list, len(child))) + pending.extend(reversed(child)) + else: + if isinstance(child, Decimal) and not child.is_finite(): + raise ValueError("non-finite JSON constant") + result.append((type(child), child)) + return tuple(result) + + +def dumps(value, *, ensure_ascii=True): + """Serialize exact JSON numbers without recursing through containers.""" + chunks, pending = [], [(False, value)] + while pending: + literal, child = pending.pop() + if literal: + chunks.append(child) + elif isinstance(child, dict): + chunks.append("{") + pending.append((True, "}")) + for index, key in reversed(list(enumerate(sorted(child)))): + pending.extend( + [ + (False, child[key]), + (True, ":"), + (True, json.dumps(key, ensure_ascii=ensure_ascii)), + ] + ) + if index: + pending.append((True, ",")) + elif isinstance(child, list): + chunks.append("[") + pending.append((True, "]")) + for index, item in reversed(list(enumerate(child))): + pending.append((False, item)) + if index: + pending.append((True, ",")) + elif isinstance(child, Decimal): + if not child.is_finite(): + raise ValueError("non-finite JSON constant") + number = str(child) + # Decimal('1') came from a decimal/exponent token, never an integer. + chunks.append( + number if "." in number or "e" in number.lower() else number + ".0" + ) + else: + chunks.append(json.dumps(child, allow_nan=False, ensure_ascii=ensure_ascii)) + return "".join(chunks) diff --git a/src/openenv/validation/runtime/replay.py b/src/openenv/validation/runtime/replay.py new file mode 100644 index 0000000000000000000000000000000000000000..8298dee07213ef07a3ffb7f56ef2f48318729fa0 --- /dev/null +++ b/src/openenv/validation/runtime/replay.py @@ -0,0 +1,239 @@ +"""Bounded fresh-session and independently verified fresh-container experiments.""" + +import json +import secrets +import time +import uuid +from dataclasses import replace + +from ..types import ProviderCapability +from .collector import ( + collect_runtime_evidence, + RuntimeCollectionInterrupted, + RuntimeCollectionUnsupported, +) +from .contracts import ReplayEvidence, RuntimeEvidence + +REPLAY_BUDGET_SECONDS = 300.0 +MAX_REPLAY_BYTES = 32 * 1024 * 1024 +JUDGED_REPLAYS = 20 + + +def _evidence_bytes(evidence): + return sum( + len(value.encode("utf-8")) + for value in ( + evidence.observation_schema_json or "", + evidence.reset_observation_schema_json or "", + evidence.schema_response_json or "", + evidence.telemetry_json or "", + evidence.tools_json or "", + evidence.tasks_json or "", + *( + value + for row in evidence.exchanges + for value in (row.request_json, row.response_json) + ), + ) + ) + + +def collect_replays( + provider, running, spec, plan, evidence, *, capabilities, deadline=None +): + """ + Collect the fixed replay schedule without replacing the primary transcript. + + Args: + provider (`ValidationProvider`): + Provider used for the original subject and optional fresh container. + running (`RunningSubject`): + The original subject; its lifetime remains owned by the caller. + spec (`LaunchSpec`): + Original immutable image, resource limits and explicit authorization. + plan (`RuntimePlan`): + Fixed episode identity, seed, options and public action sequence. + evidence (`RuntimeEvidence`): + Independently collected primary episode. + capabilities (`CapabilitiesSpec`): + Manifest capabilities; judged rewards require 20 identical-input samples. + deadline (`float`, *optional*): + Absolute monotonic deadline for the remaining baseline-and-replay + budget, excluding intervening independent probes. Defaults to 300 + seconds from this call; every replay collection and launch shares it. + + Returns: + `RuntimeEvidence`: the original episode plus immutable replay evidence. + """ + retained_bytes = _evidence_bytes(evidence) + budget_failure = f"total retained replay evidence exceeds {MAX_REPLAY_BYTES} bytes" + if retained_bytes > MAX_REPLAY_BYTES: + # Normal collector bounds keep a primary episode below this limit. A + # malformed oversized input must not bypass the final artifact budget. + return RuntimeEvidence( + failure_phase="replay evidence budget", + failure_reason=budget_failure, + replay_failure_reason=budget_failure, + ) + if evidence.failure_reason: + return evidence + deadline = min( + deadline if deadline is not None else float("inf"), + time.monotonic() + REPLAY_BUDGET_SECONDS, + ) + replays = [] + phase = "fresh session" + failure = None + + def remaining(): + budget = deadline - time.monotonic() + if budget <= 0: + raise TimeoutError("total replay deadline exceeded") + return budget + + def collect(target, reset_plan, token): + return collect_runtime_evidence( + target.base_url, + reset_plan, + episode_timeout_s=min(spec.resources.episode_timeout_s, remaining()), + validation_token=token, + ) + + def retain(scope, sample, **metadata): + nonlocal retained_bytes, failure + size = _evidence_bytes(sample) + if retained_bytes + size > MAX_REPLAY_BYTES: + failure = budget_failure + if scope == "container": + # Keep inspected identity and cleanup even when the transcript + # cannot be retained. An empty sample cannot pass determinism. + replays.append(ReplayEvidence(scope, RuntimeEvidence(), **metadata)) + return False + retained_bytes += size + replays.append(ReplayEvidence(scope, sample, **metadata)) + return True + + def session(scope, reset_plan): + try: + sample = collect( + running, reset_plan, spec.env_vars.get("OPENENV_VALIDATION_TOKEN") + ) + except (RuntimeCollectionInterrupted, RuntimeCollectionUnsupported) as exc: + retain(scope, exc.evidence) + raise + if not retain(scope, sample): + raise ValueError("replay evidence byte budget exceeded") + if sample.failure_reason: + raise RuntimeError("replay collection failed") + + try: + session("session", plan) + phase = "different-seed session" + changed_seed = plan.reset.model_copy( + update={"seed": (plan.reset.seed + 1) % 2**32} + ) + session("seed", plan.model_copy(update={"reset": changed_seed})) + if ProviderCapability.FRESH_CONTAINER not in provider.capabilities: + failure = "missing provider capability: fresh_container" + else: + phase = "original container inspection" + remaining() + original = running.inspect() + if ( + not isinstance(original.get("container_id"), str) + or not original["container_id"] + or original.get("image_id") != spec.image_ref + ): + raise ValueError("original container identity unavailable") + phase = "fresh container start" + fresh_spec = spec.model_copy( + update={ + "run_id": "validation-replay-" + uuid.uuid4().hex, + "startup_timeout_s": min(spec.startup_timeout_s, remaining()), + "env_vars": { + **spec.env_vars, + "OPENENV_VALIDATION_TOKEN": secrets.token_urlsafe(32), + }, + } + ) + try: + fresh = provider.start(fresh_spec) + except (Exception, KeyboardInterrupt): + # No returned handle means this layer cannot verify teardown, + # including when the provider's startup cleanup itself failed. + retain( + "container", + RuntimeEvidence( + failure_phase=phase, + failure_reason="fresh container start failed; teardown could not be confirmed", + ), + cleanup_complete=False, + ) + raise + inspection_json = None + sample = None + cleanup = False + try: + phase = "fresh container inspection" + remaining() + inspection = fresh.inspect() + inspection_json = json.dumps(inspection, allow_nan=False) + if ( + not isinstance(inspection.get("container_id"), str) + or not inspection["container_id"] + or inspection["container_id"] == original["container_id"] + or inspection.get("image_id") != spec.image_ref + ): + raise ValueError("fresh container identity did not match") + phase = "fresh container replay" + sample = collect( + fresh, plan, fresh_spec.env_vars["OPENENV_VALIDATION_TOKEN"] + ) + except (RuntimeCollectionInterrupted, RuntimeCollectionUnsupported) as exc: + sample = exc.evidence + raise + finally: + cleanup_interrupted = False + try: + fresh.stop() + cleanup = True + except KeyboardInterrupt: + cleanup_interrupted = True + failure = "fresh container cleanup interrupted" + except Exception: + failure = "fresh container cleanup failed" + if sample is None: + sample = RuntimeEvidence( + failure_phase=phase, failure_reason=f"{phase} did not complete" + ) + retained = retain( + "container", + sample, + provider_json=inspection_json, + cleanup_complete=cleanup, + ) + if cleanup_interrupted: + raise KeyboardInterrupt + if not cleanup: + raise RuntimeError("fresh container cleanup failed") + if not retained: + raise ValueError("replay evidence byte budget exceeded") + if sample.failure_reason: + raise RuntimeError("fresh container replay failed") + phase = "judged replay sampling" + if capabilities.llm_judged: + # Primary + session + container are already three identical inputs. + for _ in range(JUDGED_REPLAYS - 3): + session("session", plan) + except KeyboardInterrupt: + interrupted = replace( + evidence, + replays=tuple(replays), + replay_failure_reason=failure or f"{phase} interrupted", + ) + raise RuntimeCollectionInterrupted(interrupted) from None + except RuntimeCollectionUnsupported as exc: + failure = failure or f"{phase} unsupported ({exc})" + except Exception as exc: + failure = failure or f"{phase} failed ({type(exc).__name__})" + return replace(evidence, replays=tuple(replays), replay_failure_reason=failure) diff --git a/src/openenv/validation/runtime/scheduler.py b/src/openenv/validation/runtime/scheduler.py index 7f9cfb39acbf960bd6ff01ec59cd02e4379d8f55..5fb879927c3a7a3cfd95d6122deb64f8afd66b72 100644 --- a/src/openenv/validation/runtime/scheduler.py +++ b/src/openenv/validation/runtime/scheduler.py @@ -24,8 +24,7 @@ def order_graders(graders: list) -> list: def execute_graders(graders, subject, *, provider_capabilities=frozenset(), prior=()): - """Run independent checks despite failures, and name unmet dependencies in SKIPs.""" - results = [] + """Yield completed checks despite failures, and name unmet dependencies in SKIPs.""" outcomes = {result.check_id: result for result in prior} for grader in order_graders(graders): blocked = [ @@ -66,5 +65,4 @@ def execute_graders(graders, subject, *, provider_capabilities=frozenset(), prio duration_s=time.monotonic() - started, ) outcomes[grader.check_id] = result - results.append(result) - return results + yield result diff --git a/src/openenv/validation/schemas/manifest-v2.schema.json b/src/openenv/validation/schemas/manifest-v2.schema.json index 93525bff6eb6558a3caf8c0e482b35fa3359d3ca..541b5d8c0a663b10239b82ac17ed6221324f2f12 100644 --- a/src/openenv/validation/schemas/manifest-v2.schema.json +++ b/src/openenv/validation/schemas/manifest-v2.schema.json @@ -111,6 +111,45 @@ "title": "ExecutionDeclaration", "type": "object" }, + "HarborExecutionDeclaration": { + "additionalProperties": false, + "description": "Native process execution of a Harbor task through fresh Docker trials.", + "properties": { + "agent_boundary": { + "const": "process", + "default": "process", + "title": "Agent Boundary", + "type": "string" + }, + "contract_path": { + "const": "validation/openenv.json", + "default": "validation/openenv.json", + "title": "Contract Path", + "type": "string" + }, + "kind": { + "const": "harbor_task", + "title": "Kind", + "type": "string" + }, + "profile": { + "const": "harbor-semantic-v1", + "default": "harbor-semantic-v1", + "title": "Profile", + "type": "string" + }, + "requires_credentials": { + "default": false, + "title": "Requires Credentials", + "type": "boolean" + } + }, + "required": [ + "kind" + ], + "title": "HarborExecutionDeclaration", + "type": "object" + }, "JudgePin": { "additionalProperties": false, "description": "Pinned judge configuration. Required iff `capabilities.llm_judged`.\n\nThe pin lives in the manifest, not the rubric object: `LLMJudge.state_dict()` does\nnot serialize model/version/params, so validation checks the declared pin.", @@ -234,7 +273,7 @@ }, "RewardDeclaration": { "additionalProperties": false, - "description": "Author-declared reward contract. Graders normalize measurements against it.\n\nDeclared tolerances are bounded by the severity policy; reports carry the declared\nvalues so hubs can apply stricter ceilings.\n\nAttributes:\n range (`tuple[float, float]`):\n Declared reward range, defaults to `(0.0, 1.0)`. Must be strictly increasing.\n oracle_tolerance (`float`):\n The oracle check passes when `reward(oracle) >= max - oracle_tolerance`.\n floor_margin (`float`):\n The gap check requires `max - measured_floor >= floor_margin`.\n variance_tolerance (`float`, *optional*):\n Required iff the environment declares `llm_judged`; bounds reward variance\n for variance-mode determinism checks.", + "description": "Author-declared reward contract. Graders normalize measurements against it.\n\nDeclared tolerances are bounded by the severity policy; reports carry the declared\nvalues so hubs can apply stricter ceilings.\n\nAttributes:\n range (`tuple[float, float]`):\n Declared reward range, defaults to `(0.0, 1.0)`. Must be strictly increasing.\n oracle_tolerance (`float`):\n Fraction of the declared range allowed below the maximum.\n The oracle check requires `reward(oracle) >= max - oracle_tolerance * width`,\n where `width = max - min`.\n floor_margin (`float`):\n Fraction of the declared range required below the maximum and every oracle.\n Both `max - measured_floor` and `reward(oracle) - measured_floor` must be\n at least `floor_margin * width`.\n variance_tolerance (`float`, *optional*):\n Required iff the environment declares `llm_judged`; bounds reward variance\n for variance-mode determinism checks.", "properties": { "floor_margin": { "minimum": 0.0, @@ -398,7 +437,15 @@ "$ref": "#/$defs/CapabilitiesSpec" }, "execution": { - "$ref": "#/$defs/ExecutionDeclaration" + "anyOf": [ + { + "$ref": "#/$defs/ExecutionDeclaration" + }, + { + "$ref": "#/$defs/HarborExecutionDeclaration" + } + ], + "title": "Execution" }, "judge": { "anyOf": [ diff --git a/src/openenv/validation/schemas/manifest.schema.json b/src/openenv/validation/schemas/manifest.schema.json index d91a469c9655bf835446019da2689892d4e733fc..1c342e0342b9de9b4ec67d00fa46c0ab8bc50192 100644 --- a/src/openenv/validation/schemas/manifest.schema.json +++ b/src/openenv/validation/schemas/manifest.schema.json @@ -194,7 +194,7 @@ }, "RewardDeclaration": { "additionalProperties": false, - "description": "Author-declared reward contract. Graders normalize measurements against it.\n\nDeclared tolerances are bounded by the severity policy; reports carry the declared\nvalues so hubs can apply stricter ceilings.\n\nAttributes:\n range (`tuple[float, float]`):\n Declared reward range, defaults to `(0.0, 1.0)`. Must be strictly increasing.\n oracle_tolerance (`float`):\n The oracle check passes when `reward(oracle) >= max - oracle_tolerance`.\n floor_margin (`float`):\n The gap check requires `max - measured_floor >= floor_margin`.\n variance_tolerance (`float`, *optional*):\n Required iff the environment declares `llm_judged`; bounds reward variance\n for variance-mode determinism checks.", + "description": "Author-declared reward contract. Graders normalize measurements against it.\n\nDeclared tolerances are bounded by the severity policy; reports carry the declared\nvalues so hubs can apply stricter ceilings.\n\nAttributes:\n range (`tuple[float, float]`):\n Declared reward range, defaults to `(0.0, 1.0)`. Must be strictly increasing.\n oracle_tolerance (`float`):\n Fraction of the declared range allowed below the maximum.\n The oracle check requires `reward(oracle) >= max - oracle_tolerance * width`,\n where `width = max - min`.\n floor_margin (`float`):\n Fraction of the declared range required below the maximum and every oracle.\n Both `max - measured_floor` and `reward(oracle) - measured_floor` must be\n at least `floor_margin * width`.\n variance_tolerance (`float`, *optional*):\n Required iff the environment declares `llm_judged`; bounds reward variance\n for variance-mode determinism checks.", "properties": { "floor_margin": { "minimum": 0.0, diff --git a/src/openenv/validation/schemas/report-v2.schema.json b/src/openenv/validation/schemas/report-v2.schema.json index 4f4d16e311c9b83beca040bad5e30e0a30bd59b9..9da03461a2e8a16aaff6cf6436e6a1c3857551b4 100644 --- a/src/openenv/validation/schemas/report-v2.schema.json +++ b/src/openenv/validation/schemas/report-v2.schema.json @@ -172,6 +172,45 @@ "title": "ExecutionDeclaration", "type": "object" }, + "HarborExecutionDeclaration": { + "additionalProperties": false, + "description": "Native process execution of a Harbor task through fresh Docker trials.", + "properties": { + "agent_boundary": { + "const": "process", + "default": "process", + "title": "Agent Boundary", + "type": "string" + }, + "contract_path": { + "const": "validation/openenv.json", + "default": "validation/openenv.json", + "title": "Contract Path", + "type": "string" + }, + "kind": { + "const": "harbor_task", + "title": "Kind", + "type": "string" + }, + "profile": { + "const": "harbor-semantic-v1", + "default": "harbor-semantic-v1", + "title": "Profile", + "type": "string" + }, + "requires_credentials": { + "default": false, + "title": "Requires Credentials", + "type": "boolean" + } + }, + "required": [ + "kind" + ], + "title": "HarborExecutionDeclaration", + "type": "object" + }, "JudgePin": { "additionalProperties": false, "description": "Pinned judge configuration. Required iff `capabilities.llm_judged`.\n\nThe pin lives in the manifest, not the rubric object: `LLMJudge.state_dict()` does\nnot serialize model/version/params, so validation checks the declared pin.", @@ -328,7 +367,15 @@ "$ref": "#/$defs/CapabilitiesSpec" }, "execution": { - "$ref": "#/$defs/ExecutionDeclaration" + "anyOf": [ + { + "$ref": "#/$defs/ExecutionDeclaration" + }, + { + "$ref": "#/$defs/HarborExecutionDeclaration" + } + ], + "title": "Execution" }, "judge": { "anyOf": [ @@ -475,7 +522,7 @@ }, "RewardDeclaration": { "additionalProperties": false, - "description": "Author-declared reward contract. Graders normalize measurements against it.\n\nDeclared tolerances are bounded by the severity policy; reports carry the declared\nvalues so hubs can apply stricter ceilings.\n\nAttributes:\n range (`tuple[float, float]`):\n Declared reward range, defaults to `(0.0, 1.0)`. Must be strictly increasing.\n oracle_tolerance (`float`):\n The oracle check passes when `reward(oracle) >= max - oracle_tolerance`.\n floor_margin (`float`):\n The gap check requires `max - measured_floor >= floor_margin`.\n variance_tolerance (`float`, *optional*):\n Required iff the environment declares `llm_judged`; bounds reward variance\n for variance-mode determinism checks.", + "description": "Author-declared reward contract. Graders normalize measurements against it.\n\nDeclared tolerances are bounded by the severity policy; reports carry the declared\nvalues so hubs can apply stricter ceilings.\n\nAttributes:\n range (`tuple[float, float]`):\n Declared reward range, defaults to `(0.0, 1.0)`. Must be strictly increasing.\n oracle_tolerance (`float`):\n Fraction of the declared range allowed below the maximum.\n The oracle check requires `reward(oracle) >= max - oracle_tolerance * width`,\n where `width = max - min`.\n floor_margin (`float`):\n Fraction of the declared range required below the maximum and every oracle.\n Both `max - measured_floor` and `reward(oracle) - measured_floor` must be\n at least `floor_margin * width`.\n variance_tolerance (`float`, *optional*):\n Required iff the environment declares `llm_judged`; bounds reward variance\n for variance-mode determinism checks.", "properties": { "floor_margin": { "minimum": 0.0, diff --git a/src/openenv/validation/schemas/report.schema.json b/src/openenv/validation/schemas/report.schema.json index 104c69bd0609c8e00f46a8cab49efa3431211650..ca908b59d9394abbfeab283d38cb21980776df96 100644 --- a/src/openenv/validation/schemas/report.schema.json +++ b/src/openenv/validation/schemas/report.schema.json @@ -353,7 +353,7 @@ }, "RewardDeclaration": { "additionalProperties": false, - "description": "Author-declared reward contract. Graders normalize measurements against it.\n\nDeclared tolerances are bounded by the severity policy; reports carry the declared\nvalues so hubs can apply stricter ceilings.\n\nAttributes:\n range (`tuple[float, float]`):\n Declared reward range, defaults to `(0.0, 1.0)`. Must be strictly increasing.\n oracle_tolerance (`float`):\n The oracle check passes when `reward(oracle) >= max - oracle_tolerance`.\n floor_margin (`float`):\n The gap check requires `max - measured_floor >= floor_margin`.\n variance_tolerance (`float`, *optional*):\n Required iff the environment declares `llm_judged`; bounds reward variance\n for variance-mode determinism checks.", + "description": "Author-declared reward contract. Graders normalize measurements against it.\n\nDeclared tolerances are bounded by the severity policy; reports carry the declared\nvalues so hubs can apply stricter ceilings.\n\nAttributes:\n range (`tuple[float, float]`):\n Declared reward range, defaults to `(0.0, 1.0)`. Must be strictly increasing.\n oracle_tolerance (`float`):\n Fraction of the declared range allowed below the maximum.\n The oracle check requires `reward(oracle) >= max - oracle_tolerance * width`,\n where `width = max - min`.\n floor_margin (`float`):\n Fraction of the declared range required below the maximum and every oracle.\n Both `max - measured_floor` and `reward(oracle) - measured_floor` must be\n at least `floor_margin * width`.\n variance_tolerance (`float`, *optional*):\n Required iff the environment declares `llm_judged`; bounds reward variance\n for variance-mode determinism checks.", "properties": { "floor_margin": { "minimum": 0.0, diff --git a/src/openenv/validation/signature.py b/src/openenv/validation/signature.py index d6b9c6d15a125fb244ab2ccbc1ac8182294aea4b..80312ae5953118990a0db078faee4dad1700815e 100644 --- a/src/openenv/validation/signature.py +++ b/src/openenv/validation/signature.py @@ -6,6 +6,7 @@ from .types import SignatureKind WELL_KNOWN_FILES: dict[SignatureKind, str] = { SignatureKind.OPENENV_SERVED: "openenv.yaml", + SignatureKind.HARBOR_TASK: "task.toml", } """Formats this build can parse. Values are the enum filenames.""" diff --git a/src/openenv/validation/types.py b/src/openenv/validation/types.py index bb775596f108d79e97cfa744b4afd9db43db5ac3..0cbf0fd8e7fe3ee2f38a263ab605c8485dc73bfc 100644 --- a/src/openenv/validation/types.py +++ b/src/openenv/validation/types.py @@ -82,7 +82,10 @@ class ProviderCapability(str, Enum): """Capabilities a validation provider may declare; graders require them by name.""" NETWORK_POLICY = "network_policy" + INSPECTED_ISOLATION = "inspected_isolation" + RESOURCE_ENFORCEMENT = "resource_enforcement" EXEC = "exec" IMAGE_BUILD = "image_build" GPU = "gpu" REMOTE = "remote" + FRESH_CONTAINER = "fresh_container"