diff --git a/.github/workflows/security.yml b/.github/workflows/security.yml index a6135f92..c8ac90c2 100644 --- a/.github/workflows/security.yml +++ b/.github/workflows/security.yml @@ -46,3 +46,10 @@ jobs: --no-deps \ --disable-pip \ --progress-spinner off + # The sandbox image's hashed mcp-server-fetch venv. A separate call: pip-audit + # refuses to mix a hashed requirements file with an unhashed one. + uvx pip-audit \ + --requirement benchmarks/sandbox/fetch-requirements.txt \ + --no-deps \ + --disable-pip \ + --progress-spinner off diff --git a/CHANGELOG.md b/CHANGELOG.md index 301b1ece..303a596c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,9 +14,26 @@ this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.htm worker processes. CI runs it end to end with scripted models and no network. The provider SDKs join the `dev` dependency group at exact pins: `anthropic` 1.15.0, `openai` 3.32.0 and `google-genai` 2.31.0. +- Benchmark sandbox (development tooling, not part of the package): + `benchmarks/sandbox/` builds a hardened worker container and runs each + (model, system) job in its own container behind its own logging Squid egress + proxy, after a keyless isolation probe. +- `agentic-run --launcher container`, a dry run by default, with `--live`, one + authorization gate (refused under `CI`, then an interactive confirmation of + each provider's spend, cap and estimate) and `--reference-run` for the + full-run gate. +- The Ollama client for the benchmark's air-gapped arm, with host offline checks + around every trajectory. +- The "Air-gapped install" README section. ### Changed +- The benchmark's `docs-fetch` and `python-docs` systems reach the network only + through the run's egress proxy. +- Benchmark keys reach a worker only as a bootstrap frame on its stdin, never + through a container's environment, `--env-file` or argv. This is a recorded + departure from the agentic design §7.3. + - The benchmark harness (development tooling, not part of the package) now reports success latency and failed-cell latency separately, lists manifest exclusions, keeps the real reason when a cell fails inside MCP task groups, @@ -37,6 +54,12 @@ this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.htm ### Security +- The Security workflow's dependency audit also covers + `benchmarks/sandbox/fetch-requirements.txt`, the hashed `mcp-server-fetch` + 2026.10.19 environment of the benchmark sandbox image. +- The benchmark sandbox never follows a link in a proxy's world-writable log + directory: logs are read with `O_NOFOLLOW` and only as regular files, and the + host writes there only through new files renamed over the name. - Updated locked Pydantic (2.14.2, pydantic-core 2.50.2, with the typing-extensions 4.16.0 and typing-inspection 0.4.4 it requires) and Platformdirs (4.14.0). Pydantic 2.14.2 fixes four validation advisories diff --git a/README.md b/README.md index a05e8bad..5bb03d7d 100644 --- a/README.md +++ b/README.md @@ -306,6 +306,42 @@ docs index, older entries are ignored automatically. Deleting `retrieved-docs-cache.sqlite3` is safe; it removes cached retrieval results, not the docs index. +## Air-gapped install + +The server needs no network at query time. To install it on a machine with no +network: + +1. On a connected machine with the same OS, CPU architecture and Python minor + version, download the wheels and build the index. Elsewhere, add pip's + `--platform`, `--python-version` and `--only-binary=:all:` options to + `pip download`. + + ```bash + pip download python-docs-mcp-server== -d wheels/ + pip install python-docs-mcp-server== + python-docs-mcp-server build-index --versions 3.10,3.11,3.12,3.13,3.14 + ``` + +2. Copy `wheels/` and the built `index.db` to the target machine. +3. On the target, install from the copied wheels only: + + ```bash + pip install --no-index --find-links wheels/ python-docs-mcp-server== + ``` + +4. Put `index.db` at `~/Library/Caches/mcp-python-docs/index.db` on macOS, or + at `~/.cache/mcp-python-docs/index.db` on Linux + (`$XDG_CACHE_HOME/mcp-python-docs/index.db` when `XDG_CACHE_HOME` is set). +5. Set `PYTHON_DOCS_MCP_DISABLE_AUTO_INDEX=1`, so a missing index never starts + a network build, and check the install: + + ```bash + PYTHON_DOCS_MCP_DISABLE_AUTO_INDEX=1 python-docs-mcp-server doctor + ``` + +`lookup_package_docs` needs PyPI. Offline, it returns a clear note instead of +package sources. There is no separate offline command. + ## PyPI package docs lookup `lookup_package_docs` queries the official PyPI JSON API documented at diff --git a/benchmarks/__main__.py b/benchmarks/__main__.py index 847f6a58..26a6bd60 100644 --- a/benchmarks/__main__.py +++ b/benchmarks/__main__.py @@ -6,6 +6,7 @@ import json import sys from pathlib import Path +from typing import Any from benchmarks.corpus import validate_corpus from benchmarks.report import generate_readme_summary, generate_report @@ -178,7 +179,33 @@ def _build_parser() -> argparse.ArgumentParser: agentic.add_argument("--repeats", type=int, default=3) agentic.add_argument("--seed", type=int) agentic.add_argument("--run-id") - agentic.add_argument("--dry-run", action="store_true", help="Write the plan; no ledger.") + mode = agentic.add_mutually_exclusive_group() + mode.add_argument("--dry-run", action="store_true", help="Write the plan; no ledger.") + mode.add_argument( + "--live", + action="store_true", + help="Container launcher only: run for real, after the CI refusal and a typed 'yes'.", + ) + agentic.add_argument( + "--launcher", + choices=("local", "container"), + default="local", + help="local: scripted models only. container: the sandbox, a dry run unless --live.", + ) + agentic.add_argument("--image", help="The sandbox worker image ID (sha256:...).") + agentic.add_argument( + "--keys-file", + type=Path, + help="Mode-600 NAME=VALUE file; only the container launcher reads it, one key per worker.", + ) + agentic.add_argument( + "--index", type=Path, help="The docs index for python-docs jobs (default: the cache's)." + ) + agentic.add_argument( + "--reference-run", + type=Path, + help="A finished pilot run whose per-cell cost and time the full-run gate scales.", + ) agentic.add_argument( "--acknowledge-overrun", action="append", @@ -191,11 +218,42 @@ def _build_parser() -> argparse.ArgumentParser: subparsers.add_parser( "agentic-worker", help="Internal: run one agentic (model, system) job for the host." ) + # Run by the container launcher in a keyless probe container, never by hand. + probe = subparsers.add_parser( + "agentic-probe", help="Internal: check a sandbox network's isolation from inside it." + ) + probe.add_argument("--spec", required=True, help="The probe's checks, as JSON.") return parser +def _container_launcher(args: argparse.Namespace, run_id: str) -> Any: + """The production sandbox: the real image check, the real probes, docker on this host.""" + from benchmarks.agentic.sandbox import ContainerLauncher, Sandbox, SandboxConfig + from benchmarks.runner import _repo_commit_sha + from mcp_server_python_docs.storage.db import get_index_path + + config = SandboxConfig( + image=args.image, + run_id=run_id, + out_dir=args.out, + index_path=args.index or get_index_path(), + keys_file=args.keys_file, + repo_commit=_repo_commit_sha(), + ) + return ContainerLauncher(Sandbox(config)) + + def main(argv: list[str] | None = None) -> int: parser = _build_parser() + argv = sys.argv[1:] if argv is None else argv + if argv and argv[0] == "agentic-run": + # argparse itself quotes invalid values (e.g. --repeats) in its diagnostics. + from benchmarks.agentic.protocol import KeyLeakError, assert_no_key_shaped_json + + try: + assert_no_key_shaped_json(argv[1:], where="agentic-run arguments") + except KeyLeakError as exc: + parser.exit(3, f"agentic run stopped on a key leak: {exc}\n") args = parser.parse_args(argv) if args.command == "agentic-worker": @@ -204,11 +262,22 @@ def main(argv: list[str] | None = None) -> int: return main_worker() + if args.command == "agentic-probe": + from benchmarks.agentic.probe import probe_main + + return probe_main(["--spec", args.spec]) + if args.command == "agentic-run": # Lazy, like agentic-worker: only agentic commands load the provider SDKs. from benchmarks.agentic import run as agentic_run - from benchmarks.agentic.protocol import KeyLeakError - + from benchmarks.agentic.protocol import KeyLeakError, scanned_json_bytes + from benchmarks.runner import _default_run_id + + if args.live and args.launcher != "container": + parser.error("--live needs --launcher container: the local launcher is scripted only") + if args.launcher == "container" and not args.image: + parser.error("--launcher container needs --image sha256:...") + run_id = args.run_id or _default_run_id() # one id for the run and its sandbox config = agentic_run.AgenticConfig( corpus_path=args.corpus, matrix_path=args.matrix, @@ -221,17 +290,21 @@ def main(argv: list[str] | None = None) -> int: questions=args.questions, repeats=args.repeats, seed=args.seed, - run_id=args.run_id, - dry_run=args.dry_run, + run_id=run_id, + # The container launcher is a dry run unless --live is given. + dry_run=args.dry_run or (args.launcher == "container" and not args.live), acknowledge_overrun=tuple(args.acknowledge_overrun), + reference_run=args.reference_run, ) try: - summary = agentic_run.run_agentic(config) + launcher = _container_launcher(args, run_id) if args.launcher == "container" else None + summary = agentic_run.run_agentic(config, launcher=launcher) + output = scanned_json_bytes(summary, where="run summary", indent=2, sort_keys=True) except KeyLeakError as exc: # before its base class parser.exit(3, f"agentic run stopped on a key leak: {exc}\n") except BenchmarkValidationError as exc: parser.exit(2, f"agentic run failed: {exc}\n") - print(json.dumps(summary, indent=2, sort_keys=True)) + print(output.decode()) return 0 if args.command == "run": diff --git a/benchmarks/adapters/guard.py b/benchmarks/adapters/guard.py index a2aa6ec9..8005be75 100644 --- a/benchmarks/adapters/guard.py +++ b/benchmarks/adapters/guard.py @@ -31,6 +31,9 @@ #: case-insensitive) for any live-provider guard to pass. LIVE_PROVIDERS_ENABLED_ENV = "BENCHMARK_LIVE_PROVIDERS_ENABLED" +#: The sandbox's egress proxy (``http://:``), the only proxy a live client uses. +EGRESS_URL_ENV = "BENCHMARK_EGRESS_URL" + #: Per-provider environment variable that must also be non-empty. #: #: ``anthropic`` (issue #89) is not a competitor/model-matrix provider -- @@ -51,6 +54,9 @@ #: The model providers' keys: they pay for every call, and no docs system ever receives one. PAID_KEY_ENVS = tuple(PROVIDER_API_KEY_ENV[p] for p in ("anthropic", "openai", "google")) +#: Keyless live providers, and the variable that must be set instead of a key (#184 ruling 9). +LIVE_LATCH_ENV = {"ollama": "OLLAMA_BASE_URL"} + _TRUTHY = {"1", "true", "yes"} #: Every provider key is made of these; anything else could be quoted by an HTTP error. _KEY_CHARACTERS = re.compile(r"[A-Za-z0-9_.-]+") @@ -67,6 +73,11 @@ class MalformedApiKeyError(LiveProviderDisabledError): """Raised when a provider API key is set but holds characters no HTTP header may carry.""" +def valid_api_key(value: str) -> bool: + """Use the same character policy for the keys file and the worker environment.""" + return _KEY_CHARACTERS.fullmatch(value) is not None + + def require_live_environment(provider: str) -> None: """Raise :class:`LiveProviderDisabledError` unless live calls are explicitly enabled. @@ -74,7 +85,8 @@ def require_live_environment(provider: str) -> None: 1. ``BENCHMARK_LIVE_PROVIDERS_ENABLED`` is set to a truthy value. 2. The provider-specific API key environment variable (see - :data:`PROVIDER_API_KEY_ENV`) is set and non-empty. + :data:`PROVIDER_API_KEY_ENV`) is set and non-empty; for a keyless provider, + its :data:`LIVE_LATCH_ENV` variable instead, and nothing else. 3. That variable's raw value uses only ``[A-Za-z0-9_.-]`` (an HTTP client error would quote any other character). @@ -89,6 +101,14 @@ def require_live_environment(provider: str) -> None: f"for provider {provider!r} (this does not by itself enable live calls; " "see benchmarks/adapters/guard.py)" ) + latch = LIVE_LATCH_ENV.get(provider) + if latch is not None: # a keyless provider: its latch, and never a key + if not os.environ.get(latch, "").strip(): + raise LiveProviderDisabledError( + f"live provider calls are disabled: missing required {latch} for " + f"provider {provider!r}" + ) + return key_env = PROVIDER_API_KEY_ENV.get(provider) if key_env is None: raise LiveProviderDisabledError(f"unknown provider for live guard: {provider!r}") @@ -98,7 +118,7 @@ def require_live_environment(provider: str) -> None: f"live provider calls are disabled: missing required {key_env} for " f"provider {provider!r}" ) - if not _KEY_CHARACTERS.fullmatch(raw_key): + if not valid_api_key(raw_key): raise MalformedApiKeyError( f"live provider calls are disabled: {key_env} holds a character outside " "[A-Za-z0-9_.-]" diff --git a/benchmarks/agentic/airgap.py b/benchmarks/agentic/airgap.py new file mode 100644 index 00000000..9fc8221c --- /dev/null +++ b/benchmarks/agentic/airgap.py @@ -0,0 +1,219 @@ +"""The air-gapped arm: host offline checks around every trajectory, and the Ollama preflight. + +Design §7.4: the Mac is offline for the whole arm. A check round runs before the first +trajectory, after each reported trajectory or discard (before the worker starts its next), +and after the last; the first failed check stops the arm. +""" + +from __future__ import annotations + +import asyncio +import json +import platform +import re +import socket +import subprocess +import urllib.request +from collections.abc import Callable, Sequence +from datetime import UTC, datetime +from pathlib import Path +from typing import Any + +from benchmarks.agentic.protocol import scanned_json_bytes, write_json_evidence +from benchmarks.runner import BenchmarkValidationError + +#: A name (DNS must be down) and an address (IP must be down too): both must fail. +OUTSIDE_TARGETS = (("pypi.org", 443), ("1.1.1.1", 443)) +REQUIRED_CONTEXT = 32_768 +MIN_OLLAMA = (0, 40, 14) # older releases override packaged sampler defaults (#200 ruling 6) +OLLAMA_LOCAL = "http://127.0.0.1:11434" +_CONNECT_S = 5.0 + +Fetch = Callable[[str, bytes | None], dict[str, Any]] + + +def _read_routes(system: str) -> str: + if system == "Darwin": + return subprocess.run(["netstat", "-rn"], capture_output=True, text=True, check=True).stdout + return "".join(Path(p).read_text() for p in ("/proc/net/route", "/proc/net/ipv6_route")) + + +def default_routes( + *, system: str | None = None, read: Callable[[], str] | None = None +) -> list[str]: + """Every default route, IPv4 or IPv6: a VPN's or Private Relay's ``utun`` one included.""" + system = system or platform.system() + text = read() if read is not None else _read_routes(system) + lines = text.splitlines() + if system == "Darwin" and not {"Internet:", "Internet6:"}.intersection(lines): + raise OSError("netstat returned no IPv4 or IPv6 routing table") + found = [] + for line in lines: + fields = line.split() + if system == "Darwin": + default = fields[:1] == ["default"] + elif len(fields) == 10: # /proc/net/ipv6_route: ::/0, not the kernel's reject on lo + default = fields[0] == "0" * 32 and fields[1] == "00" and fields[9] != "lo" + else: # /proc/net/route + default = len(fields) > 1 and fields[1] == "00000000" + if default: + found.append(line.strip()) + return found + + +def _now() -> str: + return datetime.now(UTC).isoformat(timespec="milliseconds").replace("+00:00", "Z") + + +def host_offline_checks( + *, + connect: Callable[..., Any] = socket.create_connection, + routes: Callable[[], list[str]] = default_routes, +) -> list[dict[str, Any]]: + """One check round: no outside connection, by name or by address, and no default route.""" + records = [] + for host, port in OUTSIDE_TARGETS: + try: + connect((host, port), _CONNECT_S).close() + except OSError as exc: + passed, detail = True, type(exc).__name__ + else: + passed, detail = False, "connected" + records.append( + {"check": f"outside_connect:{host}", "passed": passed, "detail": detail, "at": _now()} + ) + try: + lines = routes() + except (OSError, subprocess.CalledProcessError) as exc: + passed, route_detail = False, str(exc) + else: + passed, route_detail = not lines, lines + records.append( + {"check": "no_default_route", "passed": passed, "detail": route_detail, "at": _now()} + ) + return records + + +def _fetch(url: str, body: bytes | None) -> dict[str, Any]: + # ProxyHandler({}): no host proxy variable can send a request anywhere but local Ollama. + opener = urllib.request.build_opener(urllib.request.ProxyHandler({})) + headers = {"Content-Type": "application/json"} if body is not None else {} + request = urllib.request.Request(url, data=body, headers=headers) + with opener.open(request, timeout=600) as response: + return dict(json.loads(response.read())) + + +def _version(text: str) -> tuple[int, ...]: + return tuple(int(part) for part in re.findall(r"\d+", text)[:3]) + + +def _named(models: list[dict[str, Any]], model_id: str) -> dict[str, Any] | None: + return next((m for m in models if model_id in (m.get("name"), m.get("model"))), None) + + +def ollama_preflight( + model_id: str, *, base: str = OLLAMA_LOCAL, fetch: Fetch | None = None +) -> dict[str, Any]: + """Ollama's version, the model's digest and details, and its loaded context, recorded. + + Refuses a version before MIN_OLLAMA, a missing model, or a context that is not 32,768. + """ + get = fetch or _fetch + version = str(get(f"{base}/api/version", None).get("version", "")) + if _version(version) < MIN_OLLAMA: + raise BenchmarkValidationError( + f"Ollama {version} is older than {'.'.join(map(str, MIN_OLLAMA))}, which the " + "air-gapped arm needs (Ollama defaults)" + ) + tag = _named(list(get(f"{base}/api/tags", None).get("models") or []), model_id) + if tag is None: + raise BenchmarkValidationError(f"Ollama has no model {model_id}: ollama pull it first") + load = {"model": model_id, "prompt": "", "keep_alive": "60m"} + get(f"{base}/api/generate", json.dumps(load).encode()) + running = _named(list(get(f"{base}/api/ps", None).get("models") or []), model_id) or {} + context = running.get("context_length") + if context != REQUIRED_CONTEXT: + raise BenchmarkValidationError( + f"{model_id} is loaded with a {context}-token context, not {REQUIRED_CONTEXT}: start " + f"Ollama with OLLAMA_CONTEXT_LENGTH={REQUIRED_CONTEXT}" + ) + shown = get(f"{base}/api/show", json.dumps({"model": model_id}).encode()) + return { + "version": version, + "model": model_id, + "digest": tag.get("digest"), + "details": tag.get("details"), + "context_length": context, + "parameters": shown.get("parameters"), + } + + +class AirGapBroken(BenchmarkValidationError): + """A host offline check failed: the air-gapped arm stops.""" + + +class AirGapWatch: + """Runs check rounds, appends each record to ``airgap/records.jsonl``, stops on a failure.""" + + def __init__( + self, out_dir: Path, checks: Callable[[], list[dict[str, Any]]] = host_offline_checks + ) -> None: + self._path = out_dir / "airgap" / "records.jsonl" + self._checks = checks + self.rounds = 0 + self.broken = False + + async def check(self, when: str) -> None: + records = await asyncio.to_thread(self._checks) # connects block for up to 5 s + self.rounds += 1 + self._path.parent.mkdir(parents=True, exist_ok=True) + lines = b"".join( + scanned_json_bytes({**r, "when": when}, where="airgap/records.jsonl", sort_keys=True) + + b"\n" + for r in records + ) + with self._path.open("ab") as file: + file.write(lines) + failed = [r["check"] for r in records if not r["passed"]] + if failed: + self.broken = True + raise AirGapBroken(f"air-gap check {failed[0]} failed {when}: the arm stops") + + +#: The arm's own Ollama, reached through its proxy: never an internet host (round-2 ruling C7). +_LOCAL_OLLAMA = "host.docker.internal:11434" + + +def write_airgap_evidence( + out_dir: Path, *, rounds: int, broken: bool, job_ids: Sequence[str] +) -> dict[str, Any]: + """``out_dir/airgap/checks.json``: the C3 evidence, with exactly the keys #199 binds. + + ``internet_hosts`` is every host the air-gapped jobs actually reached (their + ``hosts_allowed`` in egress/summary.json) but local Ollama; a denied attempt left nothing + and stays in ``hosts_denied``. ``all_passed`` needs at least one round, every round + passed, the arm not stopped, a passing isolation probe and no internet host. + """ + try: + egress = json.loads((out_dir / "egress" / "summary.json").read_text(encoding="utf-8")) + jobs = egress["jobs"] + reached: set[str] = set() + probe_passed = egress.get("isolation_probe") == "pass" + for job_id in job_ids: + entry = jobs.get(job_id) + hosts = entry.get("hosts_allowed") if isinstance(entry, dict) else None + if not isinstance(hosts, list) or not all(isinstance(h, str) and h for h in hosts): + probe_passed = False + continue + reached.update(hosts) + except (OSError, ValueError, KeyError, TypeError, AttributeError): + reached, probe_passed = set(), False + internet = sorted(reached - {_LOCAL_OLLAMA}) + result = { + "all_passed": rounds > 0 and not broken and probe_passed and not internet, + "checks": rounds, + "internet_hosts": internet, + } + assert set(result) == {"all_passed", "checks", "internet_hosts"} # round-2 ruling E18 + write_json_evidence(out_dir / "airgap" / "checks.json", result) + return result diff --git a/benchmarks/agentic/bridge.py b/benchmarks/agentic/bridge.py index 6be59889..fa1d0a64 100644 --- a/benchmarks/agentic/bridge.py +++ b/benchmarks/agentic/bridge.py @@ -7,20 +7,26 @@ from __future__ import annotations -import json import os import sys -from collections.abc import AsyncIterator, Mapping +from collections.abc import AsyncIterator, Callable, Mapping from contextlib import asynccontextmanager from dataclasses import dataclass from pathlib import Path from typing import Any, Literal, Protocol -from mcp import ClientSession, MCPError, StdioServerParameters, stdio_client +from mcp import ClientSession, MCPError, StdioServerParameters from mcp.types import CONNECTION_CLOSED, CallToolResult, PaginatedRequestParams, TextContent -from benchmarks.adapters.guard import PROVIDER_API_KEY_ENV -from benchmarks.agentic.protocol import assert_no_key_shaped +from benchmarks.adapters.guard import EGRESS_URL_ENV, PROVIDER_API_KEY_ENV +from benchmarks.agentic.mcp_stdio import ReplyGuard, checked_stdio_client +from benchmarks.agentic.protocol import ( + KeyLeakError, + assert_no_key_shaped, + find_frame_too_large, + find_key_leak, + scanned_json_bytes, +) from benchmarks.agentic.types import ToolSpec from benchmarks.runner import ( _SAFE_ID, @@ -32,6 +38,8 @@ ) TRUNCATION_MARKER = "\n[benchmark harness: tool result truncated at {limit} UTF-8 bytes]" +#: A manifest env value replaced by the run's egress proxy URL, or dropped without one. +EGRESS_PLACEHOLDER = "{egress}" _TRANSPORTS: dict[str, Literal["stdio", "none"]] = {"mcp-stdio": "stdio", "none": "none"} #: System id -> its own competitor key, the only provider key a system may receive. @@ -110,15 +118,32 @@ def system_spec_from_raw(raw: Mapping[str, Any]) -> SystemSpec: def load_systems(manifest_path: Path) -> list[SystemSpec]: - data = _load_yaml_mapping(manifest_path, "manifest") + return systems_from_mapping(_load_yaml_mapping(manifest_path, "manifest")) + + +def systems_from_mapping(data: dict[str, Any]) -> list[SystemSpec]: _validate_manifest_eligibility(data) return [system_spec_from_raw(competitor.raw) for competitor in _load_competitors(data)] -def canonical_text(result: CallToolResult) -> str: +def canonical_text( + result: CallToolResult, *, check_content: Callable[[bytes], None] | None = None +) -> str: """Compact JSON of ``structured_content`` when present, else the joined text blocks.""" + # Check the decoded MCP envelope before canonicalization drops text, metadata or fields. + scanned_json_bytes( + result.model_dump(mode="json", by_alias=True), + where="MCP tool result", + check_content=check_content, + ) if result.structured_content is not None: - return json.dumps(result.structured_content, ensure_ascii=False, separators=(",", ":")) + return scanned_json_bytes( + result.structured_content, + where="structured tool result", + check_content=check_content, + ensure_ascii=False, + separators=(",", ":"), + ).decode() return "\n".join( block.text if isinstance(block, TextContent) else f"[{block.type} content omitted]" for block in result.content @@ -138,6 +163,9 @@ def truncate_utf8(text: str, limit: int) -> tuple[str, bool]: class Bridge: """One live MCP session; implements :class:`ToolBridge`.""" + check_content: Callable[[bytes], None] | None = None + _reply_guard: ReplyGuard | None = None + def __init__( self, session: ClientSession, @@ -152,28 +180,76 @@ def __init__( ] async def call(self, name: str, arguments: dict[str, Any]) -> ToolOutcome: + self.raise_if_failed() try: result = await self._session.call_tool(name, arguments) - except MCPError as exc: - if exc.code == CONNECTION_CLOSED: - raise BridgeCrash(f"MCP connection closed during {name}: {exc}") from exc - return ToolOutcome(text=str(exc.message), is_error=True) - except Exception as exc: # noqa: BLE001 - any other failure means the session is gone + except BaseException as exc: + if leak := find_key_leak(exc): + raise leak + if self._reply_guard is not None and isinstance( + self._reply_guard.failure, KeyLeakError + ): + self._reply_guard.raise_if_failed() + if not isinstance(exc, Exception): + raise + self.raise_if_failed() + if frame := find_frame_too_large(exc): + raise frame + if isinstance(exc, MCPError): + scanned_json_bytes( + exc.error.model_dump(mode="json"), + where="MCP tool error", + check_content=self.check_content, + ) + if exc.code == CONNECTION_CLOSED: + raise BridgeCrash(f"MCP connection closed during {name}: {exc}") from exc + return ToolOutcome(text=str(exc.message), is_error=True) + scanned_json_bytes( + str(exc), where="MCP tool exception", check_content=self.check_content + ) failure = cell_failure_from(exc, timeout_seconds=0.0, label=f"MCP tool {name}") raise BridgeCrash(str(failure)) from exc - return ToolOutcome(text=canonical_text(result), is_error=bool(result.is_error)) + self.raise_if_failed() + return ToolOutcome( + text=canonical_text(result, check_content=self.check_content), + is_error=bool(result.is_error), + ) + + def raise_if_failed(self) -> None: + """Check the receive task before dispatch, reservation or publication.""" + if self._reply_guard is not None: + self._reply_guard.raise_if_failed() + + +def server_env(system: SystemSpec, environ: Mapping[str, str]) -> dict[str, str]: + """The MCP server's environment: its manifest ``env``, then its ``pass_env`` names. + + An ``env`` value of ``{egress}`` becomes the worker's ``BENCHMARK_EGRESS_URL``, and the + variable is dropped when that is unset: no other proxy ever reaches a server. + """ + env: dict[str, str] = {} + for name, value in system.env.items(): + if value != EGRESS_PLACEHOLDER: + env[name] = value + elif egress := environ.get(EGRESS_URL_ENV): + env[name] = egress + env.update({name: environ[name] for name in system.pass_env if name in environ}) + return env @asynccontextmanager -async def open_bridge(system: SystemSpec) -> AsyncIterator[Bridge]: +async def open_bridge( + system: SystemSpec, *, check_content: Callable[[bytes], None] | None = None +) -> AsyncIterator[Bridge]: if system.transport != "stdio": raise BenchmarkValidationError(f"system {system.id!r} has no MCP server to open") command = [sys.executable if part == "{python}" else part for part in system.command] - env = dict(system.env) - env.update({name: os.environ[name] for name in system.pass_env if name in os.environ}) - params = StdioServerParameters(command=command[0], args=command[1:], env=env) + params = StdioServerParameters( + command=command[0], args=command[1:], env=server_env(system, os.environ) + ) # errlog read now, not at import: the worker points sys.stderr at its redactor. - async with stdio_client(params, errlog=sys.stderr) as (read, write): + guard = ReplyGuard(check_content) + async with checked_stdio_client(params, errlog=sys.stderr, guard=guard) as (read, write): async with ClientSession(read, write) as session: initialized = await session.initialize() tools_raw: list[dict[str, Any]] = [] @@ -191,4 +267,7 @@ async def open_bridge(system: SystemSpec) -> AsyncIterator[Bridge]: server_info = initialized.server_info.model_dump( mode="json", by_alias=True, exclude_unset=True ) - yield Bridge(session, server_info, tools_raw) + bridge = Bridge(session, server_info, tools_raw) + bridge._reply_guard = guard + bridge.check_content = check_content + yield bridge diff --git a/benchmarks/agentic/cleanup.py b/benchmarks/agentic/cleanup.py new file mode 100644 index 00000000..22c8bd4e --- /dev/null +++ b/benchmarks/agentic/cleanup.py @@ -0,0 +1,77 @@ +"""Wait for owned work without letting a later interrupt replace the first one.""" + +import asyncio +import traceback +from collections.abc import Awaitable +from typing import Any + +from benchmarks.agentic.protocol import ( + FrameTooLarge, + KeyLeakError, + find_key_leak, + redact_key_shaped_text, +) +from benchmarks.runner import BenchmarkValidationError + + +async def settle(task: asyncio.Future[Any]) -> asyncio.CancelledError | None: + """Leave the task's outcome for its owner, even across repeated cancellations.""" + cancelled = None + while not task.done(): + try: + await asyncio.wait((task,)) # cancelling the wait does not cancel the task + except asyncio.CancelledError as exc: + if cancelled is None: + cancelled = exc + return cancelled + + +def add_cleanup_cause(primary: BaseException, failure: BaseException) -> None: + """Retain each rollback failure on the exception already being propagated.""" + prior = primary.__cause__ + if primary is not failure and prior is not failure: + primary.__cause__ = ( + failure if prior is None else BaseExceptionGroup("cleanup failures", [prior, failure]) + ) + + +def add_safe_cleanup_cause(primary: BaseException, failure: BaseException) -> None: + """Attach diagnostics without retaining raw exceptions, their notes or chains.""" + try: + detail = redact_key_shaped_text("".join(traceback.format_exception(failure, limit=0))) + except Exception: # even broken exception formatting must not replace recognition + detail = f"could not safely report {type(failure).__name__}" + add_cleanup_cause(primary, BenchmarkValidationError(f"cleanup failed: {detail.strip()}")) + + +async def finish[T](operation: Awaitable[T], pending: BaseException | None = None) -> T: + """Finish the operation before propagating cancellation. + + If the caller is already unwinding a cancellation, leave it to propagate on + success. On failure, raise that same cancellation with the failure as its cause. + A recognized credential or frame failure also survives ordinary cleanup errors, with + a redacted diagnostic copy as its cause; interrupts retain their precedence. + """ + task = asyncio.ensure_future(operation) + cancelled = await settle(task) + if isinstance(pending, asyncio.CancelledError): + cancelled = pending + try: + result = task.result() + except BaseException as error: + if cancelled is not None and cancelled is not error: + add_cleanup_cause(cancelled, error) + raise cancelled + if not isinstance(error, Exception): + raise + if isinstance(pending, FrameTooLarge) and (leak := find_key_leak(error)): + raise leak + if not isinstance(pending, (KeyLeakError, FrameTooLarge)): + raise + add_safe_cleanup_cause(pending, error) + else: + if cancelled is not None and cancelled is not pending: + raise cancelled + return result + # Outside the handler: raising here must not set the raw error as __context__. + raise pending diff --git a/benchmarks/agentic/clients.py b/benchmarks/agentic/clients.py index dbe18556..ebde8648 100644 --- a/benchmarks/agentic/clients.py +++ b/benchmarks/agentic/clients.py @@ -11,11 +11,12 @@ import json import os import ssl -from collections.abc import Mapping, Sequence +from collections.abc import Callable, Mapping, Sequence from datetime import UTC, datetime from email.utils import parsedate_to_datetime from pathlib import Path from typing import Any +from urllib.parse import urlsplit import anthropic import certifi @@ -28,11 +29,19 @@ from google.genai import types as genai_types from benchmarks.adapters.guard import ( + EGRESS_URL_ENV, + LIVE_LATCH_ENV, PAID_KEY_ENVS, PROVIDER_API_KEY_ENV, require_live_environment, ) -from benchmarks.agentic.schemas import to_anthropic, to_gemini, to_openai_responses +from benchmarks.agentic.protocol import MAX_FRAME_BYTES, check_json_text, scanned_json_bytes +from benchmarks.agentic.schemas import ( + to_anthropic, + to_gemini, + to_openai_chat, + to_openai_responses, +) from benchmarks.agentic.types import ( Conversation, ModelClient, @@ -42,7 +51,12 @@ ToolResults, UserText, ) -from benchmarks.agentic.usage import anthropic_buckets, gemini_buckets, openai_buckets +from benchmarks.agentic.usage import ( + anthropic_buckets, + gemini_buckets, + ollama_buckets, + openai_buckets, +) from benchmarks.model_matrix import ModelFamily from benchmarks.runner import BenchmarkValidationError, _load_yaml_mapping @@ -51,20 +65,66 @@ "anthropic-messages": "anthropic", "openai-responses": "openai", "gemini-generate-content": "google", + "openai-chat-completions": "ollama", # keyless: OLLAMA_BASE_URL instead } +# Count the root container too. Leave headroom for dataclasses.asdict, evidence +# envelopes and the MCP SDK's recursive JSON validation on Python 3.12–3.14. +MAX_TOOL_ARGUMENT_DEPTH = 64 + -def tool_arguments(value: Any) -> tuple[dict[str, Any], str | None]: - """A JSON object passes; anything else is ``({}, raw)`` and never reaches a tool.""" - parsed = value +def _argument_depth_exceeded(text: str) -> bool: + """Bound decoding without recursion or allocating a tree, including shadowed fields. + + This is only a depth preflight; json.loads still decides validity. Content + inspection runs separately after usage settlement and scans the entire text. + """ + depth = 0 + quoted = escaped = False + for char in text: + if quoted: + if escaped: + escaped = False + elif char == "\\": + escaped = True + elif char == '"': + quoted = False + elif char == '"': + quoted = True + elif char in "[{": + depth += 1 + if depth > MAX_TOOL_ARGUMENT_DEPTH: + return True + elif char in "]}": + depth -= 1 + return False + + +def _parse_tool_arguments(value: Any) -> tuple[dict[str, Any], str | None]: + """Normalize a response without raising a content failure before usage is settled.""" if isinstance(value, str): + if len(value) > MAX_FRAME_BYTES or _argument_depth_exceeded(value): + return {}, value # The bounded content check runs after usage settlement. try: parsed = json.loads(value) - except json.JSONDecodeError: + except (ValueError, RecursionError): + # Includes the stdlib integer conversion and nesting limits. Keep the + # original argument for inspection/error feedback, and return known usage. return {}, value - if isinstance(parsed, dict): - return parsed, None - return {}, value if isinstance(value, str) else json.dumps(value) + return (parsed, None) if isinstance(parsed, dict) else ({}, value) + if isinstance(value, dict): + return value, None + return {}, json.dumps(value) + + +def tool_arguments( + value: Any, *, check_content: Callable[[bytes], None] | None = None +) -> tuple[dict[str, Any], str | None]: + """Check raw and decoded arguments, then accept only a JSON object for dispatch.""" + scanned_json_bytes(value, where="tool arguments", check_content=check_content) + if isinstance(value, str): + check_json_text(value, where="tool arguments", check_content=check_content) + return _parse_tool_arguments(value) def parse_retry_after(headers: Mapping[str, str]) -> float | None: @@ -97,8 +157,24 @@ def _status_error(status: int, headers: Mapping[str, str], message: str) -> Prov return ProviderCallError("rejected", message, status=status) -def _utf8_len(payload: Any) -> int: - return len(json.dumps(payload, ensure_ascii=False, separators=(",", ":")).encode("utf-8")) +def _utf8_len( + payload: Any, + *, + check_content: Callable[[bytes], None] | None = None, + ensure_ascii: bool = False, +) -> int: + # All supported renderers use this boundary, including native assistant replay. + # Check decoded fields and the exact rendered JSON: encoding can create a token boundary. + # SDK credentials and HTTP authentication headers are deliberately outside this payload. + return len( + scanned_json_bytes( + payload, + where="outgoing provider content", + check_content=check_content, + ensure_ascii=ensure_ascii, + separators=(",", ":"), + ) + ) #: Pinned, so no *_BASE_URL variable can send a key to another host. @@ -107,45 +183,84 @@ def _utf8_len(payload: Any) -> int: GEMINI_BASE_URL = "https://generativelanguage.googleapis.com/" -def _client_args(transport: Any | None) -> dict[str, Any]: +def egress_proxy(environ: Mapping[str, str]) -> str | None: + """The sandbox's egress proxy from ``BENCHMARK_EGRESS_URL``: ``http://:`` only.""" + value = environ.get(EGRESS_URL_ENV) + if value is None: + return None + try: + parts = urlsplit(value) + ok = ( + parts.scheme == "http" + and bool(parts.hostname) + and parts.port is not None + and "@" not in parts.netloc + and not (parts.path or parts.query or parts.fragment) + ) + except ValueError: # a port that is not a number + ok = False + if not ok: # never the value: it may hold user info + raise BenchmarkValidationError( + f"{EGRESS_URL_ENV} must be http://:, with no user info, path, query " + "or fragment" + ) + return value + + +def _client_args( + transport: Any | None, proxy: str | None = None, *, http: Any = httpx2 +) -> dict[str, Any]: """Never follow a redirect: it would be a second request, possibly carrying the key away. trust_env=False: no HTTPS_PROXY or SSL_CERT_FILE in a worker's env steers the connection. - The Anthropic SDK mounts env proxies even then, so each proxy route is mounted direct. - Tests inject only a transport; every other client setting is the production one. + The Anthropic SDK mounts env proxies even then, so each route is mounted explicitly: direct, + or through ``proxy`` with the direct route's own pinned trust store. ``http`` is the httpx + module the SDK uses. Tests inject only a transport, which then carries every request; every + other client setting is the production one. """ - # shortcut: no proxy from the env; PR 4's egress proxy must be passed explicitly (proxy=...), - # and PR 4's container launcher must build the worker env from an allowlist with no - # *_PROXY, SSL_CERT_* or REQUESTS_CA_BUNDLE (a SOCKS ALL_PROXY crashes the Anthropic SDK). + # No proxy from the environment. In a sandbox the egress proxy comes only from + # BENCHMARK_EGRESS_URL, and the container launcher passes no *_PROXY, SSL_CERT_* or + # REQUESTS_CA_BUNDLE (Task 10). + route = None + if proxy is not None and transport is None: + route = http.AsyncHTTPTransport(proxy=proxy, trust_env=False) return { "follow_redirects": False, "trust_env": False, - "mounts": {"http://": None, "https://": None, "all://": None}, + "mounts": {"http://": route, "https://": route, "all://": route}, **({} if transport is None else {"transport": transport}), } def anthropic_sdk( - api_key: str, timeout_s: float, *, transport: httpx2.AsyncBaseTransport | None = None + api_key: str, + timeout_s: float, + *, + transport: httpx2.AsyncBaseTransport | None = None, + proxy: str | None = None, ) -> anthropic.AsyncAnthropic: return anthropic.AsyncAnthropic( api_key=api_key, base_url=ANTHROPIC_BASE_URL, max_retries=0, timeout=timeout_s, - http_client=anthropic.DefaultAsyncHttpxClient(**_client_args(transport)), + http_client=anthropic.DefaultAsyncHttpxClient(**_client_args(transport, proxy)), ) def openai_sdk( - api_key: str, timeout_s: float, *, transport: httpx2.AsyncBaseTransport | None = None + api_key: str, + timeout_s: float, + *, + transport: httpx2.AsyncBaseTransport | None = None, + proxy: str | None = None, ) -> openai.AsyncOpenAI: return openai.AsyncOpenAI( api_key=api_key, base_url=OPENAI_BASE_URL, max_retries=0, timeout=timeout_s, - http_client=openai.DefaultAsyncHttpxClient(**_client_args(transport)), + http_client=openai.DefaultAsyncHttpxClient(**_client_args(transport, proxy)), ) @@ -153,6 +268,7 @@ class AnthropicClient: """Anthropic Messages: no sampling parameters, no ``cache_control``.""" provider = "anthropic" + api = "anthropic-messages" def __init__(self, sdk: anthropic.AsyncAnthropic, model_id: str, max_output_tokens: int): self._sdk = sdk @@ -186,12 +302,26 @@ def _messages(self, entries: Sequence[Any]) -> list[dict[str, Any]]: messages.append({"role": "assistant", "content": entry.replay}) return messages - def rendered_bytes(self, conv: Conversation, start: int) -> int: + def rendered_bytes( + self, + conv: Conversation, + start: int, + *, + check_content: Callable[[bytes], None] | None = None, + ) -> int: messages = self._messages(conv.entries[start:]) + for message in messages: + if message["role"] == "assistant": + for block in message["content"]: + if block.get("type") == "tool_use": + tool_arguments(block["input"], check_content=check_content) if start: - return _utf8_len(messages) + return _utf8_len(messages, check_content=check_content) tools = to_anthropic(conv.tools) - return _utf8_len({"system": conv.system, "tools": tools, "messages": messages}) + return _utf8_len( + {"system": conv.system, "tools": tools, "messages": messages}, + check_content=check_content, + ) async def call(self, conv: Conversation) -> ModelTurn: kwargs: dict[str, Any] = { @@ -213,7 +343,7 @@ async def call(self, conv: Conversation) -> ModelTurn: calls = [] for block in response.content: if isinstance(block, ToolUseBlock): - arguments, raw = tool_arguments(block.input) + arguments, raw = _parse_tool_arguments(block.input) calls.append(ToolCall(block.id, block.name, arguments, raw)) usage = response.usage.model_dump(mode="json") if response.usage else None return ModelTurn( @@ -233,6 +363,7 @@ class OpenAIResponsesClient: """OpenAI Responses: ``store=False``, encrypted reasoning replayed, no prompt-cache option.""" provider = "openai" + api = "openai-responses" def __init__(self, sdk: openai.AsyncOpenAI, model_id: str, max_output_tokens: int): self._sdk = sdk @@ -262,12 +393,24 @@ def _input(self, entries: Sequence[Any]) -> list[dict[str, Any]]: items += entry.replay return items - def rendered_bytes(self, conv: Conversation, start: int) -> int: + def rendered_bytes( + self, + conv: Conversation, + start: int, + *, + check_content: Callable[[bytes], None] | None = None, + ) -> int: items = self._input(conv.entries[start:]) + for item in items: + if item.get("type") == "function_call": + tool_arguments(item["arguments"], check_content=check_content) if start: - return _utf8_len(items) + return _utf8_len(items, check_content=check_content) tools = to_openai_responses(conv.tools) - return _utf8_len({"instructions": conv.system, "tools": tools, "input": items}) + return _utf8_len( + {"instructions": conv.system, "tools": tools, "input": items}, + check_content=check_content, + ) async def call(self, conv: Conversation) -> ModelTurn: kwargs: dict[str, Any] = { @@ -294,7 +437,7 @@ async def call(self, conv: Conversation) -> ModelTurn: calls, texts = [], [] for item in response.output: if item.type == "function_call": - arguments, raw = tool_arguments(item.arguments) + arguments, raw = _parse_tool_arguments(item.arguments) calls.append(ToolCall(item.call_id, item.name, arguments, raw)) elif item.type == "message": texts += [part.text for part in item.content if part.type == "output_text"] @@ -314,8 +457,133 @@ async def call(self, conv: Conversation) -> ModelTurn: ) +def ollama_sdk( + base_url: str, + timeout_s: float, + *, + transport: httpx2.AsyncBaseTransport | None = None, + proxy: str | None = None, +) -> openai.AsyncOpenAI: + # "The client requires an API key value, but Ollama ignores it" (sandbox note D.1). + return openai.AsyncOpenAI( + api_key="ollama", + base_url=base_url, + max_retries=0, + timeout=timeout_s, + http_client=openai.DefaultAsyncHttpxClient(**_client_args(transport, proxy)), + ) + + +class OllamaChatClient: + """Ollama's OpenAI-compatible Chat Completions: Ollama defaults (design §7.1). + + No ``max_tokens``, no ``tool_choice`` (unsupported; auto is Ollama's only behaviour) and no + sampling parameter is ever sent. + """ + + provider = "ollama" + api = "openai-chat-completions" + + def __init__(self, sdk: openai.AsyncOpenAI, model_id: str): + self._sdk = sdk + self.model_id = model_id + + def request_params(self) -> dict[str, Any]: + return {"model": self.model_id} + + def _messages(self, entries: Sequence[Any]) -> list[dict[str, Any]]: + messages: list[dict[str, Any]] = [] + for entry in entries: + if isinstance(entry, UserText): + messages.append({"role": "user", "content": entry.text}) + elif isinstance(entry, ToolResults): + messages += [ + {"role": "tool", "tool_call_id": r.call_id, "content": r.text} + for r in entry.results + ] + else: + messages.append(entry.replay) + return messages + + def rendered_bytes( + self, + conv: Conversation, + start: int, + *, + check_content: Callable[[bytes], None] | None = None, + ) -> int: + messages = self._messages(conv.entries[start:]) + for message in messages: + for call in message.get("tool_calls", []): + if call.get("type") == "function": + tool_arguments(call["function"]["arguments"], check_content=check_content) + if start: + return _utf8_len(messages, check_content=check_content) + system = {"role": "system", "content": conv.system} + return _utf8_len( + {"messages": [system, *messages], "tools": to_openai_chat(conv.tools)}, + check_content=check_content, + ) + + async def call(self, conv: Conversation) -> ModelTurn: + kwargs: dict[str, Any] = { + "model": self.model_id, + "messages": [{"role": "system", "content": conv.system}, *self._messages(conv.entries)], + } + if conv.tools: + kwargs["tools"] = to_openai_chat(conv.tools) + try: + response = await self._sdk.chat.completions.create(**kwargs) + except openai.APIStatusError as exc: + raise _status_error(exc.status_code, exc.response.headers, str(exc)) from exc + except openai.APITimeoutError as exc: + raise ProviderCallError("timeout", str(exc)) from exc + except openai.APIConnectionError as exc: + raise ProviderCallError("connection", str(exc)) from exc + choice = response.choices[0] if response.choices else None + message = choice.message if choice else None + calls: list[ToolCall] = [] + replayed: list[dict[str, Any]] = [] + position = 0 + for call in (message.tool_calls if message else None) or []: + if call.type != "function": + continue + position += 1 + # A call without an id gets one by position; the replay carries the same id, so + # each tool result pairs with its call. + call_id = call.id or f"call_{position}" + arguments, raw = _parse_tool_arguments(call.function.arguments) + calls.append(ToolCall(call_id, call.function.name, arguments, raw)) + replayed.append( + { + "id": call_id, + "type": "function", + "function": {"name": call.function.name, "arguments": call.function.arguments}, + } + ) + content = message.content if message else None + replay: dict[str, Any] = {"role": "assistant", "content": content} + if replayed: + replay["tool_calls"] = replayed + usage = response.usage.model_dump(mode="json") if response.usage else None + return ModelTurn( + text=content or "", + tool_calls=tuple(calls), + replay=replay, + raw_response=response.model_dump(mode="json"), + raw_usage=usage, + buckets=None if usage is None else ollama_buckets(usage), + reported_model=response.model, + stop_reason=choice.finish_reason if choice else None, + ) + + def gemini_sdk( - api_key: str, timeout_s: float, *, transport: httpx.AsyncBaseTransport | None = None + api_key: str, + timeout_s: float, + *, + transport: httpx.AsyncBaseTransport | None = None, + proxy: str | None = None, ) -> genai.Client: # Without a context the SDK builds its own from SSL_CERT_FILE and SSL_CERT_DIR: one for # httpx ("verify") and one for websockets ("ssl"). @@ -327,8 +595,9 @@ def gemini_sdk( base_url=GEMINI_BASE_URL, timeout=int(timeout_s * 1000), retry_options=genai_types.HttpRetryOptions(attempts=1), - httpx_async_client=httpx.AsyncClient(**_client_args(transport)), - client_args={"verify": ca}, + httpx_async_client=httpx.AsyncClient(**_client_args(transport, proxy, http=httpx)), + # The unused sync client reads no proxy variable either (a SOCKS one would crash it). + client_args={"verify": ca, "trust_env": False}, async_client_args={"ssl": ca}, ), ) @@ -338,6 +607,7 @@ class GeminiClient: """Gemini ``generate_content``: AUTO mode, no automatic calling, no continuation.""" provider = "google" + api = "gemini-generate-content" def __init__(self, sdk: genai.Client, model_id: str, max_output_tokens: int): self._sdk = sdk @@ -405,15 +675,27 @@ def _config(self, conv: Conversation) -> genai_types.GenerateContentConfig: max_output_tokens=self._max_output_tokens, ) - def rendered_bytes(self, conv: Conversation, start: int) -> int: + def rendered_bytes( + self, + conv: Conversation, + start: int, + *, + check_content: Callable[[bytes], None] | None = None, + ) -> int: contents = [ c.model_dump(mode="json", exclude_none=True) for c in self._contents(conv.entries[start:]) ] + # The pinned google-genai async transport uses json.dumps' ASCII escaping. + # A Unicode escape can create a lexical delimiter absent from decoded text. if start: - return _utf8_len(contents) + return _utf8_len(contents, check_content=check_content, ensure_ascii=True) tools = to_gemini(conv.tools)[0] - return _utf8_len({"systemInstruction": conv.system, "tools": tools, "contents": contents}) + return _utf8_len( + {"systemInstruction": conv.system, "tools": tools, "contents": contents}, + check_content=check_content, + ensure_ascii=True, + ) async def call(self, conv: Conversation) -> ModelTurn: try: @@ -436,7 +718,7 @@ async def call(self, conv: Conversation) -> ModelTurn: for position, part in enumerate((p for p in parts if p.function_call), 1): call = part.function_call assert call is not None - arguments, raw = tool_arguments(call.args if call.args is not None else {}) + arguments, raw = _parse_tool_arguments(call.args if call.args is not None else {}) calls.append(ToolCall(call.id or f"call_{position}", call.name or "", arguments, raw)) usage = response.usage_metadata.model_dump(mode="json") if response.usage_metadata else None reason = candidate.finish_reason if candidate else None @@ -456,8 +738,9 @@ async def call(self, conv: Conversation) -> ModelTurn: "anthropic": anthropic_buckets, "openai": openai_buckets, "google": gemini_buckets, + "ollama": ollama_buckets, } -_SCRIPT_STOP = {"anthropic": "end_turn", "openai": "completed", "google": "STOP"} +_SCRIPT_STOP = {"anthropic": "end_turn", "openai": "completed", "google": "STOP", "ollama": "stop"} def _fill_prompt(value: Any, prompt: str) -> Any: @@ -478,6 +761,8 @@ class ScriptedClient: ``prompt_contains``. A tools step applies only when every tool it names was given. """ + api = "scripted" + def __init__(self, provider: str, model_id: str, steps: list[dict[str, Any]]): self.provider = provider self.model_id = model_id @@ -489,7 +774,13 @@ def __init__(self, provider: str, model_id: str, steps: list[dict[str, Any]]): def request_params(self) -> dict[str, Any]: return {"model": self.model_id} - def rendered_bytes(self, conv: Conversation, start: int) -> int: + def rendered_bytes( + self, + conv: Conversation, + start: int, + *, + check_content: Callable[[bytes], None] | None = None, + ) -> int: rendered: list[Any] = [] for entry in conv.entries[start:]: if isinstance(entry, UserText): @@ -500,9 +791,12 @@ def rendered_bytes(self, conv: Conversation, start: int) -> int: calls = [[c.id, c.name, c.arguments] for c in entry.tool_calls] rendered.append({"role": "assistant", "text": entry.text, "calls": calls}) if start: - return _utf8_len(rendered) + return _utf8_len(rendered, check_content=check_content) tools = to_anthropic(conv.tools) - return _utf8_len({"system": conv.system, "tools": tools, "messages": rendered}) + return _utf8_len( + {"system": conv.system, "tools": tools, "messages": rendered}, + check_content=check_content, + ) def _applies(self, step: dict[str, Any], conv: Conversation, prompt: str) -> bool: if "prompt_contains" in step and str(step["prompt_contains"]) not in prompt: @@ -548,6 +842,28 @@ async def call(self, conv: Conversation) -> ModelTurn: ) +async def fetch_model_limits(client: ModelClient) -> dict[str, Any] | None: + """The model's token limits from its provider's free models endpoint, in one GET. + + Anthropic and Gemini only: the OpenAI and Ollama model endpoints report no limits, so + they make no request. It reserves no ledger unit (the endpoint is not billed), and an SDK + error is recorded as ``{"error": ""}``, never raised. + """ + try: + if isinstance(client, AnthropicClient): + info = await client._sdk.models.retrieve(client.model_id) + return {"max_input_tokens": info.max_input_tokens, "max_tokens": info.max_tokens} + if isinstance(client, GeminiClient): + model = await client._sdk.aio.models.get(model=client.model_id) + return { + "max_input_tokens": model.input_token_limit, + "max_tokens": model.output_token_limit, + } + except Exception as exc: # noqa: BLE001 - recorded in system_info, never fatal + return {"error": type(exc).__name__} + return None + + def make_client( family: ModelFamily, *, timeout_s: float, transport: Any | None = None ) -> ModelClient: @@ -566,8 +882,7 @@ def make_client( provider = _LIVE_APIS.get(family.api or "") if provider is None: raise BenchmarkValidationError( - f"model family {family.id!r} uses api {family.api!r}, which has no client yet " - "(openai-chat-completions arrives with the Ollama client in PR 4)" + f"model family {family.id!r} uses api {family.api!r}, which has no client" ) if family.provider != provider: raise BenchmarkValidationError( @@ -575,6 +890,19 @@ def make_client( f"not provider {family.provider!r}" ) require_live_environment(provider) + if provider in LIVE_LATCH_ENV: # keyless: the Ollama worker holds no paid key at all + held = [name for name in PAID_KEY_ENVS if os.environ.get(name)] + if held: + raise BenchmarkValidationError( + f"a keyless {provider} worker holds no paid key, but {', '.join(held)} is set" + ) + base_url = os.environ[LIVE_LATCH_ENV[provider]] + if not base_url.startswith(("http://", "https://")): + raise BenchmarkValidationError( + f"{LIVE_LATCH_ENV[provider]} must start with http:// or https://" + ) + sdk = ollama_sdk(base_url, timeout_s, transport=transport, proxy=egress_proxy(os.environ)) + return OllamaChatClient(sdk, family.model_id) own_key_env = PROVIDER_API_KEY_ENV[provider] others = [name for name in PAID_KEY_ENVS if name != own_key_env and os.environ.get(name)] if others: @@ -583,12 +911,13 @@ def make_client( ) if family.max_output_tokens is None: raise BenchmarkValidationError(f"model family {family.id!r} must set max_output_tokens") + proxy = egress_proxy(os.environ) key = os.environ[own_key_env] if provider == "anthropic": - sdk = anthropic_sdk(key, timeout_s, transport=transport) + sdk = anthropic_sdk(key, timeout_s, transport=transport, proxy=proxy) return AnthropicClient(sdk, family.model_id, family.max_output_tokens) if provider == "openai": - sdk = openai_sdk(key, timeout_s, transport=transport) + sdk = openai_sdk(key, timeout_s, transport=transport, proxy=proxy) return OpenAIResponsesClient(sdk, family.model_id, family.max_output_tokens) - sdk = gemini_sdk(key, timeout_s, transport=transport) + sdk = gemini_sdk(key, timeout_s, transport=transport, proxy=proxy) return GeminiClient(sdk, family.model_id, family.max_output_tokens) diff --git a/benchmarks/agentic/egress.py b/benchmarks/agentic/egress.py new file mode 100644 index 00000000..f5ce935f --- /dev/null +++ b/benchmarks/agentic/egress.py @@ -0,0 +1,415 @@ +"""Egress policy for the sandbox: allowlists, the Squid config and its access log (design §7.3). + +Imports nothing heavier than the model matrix, the runner and the key scan: the isolation probe +imports this module inside the worker container. +""" + +from __future__ import annotations + +import json +import os +import re +import secrets +import stat +from collections.abc import Iterator, Mapping, Sequence +from contextlib import contextmanager, suppress +from dataclasses import dataclass +from datetime import datetime +from ipaddress import ip_address +from pathlib import Path +from typing import TYPE_CHECKING, Any, Literal + +from benchmarks.agentic.protocol import scanned_json_bytes +from benchmarks.model_matrix import ModelFamily +from benchmarks.runner import BenchmarkValidationError + +if TYPE_CHECKING: + from benchmarks.agentic.host import WorkerJob + +EGRESS_ALIAS = "egress" +EGRESS_PORT = 3128 +EGRESS_URL = f"http://{EGRESS_ALIAS}:{EGRESS_PORT}" +#: Where the proxy writes its logs, bind-mounted from the job's private spool. +LOG_DIR_IN_PROXY = "/var/log/squid-bench" + +#: The pinned base URLs in clients.py, and the air-gapped arm's Ollama (design §7.4). +PROVIDER_HOSTS: dict[str, tuple[tuple[str, int], ...]] = { + "anthropic": (("api.anthropic.com", 443),), + "openai": (("api.openai.com", 443),), + "google": (("generativelanguage.googleapis.com", 443),), + "ollama": (("host.docker.internal", 11434),), +} +SYSTEM_HOSTS: dict[str, tuple[tuple[str, int], ...]] = { + "docs-fetch": (("docs.python.org", 443),), +} + +#: Proxy and CA variables that could steer a client: never in a worker's environment. +FORBIDDEN_ENV = re.compile(r"(?i)^(?:\w*_proxy|ssl_cert_\w*|requests_ca_bundle)$") + + +def allowlist(family: ModelFamily, system_id: str | None) -> tuple[tuple[str, int], ...]: + """Air-gapped jobs may reach only local Ollama. Hosted jobs also get their system's hosts.""" + if family.arm == "air-gapped": + return () if family.api == "scripted" else PROVIDER_HOSTS["ollama"] + provider = () if family.api == "scripted" else PROVIDER_HOSTS.get(family.provider, ()) + return provider + SYSTEM_HOSTS.get(system_id or "", ()) + + +@dataclass(frozen=True) +class ProxyEvent: + """One access-log line: one connection attempt and Squid's decision.""" + + at: str + client: str + method: str + host: str + port: int + status: int + result: str + hierarchy: str | None = None # absent in the original seven-field format + peer_status: int | None = None + + @property + def outcome(self) -> Literal["denied", "reached", "unconfirmed", "unknown"]: + # Squid 6.14 LogTags::c_str appends _TIMEDOUT, then _ABORTED. + tag = self.result.removesuffix("_ABORTED").removesuffix("_TIMEDOUT") + if tag == "TCP_DENIED": + # This config uses Squid's default 403 request ACL denial. + if ( + self.status == 403 + and self.hierarchy in (None, "HIER_NONE") + and self.peer_status is None + ): + return "denied" + return "unknown" + connect = self.method == "CONNECT" + expected = "TCP_TUNNEL" if connect else "TCP_MISS" + if self.hierarchy is None: # older logs cannot attribute a non-2xx to the origin + success = self.status == 200 if connect else 200 <= self.status < 300 + if tag == expected: + if self.result == tag and success: + return "reached" + if not connect or self.result != tag: + return "unconfirmed" # legacy transfers may break after response headers + if self.hierarchy == "HIER_DIRECT" and tag == expected: + if connect and self.status == 200 and self.peer_status is None: + return "reached" # Squid established the tunnel, then answered CONNECT itself + if not connect and self.peer_status is not None: + return "reached" # an HTTP status received from the origin, including errors + if ( + self.hierarchy in (None, "HIER_NONE", "HIER_DIRECT") + and self.peer_status is None + and (self.status == 0 or self.status >= 400) + and tag in ("TCP_MISS", "NONE_NONE", expected) + ): + return "unconfirmed" # can corroborate policy, never a billed call + return "unknown" + + @property + def allowed(self) -> bool: + """Only a logged request ACL denial establishes that Squid blocked the request.""" + return self.outcome != "denied" + + @property + def reached(self) -> bool: + return self.outcome == "reached" + + @property + def target(self) -> str: + return f"{self.host}:{self.port}" + + +def parse_proxy_log(text: str) -> list[ProxyEvent]: + """Every line of a Squid access log in the ``bench`` format; any bad line is an error. + + Each line must end with a newline: an unterminated last line means the proxy stopped + mid-write, so the log cannot be trusted. + """ + lines = text.split("\n") + if lines[-1]: + raise BenchmarkValidationError(f"proxy log line {len(lines)} is unterminated") + events = [] + width = len(lines[0].split(" ")) + for number, line in enumerate(lines[:-1], 1): + fields = line.split(" ") + try: + at, client, method, host, port, status, result, *extra = fields + if not all(fields) or len(fields) != width: + raise ValueError("empty field or log format changed") + if not re.fullmatch( + r"[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}\.[0-9]{3}Z", at + ): + raise ValueError("invalid timestamp") + datetime.fromisoformat(at) + ip_address(client) + hierarchy, peer_status = None, None + if extra: + hierarchy, peer = extra + if peer != "-": + if not re.fullmatch(r"[1-5][0-9]{2}", peer): + raise ValueError("invalid next-hop HTTP status") + peer_status = int(peer) + if not port.isascii() or not port.isdecimal() or not 0 < int(port) <= 65535: + raise ValueError("invalid port") + if not re.fullmatch(r"0|000|[1-5][0-9]{2}", status): + raise ValueError("invalid client HTTP status") + events.append( + ProxyEvent( + at, client, method, host, int(port), int(status), result, hierarchy, peer_status + ) + ) + except ValueError as exc: + raise BenchmarkValidationError(f"proxy log line {number} is malformed") from exc + return events + + +_SQUID_HEAD = f"""\ +http_port {EGRESS_PORT} +visible_hostname {EGRESS_ALIAS} +pid_filename none +cache deny all +shutdown_lifetime 1 seconds +httpd_suppress_version_string on +logfile_rotate 0 +logformat bench %{{%Y-%m-%dT%H:%M:%S}}tg.%03tuZ %>a %rm %>rd %>rP %>Hs %Ss %Sh % str: + """One proxy's config: only ``allow``, logged to a file with no rotation. + + Port 443 allows only CONNECT, any other port only plain HTTP. Every host ACL is + ``dstdomain -n``: no reverse lookup, so an IP-literal request never matches a name. + No TLS interception, and no ``dst`` ACL (it resolves names). + """ + lines = [] + for index, (host, port) in enumerate(allow, 1): + method = "CONNECT" if port == 443 else "!CONNECT" + lines += [ + f"acl allow_{index}_host dstdomain -n {host}", + f"acl allow_{index}_port port {port}", + f"http_access allow {method} allow_{index}_host allow_{index}_port", + ] + return _SQUID_HEAD + "".join(f"{line}\n" for line in lines) + "http_access deny all\n" + + +# The job's private spool is mode 0777 because Squid runs as `proxy` and the host cannot +# chown it on Docker Desktop for macOS. Anything in it may be a link a compromised proxy planted, +# so the host never follows one: read_log opens with O_NOFOLLOW and refuses a non-regular file, +# and write_new writes a new O_EXCL file and renames it over the name. Upgrade to a directory +# chowned to the proxy's uid, mode 0750, if Linux hosts are ever supported. +_READ_FLAGS = os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK | os.O_CLOEXEC # a FIFO never blocks +_NEW_FLAGS = os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW | os.O_CLOEXEC +_MAX_SQUID_LOG_BYTES = 8 * 1024 * 1024 + + +@contextmanager +def open_log_dir(path: Path) -> Iterator[int]: + try: + fd = os.open(path, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW | os.O_CLOEXEC) + except OSError as exc: + raise BenchmarkValidationError(f"log directory is a link or unavailable: {exc}") from exc + try: + yield fd + finally: + os.close(fd) + + +def read_log(path: Path) -> bytes: + with open_log_dir(path.parent) as dir_fd: + return read_log_at(dir_fd, path.name, max_bytes=_MAX_SQUID_LOG_BYTES) + + +def read_log_at(dir_fd: int, name: str, *, max_bytes: int | None = None) -> bytes: + """Read a stable-length regular file without following a link or blocking on a FIFO.""" + try: + fd = os.open(name, _READ_FLAGS, dir_fd=dir_fd) + except FileNotFoundError: + raise BenchmarkValidationError(f"{name} is missing") from None + except OSError as exc: # ELOOP: a link + raise BenchmarkValidationError(f"{name} was refused ({exc.strerror})") from None + try: + info = os.fstat(fd) + if not stat.S_ISREG(info.st_mode): + raise BenchmarkValidationError(f"{name} is not a regular file") + size = info.st_size + if max_bytes is not None and size > max_bytes: + raise BenchmarkValidationError(f"{name} exceeds the {max_bytes}-byte limit") + data = bytearray() + # Probe one byte past the descriptor's initial length, even at the limit. + while chunk := os.read(fd, min(1 << 20, size - len(data) + 1)): + if len(chunk) > size - len(data): + raise BenchmarkValidationError(f"{name} grew during collection") + data.extend(chunk) + if len(data) != size or os.fstat(fd).st_size != size: + raise BenchmarkValidationError(f"{name} changed size during collection") + return bytes(data) + finally: + os.close(fd) + + +def write_new(dir_fd: int, name: str, data: bytes, *, mode: int = 0o600) -> None: + """Replace ``name`` by a new file holding ``data``: never written through the old name. + + The bytes go to a new file in the same directory, created exclusively, then renamed over + ``name``, which replaces a link itself, never its target. + """ + temporary = f".{name}.{secrets.token_hex(8)}.tmp" + fd = os.open(temporary, _NEW_FLAGS, 0o600, dir_fd=dir_fd) + try: + try: + os.fchmod(fd, mode) # exactly ``mode``, whatever the umask + view = memoryview(data) + while view: + view = view[os.write(fd, view) :] + finally: + os.close(fd) + os.replace(temporary, name, src_dir_fd=dir_fd, dst_dir_fd=dir_fd) + except BaseException: + with suppress(FileNotFoundError): + os.unlink(temporary, dir_fd=dir_fd) + raise + + +def write_scanned_json(path: Path, record: dict[str, Any]) -> None: + """Publish complete, key-scanned probe or summary evidence.""" + data = scanned_json_bytes(record, where="JSON evidence", indent=2, sort_keys=True) + b"\n" + path.parent.mkdir(parents=True, exist_ok=True) + with open_log_dir(path.parent) as dir_fd: + write_new(dir_fd, path.name, data, mode=0o644) + + +def forbidden_env_names(environ: Mapping[str, str]) -> list[str]: + """The proxy and CA variable names set in ``environ``, sorted; never their values.""" + return sorted(name for name in environ if FORBIDDEN_ENV.match(name)) + + +# --- C1 evidence: egress/summary.json, in the shape PR 5 (#199) reads ------------------------ + + +def lookup_attempts(out_dir: Path, family_id: str, system_id: str) -> int: + """The model's ``lookup_package_docs`` calls in one job's scored and discarded records.""" + cell = re.compile(rf"{re.escape(system_id)}--{re.escape(family_id)}--r\d+") + count = 0 + for kind in ("transcripts", "discarded"): + root = out_dir / kind + cells = [c for c in root.iterdir() if cell.fullmatch(c.name)] if root.is_dir() else [] + for path in (p for c in cells for p in sorted(c.glob("*.json"))): + record = json.loads(path.read_text(encoding="utf-8")) + calls = record.get("tool_calls") if isinstance(record, dict) else None + if not isinstance(calls, list): + raise BenchmarkValidationError(f"invalid tool_calls in {path}") + for call in calls: + if not isinstance(call, dict) or not isinstance(call.get("tool"), str): + raise BenchmarkValidationError(f"invalid tool call in {path}") + count += call["tool"] == "lookup_package_docs" + return count + + +def pending_collection(out_dir: Path, job_id: str) -> Path: + """Host-owned marker, outside the proxy mount, until collection completes cleanly.""" + return out_dir / "probe" / f"{job_id}.collection-pending" + + +def _job_hosts(out_dir: Path, job: WorkerJob) -> tuple[bool, list[ProxyEvent]]: + """Whether the job's collection, probe and log all hold, and its query-time events. + + Query time is every access-log line after the probe's verified ``proxy_prefix``: probe + traffic never reaches the summary. Anything unreadable gives (False, []). + """ + job_id = job.job_id + log_dir = out_dir / "egress" / job_id + try: + probe = json.loads((out_dir / "probe" / f"{job_id}.json").read_text(encoding="utf-8")) + try: + pending_collection(out_dir, job_id).lstat() + except FileNotFoundError: + pass + else: + return False, [] + with open_log_dir(log_dir) as dir_fd: + collected = json.loads(read_log_at(dir_fd, "collected.json")) + text = read_log_at(dir_fd, "access.log").decode("utf-8") + events = parse_proxy_log(text) + except (OSError, ValueError, MemoryError): + return False, [] + prefix = probe.get("proxy_prefix") if isinstance(probe, dict) else None + if not isinstance(prefix, list) or not prefix or text.splitlines()[: len(prefix)] != prefix: + return False, [] # truncated, or lines before the probe's own + permitted = allowlist(job.family, job.system.id) + ok = ( + probe.get("passed") is True + and isinstance(collected, dict) + and collected.get("ok") is True + and all( + e.outcome == "denied" + or ( + e.outcome in ("reached", "unconfirmed") + and (e.host, e.port) in permitted + and (e.method == "CONNECT") == (e.port == 443) + ) + for e in events + ) + ) + return ok, events[len(prefix) :] + + +def write_egress_summary( + out_dir: Path, jobs: Sequence[WorkerJob], ledger_events: Sequence[Mapping[str, Any]] +) -> dict[str, Any]: + """``out_dir/egress/summary.json``: the C1 evidence, with exactly the keys #199 binds. + + ``isolation_probe`` is "pass" only when the control and every job's probe passed, every + collection was clean, every log holds its probe prefix, every non-denied attempt fits the + job ACL, each job has readable records for its lookup count, every ``ok`` settle in the ledger + is attributed to a planned job, and every hosted live job with an ``ok`` settle reached its + provider through its proxy (round-2 rulings C5, C6; round-3 items 1, 2). + """ + planned = {job.job_id for job in jobs} + reserved = {e["unit_id"]: e.get("job_id") for e in ledger_events if e["event"] == "reserve"} + billed: set[str] = set() + attributed = True + for event in ledger_events: + if event["event"] == "settle" and event.get("outcome") == "ok": + job_id = reserved.get(event["unit_id"]) + if job_id in planned: + billed.add(job_id) + else: # no reserve, a reserve without a job id, or a job outside the plan + attributed = False + try: + control = json.loads((out_dir / "probe" / "control.json").read_text(encoding="utf-8")) + passed = isinstance(control, dict) and control.get("passed") is True and attributed + except (OSError, ValueError): + passed = False + entries: dict[str, Any] = {} + for job in jobs: + ok, events = _job_hosts(out_dir, job) + allowed = sorted({e.target for e in events if e.reached}) + family = job.family + if family.arm == "hosted" and family.api != "scripted" and job.job_id in billed: + provider = {f"{h}:{p}" for h, p in PROVIDER_HOSTS.get(family.provider, ())} + ok = ok and bool(provider & set(allowed)) # billed, so it must show its provider + try: + attempts = lookup_attempts(out_dir, family.id, job.system.id) + except (OSError, ValueError): + # An interrupted record cannot establish a count. Keep the required integer + # and fail C1 without losing the other jobs or masking the run's abort. + attempts, ok = 0, False + passed = passed and ok + entries[job.job_id] = { + "hosts_allowed": allowed, + "hosts_denied": sorted({e.target for e in events if not e.allowed}), + "lookup_package_docs_attempts": attempts, + } + summary = {"jobs": entries, "isolation_probe": "pass" if passed else "fail"} + # The shape #199 reads, and nothing else (round-2 ruling E18). + assert set(summary) == {"jobs", "isolation_probe"} + assert all( + set(j) == {"hosts_allowed", "hosts_denied", "lookup_package_docs_attempts"} + for j in summary["jobs"].values() + ) + path = out_dir / "egress" / "summary.json" + write_scanned_json(path, summary) + return summary diff --git a/benchmarks/agentic/host.py b/benchmarks/agentic/host.py index d9a9c477..d55793f2 100644 --- a/benchmarks/agentic/host.py +++ b/benchmarks/agentic/host.py @@ -9,31 +9,38 @@ from __future__ import annotations import asyncio -import json import os import signal import subprocess import sys -from collections.abc import Awaitable, Callable, Mapping, Sequence -from contextlib import suppress +import tempfile +import traceback +from collections.abc import Awaitable, Callable, Iterator, Mapping, Sequence +from contextlib import contextmanager, suppress from dataclasses import asdict, dataclass +from functools import partial from pathlib import Path -from typing import Any, Protocol +from typing import Any, BinaryIO, Protocol from benchmarks.adapters.guard import PROVIDER_API_KEY_ENV from benchmarks.agentic.bridge import SystemSpec +from benchmarks.agentic.cleanup import add_cleanup_cause, add_safe_cleanup_cause, finish from benchmarks.agentic.ledger import LedgerService from benchmarks.agentic.loop import Caps from benchmarks.agentic.protocol import ( + KEY_SHAPED, MAX_FRAME_BYTES, + WORKER_FRAME_LIMIT_EXIT, + WORKER_LEAK_REASON, FrameTooLarge, KeyLeakError, - assert_no_key_shaped, encode_frame, read_frame, redact_key_shaped, + redact_key_shaped_text, ) from benchmarks.agentic.types import Buckets +from benchmarks.agentic.worker import MAX_RERUNS from benchmarks.model_matrix import ModelFamily from benchmarks.runner import BenchmarkValidationError @@ -41,6 +48,8 @@ _LOCAL_ENV = ("PATH", "HOME", "LANG", "TMPDIR", "XDG_CACHE_HOME", "VIRTUAL_ENV") #: How long teardown waits for a killed worker to exit before it scrubs and settles anyway. _EXIT_WAIT_S = 30.0 +#: Scan a whole snapshot so a token cannot straddle scan boundaries. Fail closed above this size. +_MAX_LOG_BYTES = 8 * 1024 * 1024 @dataclass(frozen=True) @@ -51,6 +60,21 @@ class WorkerJob: trajectories: tuple[dict[str, Any], ...] # {"corpus_id", "prompt", "repeat"}, in run order caps: Caps + def report_coordinates(self, message: dict[str, Any]) -> tuple[str, int]: + """Validate a cell report and return its host-planned output coordinates.""" + if message["type"] != "not_run" or "attempt" in message: + attempt = message.get("attempt") + if type(attempt) is not int or not 1 <= attempt <= 1 + MAX_RERUNS: + raise BenchmarkValidationError(f"worker {self.job_id} reported an invalid attempt") + + corpus_id, repeat = message.get("corpus_id"), message.get("repeat") + # JSON booleans and floats can compare equal to an integer repeat. + if isinstance(corpus_id, str) and type(repeat) is int: + for item in self.trajectories: + if (item["corpus_id"], item["repeat"]) == (corpus_id, repeat): + return item["corpus_id"], item["repeat"] + raise BenchmarkValidationError(f"worker {self.job_id} reported an unassigned trajectory") + class Launcher(Protocol): def supports(self, family: ModelFamily) -> bool: @@ -61,6 +85,22 @@ def command(self, job: WorkerJob) -> tuple[list[str], dict[str, str]]: """The worker's argv and its whole environment.""" raise NotImplementedError + def bootstrap_frame(self, job: WorkerJob) -> dict[str, Any] | None: + """The private first frame for the worker's stdin, or None. Called once, after prepare.""" + raise NotImplementedError + + async def prepare(self, jobs: Sequence[WorkerJob]) -> None: + """Before any worker starts; raise to stop the run with nothing spent.""" + raise NotImplementedError + + async def stop_worker(self, job: WorkerJob) -> None: + """After the group kill and before the job's in-flight unit is settled.""" + raise NotImplementedError + + async def close(self) -> list[str]: + """After every worker is gone: release all; return problems, raise only KeyLeakError.""" + raise NotImplementedError + class LocalLauncher: """A local process with no provider key: scripted models only (PR 4 adds containers).""" @@ -72,6 +112,18 @@ def command(self, job: WorkerJob) -> tuple[list[str], dict[str, str]]: env = {name: os.environ[name] for name in _LOCAL_ENV if name in os.environ} return [sys.executable, "-m", "benchmarks", "agentic-worker"], env + def bootstrap_frame(self, job: WorkerJob) -> dict[str, Any] | None: + return None + + async def prepare(self, jobs: Sequence[WorkerJob]) -> None: + return None + + async def stop_worker(self, job: WorkerJob) -> None: + return None + + async def close(self) -> list[str]: + return [] + def refuse_host_keys(environ: Mapping[str, str]) -> None: # Every key name, competitors included. Only agentic-run calls this: the fixed-flow @@ -92,7 +144,8 @@ def _start_anchor() -> subprocess.Popen[bytes]: its pid, which is the group id, cannot be reused while the host may still signal it. It reads its stdin, a pipe only the host holds, so it also ends with a host killed outright. """ - # shortcut: needs cat on PATH (every CI runner image has it); PR 4's worker image must too + # The host's `cat`; run.sh checks for it, and the worker image has it too + # (benchmarks/sandbox/Dockerfile). return subprocess.Popen( ["cat"], stdin=subprocess.PIPE, @@ -107,8 +160,8 @@ def _kill_group(anchor: subprocess.Popen[bytes]) -> None: The anchor is not reaped before this, so the group id is still this job's. """ - # shortcut: reaches only this host's process tree; PR 4's container launcher must give the - # same guarantee, which removing the container does, and signal only what it holds. + # Reaches only this host's process tree. A container launcher's `stop_worker` removes its + # own container, which ends everything in it, before the unit is settled. # ESRCH, or EPERM (macOS, when the group holds only zombies, the anchor included). with suppress(ProcessLookupError, PermissionError): os.killpg(anchor.pid, signal.SIGKILL) @@ -122,45 +175,123 @@ async def _reap(anchor: subprocess.Popen[bytes]) -> None: await asyncio.to_thread(anchor.wait, _EXIT_WAIT_S) +def _diagnostic(message: str) -> None: + # During terminal hangup even stderr can be closed. + if sys.stderr is not None: + with suppress(OSError, ValueError): + print(redact_key_shaped_text(message), file=sys.stderr, flush=True) + + async def _teardown( - proc: asyncio.subprocess.Process, + proc: asyncio.subprocess.Process | None, anchor: subprocess.Popen[bytes], log_path: Path, ledger: LedgerService, in_flight: str | None, -) -> str | None: - """Kill the worker's group, scrub its log and book its open unit; the log's key pattern.""" - try: - # The whole group, even after the worker exited: no descendant outlives it to write. + worker_log: BinaryIO, + stop_worker: Callable[[], Awaitable[None]] | None = None, + on_leak: Callable[[KeyLeakError], None] | None = None, +) -> None: + """Kill the worker, scrub its log and book any open unit before teardown returns.""" + + errors: list[BaseException] = [] + location = f"worker teardown ({log_path.name})" + + @contextmanager + def attempt() -> Iterator[None]: + # Report each job's failures before gather drains it, and attempt every cleanup step. try: - _kill_group(anchor) - with suppress(TimeoutError): # a worker that never exits cannot hang the run + yield + except BaseException as exc: # noqa: BLE001 - propagate after all cleanup steps + if isinstance(exc, KeyLeakError): + ledger.stop_grants() + if on_leak is not None: + on_leak(exc) + errors.append(exc) + + with attempt(): + _kill_group(anchor) + if proc is not None: + with suppress(TimeoutError): await asyncio.wait_for(proc.wait(), _EXIT_WAIT_S) - finally: - await _reap(anchor) - return _publish_scrubbed(log_path) - finally: # whatever happened to the log - if in_flight is not None: # may have been billed: booked at twice its bound + with attempt(): + await _reap(anchor) + if stop_worker is not None: + with attempt(): + await stop_worker() + with attempt(): + redacted, pattern = _scrubbed_snapshot(worker_log) + if pattern: + ledger.stop_grants() + detected = f"a key-shaped string ({pattern} pattern) was found in {log_path}" + leak = KeyLeakError(detected) if pattern else None + if leak is not None and on_leak is not None: + on_leak(leak) + try: + _publish_worker_log(redacted, log_path) + except Exception: + if leak is not None: + # Keep the leak primary and report the storage error after settlement. + leak.args = (f"{detected}; scrubbed log publication failed",) + errors.append(leak) + raise + if leak is not None: + leak.args = (f"{detected}; redacted there",) + raise leak + with attempt(): + worker_log.close() + if in_flight is not None: + with attempt(): await ledger.settle(in_flight, outcome="worker_lost", buckets=None) - -def _publish_scrubbed(log_path: Path) -> str | None: - """Replace the log by its scrubbed snapshot; the key pattern it held, if any. - - On every exit, a raise or a cancel included, the leaked bytes never stay on disk. The copy - replaces the log, so a writer still holding it writes into an unlinked file. If the copy - cannot be published, the log is unlinked instead, for the same reason. - """ - redacted, pattern = redact_key_shaped(log_path.read_bytes()) - scrubbed = log_path.with_name(log_path.name + ".tmp") + # Formatting failures must never interrupt mandatory scrubbing or accounting. + for i, exc in enumerate(errors): + try: + detail = f"{location}: {type(exc).__name__}: {redact_key_shaped_text(str(exc))}" + if KEY_SHAPED.search("".join(traceback.format_exception(exc, limit=0))): + # An outer exception may be clean while its notes or chained daemon error leak. + leak = KeyLeakError(detail + " (key shape redacted)") + errors[i] = leak + ledger.stop_grants() + if on_leak is not None: + on_leak(leak) + else: + exc.add_note(location) + _diagnostic(detail) + except Exception: # noqa: BLE001 - an unscannable failure must not enter the traceback + leak = KeyLeakError(f"{location}: could not safely report {type(exc).__name__}") + errors[i] = leak + ledger.stop_grants() + if on_leak is not None: + on_leak(leak) + if errors: + for primary, secondary in zip(errors, errors[1:]): + add_cleanup_cause(primary, secondary) + raise errors[0] + + +def _scrubbed_snapshot(worker_log: BinaryIO) -> tuple[bytes, str | None]: + """Late writers keep their anonymous inode and offset.""" + fd = worker_log.fileno() + size = os.fstat(fd).st_size + if size > _MAX_LOG_BYTES: + raise BenchmarkValidationError(f"worker log exceeds the {_MAX_LOG_BYTES}-byte scan limit") + data = os.pread(fd, size, 0) + if len(data) != size: + raise OSError("incomplete worker log read") + return redact_key_shaped(data) + + +def _publish_worker_log(redacted: bytes, log_path: Path) -> None: + stage = tempfile.NamedTemporaryFile(dir=log_path.parent, suffix=".tmp", delete=False) try: - scrubbed.write_bytes(redacted) - os.replace(scrubbed, log_path) - except OSError: # a full or read-only disk, say - log_path.unlink(missing_ok=True) - scrubbed.unlink(missing_ok=True) + with stage: + if stage.write(redacted) != len(redacted): + raise OSError("incomplete scrubbed log write") + os.replace(stage.name, log_path) + except BaseException: + os.unlink(stage.name) raise - return pattern async def _supervise( @@ -172,32 +303,55 @@ async def _supervise( log_dir: Path, cwd: Path, max_frame_bytes: int, + aborted: asyncio.Event, + on_failure: Callable[[KeyLeakError | FrameTooLarge], None], ) -> None: argv, env = launcher.command(job) log_path = log_dir / f"{job.job_id}.stderr.log" - anchor = _start_anchor() + # On POSIX the TemporaryFile fallback unlinks before returning the descriptor. + with tempfile.TemporaryDirectory() as private_dir: + log = tempfile.TemporaryFile(dir=private_dir, buffering=0) try: - with log_path.open("wb") as log: - proc = await asyncio.create_subprocess_exec( - *argv, - env=env, - cwd=cwd, - stdin=asyncio.subprocess.PIPE, - stdout=asyncio.subprocess.PIPE, - stderr=log, - process_group=anchor.pid, # the anchor's group, which teardown kills whole - ) - except BaseException: # the start error, never a kill error, reaches the summary - _kill_group(anchor) - await _reap(anchor) + anchor = _start_anchor() + except BaseException: + log.close() raise - assert proc.stdin is not None and proc.stdout is not None + proc = None in_flight: str | None = None reported: set[tuple[str, int]] = set() done = False lost_reason = "worker_lost" try: + proc = await asyncio.create_subprocess_exec( + *argv, + env=env, + cwd=cwd, + stdin=asyncio.subprocess.PIPE, + stdout=asyncio.subprocess.PIPE, + stderr=log, + process_group=anchor.pid, # the anchor's group, which teardown kills whole + ) + assert proc.stdin is not None and proc.stdout is not None + silence_s = job.caps.trajectory_s + job.caps.model_call_timeout_s + + async def check_terminal_status() -> None: + # EOF can precede process exit (including the redactor's final drain). Only + # inspect this owned child, before teardown can replace its status with SIGKILL. + with suppress(TimeoutError): + status = await asyncio.wait_for(proc.wait(), min(silence_s, 5)) + if status == 3: + raise KeyLeakError(f"worker {job.job_id}: {WORKER_LEAK_REASON} (exit 3)") + if status == WORKER_FRAME_LIMIT_EXIT: + raise FrameTooLarge( + f"worker {job.job_id}: protocol frame limit exceeded (exit {status})" + ) + try: + # The private key frame first, then the job. The frame is never logged or kept. + if (bootstrap := launcher.bootstrap_frame(job)) is not None: + proc.stdin.write(encode_frame(bootstrap)) + del bootstrap + await proc.stdin.drain() job_frame = { "type": "job", "job_id": job.job_id, @@ -206,18 +360,19 @@ async def _supervise( "trajectories": list(job.trajectories), "caps": asdict(job.caps), } - proc.stdin.write(encode_frame(job_frame)) + proc.stdin.write(encode_frame(job_frame, where="job frame")) await proc.stdin.drain() # Between two frames a worker runs one model call or a trajectory's other tool # calls, plus a backoff of at most 120 s: silent for longer, it is lost. - silence_s = job.caps.trajectory_s + job.caps.model_call_timeout_s - while ( - message := await asyncio.wait_for( - read_frame(proc.stdout, limit=max_frame_bytes), silence_s - ) - ) is not None: - where = f"a frame from worker {job.job_id}" - assert_no_key_shaped(json.dumps(message, ensure_ascii=False), where=where) + while True: + # Decode in this task so a credential failure latches before another task runs. + async with asyncio.timeout(silence_s): + message = await read_frame( + proc.stdout, limit=max_frame_bytes, where="worker frame" + ) + if message is None: + await check_terminal_status() + break kind = message.get("type") reply: dict[str, Any] | None = None if kind == "reserve": @@ -233,6 +388,7 @@ async def _supervise( int(message["output_bound"]), job.family.max_output_tokens or 0 ), kind=str(message.get("kind", "model_call")), + job_id=job.job_id, ) reply = ( {"type": "grant", "unit_id": in_flight} if in_flight else {"type": "deny"} @@ -252,49 +408,57 @@ async def _supervise( reply = {"type": "ack"} elif kind == "error": reason = str(message.get("reason")) + recognized: KeyLeakError | FrameTooLarge | None = None + if reason in (WORKER_LEAK_REASON, "own key found in output"): + recognized = KeyLeakError(f"worker {job.job_id}: {reason}") + elif reason.startswith("FrameTooLarge:"): + recognized = FrameTooLarge(f"worker {job.job_id}: {reason}") + if recognized is not None: + on_failure(recognized) # before waiting for exit or sibling cleanup with suppress(TimeoutError): # its drain writes the last lines to the log await asyncio.wait_for(proc.wait(), 5) - if reason == "own key found in output": - raise KeyLeakError(f"worker {job.job_id}: {reason}") - if reason.startswith("FrameTooLarge:"): - raise FrameTooLarge(f"worker {job.job_id}: {reason}") + if recognized is not None: + raise recognized # Any other failure costs only this job's cells, like a lost worker. lost_reason = "worker_error" await on_message(job, {"type": "worker_error", "reason": reason}) break else: - await on_message(job, message) - # Only a final report: a retries_exhausted discard still owes its rerun, - # and its last attempt sends its own not_run. - if kind in ("trajectory", "not_run") or ( - kind == "discarded" and message["reason"] == "budget_stop" - ): - reported.add((message["corpus_id"], message["repeat"])) + if kind in ("trajectory", "discarded", "not_run"): + coordinates = job.report_coordinates(message) + # A retries_exhausted discard still owes its rerun or a final not_run. + if kind != "discarded" or message["reason"] == "budget_stop": + reported.add(coordinates) + if not aborted.is_set(): + await on_message(job, message) done = done or kind == "done" if kind in ("trajectory", "discarded"): reply = {"type": "ack"} if reply is not None: - proc.stdin.write(encode_frame(reply)) + proc.stdin.write(encode_frame(reply, where="host reply")) await proc.stdin.drain() - except (BrokenPipeError, ConnectionResetError, TimeoutError): + except (BrokenPipeError, ConnectionResetError): + await check_terminal_status() + except TimeoutError: pass # the worker died or stalled; handled as a lost worker below + except (KeyLeakError, FrameTooLarge) as recognized: + on_failure(recognized) + raise finally: - # Runs to its end even when a second abort cancels this task meanwhile; then re-raise. - teardown = asyncio.ensure_future(_teardown(proc, anchor, log_path, ledger, in_flight)) - cancelled: asyncio.CancelledError | None = None - while not teardown.done(): - try: - await asyncio.shield(teardown) - except asyncio.CancelledError as exc: - cancelled = exc - pattern = teardown.result() - if cancelled is not None: - raise cancelled - if pattern: - raise KeyLeakError( - f"a key-shaped string ({pattern} pattern) was found in {log_path}; redacted there" + await finish( + _teardown( + proc, + anchor, + log_path, + ledger, + in_flight, + log, + partial(launcher.stop_worker, job), + on_failure, + ), + sys.exception(), ) - if not done: + if not done and not aborted.is_set(): for item in job.trajectories: if (item["corpus_id"], item["repeat"]) not in reported: await on_message( @@ -324,27 +488,118 @@ async def run_jobs( if unsupported: raise BenchmarkValidationError( f"the {type(launcher).__name__} cannot run model families {unsupported}: " - "the local launcher runs only scripted models (live runs need PR 4's containers)" + "the local launcher runs only scripted models; use --launcher container" ) log_dir.mkdir(parents=True, exist_ok=True) - tasks = [ - asyncio.create_task( - _supervise( - job, - launcher=launcher, - ledger=ledger, - on_message=on_message, - log_dir=log_dir, - cwd=cwd, - max_frame_bytes=max_frame_bytes, - ) - ) - for job in jobs - ] + primary: KeyLeakError | FrameTooLarge | None = None + aborted = asyncio.Event() + + def recognize(failure: KeyLeakError | FrameTooLarge) -> None: + nonlocal primary + ledger.stop_grants() + aborted.set() + if primary is None: + primary = failure + elif isinstance(primary, FrameTooLarge) and isinstance(failure, KeyLeakError): + add_safe_cleanup_cause(failure, primary) + primary = failure + + failed = True try: - await asyncio.gather(*tasks) - except BaseException: - for task in tasks: - task.cancel() # each supervisor kills its worker on the way out - await asyncio.gather(*tasks, return_exceptions=True) - raise + await launcher.prepare(jobs) # raises before any worker starts + tasks = [ + asyncio.create_task( + _supervise( + job, + launcher=launcher, + ledger=ledger, + on_message=on_message, + log_dir=log_dir, + cwd=cwd, + max_frame_bytes=max_frame_bytes, + aborted=aborted, + on_failure=recognize, + ) + ) + for job in jobs + ] + failure: BaseException | None = None + try: + await asyncio.gather(*tasks) + except BaseException as exc: + for task in tasks: + task.cancel() # each supervisor kills its worker on the way out + + async def outcome(task: asyncio.Task[None]) -> BaseException | None: + try: + await task + except BaseException as error: + # gather(return_exceptions=True) substitutes a fresh CancelledError, + # losing any teardown failure chained to the original cancellation. + return error + return None + + drained = asyncio.gather(*(outcome(task) for task in tasks)) + try: + await finish(drained, exc) + except BaseException as interrupted: + failure = interrupted + else: + failure = exc + if primary is not None: + # Preserve interrupts, then credential failures, then structural frame failures, + # even when the recognizing supervisor was cancelled during cleanup. + selected = failure if not isinstance(failure, Exception) else primary + prior = selected.__cause__ if selected is not primary else None + if prior is not None and prior is not primary: + selected.__cause__ = None + seen = {id(selected)} + if selected.__cause__ is primary: + seen.add(id(primary)) + for error in (failure, primary, prior, selected.__context__, *drained.result()): + if isinstance(error, asyncio.CancelledError): + error = error.__cause__ or error.__context__ + if isinstance(error, Exception) and id(error) not in seen: + seen.add(id(error)) + add_safe_cleanup_cause(selected, error) + # A cancellation raised by finish while handling a sibling exception + # acquires that raw exception as implicit context. Keep only its safe copy. + selected.__context__ = None + failure = selected + if failure is not None: + # Outside the handler: don't retain the losing raw exception as __context__. + raise failure + failed = False + finally: + reported: BenchmarkValidationError | None = None + + async def close() -> None: + nonlocal reported + if problems := await launcher.close(): + detail = redact_key_shaped_text("; ".join(problems)) + if failed: + _diagnostic(f"launcher cleanup problems: {detail}") + reason = ( + "launcher cleanup problems" + if failed + else "the run completed, but the launcher reported problems" + ) + reported = BenchmarkValidationError(f"{reason}: {detail}") + raise reported + + pending = sys.exception() + try: + await finish(close(), pending) + except KeyLeakError as leak: + if leak is pending: + raise + if isinstance(pending, Exception): + # The CLI prints only the final message. Keep earlier resource IDs visible. + earlier = redact_key_shaped_text(str(pending)) + raise KeyLeakError( + f"{redact_key_shaped_text(str(leak))}; earlier failure: {earlier}" + ) from None + raise + except BenchmarkValidationError as exc: + if not failed or exc is not reported: + raise diff --git a/benchmarks/agentic/inputs.py b/benchmarks/agentic/inputs.py new file mode 100644 index 00000000..8f7e4a6c --- /dev/null +++ b/benchmarks/agentic/inputs.py @@ -0,0 +1,107 @@ +"""Captured, scanned input bytes shared by planning and reference evidence readers. + +Scan raw bytes and decoded values before any schema validator can quote them. YAML +scalars are checked before construction loses aliases, merges or duplicate values. +""" + +from __future__ import annotations + +import json +from dataclasses import dataclass +from pathlib import Path +from typing import Any + +import yaml +from yaml.tokens import ScalarToken + +from benchmarks.agentic.protocol import ( + KeyLeakError, + assert_no_key_shaped, + assert_no_key_shaped_json, +) +from benchmarks.runner import BenchmarkValidationError, _require_yaml_mapping + + +def _read_bytes(path: Path, name: str, label: str) -> bytes: + where = f"input {name}" + assert_no_key_shaped(str(path), where="input path") + try: + content = path.read_bytes() + except FileNotFoundError: + raise BenchmarkValidationError(f"{label} file does not exist: {path}") from None + except OSError as exc: + raise BenchmarkValidationError(f"cannot read {label} file {path}: {exc.strerror}") from None + assert_no_key_shaped(content, where=where) # includes comments and discarded values + return content + + +@dataclass(frozen=True) +class CapturedInput: + name: str + content: bytes + mapping: dict[str, Any] + + @classmethod + def read(cls, path: Path, name: str, label: str) -> CapturedInput: + content = _read_bytes(path, name, label) + where = f"input {name}" + try: + text = content.decode("utf-8") # same encoding as the path-based loaders + for token in yaml.scan(text, Loader=yaml.SafeLoader): + if isinstance(token, ScalarToken): + # Construction can discard a value under a merge or a duplicate key. + assert_no_key_shaped(token.value, where=where) + data = yaml.safe_load(text) + except KeyLeakError: + raise + except ( + yaml.YAMLError, + ValueError, + TypeError, + LookupError, + AttributeError, + OverflowError, + RecursionError, + ) as exc: + # PyYAML messages can quote source, even for constructor errors without a mark. + mark = getattr(exc, "problem_mark", None) + location = f" at line {mark.line + 1}, column {mark.column + 1}" if mark else "" + raise BenchmarkValidationError(f"{label} file is not valid YAML{location}") from None + assert_no_key_shaped_json(data, where=where) # e.g. bytes constructed by !!binary + return cls(name, content, _require_yaml_mapping(data, label)) + + +def _json_mapping(content: bytes, label: str) -> dict[str, Any]: + def checked_pairs(pairs: list[tuple[str, Any]]) -> dict[str, Any]: + # Scan before dict construction discards a duplicate key's earlier value. + assert_no_key_shaped_json(pairs, where=label) + return dict(pairs) + + try: + data = json.loads(content, object_pairs_hook=checked_pairs) + except KeyLeakError: + raise + except (ValueError, TypeError, RecursionError): + raise BenchmarkValidationError(f"{label} file is not valid JSON") from None + assert_no_key_shaped_json(data, where=label) + return _require_yaml_mapping(data, label) + + +@dataclass(frozen=True) +class CapturedJSON: + content: bytes + mapping: dict[str, Any] + + @classmethod + def read(cls, path: Path, label: str) -> CapturedJSON: + content = _read_bytes(path, label, label) + return cls(content, _json_mapping(content, label)) + + +def read_json(path: Path, label: str) -> dict[str, Any]: + return CapturedJSON.read(path, label).mapping + + +def read_jsonl(path: Path, label: str) -> list[dict[str, Any]]: + content = _read_bytes(path, label, label) + return [_json_mapping(line, label) for line in content.splitlines() if line] diff --git a/benchmarks/agentic/ledger.py b/benchmarks/agentic/ledger.py index 069d8939..e4abceca 100644 --- a/benchmarks/agentic/ledger.py +++ b/benchmarks/agentic/ledger.py @@ -21,6 +21,7 @@ from pathlib import Path from typing import Any, Literal +from benchmarks.agentic.protocol import scanned_json_bytes from benchmarks.agentic.types import Buckets from benchmarks.model_matrix import ModelFamily from benchmarks.runner import BenchmarkValidationError, _load_yaml_mapping @@ -37,6 +38,9 @@ "google": Decimal(20), } +#: Local providers: one unit in flight at a time, never priced, capped or booked. +UNMETERED_PROVIDERS = frozenset({"ollama"}) + Outcome = Literal[ "ok", "rejected", @@ -85,7 +89,10 @@ class PriceSnapshot: def load_price_snapshot(path: Path) -> PriceSnapshot: - data = _load_yaml_mapping(path, "price snapshot") + return price_snapshot_from_mapping(_load_yaml_mapping(path, "price snapshot")) + + +def price_snapshot_from_mapping(data: dict[str, Any]) -> PriceSnapshot: captured_on = _date(data.get("captured_on"), "captured_on") if captured_on is None: raise BenchmarkValidationError("price snapshot must set 'captured_on'") @@ -236,6 +243,7 @@ def __init__(self, ledger_dir: Path, run_id: str, caps: dict[str, Decimal], lock self._caps = caps self._lock_fd: int | None = lock_fd self._events: list[dict[str, Any]] = [] + self._invocation_start = 0 self._spent: dict[str, Decimal] = {} self._stops: dict[str, str] = {} self._units: dict[str, tuple[str, Decimal]] = {} # unit id -> (provider, bound) @@ -248,28 +256,28 @@ def open( ledger_dir.mkdir(parents=True, exist_ok=True) lock_path = ledger_dir / ".lock" fd = os.open(lock_path, os.O_RDWR | os.O_CREAT, 0o600) - os.fchmod(fd, 0o600) # also an existing lock file, whatever mode it was left with - try: - # shortcut: fcntl is POSIX only; the harness runs on macOS and Linux, add msvcrt.locking if Windows runs are ever needed # noqa: E501 - fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB) - except OSError as exc: - os.close(fd) - raise BenchmarkValidationError( - f"spend ledger {lock_path} is locked by another process; one run at a time" - ) from exc - ledger = cls(ledger_dir, run_id, dict(caps), fd) try: + os.fchmod(fd, 0o600) # an existing lock file must also be private + try: + fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB) + except OSError as exc: + raise BenchmarkValidationError( + f"spend ledger {lock_path} is locked by another process; one run at a time" + ) from exc + ledger = cls(ledger_dir, run_id, dict(caps), fd) ledger._load() + return ledger except BaseException: - ledger.close() + os.close(fd) # closing also releases any lock acquired before the interruption raise - return ledger def close(self) -> None: - if self._lock_fd is not None: - fcntl.flock(self._lock_fd, fcntl.LOCK_UN) - os.close(self._lock_fd) - self._lock_fd = None + fd, self._lock_fd = self._lock_fd, None + if fd is not None: + try: + fcntl.flock(fd, fcntl.LOCK_UN) + finally: + os.close(fd) def _load(self) -> None: pending: dict[str, None] = {} # ordered set of reserves without a settle @@ -288,6 +296,7 @@ def _load(self) -> None: pending[event["unit_id"]] = None elif event["event"] == "settle": pending.pop(event["unit_id"], None) + self._invocation_start = len(self._events) for unit_id in pending: provider, _ = self._units[unit_id] self._in_flight[provider] = unit_id @@ -314,8 +323,9 @@ def _apply(self, event: dict[str, Any]) -> None: def _append(self, provider: str, fields: dict[str, Any]) -> None: event = {"run_id": self._run_id, "provider": provider, "at": _utc_now(), **fields} - with (self._dir / f"{provider}.jsonl").open("a", encoding="utf-8") as file: - file.write(json.dumps(event, sort_keys=True) + "\n") + line = scanned_json_bytes(event, where="spend ledger", sort_keys=True) + b"\n" + with (self._dir / f"{provider}.jsonl").open("ab") as file: + file.write(line) self._events.append(event) def spent(self, provider: str) -> Decimal: @@ -337,6 +347,7 @@ def reserve( bound: Decimal, input_bound: int, output_bound: int, + job_id: str | None = None, ) -> str | None: cap = self._caps.get(provider) if cap is None: @@ -361,6 +372,7 @@ def reserve( "bound": str(bound), "input_bound": input_bound, "output_bound": output_bound, + "job_id": job_id, # set by the host; attributes the unit's settle (C1) }, ) self._units[unit_id] = (provider, bound) @@ -403,6 +415,10 @@ def acknowledge_overrun(self, provider: str) -> None: del self._stops[provider] self._append(provider, {"event": "resume"}) + def invocation_events(self) -> list[dict[str, Any]]: + """Events written since this open, including recovery of earlier pending units.""" + return [dict(event) for event in self._events[self._invocation_start :]] + def events(self, run_id: str) -> list[dict[str, Any]]: return [dict(event) for event in self._events if event["run_id"] == run_id] @@ -421,6 +437,12 @@ def __init__( self._families = dict(families) self._locks: dict[str, asyncio.Lock] = {} self._units: dict[str, tuple[str, ModelPrice, int]] = {} + self._unmetered: dict[str, str] = {} # unit id -> provider + self._grants_stopped = False + + def stop_grants(self) -> None: + """Latch this invocation's stop without changing settlement or durable provider caps.""" + self._grants_stopped = True async def reserve( self, @@ -430,7 +452,19 @@ async def reserve( input_bound: int, output_bound: int, kind: str = "model_call", + job_id: str | None = None, ) -> str | None: + if self._grants_stopped: + return None + if provider in UNMETERED_PROVIDERS: # the Ledger never sees it + lock = self._locks.setdefault(provider, asyncio.Lock()) + await lock.acquire() + if self._grants_stopped: + lock.release() + return None + unit_id = f"{provider}-{uuid.uuid4().hex}" + self._unmetered[unit_id] = provider + return unit_id price = self._prices.get(model_id) if price is None: raise BenchmarkValidationError(f"no price snapshot entry for model {model_id!r}") @@ -440,6 +474,9 @@ async def reserve( bound = bound_cost(price, input_bound=input_bound, output_bound=output_bound) lock = self._locks.setdefault(provider, asyncio.Lock()) await lock.acquire() # held until this unit's settle + if self._grants_stopped: + lock.release() + return None try: unit_id = self._ledger.reserve( provider, @@ -448,6 +485,7 @@ async def reserve( bound=bound, input_bound=input_bound, output_bound=output_bound, + job_id=job_id, ) except BaseException: lock.release() @@ -459,6 +497,9 @@ async def reserve( return unit_id async def settle(self, unit_id: str, *, outcome: Outcome, buckets: Buckets | None) -> None: + if (local := self._unmetered.pop(unit_id, None)) is not None: + self._locks[local].release() + return provider, price, input_bound = self._units.pop(unit_id) try: if outcome == "ok" and (buckets is None or buckets.is_empty): diff --git a/benchmarks/agentic/live.py b/benchmarks/agentic/live.py new file mode 100644 index 00000000..4cf5b68b --- /dev/null +++ b/benchmarks/agentic/live.py @@ -0,0 +1,320 @@ +"""Live-run safety: the one authorization gate, reference rates and the full-run gate. + +``authorize_live`` is the one host-side check every live entry point calls (round-2 ruling +D9). It runs before any key is read and before any keyed container starts: it refuses under +``CI``, then needs an interactive ``yes`` to a plan that shows each provider's spend, cap, +remaining budget and estimate. +""" + +from __future__ import annotations + +import math +import os +import sys +from collections import defaultdict +from collections.abc import Callable, Mapping, Sequence +from dataclasses import dataclass +from decimal import Decimal, DecimalException +from pathlib import Path +from typing import TYPE_CHECKING, TextIO + +from benchmarks.agentic.inputs import CapturedInput, CapturedJSON, read_json, read_jsonl +from benchmarks.agentic.ledger import PROVIDER_MARGINS, UNMETERED_PROVIDERS +from benchmarks.agentic.protocol import KeyLeakError, assert_no_key_shaped +from benchmarks.agentic.reference import ReferenceTranscripts, ReferenceUnits +from benchmarks.model_matrix import model_matrix_from_mapping +from benchmarks.runner import BenchmarkValidationError + +if TYPE_CHECKING: + from benchmarks.agentic.host import WorkerJob + +#: Design §12: 10 questions x 3 systems x k = 3. More per provider needs a reference run. +PILOT_TRAJECTORIES_PER_PROVIDER = 90 +SAFETY = Decimal("1.25") +WINDOW_S = 86_400 +_NOT_CI = frozenset({"", "0", "false", "no"}) + + +@dataclass(frozen=True) +class ReferenceRate: + family_id: str + provider: str + cells: int # logical cells: one (cell, corpus_id), every attempt included + usd_per_cell: Decimal + seconds_per_cell: float + model_id: str | None = None + api: str | None = None + + +@dataclass(frozen=True) +class ProviderPlan: + provider: str + trajectories: int + spent: Decimal | None # the money fields are None for an unmetered provider + cap: Decimal | None + estimate: Decimal | None # None without a reference run + + +def reference_rates(run_dir: Path) -> dict[str, ReferenceRate]: + """Per family, a finished run's cost and time per logical cell (round-2 ruling D8). + + A logical cell is one (cell, corpus_id) over the family's scored and discarded records, + every attempt included, so a retry-heavy pilot never halves the estimate. + """ + try: + return _read_reference_rates(run_dir) + except KeyLeakError: + raise + except (OSError, ValueError, KeyError, TypeError, DecimalException, OverflowError) as exc: + diagnostic = f"invalid reference run {run_dir}: {exc}" + assert_no_key_shaped(diagnostic, where="reference diagnostic") + raise BenchmarkValidationError(diagnostic) from exc + + +def _read_reference_rates(run_dir: Path) -> dict[str, ReferenceRate]: + summary = read_json(run_dir / "run-summary.json", "reference summary") + if summary["status"] != "completed": + raise ValueError("the run did not complete") + # Budget stops and worker errors can leave status "completed" with cells unscored. + if ( + type(summary["scored_cells"]) is not int + or type(summary["planned_cells"]) is not int + or summary["scored_cells"] <= 0 + or summary["scored_cells"] != summary["planned_cells"] + ): + raise ValueError("the run did not score every planned cell") + seconds: dict[str, dict[tuple[str, str], float]] = defaultdict(lambda: defaultdict(float)) + matrix_input = CapturedInput.read( + run_dir / "snapshots" / "model-matrix.yml", "reference model-matrix.yml", "reference matrix" + ) + matrix = model_matrix_from_mapping(matrix_input.mapping) + families = {family.id: family for family in matrix.model_families} + units = ReferenceUnits() + transcripts = ReferenceTranscripts(summary) + scored: set[tuple[str, str]] = set() + discarded = { + (d["cell"], f"{d['corpus_id']}--attempt{d['attempt']}.json") for d in summary["discarded"] + } + for kind in ("transcripts", "discarded"): + for path in sorted((run_dir / kind).glob("*/*.json")): + captured = CapturedJSON.read(path, "reference transcript") + record = captured.mapping + transcripts.verify(path.relative_to(run_dir).as_posix(), captured.content, record) + family_id = record["model_family_id"] + provider = record["provider"] + family = families[family_id] + execution = record.get("execution") + if not isinstance(execution, dict) or any( + not isinstance(execution.get(field), str) or not execution[field] + for field in ("provider", "model_id", "api") + ): + raise ValueError( + f"reference transcript lacks executed provider/model/API for {family_id}" + ) + if (execution["provider"], execution["model_id"], execution["api"]) != ( + family.provider, + family.model_id, + family.api, + ): + raise ValueError( + f"executed client disagrees with the model snapshot for {family_id}" + ) + if (provider, record["model_id"]) != (family.provider, family.model_id): + raise ValueError(f"transcript disagrees with the model snapshot for {family_id}") + if record["competitor_id"] != path.parent.name: + raise ValueError("reference transcript cell disagrees with its path") + units.add(record, family) + timing = record["timing"] + cell = (record["competitor_id"], record["corpus_id"]) + elapsed = (timing["wall_ms"] - timing["grant_wait_ms"]) / 1000 + if not math.isfinite(elapsed) or elapsed < 0 or timing["grant_wait_ms"] < 0: + raise ValueError(f"invalid timing for {family_id} {cell}") + seconds[family_id][cell] += elapsed + if kind == "transcripts": + if cell in scored: + raise ValueError("duplicate scored reference cell") + scored.add(cell) + else: + discarded.remove((path.parent.name, path.name)) + transcripts.finish() + if discarded: + raise ValueError("missing discarded attempts from the reference run") + if len(scored) != summary["scored_cells"] or any( + cells.keys() - scored for cells in seconds.values() + ): + raise ValueError("scored transcripts do not cover the reference cells") + + # These events are parsed from the same captured bytes that were scanned for keys. + events = read_jsonl(run_dir / "ledger-events.jsonl", "reference ledger") + booked, measured = units.reconcile(events, summary) + rates = { + family_id: ReferenceRate( + family_id=family_id, + provider=families[family_id].provider, + model_id=families[family_id].model_id, + api=families[family_id].api, + cells=len(cells), + usd_per_cell=booked.get(family_id, Decimal(0)) / len(cells), + seconds_per_cell=sum(cells.values()) / len(cells), + ) + for family_id, cells in seconds.items() + if families[family_id].provider in UNMETERED_PROVIDERS or family_id in measured + if sum(cells.values()) > 0 + } + if not rates: + raise ValueError("no family has usable cost and timing measurements") + return rates + + +def _live_counts(jobs: Sequence[WorkerJob]) -> dict[str, dict[str, int]]: + """Planned live trajectories, per provider then per family.""" + counts: dict[str, dict[str, int]] = defaultdict(lambda: defaultdict(int)) + for job in jobs: + if job.family.api != "scripted": + counts[job.family.provider][job.family.id] += len(job.trajectories) + return counts + + +def _matching_rates( + jobs: Sequence[WorkerJob], rates: Mapping[str, ReferenceRate] | None +) -> dict[str, ReferenceRate]: + matching = {} + for job in jobs: + family = job.family + rate = rates.get(family.id) if rates is not None else None + if ( + rate is not None + and family.api not in (None, "scripted") + and (rate.provider, rate.model_id, rate.api) + == (family.provider, family.model_id, family.api) + ): + matching[family.id] = rate + return matching + + +def provider_plans( + jobs: Sequence[WorkerJob], + spent: Mapping[str, Decimal], + caps: Mapping[str, Decimal], + rates: Mapping[str, ReferenceRate] | None, +) -> list[ProviderPlan]: + """One plan per provider with live trajectories, sorted by provider.""" + plans = [] + matching = _matching_rates(jobs, rates) + for provider, families in sorted(_live_counts(jobs).items()): + trajectories = sum(families.values()) + if provider not in caps: # local and unmetered + plans.append(ProviderPlan(provider, trajectories, None, None, None)) + continue + estimate = None + if families.keys() <= matching.keys(): + estimate = sum( + (n * matching[f].usd_per_cell for f, n in families.items()), start=Decimal(0) + ) + plans.append( + ProviderPlan( + provider, trajectories, spent.get(provider, Decimal(0)), caps[provider], estimate + ) + ) + return plans + + +def full_run_gate( + plans: Sequence[ProviderPlan], + jobs: Sequence[WorkerJob], + rates: Mapping[str, ReferenceRate] | None, +) -> list[str]: + """Why this live run must not start: cost or time over budget, or no reference run. + + The per-graded-answer term of design §12 comes from PR 5's grading/summary.json. + """ + problems = [] + counts = _live_counts(jobs) + matching = _matching_rates(jobs, rates) + for plan in plans: + if rates is not None and (missing := counts[plan.provider].keys() - matching.keys()): + problems.append( + f"{plan.provider}: the reference needs measurements from the same model ID " + f"and live API for each requested family ({', '.join(sorted(missing))})" + ) + continue + if plan.cap is None or plan.spent is None: + continue + if plan.estimate is None: + if plan.trajectories > PILOT_TRAJECTORIES_PER_PROVIDER: + problems.append( + f"{plan.provider}: {plan.trajectories} trajectories is more than the " + f"{PILOT_TRAJECTORIES_PER_PROVIDER}-trajectory pilot; pass --reference-run " + " for an estimate" + ) + continue + remaining = plan.cap - plan.spent + if plan.estimate * SAFETY > remaining: + problems.append( + f"{plan.provider}: the estimate ${plan.estimate} x {SAFETY} = " + f"${plan.estimate * SAFETY} is over the ${remaining} left under its cap" + ) + for provider_families in counts.values(): + for family_id, trajectories in provider_families.items(): + rate = matching.get(family_id) + if rate is not None and trajectories * rate.seconds_per_cell * float(SAFETY) > WINDOW_S: + hours = trajectories * rate.seconds_per_cell * float(SAFETY) / 3600 + problems.append( + f"{family_id}: {trajectories} trajectories x {rate.seconds_per_cell:.1f} s " + f"x {SAFETY} is {hours:.1f} h, over the 24-hour window" + ) + return problems + + +def confirmation_text(plans: Sequence[ProviderPlan]) -> str: + """One line per provider: trajectories, spent, cap, remaining and the estimate.""" + lines = [] + for plan in plans: + head = f"{plan.provider}: {plan.trajectories} trajectories" + if plan.cap is None or plan.spent is None: + lines.append(f"{head}; local, unmetered") + continue + estimate = "no reference run (the remaining cap is the worst case)" + if plan.estimate is not None: + scaled = _dollars(plan.estimate * SAFETY) + estimate = f"estimate {_dollars(plan.estimate)} (x {SAFETY} = {scaled})" + margin = PROVIDER_MARGINS.get(plan.provider) + lines.append( + f"{head}; spent ${plan.spent} of cap ${plan.cap}, ${plan.cap - plan.spent} " + f"remaining; {estimate}; the ledger stops at the cap; one overrun is at most the " + f"${margin} margin" + ) + return "\n".join(lines) + + +def _dollars(amount: Decimal) -> str: + return "<$0.01" if 0 < amount < Decimal("0.01") else f"${amount:.2f}" + + +def interactive_confirm( + text: str, *, stdin: TextIO | None = None, stderr: TextIO | None = None +) -> bool: + """Ask on stderr, read stdin's next line; only an exact ``yes`` from a terminal agrees. + + stdout carries only the summary JSON, so nothing is written to it (round-3 item 6). + """ + reader = sys.stdin if stdin is None else stdin + writer = sys.stderr if stderr is None else stderr + if reader is None or writer is None or not reader.isatty(): + return False + writer.write(f"{text}\nType yes to start this live run: ") + writer.flush() + return reader.readline().rstrip("\r\n") == "yes" + + +def authorize_live( + text: str, + *, + environ: Mapping[str, str] = os.environ, + confirm: Callable[[str], bool] = interactive_confirm, +) -> None: + """The one gate for every live entry point: refused under CI, then confirmed by a person.""" + if environ.get("CI", "").strip().lower() not in _NOT_CI: + raise BenchmarkValidationError("live calls are refused under CI") + if not confirm(text): + raise BenchmarkValidationError("live run not confirmed") diff --git a/benchmarks/agentic/loop.py b/benchmarks/agentic/loop.py index 89d88f31..0908740b 100644 --- a/benchmarks/agentic/loop.py +++ b/benchmarks/agentic/loop.py @@ -21,6 +21,7 @@ from benchmarks.agentic.ledger import Outcome from benchmarks.agentic.ledger import _utc_now as _utc_now_ms # wall_s needs sub-second times from benchmarks.agentic.prompt import SYSTEM_PROMPT +from benchmarks.agentic.protocol import scanned_json_bytes from benchmarks.agentic.schemas import schemas_sha256 from benchmarks.agentic.types import ( Buckets, @@ -156,6 +157,7 @@ def __init__( caps: Caps, seen_tool_args: set[str], sleep: Callable[[float], Awaitable[None]], + check_content: Callable[[bytes], None] | None, ) -> None: if family.max_output_tokens is None or family.framing_allowance_tokens is None: raise BenchmarkValidationError( @@ -164,6 +166,7 @@ def __init__( ) self.client, self.bridge, self.ledger, self.caps = client, bridge, ledger, caps self.seen, self.sleep = seen_tool_args, sleep + self.check_content = check_content self.output_bound = family.max_output_tokens self.framing = family.framing_allowance_tokens tools = list(bridge.tools) if bridge is not None else [] @@ -180,7 +183,7 @@ def record(self, status: str, error: dict[str, str] | None, answer: str) -> dict wall = time.perf_counter() - self.started s = self.seconds overhead = wall - sum(s[k] for k in s if k != "used") - return { + record = { "status": status, "error": error, "answer": answer, @@ -197,6 +200,18 @@ def record(self, status: str, error: dict[str, str] | None, answer: str) -> dict "started_at": self.started_at, "completed_at": _utc_now_ms(), } + self.scan(record, where="trajectory record") + return record + + def scan(self, value: object, *, where: str) -> None: + scanned_json_bytes(value, where=where, check_content=self.check_content) + + def check_request(self) -> None: + self.scan(self.client.request_params(), where="outgoing provider settings") + if self.check_content is None: + self.client.rendered_bytes(self.conv, 0) + else: + self.client.rendered_bytes(self.conv, 0, check_content=self.check_content) def discard( self, reason: Literal["budget_stop", "retries_exhausted"], message: str @@ -261,6 +276,11 @@ async def model_call(self, bound: int) -> ModelTurn: self.model_calls.append(entry) retries = 0 while True: + # Shared spend boundary for every client and every attempt. Incremental bounds + # alone omit earlier native replay; validate the complete rendered request even + # when usage lets us reserve using only the added entries. Rendering checks both + # decoded fields and the JSON actually used for provider messages, never SDK auth. + self.check_request() waited = time.perf_counter() unit = await self.ledger.reserve( provider=self.client.provider, @@ -304,12 +324,21 @@ async def model_call(self, bound: int) -> ModelTurn: "tool_calls_requested": len(turn.tool_calls), } self.conv.entries.append(turn) # kept even when the clock now ends the trajectory + # The response and its usage already exist: settle them before checking + # content. Check every call and the actual native argument replay before + # any MCP dispatch, model cap, or another paid reservation. The callback + # stays local to this bootstrapped worker and never sees SDK auth headers. + self.scan([asdict(call) for call in turn.tool_calls], where="outgoing MCP calls") + self.check_request() self.use(wall, "model") return turn assert error is not None attempt |= {"outcome": error.kind, "status": error.status} await self.ledger.settle(unit, outcome=error.kind, buckets=None) self.seconds["failed_attempt"] += wall + # A failed attempt is already billed/settled. Unsafe diagnostics must stop here, + # before retry backoff, another reservation, or publishing a failure transcript. + self.scan(str(error), where="provider error") if error.kind not in RETRYABLE: raise _Failed("provider_rejected", str(error), "ProviderCallError") retries += 1 @@ -331,6 +360,7 @@ async def run_tools(self, turn: ModelTurn) -> None: self.conv.entries.append(ToolResults(tuple(results))) async def _run_tools(self, turn: ModelTurn, results: list[ToolResult]) -> None: + self.scan([asdict(call) for call in turn.tool_calls], where="outgoing MCP calls") for call in turn.tool_calls: if len(self.tool_calls) >= self.caps.tool_calls: raise _Failed( @@ -373,7 +403,9 @@ async def _run_tools(self, turn: ModelTurn, results: list[ToolResult]) -> None: wall = time.perf_counter() - started self.seen.add(key) text, is_error = outcome.text, outcome.is_error + self.scan(text, where="raw tool result") sent, truncated = truncate_utf8(text, self.caps.result_bytes) + self.scan(sent, where="outgoing tool result") entry |= { "result": text, "result_sha256": hashlib.sha256(text.encode("utf-8")).hexdigest(), @@ -395,12 +427,19 @@ async def run_trajectory( caps: Caps, seen_tool_args: set[str], sleep: Callable[[float], Awaitable[None]] = asyncio.sleep, + check_content: Callable[[bytes], None] | None = None, ) -> dict[str, Any]: """Run one trajectory to an answer or a scored failure; raise TrajectoryDiscarded.""" - trajectory = _Trajectory(client, bridge, family, prompt, ledger, caps, seen_tool_args, sleep) + trajectory = _Trajectory( + client, bridge, family, prompt, ledger, caps, seen_tool_args, sleep, check_content + ) try: answer = await trajectory.run() except _Failed as failure: error = {"category": failure.category, "type": failure.kind, "message": str(failure)} return trajectory.record("failed", error, "") + except Exception as exc: + # Unexpected bridge/client failures must not escape with untrusted diagnostics. + trajectory.scan(str(exc), where="trajectory exception") + raise return trajectory.record("succeeded", None, answer) diff --git a/benchmarks/agentic/mcp_stdio.py b/benchmarks/agentic/mcp_stdio.py new file mode 100644 index 00000000..3697c093 --- /dev/null +++ b/benchmarks/agentic/mcp_stdio.py @@ -0,0 +1,154 @@ +"""Credential checks on normal MCP stdio lines, before SDK parsing loses fields. + +The SDK has no pre-parse observer on stdio_client. Keep its process ownership +and bounded shutdown helpers; only the pipe-to-SessionMessage boundary differs. +No SDK globals or caller-owned streams are patched. +""" + +from __future__ import annotations + +from collections.abc import AsyncIterator, Callable +from contextlib import asynccontextmanager, suppress +from typing import TextIO + +import anyio +from mcp import StdioServerParameters +from mcp.client._transport import TransportStreams +from mcp.client.stdio import ( + _create_platform_compatible_process, + _get_executable_command, + _parse_line, + _stop_server_process, + get_default_environment, +) +from mcp.shared.message import SessionMessage + +from benchmarks.agentic.protocol import ( + MAX_FRAME_BYTES, + FrameTooLarge, + KeyLeakError, + assert_no_key_shaped, + check_json_text, +) + + +def checked_line( + line: bytes, params: StdioServerParameters, check_content: Callable[[bytes], None] | None +) -> SessionMessage | Exception: + """Scan bytes and decoded JSON before even the JSON-RPC envelope is converted.""" + assert_no_key_shaped(line, where="MCP stdio reply") + if check_content is not None: + check_content(line) + try: + text = line.decode(params.encoding) + except UnicodeDecodeError as exc: + prefix = line[: exc.start].decode(params.encoding, errors="ignore") + check_json_text(prefix, where="MCP stdio reply", check_content=check_content) + raise KeyLeakError("MCP stdio reply contains undecodable bytes") from None + check_json_text(text, where="MCP stdio reply", check_content=check_content) + return _parse_line(text) + + +class ReplyGuard: + """Latch a receive-task failure before connection closure wakes a pending SDK call.""" + + def __init__(self, check_content: Callable[[bytes], None] | None = None) -> None: + self.check_content = check_content + self.failure: KeyLeakError | FrameTooLarge | None = None + + def frame_too_large(self) -> None: + # Use one fixed diagnostic without interpolating reply bytes. A known leak wins. + if self.failure is None: + self.failure = FrameTooLarge("MCP stdio reply exceeds the frame limit") + self.raise_if_failed() + + def parse(self, line: bytes, params: StdioServerParameters) -> SessionMessage | Exception: + self.raise_if_failed() + try: + return checked_line(line, params, self.check_content) + except KeyLeakError as error: + self.failure = error + raise + + def raise_if_failed(self) -> None: + failure = self.failure + if isinstance(failure, (KeyLeakError, FrameTooLarge)): + raise failure + + +@asynccontextmanager +async def checked_stdio_client( + params: StdioServerParameters, + *, + errlog: TextIO, + guard: ReplyGuard, +) -> AsyncIterator[TransportStreams]: + """SDK-compatible streams, with SDK-owned process groups and bounded cleanup.""" + process = await _create_platform_compatible_process( + command=await _get_executable_command(params.command), + args=params.args, + env=get_default_environment() | (params.env or {}), + errlog=errlog, + cwd=params.cwd, + ) + incoming, read = anyio.create_memory_object_stream[SessionMessage | Exception](0) + write, outgoing = anyio.create_memory_object_stream[SessionMessage](0) + writer_done = anyio.Event() + + async def reader() -> None: + assert process.stdout is not None + buffer = bytearray() + delivering = True + # Drain while shutdown closes stdin/stops the owned process. A blocked + # delivery is released by read.close(); subsequent lines are still scanned. + with anyio.CancelScope(shield=True): + with suppress(anyio.ClosedResourceError, anyio.BrokenResourceError, ConnectionError): + async with incoming: + async for chunk in process.stdout: + for part in chunk.splitlines(keepends=True): + buffer.extend(part) + if len(buffer) > MAX_FRAME_BYTES: + guard.frame_too_large() + if not buffer.endswith(b"\n"): + continue + item = guard.parse(bytes(buffer), params) + buffer.clear() + if delivering: + try: + await incoming.send(item) + except (anyio.ClosedResourceError, anyio.BrokenResourceError): + delivering = False + if buffer: + guard.parse(bytes(buffer), params) + + async def writer() -> None: + assert process.stdin is not None + try: + async with outgoing: + async for item in outgoing: + data = item.message.model_dump_json(by_alias=True, exclude_unset=True) + "\n" + await process.stdin.send( + data.encode(params.encoding, errors=params.encoding_error_handler) + ) + except (anyio.ClosedResourceError, anyio.BrokenResourceError, OSError): + await incoming.aclose() + finally: + writer_done.set() + + async with anyio.create_task_group() as group: + group.start_soon(reader) + group.start_soon(writer) + try: + yield read, write + finally: + with anyio.CancelScope(shield=True): + read.close() + write.close() + with anyio.move_on_after(0.5): + await writer_done.wait() + try: + await _stop_server_process(process) + finally: + for stream in (read, write, incoming, outgoing): + await stream.aclose() + group.cancel_scope.cancel() diff --git a/benchmarks/agentic/probe.py b/benchmarks/agentic/probe.py new file mode 100644 index 00000000..761d277a --- /dev/null +++ b/benchmarks/agentic/probe.py @@ -0,0 +1,362 @@ +"""The isolation probe: every sandboxed job's network is checked keyless before any worker starts. + +Two halves. In a probe container on the job's internal network, ``run_probe_checks`` tries +every way out it should not have (direct connections to the Mac and the network's gateways, +DNS, a denied proxy target) and the one it should (an allowed URL through the proxy). It uses +only the standard library and ``egress``. On the host, a ``Canary`` listener must never see the +probe's token, the proxy's own log must show both denials, and a control container on the +outside network must reach the canary, so a silent canary means something. +""" + +from __future__ import annotations + +import argparse +import asyncio +import json +import os +import secrets +import socket +import sys +from collections.abc import Mapping, Sequence +from contextlib import suppress +from typing import TYPE_CHECKING, Any +from urllib.parse import urlsplit + +from benchmarks.agentic.cleanup import finish +from benchmarks.agentic.egress import ( + EGRESS_ALIAS, + EGRESS_PORT, + ProxyEvent, + forbidden_env_names, + parse_proxy_log, + read_log, + write_scanned_json, +) +from benchmarks.agentic.protocol import ( + KeyLeakError, + assert_no_key_shaped, + assert_no_key_shaped_json, + redact_key_shaped, + scanned_json_bytes, +) +from benchmarks.runner import BenchmarkValidationError + +if TYPE_CHECKING: + from benchmarks.agentic.sandbox import Egress, Sandbox + from benchmarks.model_matrix import ModelFamily + +_CONNECT_S = 2.0 +_PROXY_S = 5.0 +_OLLAMA_VERSION_URL = "http://host.docker.internal:11434/api/version" +#: The hosts every probe tries directly, besides the Mac's own addresses and the gateways. +_MAC_NAMES = ("host.docker.internal", "gateway.docker.internal") +_OLLAMA_PORT = 11434 +#: How long the host waits for the proxy's log lines and the canary's bytes to land. +_SETTLE_S = 3.0 +#: Every interface, so the canary is reachable however the Mac is addressed (tests use loopback). +_CANARY_BIND = "0.0.0.0" + + +# --- in the container -------------------------------------------------------------------------- + + +def _result(check: str, target: str, passed: bool, detail: str) -> dict[str, Any]: + return {"check": check, "target": target, "passed": passed, "detail": detail} + + +def _direct(host: str, port: int, token: str) -> dict[str, Any]: + """A direct connection must fail; one that succeeds sends the token to whoever listens.""" + target = f"{host}:{port}" + try: + with socket.create_connection((host, port), timeout=_CONNECT_S) as conn: + with suppress(OSError): + conn.sendall(f"GET / HTTP/1.0\r\nAuthorization: Bearer {token}\r\n\r\n".encode()) + except OSError as exc: + return _result("direct", target, True, type(exc).__name__) + return _result("direct", target, False, "connected") + + +def _through_proxy(proxy: tuple[str, int], request: str) -> int | None: + """The status code the proxy answers ``request`` with; None if it gives none.""" + try: + with socket.create_connection(proxy, timeout=_PROXY_S) as conn: + conn.sendall(request.encode()) + data = b"" + while b"\r\n" not in data and (chunk := conn.recv(4096)): + data += chunk + except OSError: + return None + parts = data.split(b"\r\n", 1)[0].split(b" ") + return int(parts[1]) if len(parts) > 1 and parts[1].isdigit() else None + + +def run_probe_checks( + spec: Mapping[str, Any], *, proxy: tuple[str, int] = (EGRESS_ALIAS, EGRESS_PORT) +) -> list[dict[str, Any]]: + """Every check the spec asks for, each ``{"check", "target", "passed", "detail"}``.""" + token = str(spec.get("token", "")) + forbidden = forbidden_env_names(os.environ) + names = ", ".join(forbidden) # names, never values: a failure names what was injected + results = [_result("env", names, not forbidden, names)] + results += [_direct(str(host), int(port), token) for host, port in spec.get("direct", [])] + if dns_name := spec.get("dns_name"): + try: + socket.getaddrinfo(dns_name, 443) + except OSError as exc: + results.append(_result("dns", dns_name, True, type(exc).__name__)) + else: + results.append(_result("dns", dns_name, False, "resolved")) + if denied := spec.get("denied"): + target = f"{denied[0]}:{denied[1]}" + status = _through_proxy(proxy, f"CONNECT {target} HTTP/1.1\r\nHost: {target}\r\n\r\n") + results.append(_result("proxy_denied", target, status == 403, str(status))) + if canary := spec.get("canary_via_proxy"): + target = f"{canary[0]}:{canary[1]}" + status = _through_proxy( + proxy, + f"GET http://{target}/ HTTP/1.1\r\nHost: {target}\r\n" + f"Authorization: Bearer {token}\r\nConnection: close\r\n\r\n", + ) + results.append(_result("proxy_canary", target, status == 403, str(status))) + for url in spec.get("allowed_http", []): + host = urlsplit(url).netloc + request = f"GET {url} HTTP/1.1\r\nHost: {host}\r\nConnection: close\r\n\r\n" + status = _through_proxy(proxy, request) + results.append(_result("allowed_http", url, status == 200, str(status))) + return results + + +def run_control(canary: tuple[str, int], token: str) -> dict[str, Any]: + """From the outside network the canary must be reachable, and receive the token.""" + host, port = canary + try: + with socket.create_connection((host, port), timeout=_CONNECT_S) as conn: + conn.sendall(f"GET / HTTP/1.0\r\nAuthorization: Bearer {token}\r\n\r\n".encode()) + except OSError as exc: + return _result("control", f"{host}:{port}", False, type(exc).__name__) + return _result("control", f"{host}:{port}", True, "connected") + + +def probe_main(argv: list[str]) -> int: + """``agentic-probe --spec ``: one JSON object ``{"checks": [...]}``, exit 0 whatever.""" + parser = argparse.ArgumentParser(prog="python -m benchmarks agentic-probe") + parser.add_argument("--spec", required=True) + spec = json.loads(parser.parse_args(argv).spec) + if "control" in spec: + checks = [run_control((spec["control"][0], int(spec["control"][1])), spec["token"])] + else: + checks = run_probe_checks(spec) + print(scanned_json_bytes({"checks": checks}, where="probe output").decode()) + return 0 + + +# --- on the host -------------------------------------------------------------------------------- + + +class IsolationProbeFailed(BenchmarkValidationError): + """A sandboxed job's network let something out, or the probe could not show it did not.""" + + +class Canary: + """A TCP listener on every interface of the Mac; it records what each connection sends.""" + + def __init__(self) -> None: + self.port = 0 + self.received: list[bytes] = [] + self._server: asyncio.Server | None = None + + async def _handle(self, reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None: + with suppress(TimeoutError, OSError): + self.received.append(await asyncio.wait_for(reader.read(4096), _CONNECT_S)) + writer.close() + + async def __aenter__(self) -> Canary: + self._server = await asyncio.start_server(self._handle, _CANARY_BIND, 0) + self.port = self._server.sockets[0].getsockname()[1] + return self + + async def __aexit__( + self, exc_type: object, exc: BaseException | None, traceback: object + ) -> None: + if (server := self._server) is not None: + + async def close() -> None: + server.close() + await server.wait_closed() + + await finish(close(), exc) + + +def host_addresses() -> list[str]: + """The Mac's non-loopback IPv4 addresses; short or empty offline, never an error.""" + found: list[str] = [] + with suppress(OSError): + found += socket.gethostbyname_ex(socket.gethostname())[2] + with suppress(OSError), socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as udp: + udp.connect(("192.0.2.1", 9)) # no packet is sent: this only picks the route + found.append(udp.getsockname()[0]) + return sorted({a for a in found if not a.startswith("127.")}) + + +def probe_verdict( + checks: Sequence[Mapping[str, Any]], + *, + canary_received: Sequence[bytes], + token: str, + proxy_events: Sequence[ProxyEvent], + denied: tuple[str, int], + canary: tuple[str, int], +) -> list[str]: + """What failed: each failed check, a canary that saw the token, a denial not logged.""" + failed = [f"{c['check']} {c['target']}".strip() for c in checks if not c["passed"]] + if any(token.encode() in data for data in canary_received): + failed.append("canary_saw_token") + refused = [(e.method, e.host, e.port) for e in proxy_events if not e.allowed] + connect_logged = ("CONNECT", *denied) in refused + canary_logged = any(m != "CONNECT" and (h, p) == canary for m, h, p in refused) + if not (connect_logged and canary_logged): + failed.append("denial_not_logged") + return failed + + +async def _one_shot(sandbox: Sandbox, argv: list[str], name: str) -> list[dict[str, Any]]: + """Run a probe container to its end; it is removed even on a timeout or a cancellation.""" + container_id = await sandbox.create_resource(name, *argv[1:]) + try: + proc = await sandbox.docker(["docker", "start", "--attach", container_id]) + finally: + await sandbox.remove_container(container_id, pending=sys.exception()) + if proc.returncode != 0: + reason = f"exit {proc.returncode}" + else: + assert_no_key_shaped(proc.stdout, where="probe output") + try: + checks = list(json.loads(proc.stdout)["checks"]) + except (ValueError, KeyError, TypeError) as exc: + reason = f"invalid probe output ({type(exc).__name__})" + else: + assert_no_key_shaped_json(checks, where="probe output") + return checks + + detail = proc.stderr.decode("utf-8", errors="replace").strip() + assert_no_key_shaped(detail, where="probe stderr") + message = f"probe container {name} failed ({reason}): {detail[-300:]}" + assert_no_key_shaped(message, where="probe diagnostic") + raise IsolationProbeFailed(message) + + +def _probe_argv( + sandbox: Sandbox, name: str, network: str, spec: dict[str, Any], env: Any +) -> list[str]: + return sandbox.container_argv( + name=name, + network=network, + env=env, + mounts=[], + argv=["python", "-m", "benchmarks", "agentic-probe", "--spec", json.dumps(spec)], + interactive=False, + create_only=True, + ) + + +async def _settle(done: Any) -> None: + """Wait a bounded time for something the host checks next to land.""" + loop = asyncio.get_running_loop() + deadline = loop.time() + _SETTLE_S + while not done() and loop.time() < deadline: + await asyncio.sleep(0.05) + + +async def isolation_probe( + sandbox: Sandbox, egress: Egress, *, job_id: str, family: ModelFamily, system_id: str +) -> dict[str, Any]: + """The default ProbeFn: probe the job's network keyless; write ``probe/.json``.""" + from benchmarks.agentic.sandbox import worker_env # host side only + + token = secrets.token_hex(16) + denied = ("example.com", 443) + async with Canary() as canary: + via_proxy = ("host.docker.internal", canary.port) + hosts = [*_MAC_NAMES, *host_addresses(), *egress.gateways] + allowed_http = ( + [_OLLAMA_VERSION_URL] if ("host.docker.internal", _OLLAMA_PORT) in egress.allow else [] + ) + spec = { + "token": token, + "direct": [[host, port] for host in hosts for port in (canary.port, _OLLAMA_PORT)], + "dns_name": "pypi.org", + "denied": list(denied), + "canary_via_proxy": list(via_proxy), + "allowed_http": allowed_http, + } + name = f"{sandbox.worker_name(job_id)}-probe" + argv = _probe_argv(sandbox, name, egress.network, spec, worker_env(family)) + checks = await _one_shot(sandbox, argv, name) + log = egress.spool_dir / "access.log" + + def verdict() -> tuple[list[str], list[str]]: + try: + data, pattern = redact_key_shaped(read_log(log)) + if pattern: + raise KeyLeakError( + f"key-shaped string ({pattern} pattern) in {job_id}/access.log" + ) + text = data.decode("utf-8") + events = parse_proxy_log(text) + except KeyLeakError: + raise + except (OSError, ValueError) as exc: + return [f"proxy_log {exc}"], [] + found = probe_verdict( + checks, + canary_received=canary.received, + token=token, + proxy_events=events, + denied=denied, + canary=via_proxy, + ) + for url in allowed_http: + target = urlsplit(url).netloc + if not any( + e.method == "GET" and e.target == target and e.status == 200 and e.reached + for e in events + ): + found.append(f"allowed_http_not_logged {url}") + return found, text.splitlines() + + await _settle(lambda: not verdict()[0]) + failed, prefix = verdict() + record = { + "job_id": job_id, + "checks": checks, + "failed": failed, + "passed": not failed, + "network_inspect": egress.inspect, + "proxy_prefix": prefix, # the exact access-log lines when the verdict was taken + } + write_scanned_json(sandbox.config.out_dir / "probe" / f"{job_id}.json", record) + if failed: + raise IsolationProbeFailed(f"isolation probe failed for {job_id}: {', '.join(failed)}") + return record + + +async def control_probe(sandbox: Sandbox) -> dict[str, Any]: + """From the outside network the canary must be reached, else every probe is inconclusive.""" + await sandbox.ensure_outside() + token = secrets.token_hex(16) + async with Canary() as canary: + name = f"pdmcp-{sandbox.config.run_id}-control" + spec = {"control": ["host.docker.internal", canary.port], "token": token} + argv = _probe_argv(sandbox, name, sandbox.outside, spec, {"HOME": "/tmp"}) + checks = await _one_shot(sandbox, argv, name) + await _settle(lambda: any(token.encode() in data for data in canary.received)) + reached = any(token.encode() in data for data in canary.received) + passed = reached and all(c["passed"] for c in checks) + record = {"checks": checks, "canary_reached": reached, "passed": passed} + write_scanned_json(sandbox.config.out_dir / "probe" / "control.json", record) + if not passed: + raise IsolationProbeFailed( + "inconclusive: a control container on the outside network could not reach the " + "host canary, so a silent canary proves nothing" + ) + return record diff --git a/benchmarks/agentic/protocol.py b/benchmarks/agentic/protocol.py index 634ac7ac..632f7770 100644 --- a/benchmarks/agentic/protocol.py +++ b/benchmarks/agentic/protocol.py @@ -9,21 +9,32 @@ import asyncio import json +import os import re +from collections.abc import Callable, Mapping +from pathlib import Path from typing import Any from benchmarks.runner import BenchmarkValidationError MAX_FRAME_BYTES = 64 * 1024 * 1024 -#: A key starts a token, or follows a URL escape such as %20; a run of base64 never does. -_START = r"(?:(?<=%[0-9A-Fa-f]{2})|(?{p})" for name, p in KEY_PATTERNS.items())) _KEY_SHAPED_BYTES = re.compile(KEY_SHAPED.pattern.encode()) @@ -33,19 +44,53 @@ class KeyLeakError(BenchmarkValidationError): """A provider key, or a string shaped like one, was about to leave a process.""" +def find_key_leak(error: BaseException) -> KeyLeakError | None: + """Find a recognized leak through task groups and MCP/cleanup exception chains.""" + return _find_failure(error, KeyLeakError) + + +def _find_failure[T: BaseException](error: BaseException, kind: type[T]) -> T | None: + pending = [error] + visited: set[int] = set() + while pending: + current = pending.pop() + if id(current) in visited: + continue + visited.add(id(current)) + if isinstance(current, kind): + return current + if isinstance(current, BaseExceptionGroup): + pending.extend(current.exceptions) + for linked in (current.__cause__, current.__context__): + if linked is not None: + pending.append(linked) + return None + + class FrameTooLarge(BenchmarkValidationError): """A frame over the size limit: a harness error, never a model failure.""" -def encode_frame(message: dict[str, Any], *, limit: int = MAX_FRAME_BYTES) -> bytes: - body = json.dumps(message, ensure_ascii=False, separators=(",", ":")).encode("utf-8") +def find_frame_too_large(error: BaseException) -> FrameTooLarge | None: + """Retain structural frame failures through SDK and teardown exception groups.""" + return _find_failure(error, FrameTooLarge) + + +def encode_frame( + message: dict[str, Any], *, limit: int = MAX_FRAME_BYTES, where: str | None = None +) -> bytes: + # Only the private host-to-worker bootstrap may carry a credential. + if where is None: + body = json.dumps(message, ensure_ascii=False, separators=(",", ":")).encode("utf-8") + else: + body = scanned_json_bytes(message, where=where, ensure_ascii=False, separators=(",", ":")) if len(body) > limit: raise FrameTooLarge(f"a {len(body)}-byte frame is over the {limit}-byte limit") return len(body).to_bytes(8, "big") + body async def read_frame( - reader: asyncio.StreamReader, *, limit: int = MAX_FRAME_BYTES + reader: asyncio.StreamReader, *, limit: int = MAX_FRAME_BYTES, where: str | None = None ) -> dict[str, Any] | None: """The next frame; None at a clean EOF or a partial frame (the writer died).""" try: @@ -55,7 +100,39 @@ async def read_frame( body = await reader.readexactly(length) except asyncio.IncompleteReadError: return None - return json.loads(body) + if where is not None: + assert_no_key_shaped(body, where=where) + message = json.loads(body) + if where is not None: + assert_no_key_shaped_json(message, where=where) + return message + + +def _read_exactly(fd: int, size: int) -> bytes | None: + parts: list[bytes] = [] + while size: + chunk = os.read(fd, size) + if not chunk: + return None + parts.append(chunk) + size -= len(chunk) + return b"".join(parts) + + +def read_frame_fd(fd: int, *, limit: int = MAX_FRAME_BYTES) -> dict[str, Any] | None: + """Exactly one frame from ``fd``, unbuffered, so no byte of the next frame is consumed. + + None at EOF or a partial frame. The worker reads its first frame this way, before any + stream wraps its stdin. + """ + header = _read_exactly(fd, 8) + if header is None: + return None + length = int.from_bytes(header, "big") + if length > limit: + raise FrameTooLarge(f"a {length}-byte frame is over the {limit}-byte limit") + body = _read_exactly(fd, length) + return None if body is None else json.loads(body) def redact_key_shaped(data: bytes) -> tuple[bytes, str | None]: @@ -63,10 +140,107 @@ def redact_key_shaped(data: bytes) -> tuple[bytes, str | None]: match = _KEY_SHAPED_BYTES.search(data) if match is None: return data, None - return _KEY_SHAPED_BYTES.sub(b"[redacted]", data), match.lastgroup + redacted = _KEY_SHAPED_BYTES.sub(b"[redacted]", data) + # Removing a key can give an adjacent key a token boundary. Withhold ambiguous output. + if _KEY_SHAPED_BYTES.search(redacted): + redacted = b"[redacted]" + return redacted, match.lastgroup + + +def redact_key_shaped_text(text: str) -> str: + """Use the same key scan for printable errors and byte-oriented artifacts.""" + redacted, pattern = redact_key_shaped(text.encode("utf-8", errors="surrogatepass")) + return redacted.decode("utf-8", errors="surrogatepass") if pattern else text -def assert_no_key_shaped(text: str, *, where: str) -> None: - if match := KEY_SHAPED.search(text): +def assert_no_key_shaped(text: str | bytes, *, where: str) -> None: + match = _KEY_SHAPED_BYTES.search(text) if isinstance(text, bytes) else KEY_SHAPED.search(text) + if match: # Names the place and the pattern, never the match. raise KeyLeakError(f"a key-shaped string ({match.lastgroup} pattern) was found in {where}") + + +def assert_no_key_shaped_json( + value: object, *, where: str, check_content: Callable[[bytes], None] | None = None +) -> None: + """Check decoded JSON strings and object names before escaping changes token boundaries.""" + stack = [value] + visited: set[int] = set() + while stack: + node = stack.pop() + if isinstance(node, (str, bytes)): + assert_no_key_shaped(node, where=where) + try: + data = node if isinstance(node, bytes) else node.encode("utf-8") + except UnicodeEncodeError: + raise KeyLeakError(f"uninspectable JSON string in {where}") from None + if check_content is not None: + check_content(data) + elif isinstance(node, (Mapping, list, tuple, set, frozenset)) and id(node) not in visited: + # YAML snapshots can contain repeated or cyclic aliases. + visited.add(id(node)) + stack.extend(node) + if isinstance(node, Mapping): + stack.extend(node.values()) + + +# One non-overlapping pass through string bodies. This is deliberately not a JSON +# document parser: malformed structure, trailing text and duplicate fields must not +# hide strings. Each match consumes a plain run or one complete JSON escape. +_JSON_STRING_PART = re.compile(r'[^"\\]+|\\(?:["\\/bfnrt]|u[0-9a-fA-F]{4})') + + +def check_json_text( + text: str, *, where: str, check_content: Callable[[bytes], None] | None = None +) -> None: + """Check raw text and recoverable JSON strings in linear, frame-bounded work. + + Decode each string once with the stdlib, adding a closing quote for an + unfinished string. Check the completed prefix before refusing a broken escape; + uninspectable content must never be replayed. Document validity remains the + caller's/native SDK's decision, including unescaped controls (strict=False). + """ + if len(text) > MAX_FRAME_BYTES: + raise KeyLeakError(f"content inspection limit exceeded in {where}") + assert_no_key_shaped_json(text, where=where, check_content=check_content) + position = 0 + while position < len(text): + start = text.find('"', position) + # Escapes outside a string have no unambiguous JSON interpretation. + gap_end = start if start != -1 else len(text) + if text.find("\\", position, gap_end) != -1: + raise KeyLeakError(f"uninspectable JSON escape in {where}") + if start == -1: + break + end = start + 1 + while match := _JSON_STRING_PART.match(text, end): + end = match.end() + decoded = json.loads('"' + text[start + 1 : end] + '"', strict=False) + scanned_json_bytes(decoded, where=where, check_content=check_content) + if end < len(text) and text[end] != '"': + raise KeyLeakError(f"uninspectable JSON string in {where}") + position = end + 1 + + +def scanned_json_bytes( + value: object, + *, + where: str, + check_content: Callable[[bytes], None] | None = None, + **options: Any, +) -> bytes: + """Serialize only after checking the fields, then check the exact UTF-8 JSON for publication.""" + assert_no_key_shaped_json(value, where=where, check_content=check_content) + body = json.dumps(value, **options).encode("utf-8") + assert_no_key_shaped(body, where=where) + if check_content is not None: + check_content(body) + return body + + +def write_json_evidence(path: Path, record: dict[str, Any]) -> bytes: + """Publish scanned JSON and return the exact bytes for host-owned evidence hashes.""" + data = scanned_json_bytes(record, where="JSON evidence", indent=2, sort_keys=True) + b"\n" + path.parent.mkdir(parents=True, exist_ok=True) + path.write_bytes(data) + return data diff --git a/benchmarks/agentic/reference.py b/benchmarks/agentic/reference.py new file mode 100644 index 00000000..4a334597 --- /dev/null +++ b/benchmarks/agentic/reference.py @@ -0,0 +1,275 @@ +"""Join captured pilot attempts to the invocation's spend events. + +Unit IDs are the producer's link between channels. This checks consistency of saved +evidence, not authenticity: neither transcripts nor ledger exports are signed. +""" + +from __future__ import annotations + +import hashlib +from collections import defaultdict +from dataclasses import dataclass +from decimal import Decimal +from typing import Any + +from benchmarks.agentic.ledger import UNMETERED_PROVIDERS, booked_cost +from benchmarks.agentic.types import Buckets +from benchmarks.model_matrix import ModelFamily + +_CALL_OUTCOMES = frozenset( + {"ok", "no_usage", "rejected", "rate_limited", "server", "timeout", "connection"} +) + +_COORDINATES = ( + "competitor_id", + "corpus_id", + "system_id", + "model_family_id", + "provider", + "model_id", + "repeat", + "attempt", +) + + +class ReferenceTranscripts: + """Match every captured transcript to the host's publication-time inventory.""" + + def __init__(self, summary: dict[str, Any]) -> None: + items = summary.get("transcript_inventory") + if not isinstance(items, list) or not items: + raise ValueError( + "missing transcript inventory; regenerate the pilot with the current runner" + ) + self.pending: dict[str, dict[str, Any]] = {} + for item in items: + if not isinstance(item, dict) or any(field not in item for field in _COORDINATES): + raise ValueError("invalid transcript inventory coordinates") + if any(not isinstance(item[f], str) or not item[f] for f in _COORDINATES[:-2]): + raise ValueError("invalid transcript inventory coordinates") + if any(type(item[f]) is not int or item[f] < 1 for f in ("repeat", "attempt")): + raise ValueError("invalid transcript inventory attempt/repeat") + cell = f"{item['system_id']}--{item['model_family_id']}--r{item['repeat']}" + path = item.get("path") + if item["competitor_id"] != cell or path not in ( + f"transcripts/{cell}/{item['corpus_id']}.json", + f"discarded/{cell}/{item['corpus_id']}--attempt{item['attempt']}.json", + ): + raise ValueError("transcript inventory path contradicts its coordinates") + digest = item.get("sha256") + if ( + not isinstance(digest, str) + or len(digest) != 64 + or any(c not in "0123456789abcdef" for c in digest) + ): + raise ValueError("transcript inventory lacks a valid SHA256") + if path in self.pending: + raise ValueError("duplicate transcript inventory path") + self.pending[path] = item + + def verify(self, path: str, content: bytes, record: dict[str, Any]) -> None: + item = self.pending.pop(path, None) + if item is None: + raise ValueError(f"transcript absent from the host inventory: {path}") + if hashlib.sha256(content).hexdigest() != item["sha256"]: + raise ValueError(f"transcript SHA256 disagrees with the host inventory: {path}") + if any( + type(record.get(f)) is not type(item[f]) or record.get(f) != item[f] + for f in _COORDINATES + ): + raise ValueError(f"transcript coordinates disagree with the host inventory: {path}") + + def finish(self) -> None: + if self.pending: + raise ValueError( + "missing transcripts from the host inventory: " + ", ".join(sorted(self.pending)) + ) + + +def nonnegative_decimal(value: Any) -> Decimal: + if isinstance(value, bool) or not isinstance(value, (str, int, float, Decimal)): + raise ValueError("invalid reference amount") + amount = Decimal(str(value)) + if not amount.is_finite() or amount < 0: + raise ValueError("invalid reference amount") + return amount + + +def _buckets(value: Any) -> Buckets | None: + if value is None: + return None + if not isinstance(value, dict): + raise ValueError("invalid reference usage") + buckets = Buckets(**value) + if any(type(n) is not int or n < 0 for n in vars(buckets).values()): + raise ValueError("invalid reference usage") + return buckets + + +@dataclass(frozen=True) +class _Attempt: + family: ModelFamily + job_id: str + outcome: str + buckets: Buckets | None + input_bound: int | None + output_bound: int | None + + +class ReferenceUnits: + """Every actual call appears once in transcripts and, if metered, in the ledger.""" + + def __init__(self) -> None: + self.attempts: dict[str, _Attempt] = {} + + def add(self, record: dict[str, Any], family: ModelFamily) -> None: + calls = record["model_calls"] + if not isinstance(calls, list): + raise ValueError("reference model calls must be a list") + for call in calls: + if not isinstance(call, dict): + raise ValueError("invalid reference model call") + for field in ("input_bound", "output_bound"): + if field in call and (type(call[field]) is not int or call[field] < 0): + raise ValueError("invalid reference call bound") + params = call["request_params"] + if not isinstance(params, dict) or params.get("model") != family.model_id: + raise ValueError("reference request model contradicts executed identity") + raw = call.get("raw_response") + if raw is not None and not isinstance(raw, dict): + raise ValueError("invalid reference response") + if family.api != "scripted" and raw is not None and "scripted_step" in raw: + raise ValueError("scripted response contradicts live reference identity") + attempts = call["attempts"] + if not isinstance(attempts, list): + raise ValueError("invalid reference attempts") + usage = _buckets(call["buckets"]) + if not attempts and (raw is not None or usage is not None): + raise ValueError("reference response lacks its call attempt") + for index, attempt in enumerate(attempts): + if not isinstance(attempt, dict): + raise ValueError("invalid reference attempt") + for field in ("wall_ms", "wait_ms"): + if field in attempt: + nonnegative_decimal(attempt[field]) + unit, outcome = attempt["unit_id"], attempt["outcome"] + if not isinstance(unit, str) or not unit or unit in self.attempts: + raise ValueError("missing or duplicate reference unit") + if outcome not in _CALL_OUTCOMES: + raise ValueError("invalid reference call outcome") + terminal = index == len(attempts) - 1 + if outcome in {"ok", "no_usage"} and not terminal: + raise ValueError("reference retries a successful call") + buckets = usage if terminal else None + if outcome == "ok": + if buckets is None or buckets.is_empty or raw is None: + raise ValueError("successful reference call lacks usage or response") + elif outcome == "no_usage": + if (buckets is not None and not buckets.is_empty) or raw is None: + raise ValueError("reference no-usage call contradicts response") + buckets = None # the loop sends no buckets when all counters are zero + elif terminal and (buckets is not None or raw is not None): + raise ValueError("failed reference call contradicts response") + self.attempts[unit] = _Attempt( + family, + f"{family.id}--{record['system_id']}", + outcome, + buckets, + call.get("input_bound"), + call.get("output_bound"), + ) + + def reconcile( + self, events: list[dict[str, Any]], summary: dict[str, Any] + ) -> tuple[dict[str, Decimal], set[str]]: + run_id = summary["run_id"] + if not isinstance(run_id, str) or not run_id: + raise ValueError("reference lacks run identity") + pending: dict[str, tuple[_Attempt, Decimal]] = {} + seen: set[str] = set() + settled: set[str] = set() + started = False + booked: dict[str, Decimal] = defaultdict(Decimal) + measured: set[str] = set() + recovery: dict[str, Decimal] = defaultdict(Decimal) + for event in events: + provider, kind = event["provider"], event["event"] + if event["run_id"] != run_id or provider in UNMETERED_PROVIDERS: + raise ValueError("ledger event contradicts reference run/provider") + if kind in {"stop", "resume"}: + continue + unit = event["unit_id"] + if not isinstance(unit, str) or not unit: + raise ValueError("reference ledger lacks unit identity") + if kind == "reserve": + started = True + if unit in seen: + raise ValueError("duplicate reference reservation") + seen.add(unit) + attempt = self.attempts[unit] + family = attempt.family + if (provider, event["job_id"], event["model_id"], event["kind"]) != ( + family.provider, + attempt.job_id, + family.model_id, + "model_call", + ) or event.get("api", family.api) != family.api: + raise ValueError("reservation contradicts reference attempt identity") + for field in ("input_bound", "output_bound"): + if type(event[field]) is not int or event[field] < 0: + raise ValueError("invalid reference token bound") + expected = getattr(attempt, field) + if field == "input_bound" and family.max_input_tokens is not None: + expected = ( + min(expected, family.max_input_tokens) if expected is not None else None + ) + if expected is not None and event[field] != expected: + raise ValueError("reservation contradicts reference call bound") + pending[unit] = attempt, nonnegative_decimal(event["bound"]) + elif kind == "settle": + amount = nonnegative_decimal(event["booked"]) + actual = None if event["actual"] is None else nonnegative_decimal(event["actual"]) + buckets = _buckets(event["buckets"]) + # Ledger.open recovers old pending units before spent_before is captured. + # Their reserve is intentionally absent, even when run labels are reused. + if event["outcome"] == "unsettled_at_load" and unit not in self.attempts: + if started or unit in seen or actual is not None or buckets is not None: + raise ValueError("invalid reference recovery settlement") + seen.add(unit) + recovery[provider] += amount + continue + attempt, bound = pending.pop(unit) + if provider != attempt.family.provider or event["outcome"] != attempt.outcome: + raise ValueError("settlement contradicts reference attempt identity/outcome") + if buckets != attempt.buckets or (attempt.outcome != "ok" and actual is not None): + raise ValueError("settlement contradicts reference usage") + if amount != booked_cost(event["outcome"], bound=bound, actual=actual): + raise ValueError("reference settlement booking contradicts its outcome") + settled.add(unit) + booked[attempt.family.id] += amount + if attempt.outcome == "ok" and amount > 0: + measured.add(attempt.family.id) + else: + raise ValueError("unknown reference ledger event") + metered = { + u for u, a in self.attempts.items() if a.family.provider not in UNMETERED_PROVIDERS + } + if pending or settled != metered: + raise ValueError("reference attempts and settled reservations do not match") + balances = summary["ledger"] + providers = {a.family.provider for a in self.attempts.values()} - UNMETERED_PROVIDERS + if not isinstance(balances, dict) or (providers | recovery.keys()) - balances.keys(): + raise ValueError("reference summary lacks provider spend") + for provider, balance in balances.items(): + before = nonnegative_decimal(balance["spent_before"]) + after = nonnegative_decimal(balance["spent_after"]) + if "cap" in balance: + nonnegative_decimal(balance["cap"]) + # Each family's total is counted once, regardless of its number of attempts. + family_ids = { + a.family.id for a in self.attempts.values() if a.family.provider == provider + } + spend = sum((booked[f] for f in family_ids), start=Decimal(0)) + if after - before != spend or before < recovery[provider]: + raise ValueError("reference settlements disagree with the run's spend") + return booked, measured diff --git a/benchmarks/agentic/run.py b/benchmarks/agentic/run.py index 1f464ee7..7602692b 100644 --- a/benchmarks/agentic/run.py +++ b/benchmarks/agentic/run.py @@ -10,13 +10,12 @@ import asyncio import hashlib -import json import os import random import signal import sys from collections import Counter -from collections.abc import Coroutine, Mapping, Sequence +from collections.abc import Callable, Coroutine, Mapping, Sequence from dataclasses import dataclass, field, replace from datetime import UTC, date, datetime from decimal import Decimal @@ -27,24 +26,50 @@ import benchmarks from benchmarks.adapters.claude_tokens import ANTHROPIC_API_VERSION, DEFAULT_COUNT_MODEL -from benchmarks.agentic.bridge import SystemSpec, load_systems +from benchmarks.agentic.airgap import ( + AirGapWatch, + host_offline_checks, + ollama_preflight, + write_airgap_evidence, +) +from benchmarks.agentic.bridge import SystemSpec, systems_from_mapping +from benchmarks.agentic.cleanup import add_cleanup_cause +from benchmarks.agentic.egress import write_egress_summary from benchmarks.agentic.host import Launcher, LocalLauncher, WorkerJob, refuse_host_keys, run_jobs +from benchmarks.agentic.inputs import CapturedInput from benchmarks.agentic.ledger import ( PROVIDER_CAPS, Ledger, LedgerService, - load_price_snapshot, + price_snapshot_from_mapping, refuse_stale_snapshot, ) +from benchmarks.agentic.live import ( + authorize_live, + confirmation_text, + full_run_gate, + interactive_confirm, + provider_plans, + reference_rates, +) from benchmarks.agentic.loop import AIR_GAPPED_CAPS, HOSTED_CAPS from benchmarks.agentic.prompt import SYSTEM_PROMPT -from benchmarks.agentic.protocol import assert_no_key_shaped +from benchmarks.agentic.protocol import ( + KeyLeakError, + assert_no_key_shaped_json, + redact_key_shaped_text, + scanned_json_bytes, +) +from benchmarks.agentic.protocol import ( + write_json_evidence as _write, +) +from benchmarks.agentic.sandbox import ContainerLauncher from benchmarks.agentic.worker import _client_versions from benchmarks.model_matrix import ( _HOSTED_REQUIRED_FIELDS, METHODOLOGY_TOKEN_LABEL, ModelFamily, - load_model_matrix, + model_matrix_from_mapping, ) from benchmarks.runner import ( BenchmarkCell, @@ -54,10 +79,8 @@ _default_run_id, _environment_metadata, _load_questions, - _load_yaml_mapping, _scoring_record, _utc_now, - _write_json, ) #: Answer-turn stop reasons that mean the output cap cut the answer; the pilot's 1% rule @@ -91,6 +114,7 @@ class AgenticConfig: run_id: str | None = None dry_run: bool = False acknowledge_overrun: tuple[str, ...] = () + reference_run: Path | None = None # a finished pilot run, for the full-run gate async def _until_signalled(run: Coroutine[Any, Any, None]) -> None: @@ -101,8 +125,17 @@ async def _until_signalled(run: Coroutine[Any, Any, None]) -> None: that cannot take signals runs without the handlers, and each disposition the handlers replaced is restored afterwards. """ - task = asyncio.ensure_future(run) + task = asyncio.create_task(run) loop = asyncio.get_running_loop() + signal_seen = False + + def interrupt(signum: signal.Signals) -> None: + nonlocal signal_seen + if not signal_seen: + signal_seen = True + if not task.cancelling(): + task.cancel(f"signal {signum.name}") + wanted = [ # an ignored signal stays ignored, as under nohup (signum, previous) for signum in (signal.SIGTERM, signal.SIGHUP) @@ -111,7 +144,7 @@ async def _until_signalled(run: Coroutine[Any, Any, None]) -> None: installed: list[tuple[signal.Signals, Any]] = [] # each with the disposition it replaced try: for signum, previous in wanted: - loop.add_signal_handler(signum, task.cancel, f"signal {signum.name}") + loop.add_signal_handler(signum, interrupt, signum) installed.append((signum, previous)) except (RuntimeError, NotImplementedError, ValueError) as exc: # Not the main thread, or a loop without signal support: run without those handlers. @@ -129,6 +162,28 @@ async def _until_signalled(run: Coroutine[Any, Any, None]) -> None: signal.signal(signum, signal.SIG_DFL if previous is None else previous) +def limits_mismatch(reported: Mapping[str, Any] | None, family: ModelFamily) -> list[str]: + """Each difference between a worker's reported model limits and the model matrix. + + The maintainer corrects model-matrix.yml by hand; the run itself goes on. + """ + if reported is None: + return [] + if "error" in reported: + return [f"model limits could not be read ({reported['error']})"] + problems = [] + max_input = reported.get("max_input_tokens") + if max_input is not None and max_input != family.max_input_tokens: + problems.append( + f"max_input_tokens {max_input} != max_input_tokens {family.max_input_tokens} " + "in the model matrix" + ) + max_tokens, cap = reported.get("max_tokens"), family.max_output_tokens + if max_tokens is not None and cap is not None and max_tokens < cap: + problems.append(f"max_tokens {max_tokens} < max_output_tokens {cap} in the model matrix") + return problems + + def cell_id(system_id: str, family_id: str, repeat: int) -> str: return f"{system_id}--{family_id}--r{repeat}" @@ -169,11 +224,6 @@ def plan_jobs( return jobs -def _write(path: Path, data: dict[str, Any]) -> None: - assert_no_key_shaped(json.dumps(data, sort_keys=True), where=str(path)) - _write_json(path, data) - - class _HasId(Protocol): @property def id(self) -> str: @@ -250,22 +300,28 @@ def __init__( self.succeeded = 0 self.failed = 0 self.discarded: list[dict[str, Any]] = [] + self.transcript_inventory: list[dict[str, Any]] = [] self.not_run: list[dict[str, Any]] = [] self.worker_errors: list[dict[str, Any]] = [] + self.limits_mismatch: list[str] = [] async def on_message(self, job: WorkerJob, message: dict[str, Any]) -> None: kind = message["type"] if kind == "system_info": info = {k: v for k, v in message.items() if k != "type"} _write(self.out / "systems" / f"{job.job_id}.json", info) + self.limits_mismatch += [ + f"{job.job_id}: {line}" + for line in limits_mismatch(message.get("model_limits"), job.family) + ] return if kind == "worker_error": self.worker_errors.append({"job_id": job.job_id, "reason": message["reason"]}) return if kind not in ("trajectory", "discarded", "not_run"): return - cell = cell_id(job.system.id, job.family.id, message["repeat"]) - corpus_id = message["corpus_id"] + corpus_id, repeat = job.report_coordinates(message) + cell = cell_id(job.system.id, job.family.id, repeat) if kind == "not_run": self.not_run.append( { @@ -280,45 +336,49 @@ async def on_message(self, job: WorkerJob, message: dict[str, Any]) -> None: stats = self.families[job.family.id] stats.add(record) stats.reruns += message["attempt"] > 1 # a rerun counts once it has run + ident = {**self._ident(job, cell, corpus_id, repeat), "attempt": message["attempt"]} if kind == "discarded": reason, attempt = message["reason"], message["attempt"] self.discarded.append( {"cell": cell, "corpus_id": corpus_id, "reason": reason, "attempt": attempt} ) path = self.out / "discarded" / cell / f"{corpus_id}--attempt{attempt}.json" - _write(path, {**record, **self._ident(job, cell, message), "reason": reason}) + self._write_transcript(path, {**record, **ident, "reason": reason}, ident) return - self._write_cell(job, cell, message, record, stats) + self._write_cell(ident, record) + + def _write_transcript(self, path: Path, record: dict[str, Any], ident: dict[str, Any]) -> None: + content = _write(path, record) + self.transcript_inventory.append( + { + **ident, + "path": path.relative_to(self.out).as_posix(), + "sha256": hashlib.sha256(content).hexdigest(), + } + ) - def _ident(self, job: WorkerJob, cell: str, message: dict[str, Any]) -> dict[str, Any]: + def _ident(self, job: WorkerJob, cell: str, corpus_id: str, repeat: int) -> dict[str, Any]: family, system = job.family, job.system return { "competitor_id": cell, - "corpus_id": message["corpus_id"], + "corpus_id": corpus_id, "system_id": system.id, "model_family_id": family.id, "provider": family.provider, "model_id": family.model_id, - "repeat": message["repeat"], - "attempt": message.get("attempt"), + "repeat": repeat, "tool_model_key": tool_model_key(system.id, family.provider, family.model_id), } - def _write_cell( - self, - job: WorkerJob, - cell: str, - message: dict[str, Any], - record: dict[str, Any], - stats: _FamilyStats, - ) -> None: - ident = self._ident(job, cell, message) - ident.pop("attempt") + def _write_cell(self, ident: dict[str, Any], record: dict[str, Any]) -> None: + cell = ident["competitor_id"] corpus_id, key = ident["corpus_id"], ident["tool_model_key"] status, error = record["status"], record["error"] question = self.questions[corpus_id] base = {"competitor_id": cell, "tool_model_key": key, "corpus_id": corpus_id} - _write(self.out / "transcripts" / cell / f"{corpus_id}.json", {**record, **ident}) + self._write_transcript( + self.out / "transcripts" / cell / f"{corpus_id}.json", {**record, **ident}, ident + ) _write( self.out / "scoring" / cell / f"{corpus_id}.json", _scoring_record( @@ -376,15 +436,48 @@ def _write_cell( self.cells.add(cell) +def _finalization_failure(primary: BaseException | None, later: BaseException) -> BaseException: + if primary is None: + return later + if isinstance(primary, Exception): + # Preserve an operator interrupt even if an earlier ordinary operation failed. + if not isinstance(later, Exception): + add_cleanup_cause(later, BenchmarkValidationError(redact_key_shaped_text(str(primary)))) + return later + if isinstance(later, KeyLeakError) and not isinstance(primary, KeyLeakError): + return KeyLeakError( + f"{redact_key_shaped_text(str(later))}; " + f"earlier failure: {redact_key_shaped_text(str(primary))}" + ) + detail = f"{type(later).__name__}: {redact_key_shaped_text(str(later))}" + add_cleanup_cause(primary, BenchmarkValidationError(detail)) + return primary + + def run_agentic( config: AgenticConfig, *, launcher: Launcher | None = None, caps: Mapping[str, Decimal] = PROVIDER_CAPS, today: date | None = None, + confirm: Callable[[str], bool] = interactive_confirm, + offline_checks: Callable[[], list[dict[str, Any]]] = host_offline_checks, + preflight: Callable[[str], dict[str, Any]] = ollama_preflight, ) -> dict[str, Any]: - """Validate everything, then run every planned trajectory; return the run summary.""" + """Validate everything, then run every planned trajectory; return the run summary. + + A run with any live family passes the full-run gate and ``authorize_live`` (``confirm``) + after the ledger opens and before any key is read or any container starts. + """ refuse_host_keys(os.environ) + for value in vars(config).values(): + assert_no_key_shaped_json( + str(value) if isinstance(value, Path) else value, where="run options" + ) + corpus_input = CapturedInput.read(config.corpus_path, "corpus.yml", "corpus") + matrix_input = CapturedInput.read(config.matrix_path, "model-matrix.yml", "model matrix") + manifest_input = CapturedInput.read(config.manifest_path, "competitor-manifest.yml", "manifest") + prices_input = CapturedInput.read(config.prices_path, "price-snapshot.yml", "price snapshot") launcher = launcher or LocalLauncher() out = config.out_dir if out.exists() and any(out.iterdir()): @@ -393,13 +486,14 @@ def run_agentic( ) if config.repeats < 1: raise BenchmarkValidationError("--repeats must be at least 1") - corpus = _load_questions(_load_yaml_mapping(config.corpus_path, "corpus")) + corpus = _load_questions(corpus_input.mapping) questions = _select(corpus, config.questions, "corpus question") - matrix = load_model_matrix(config.matrix_path).model_families + matrix = model_matrix_from_mapping(matrix_input.mapping).model_families families = ( _select(matrix, config.models, "model family") if config.models is not None - else [f for f in matrix if launcher.supports(f)] + # The air-gapped arm is named with --models, never run by default (round-2 D11). + else [f for f in matrix if f.arm == "hosted" and launcher.supports(f)] ) if not families: raise BenchmarkValidationError("no model family to run") @@ -407,10 +501,32 @@ def run_agentic( if unsupported: raise BenchmarkValidationError( f"{type(launcher).__name__} cannot run {unsupported}: the local launcher runs only " - "scripted models; live models need PR 4's container launcher" + "scripted models; use --launcher container" + ) + if len({f.arm == "air-gapped" for f in families}) > 1: + raise BenchmarkValidationError( + "the air-gapped arm runs alone, with the host offline: name only air-gapped " + "families, or only others, in --models" ) - systems = _select(load_systems(config.manifest_path), config.systems, "system") - snapshot = load_price_snapshot(config.prices_path) + requested_systems = config.systems + if families[0].arm == "air-gapped": + for family in families: + if family.api != "scripted" and ( + family.provider != "ollama" or family.api != "openai-chat-completions" + ): + raise BenchmarkValidationError( + f"the air-gapped arm requires local Ollama for live family {family.id!r}" + ) + offline_systems = ("python-docs", "no-docs") + if requested_systems is None: + requested_systems = offline_systems + elif not requested_systems or not set(requested_systems).issubset(offline_systems): + raise BenchmarkValidationError( + f"the air-gapped arm permits only {offline_systems} in --systems, " + f"got {requested_systems}" + ) + systems = _select(systems_from_mapping(manifest_input.mapping), requested_systems, "system") + snapshot = price_snapshot_from_mapping(prices_input.mapping) for family in families: if family.output_cap_includes_reasoning is False: raise BenchmarkValidationError( @@ -423,7 +539,8 @@ def run_agentic( missing = [name for name in _HOSTED_REQUIRED_FIELDS if getattr(family, name) is None] if missing: raise BenchmarkValidationError(f"model family {family.id!r} must set {missing}") - if any(family.api != "scripted" for family in families): + if any(family.api != "scripted" and family.provider in caps for family in families): + # Only a live, metered family is priced: the air-gapped arm never reads the snapshot. refuse_stale_snapshot(snapshot, today=today or datetime.now(UTC).date()) run_id = config.run_id or _default_run_id() @@ -440,19 +557,12 @@ def run_agentic( seed=seed, matrix_dir=config.matrix_path.parent, ) - inputs = { - "corpus.yml": config.corpus_path.read_bytes(), - "competitor-manifest.yml": config.manifest_path.read_bytes(), - "model-matrix.yml": config.matrix_path.read_bytes(), - "price-snapshot.yml": config.prices_path.read_bytes(), - } - for name, data in inputs.items(): # every input, before any snapshot is written - assert_no_key_shaped(data.decode("utf-8", errors="replace"), where=f"input {name}") + rates = reference_rates(config.reference_run) if config.reference_run else None out.mkdir(parents=True, exist_ok=True) snapshots = out / "snapshots" snapshots.mkdir() - for name, data in inputs.items(): # the exact bytes that were scanned - (snapshots / name).write_bytes(data) + for source in (corpus_input, matrix_input, manifest_input, prices_input): + (snapshots / source.name).write_bytes(source.content) (snapshots / "system-prompt.txt").write_text(SYSTEM_PROMPT, encoding="utf-8") environment = { **_environment_metadata(run_id=run_id, dry_run=config.dry_run), @@ -493,24 +603,59 @@ def run_agentic( if config.dry_run: # never opens the ledger return summary - ledger = Ledger.open(config.ledger_dir, run_id=run_id, caps=caps) - spent_before = {provider: ledger.spent(provider) for provider in caps} # after any recovery + spent_before: dict[str, Decimal] = {} collector = _Collector(out, {q.id: q for q in questions}, families) + # The air-gapped arm runs alone (checked above), so either every family is in it or none. + watch = AirGapWatch(out, offline_checks) if families[0].arm == "air-gapped" else None + + async def on_message(job: WorkerJob, message: dict[str, Any]) -> None: + await collector.on_message(job, message) + if watch is not None and message["type"] in ("trajectory", "discarded"): + # Before the host acknowledges it, so before the worker starts its next trajectory. + cell = cell_id(job.system.id, job.family.id, message["repeat"]) + await watch.check(f"after {cell}/{message['corpus_id']}") + + async def run_arm() -> None: + if watch is not None: + await watch.check("before_first") + await run_jobs( + jobs, + launcher=launcher, + ledger=service, + on_message=on_message, + log_dir=out / "logs", + cwd=_REPO_ROOT, + ) + if watch is not None: + await watch.check("after_last") - def write_outcome() -> None: + def write_outcome(ledger: Ledger) -> None: """ledger-events.jsonl and run-summary.json, for a completed or an aborted run.""" - run_events = ledger.events(run_id) - events = "".join(json.dumps(e, sort_keys=True) + "\n" for e in run_events) + run_events = ledger.invocation_events() + events = b"".join( + scanned_json_bytes(e, where="ledger-events.jsonl", sort_keys=True) + b"\n" + for e in run_events + ) # The pilot reads how often reported input passed its bound (design §12). exceeded = Counter( e["provider"] for e in run_events if e["event"] == "settle" and e["input_bound_exceeded"] ) - assert_no_key_shaped(events, where="ledger-events.jsonl") - (out / "ledger-events.jsonl").write_text(events, encoding="utf-8") + (out / "ledger-events.jsonl").write_bytes(events) + if isinstance(launcher, ContainerLauncher): # C1 evidence, "fail" for a stopped run + write_egress_summary(out, jobs, run_events) scored = collector.succeeded + collector.failed summary.setdefault("status", "completed") + if watch is not None: # design §7.4: how many rounds ran, and whether the arm stopped + summary["airgap"] = {"checks": watch.rounds, "broken": watch.broken} + # C3 evidence, after the C1 summary it reads; an aborted arm never passes. + write_airgap_evidence( + out, + rounds=watch.rounds, + broken=watch.broken or summary["status"] == "aborted", + job_ids=[job.job_id for job in jobs], + ) summary.update( { "completed_at": _utc_now(), @@ -521,12 +666,16 @@ def write_outcome() -> None: "failed_cells_included_in_correctness_denominator": True, "competitors": sorted(collector.cells), "discarded": collector.discarded, + "transcript_inventory": collector.transcript_inventory, "not_run": collector.not_run, "worker_errors": collector.worker_errors, + "model_limits_mismatch": collector.limits_mismatch, "families": {fid: stats.summary() for fid, stats in collector.families.items()}, "ledger": { provider: { - "spent_before": str(spent_before[provider]), + "spent_before": str(spent_before[provider]) + if provider in spent_before + else None, "spent_after": str(ledger.spent(provider)), "cap": str(caps[provider]), "stopped": ledger.stopped(provider), @@ -544,7 +693,12 @@ def write_outcome() -> None: ) _write(out / "run-summary.json", summary) - try: # every step after the open, the overrun check included, ends in write_outcome + failure: BaseException | None = None + ledger: Ledger | None = None + try: + ledger = Ledger.open(config.ledger_dir, run_id=run_id, caps=caps) + for provider in caps: + spent_before[provider] = ledger.spent(provider) # after recovery for provider in config.acknowledge_overrun: ledger.acknowledge_overrun(provider) overrun = sorted({f.provider for f in families if ledger.stopped(f.provider) == "overrun"}) @@ -559,26 +713,36 @@ def write_outcome() -> None: f"spent {spent_before[provider]} of cap {cap}", file=sys.stderr, ) + if any(f.api != "scripted" for f in families): + # Before any key is read (bootstrap_frame) or any container starts (prepare). + plans = provider_plans(jobs, spent_before, caps, rates) + problems = full_run_gate(plans, jobs, rates) + if problems: + raise BenchmarkValidationError("the full-run gate refused: " + "; ".join(problems)) + summary["live_confirmation"] = text = confirmation_text(plans) + authorize_live(text, confirm=confirm) prices = {f.model_id: snapshot.models[f.model_id] for f in families if f.provider in caps} service = LedgerService(ledger, prices, {f.model_id: f for f in families}) - asyncio.run( - _until_signalled( - run_jobs( - jobs, - launcher=launcher, - ledger=service, - on_message=collector.on_message, - log_dir=out / "logs", - cwd=_REPO_ROOT, - ) - ) - ) - except BaseException as exc: # still write what was spent and what ran - summary |= {"status": "aborted", "abort_reason": f"{type(exc).__name__}: {exc}"} - raise + if watch is not None: # local Ollama only, never through a proxy variable + loaded = {f.id: preflight(f.model_id) for f in families if f.api != "scripted"} + if loaded: + _write(out / "ollama.json", loaded) + asyncio.run(_until_signalled(run_arm())) + except BaseException as exc: + failure = exc + detail = redact_key_shaped_text(str(exc)) + summary |= {"status": "aborted", "abort_reason": f"{type(exc).__name__}: {detail}"} finally: - try: - write_outcome() - finally: - ledger.close() + if ledger is not None: + try: + write_outcome(ledger) + except BaseException as exc: # retain the interrupt or leak while closing the ledger + failure = _finalization_failure(failure, exc) + finally: + try: + ledger.close() + except BaseException as exc: + failure = _finalization_failure(failure, exc) + if failure is not None: + raise failure return summary diff --git a/benchmarks/agentic/sandbox.py b/benchmarks/agentic/sandbox.py new file mode 100644 index 00000000..f93775a0 --- /dev/null +++ b/benchmarks/agentic/sandbox.py @@ -0,0 +1,903 @@ +"""The container sandbox: keyless worker containers behind one logging egress proxy per job. + +Design §7.2 and §7.3, as amended on #200: a key never enters a container's environment or +config, the docker CLI's environment, argv or a file other than the keys file. A live +worker's one key reaches it only in the bootstrap frame on its stdin (``bootstrap_frame``). + +Imports no provider SDK: ``run.sh`` imports ``SQUID_IMAGE`` from it on the host. +""" + +from __future__ import annotations + +import asyncio +import json +import os +import re +import secrets +import subprocess +import tempfile +from collections.abc import Awaitable, Callable, Mapping, Sequence +from dataclasses import dataclass +from pathlib import Path +from typing import TYPE_CHECKING, Any + +import benchmarks +from benchmarks.adapters.guard import ( + EGRESS_URL_ENV, + LIVE_LATCH_ENV, + LIVE_PROVIDERS_ENABLED_ENV, + PROVIDER_API_KEY_ENV, + valid_api_key, +) +from benchmarks.agentic.cleanup import add_cleanup_cause, finish, settle +from benchmarks.agentic.egress import ( + EGRESS_ALIAS, + EGRESS_URL, + LOG_DIR_IN_PROXY, + allowlist, + open_log_dir, + pending_collection, + read_log, + squid_conf, + write_new, + write_scanned_json, +) +from benchmarks.agentic.protocol import ( + KeyLeakError, + assert_no_key_shaped, + assert_no_key_shaped_json, + redact_key_shaped, + redact_key_shaped_text, + scanned_json_bytes, +) +from benchmarks.model_matrix import KNOWN_APIS, ModelFamily +from benchmarks.runner import BenchmarkValidationError + +if TYPE_CHECKING: + from benchmarks.agentic.host import WorkerJob + +SQUID_IMAGE = ( + "ubuntu/squid:6.6-24.04_edge" + "@sha256:8a3baed477e2c282ab8aa5edad442f69873246964f225c5c2ae8364b6610963c" +) +WORKER_USER = "10001:10001" +PROXY_USER = "proxy" +RUN_LABEL = "org.python-docs-mcp.benchmark-run" +MIN_ENGINE = (28, 0) +REPO_ROOT = Path(benchmarks.__file__).resolve().parent.parent +#: Ollama on the Mac, as a worker container sees it through its egress proxy (design §7.4). +OLLAMA_URL_IN_SANDBOX = "http://host.docker.internal:11434/v1" +_REVISION_LABEL = "org.opencontainers.image.revision" +_IMAGE_ID = re.compile(r"^sha256:[0-9a-f]{64}$") +#: The docker CLI child's whole environment, each name when set. Never a key. +_CLI_ENV = ( + "PATH", + "HOME", + "DOCKER_HOST", + "DOCKER_CONTEXT", + "DOCKER_CONFIG", + "DOCKER_CERT_PATH", + "DOCKER_TLS_VERIFY", +) +_DOCKER_TIMEOUT_S = 120 +_RESOURCE_RECOVERY_S = 5.0 + +DockerRun = Callable[[Sequence[str]], Awaitable[subprocess.CompletedProcess[bytes]]] + + +def read_key(keys_file: Path, name: str) -> str: + """The value of ``name`` in a ``NAME=VALUE`` keys file; errors name no value. + + ``export`` prefixes, matching quotes, comments and blank lines are handled. A file with + any group or other permission bit is refused. + """ + try: + mode = keys_file.stat().st_mode + text = keys_file.read_text(encoding="utf-8") if not mode & 0o077 else "" + except OSError as exc: + raise BenchmarkValidationError( + f"keys file {keys_file} cannot be read for {name}: {type(exc).__name__}" + ) from None + if mode & 0o077: + raise BenchmarkValidationError( + f"keys file {keys_file} is readable beyond its owner (mode {mode & 0o777:o}); " + f"chmod 600 it. {name} was not read" + ) + for raw in text.splitlines(): + line = raw.strip() + if not line or line.startswith("#"): + continue + key, sep, value = line.removeprefix("export ").partition("=") + if not sep or key.strip() != name: + continue + value = value.strip() + if len(value) >= 2 and value[0] == value[-1] and value[0] in "'\"": + value = value[1:-1] + if not value: + raise BenchmarkValidationError(f"keys file {keys_file} sets {name} to an empty value") + if not valid_api_key(value): + raise BenchmarkValidationError(f"keys file contains invalid characters for {name}") + return value + raise BenchmarkValidationError(f"keys file {keys_file} does not set {name}") + + +def cli_env(environ: Mapping[str, str]) -> dict[str, str]: + """The docker CLI's environment: the allowlist only, so it never holds a key or a proxy.""" + return {name: environ[name] for name in _CLI_ENV if name in environ} + + +def docker_runner(env: Mapping[str, str]) -> DockerRun: + """Run one docker CLI command with ``env`` as its whole environment.""" + + async def run(argv: Sequence[str]) -> subprocess.CompletedProcess[bytes]: + return await asyncio.to_thread( + subprocess.run, + list(argv), + capture_output=True, + env=dict(env), + stdin=subprocess.DEVNULL, + process_group=0, # the host's foreground signals must not interrupt rollback + timeout=_DOCKER_TIMEOUT_S, + ) + + return run + + +@dataclass(frozen=True) +class SandboxConfig: + image: str # the worker image's ID, never a tag + run_id: str + out_dir: Path + index_path: Path + keys_file: Path | None + repo_commit: str + + def __post_init__(self) -> None: + if not _IMAGE_ID.fullmatch(self.image): + raise BenchmarkValidationError( + f"--image must be an image ID (sha256:<64 hex>), never a tag: {self.image!r}" + ) + + +@dataclass(frozen=True) +class Egress: + job_id: str + network: str # the job's internal network + proxy: str # its Squid container, aliased "egress" on that network + allow: tuple[tuple[str, int], ...] + log_dir: Path # out_dir/egress//: squid.conf, access.log, cache.log, collected.json + gateways: tuple[str, ...] # every IPAM gateway of the internal network + inspect: dict[str, Any] # its `docker network inspect` record + network_id: str + proxy_id: str + staging: tempfile.TemporaryDirectory[str] + + @property + def spool_dir(self) -> Path: + return Path(self.staging.name) / "logs" + + +VerifyFn = Callable[["Sandbox"], Awaitable[dict[str, str]]] +ProbeFn = Callable[..., Awaitable[dict[str, Any]]] +ControlFn = Callable[["Sandbox"], Awaitable[dict[str, Any]]] + + +def worker_env(family: ModelFamily) -> dict[str, str]: + """A worker container's whole environment (Global Constraints allowlist): never a key.""" + env = { + "HOME": "/tmp", + "XDG_CACHE_HOME": "/cache", + "PYTHON_DOCS_MCP_DISABLE_AUTO_INDEX": "1", + EGRESS_URL_ENV: EGRESS_URL, + } + if family.api != "scripted": + env[LIVE_PROVIDERS_ENABLED_ENV] = "1" + if family.provider in LIVE_LATCH_ENV: + env[LIVE_LATCH_ENV[family.provider]] = OLLAMA_URL_IN_SANDBOX + return env + + +def _tail(proc: subprocess.CompletedProcess[bytes]) -> str: + scrubbed, _ = redact_key_shaped(proc.stderr) + lines = scrubbed.decode("utf-8", errors="replace").strip().splitlines() + return lines[-1] if lines else f"exit {proc.returncode}" + + +async def _remove(docker: DockerRun, *args: str) -> subprocess.CompletedProcess[bytes]: + # Even if the CLI cannot start or times out, the operator needs the immutable ID. + try: + return await docker(["docker", *args]) + except (OSError, subprocess.TimeoutExpired) as exc: + detail = redact_key_shaped_text(str(exc)) + raise BenchmarkValidationError(f"docker {' '.join(args)} failed: {detail}") from None + + +async def _rollback( + operation: Awaitable[None], + setup_error: BaseException, + cancelled: asyncio.CancelledError | None = None, +) -> None: + """Finish rollback with the original cancellation or a CLI-visible setup and recovery error.""" + try: + await finish(operation, cancelled or setup_error) + except asyncio.CancelledError as interrupt: + if cancelled is None and interrupt is not setup_error: + # A signal arrived after setup failed. Later close failures can hide its context. + reason = redact_key_shaped_text(str(setup_error)) + add_cleanup_cause(interrupt, BenchmarkValidationError(reason)) + raise + except BenchmarkValidationError as exc: + if exc is setup_error: + raise + reason = redact_key_shaped_text(str(setup_error)) + raise BenchmarkValidationError(f"{reason}; rollback failed: {exc}") from None + + +def _engine(version: str) -> tuple[int, int]: + match = re.match(r"(\d+)\.(\d+)", version.strip()) + return (int(match[1]), int(match[2])) if match else (0, 0) + + +async def verify_image(sandbox: Sandbox, *, repo_root: Path = REPO_ROOT) -> dict[str, str]: + """Check the daemon, both images, the engine and the checkout before any container starts. + + A local ``unix://`` daemon only (round-3 item 4), so a bootstrap frame never crosses a + network. Writes and returns ``out_dir/sandbox.json``. + """ + config = sandbox.config + context = json.loads(await sandbox.output("context", "inspect", "--format", "{{json .}}")) + endpoint = str(((context.get("Endpoints") or {}).get("docker") or {}).get("Host", "")) + assert_no_key_shaped_json([context.get("Name"), endpoint], where="Docker context") + if not endpoint.startswith("unix://"): + raise BenchmarkValidationError( + f"docker context {context.get('Name')!r} points at {endpoint!r}: the sandbox " + "runs only on a local unix:// daemon" + ) + host = sandbox.env.get("DOCKER_HOST") + if host is not None: + assert_no_key_shaped(host, where="DOCKER_HOST") + if host is not None and not host.startswith("unix://"): + raise BenchmarkValidationError( + f"DOCKER_HOST is {host!r}: the sandbox runs only on a local unix:// daemon" + ) + image = json.loads( + await sandbox.output("image", "inspect", "--format", "{{json .}}", config.image) + ) + revision = ((image.get("Config") or {}).get("Labels") or {}).get(_REVISION_LABEL) + assert_no_key_shaped_json([image.get("Id"), revision], where="Docker worker image") + if image.get("Id") != config.image: + raise BenchmarkValidationError(f"image {config.image} inspects as {image.get('Id')}") + if revision != config.repo_commit: + raise BenchmarkValidationError( + f"image {config.image} was built from {revision}, not this checkout's " + f"{config.repo_commit}: rebuild it with benchmarks/sandbox/run.sh" + ) + proxy = json.loads( + await sandbox.output("image", "inspect", "--format", "{{json .}}", SQUID_IMAGE) + ) + engine = (await sandbox.output("version", "--format", "{{.Server.Version}}")).strip() + assert_no_key_shaped(engine, where="Docker Engine version") + if _engine(engine) < MIN_ENGINE: + raise BenchmarkValidationError( + f"Docker Engine {engine} is older than {'.'.join(map(str, MIN_ENGINE))}, which the " + "isolated gateway mode needs" + ) + # --untracked-files=normal: a status.showUntrackedFiles=no config cannot hide a file. + status = await asyncio.to_thread( + subprocess.run, + ["git", "-C", str(repo_root), "status", "--porcelain", "--untracked-files=normal"], + capture_output=True, + text=True, + ) + if status.returncode != 0 or status.stdout.strip(): + raise BenchmarkValidationError( + f"the checkout at {repo_root} is dirty or unreadable: the image must hold exactly " + "the committed run commit" + ) + record = { + "image": config.image, + "revision": str(revision), + "proxy_image": SQUID_IMAGE, + "proxy_image_id": str(proxy.get("Id")), + "engine_version": engine, + "docker_context": str(context.get("Name")), + "docker_endpoint": endpoint, + } + write_scanned_json(config.out_dir / "sandbox.json", record) + return record + + +class Sandbox: + """The run's docker resources: one internal network and one proxy per job.""" + + def __init__( + self, + config: SandboxConfig, + docker: DockerRun | None = None, + verify: VerifyFn = verify_image, + ) -> None: + self.config = config + self.env = cli_env(os.environ) # the docker CLI's whole environment + self.docker = docker or docker_runner(self.env) + self.verify = verify # the test seam (round-4 item 2); production keeps the real check + self.leaks: list[str] = [] # key shapes found and redacted in a proxy's logs + self.outside_id: str | None = None + self._invocation = secrets.token_hex(16) + + @property + def outside_created(self) -> bool: + return self.outside_id is not None + + @property + def outside(self) -> str: + return f"pdmcp-{self.config.run_id}-out" + + def worker_name(self, job_id: str) -> str: + return f"pdmcp-{self.config.run_id}-{job_id}" + + def _ownership(self, name: str) -> str: + return f"org.python-docs-mcp.benchmark-resource={self._invocation}.{name}" + + def _label(self, name: str) -> list[str]: + return ["--label", f"{RUN_LABEL}={self.config.run_id}", "--label", self._ownership(name)] + + async def run(self, *args: str) -> subprocess.CompletedProcess[bytes]: + """One docker command; raises BenchmarkValidationError when it fails.""" + removing = args[:2] in (("network", "rm"), ("rm", "-f")) + proc = ( + await _remove(self.docker, *args) if removing else await self.docker(["docker", *args]) + ) + if proc.returncode != 0: + operation = args if removing else args[:2] + raise BenchmarkValidationError(f"docker {' '.join(operation)} failed: {_tail(proc)}") + return proc + + async def output(self, *args: str) -> str: + return (await self.run(*args)).stdout.decode("utf-8", errors="replace") + + async def remove_container( + self, container_id: str, *, pending: BaseException | None = None + ) -> None: + """Finish removing this ID even if the caller is cancelled. --rm may have won.""" + + async def remove() -> None: + loop = asyncio.get_running_loop() + deadline = loop.time() + _RESOURCE_RECOVERY_S + while True: + proc = await _remove(self.docker, "rm", "-f", container_id) + detail = _tail(proc) + if proc.returncode == 0 or "No such container" in detail: + return + conflict = f"removal of container {container_id} is already in progress" + if conflict not in detail or loop.time() >= deadline: + raise BenchmarkValidationError(f"docker rm -f {container_id} failed: {detail}") + await asyncio.sleep(0.1) + + await finish(remove(), pending) + + async def _remove_resources( + self, + *, + containers: Sequence[str] = (), + networks: Sequence[str] = (), + staging: tempfile.TemporaryDirectory[str] | None = None, + ) -> None: + """Remove every owned resource, even after a sibling removal fails.""" + failures: list[str] = [] + for network, ids in ((False, containers), (True, networks)): + for resource_id in ids: + try: + if network: + await self.run("network", "rm", resource_id) + else: + await self.remove_container(resource_id) + except Exception as exc: # noqa: BLE001 - still remove the other owned IDs + failures.append(f"{resource_id}: {redact_key_shaped_text(str(exc))}") + if staging is not None: + try: + staging.cleanup() + except (OSError, MemoryError) as exc: + failures.append( + f"private proxy spool {staging.name}: {redact_key_shaped_text(str(exc))}" + ) + if failures: + raise BenchmarkValidationError("; ".join(failures)) + + async def remove_owned(self, name: str, *, network: bool = False) -> None: + """Recover an ambiguous create by its invocation label, never by its name.""" + ls = ("network", "ls") if network else ("container", "ls", "--all") + label_filter = f"label={self._ownership(name)}" + loop = asyncio.get_running_loop() + deadline = loop.time() + _RESOURCE_RECOVERY_S + while True: + try: + ids = await self.output(*ls, "--no-trunc", "--quiet", "--filter", label_filter) + except (BenchmarkValidationError, OSError, subprocess.TimeoutExpired) as exc: + detail = redact_key_shaped_text(str(exc)) + raise BenchmarkValidationError( + f"Docker lookup for {label_filter} failed: {detail}" + ) from None + if ids.strip(): + break + # A CLI failure can precede publication of a create the daemon already accepted. + remaining = deadline - loop.time() + if remaining <= 0: + raise BenchmarkValidationError( + f"Docker create outcome is unknown for {name}; " + f"check the daemon for {label_filter}" + ) + await asyncio.sleep(min(0.1, remaining)) + if network: + await self._remove_resources(networks=ids.split()) + else: + await self._remove_resources(containers=ids.split()) + + async def create_resource(self, name: str, *args: str) -> str: + """Wait for create before handing off its ID or rolling it back on cancellation.""" + network = args[0] == "network" + task = asyncio.create_task(self.output(*args)) + cancelled = await settle(task) + try: + resource_id = task.result().strip() + if not resource_id: + raise BenchmarkValidationError(f"Docker returned no ID for {name}") + except BaseException as exc: + if isinstance(exc, (subprocess.TimeoutExpired, BenchmarkValidationError)): + await _rollback(self.remove_owned(name, network=network), exc, cancelled) + if cancelled is not None: + raise cancelled from exc + raise + if cancelled is not None: + if network: + await finish(self.run("network", "rm", resource_id), cancelled) + else: + await self.remove_container(resource_id, pending=cancelled) + raise cancelled + return resource_id + + async def ensure_outside(self) -> None: + """The run's one outside network, for the proxies and the control probe.""" + if not self.outside_created: + self.outside_id = await self.create_resource( + self.outside, "network", "create", *self._label(self.outside), self.outside + ) + + async def open_egress(self, job_id: str, allow: Sequence[tuple[str, int]]) -> Egress: + """The job's internal network and its proxy, logging to ``out_dir/egress//``.""" + await self.ensure_outside() + name = self.worker_name(job_id) + network, proxy = f"{name}-net", f"{name}-proxy" + network_id = await self.create_resource( + network, + "network", + "create", + "--internal", + "--ipv6=false", + "-o", + "com.docker.network.bridge.gateway_mode_ipv4=isolated", + *self._label(network), + network, + ) + proxy_id = None + staging = None + try: + (inspect,) = json.loads(await self.output("network", "inspect", network_id)) + if inspect.get("EnableIPv6"): + raise BenchmarkValidationError( + f"network {network} kept IPv6 despite --ipv6=false: refused, no fallback" + ) + gateways = tuple( + str(c["Gateway"]) + for c in (inspect.get("IPAM") or {}).get("Config") or [] + if c.get("Gateway") + ) + log_dir = self.config.out_dir / "egress" / job_id + if os.path.lexists(log_dir): # a new directory of ours, never a planted link + raise BenchmarkValidationError( + f"log directory {log_dir} already exists (it may be a link): refused" + ) + log_dir.mkdir(mode=0o700, parents=True) + pending = pending_collection(self.config.out_dir, job_id) + pending.parent.mkdir(exist_ok=True) + pending.touch(exist_ok=False) + conf = log_dir / "squid.conf" + with open_log_dir(log_dir) as dir_fd: + # Readable by `proxy` under any umask (round-4 item 4). + config_text = squid_conf(allow) + assert_no_key_shaped(config_text, where="squid.conf") + write_new(dir_fd, conf.name, config_text.encode(), mode=0o644) + temp_root = Path(tempfile.gettempdir()).resolve() + if temp_root.is_relative_to(self.config.out_dir.resolve()): + raise BenchmarkValidationError("proxy staging must be outside the artifact tree") + staging = tempfile.TemporaryDirectory(prefix="pdmcp-squid-", dir=temp_root) + spool = Path(staging.name) / "logs" + spool.mkdir() + spool.chmod(0o777) # Docker Desktop maps Squid's proxy uid into this mount + proxy_id = await self.create_resource( + proxy, + "run", + "-d", + "--pull", + "never", + "--name", + proxy, + *self._label(proxy), + "--network", + self.outside, + "--read-only", + "--tmpfs", + "/run", + "--tmpfs", + "/var/spool/squid", + "--cap-drop", + "ALL", + "--security-opt", + "no-new-privileges", + "--user", + PROXY_USER, + "--memory", + "256m", + "--cpus", + "0.5", + "--entrypoint", + "/usr/sbin/squid", + "--mount", + f"type=bind,src={conf},dst=/etc/squid/squid.conf,readonly", + "--mount", + f"type=bind,src={spool},dst={LOG_DIR_IN_PROXY}", + SQUID_IMAGE, + "-N", + "-f", + "/etc/squid/squid.conf", + ) + await finish( + self.run("network", "connect", "--alias", EGRESS_ALIAS, network_id, proxy_id) + ) + except BaseException as exc: + # Nothing of this job's may outlive the failure (amendment 2). + await _rollback( + self._remove_resources( + containers=[proxy_id] if proxy_id else [], + networks=[network_id], + staging=staging, + ), + exc, + ) + raise + return Egress( + job_id, + network, + proxy, + tuple(allow), + log_dir, + gateways, + inspect, + network_id, + proxy_id, + staging, + ) + + def container_argv( + self, + *, + name: str, + network: str, + env: Mapping[str, str], + mounts: Sequence[str], + argv: Sequence[str], + interactive: bool = True, + create_only: bool = False, + ) -> list[str]: + """``docker run`` with the design §7.2 hardening. It has no key parameter.""" + return [ + "docker", + "create" if create_only else "run", + "--name", + name, + *self._label(name), + "--network", + network, + "--read-only", + "--tmpfs", + "/tmp", + "--cap-drop", + "ALL", + "--security-opt", + "no-new-privileges", + "--user", + WORKER_USER, + "--memory", + "1g", + "--cpus", + "1", + "--pids-limit", + "256", + "--init", + "--rm", + *(["-i"] if interactive else []), + "--pull", + "never", + "--log-driver", + "none", # the daemon keeps no second copy of worker output + *[item for key, value in env.items() for item in ("-e", f"{key}={value}")], + *[item for mount in mounts for item in ("--mount", mount)], + self.config.image, + *argv, + ] + + async def _state(self, container: str, problems: list[str], when: str) -> dict[str, Any]: + try: + out = await self.output("inspect", "--format", "{{json .State}}", container) + return dict(json.loads(out)) + except Exception as exc: # noqa: BLE001 - every collection step runs, failures listed + problems.append(f"inspecting the proxy {when} our stop failed: {exc}") + return {} + + async def close_egress(self, egress: Egress) -> list[str]: + """Stop the job's proxy, check how it ended and its logs, remove what was created. + + Every step runs even after a failure; failures are returned as problems and written + to ``collected.json``, whose ``ok`` is false after any of them. + """ + problems: list[str] = [] + # These messages contain only the removal command and its scrubbed immutable ID. + # Keep them independent of state/log diagnostics that might have to be withheld. + removal_failures: list[str] = [] + try: + if any(leak.startswith(f"{egress.job_id}/") for leak in self.leaks): + problems.append("a key-shaped string was found during the job probe") + before, after = await self._stop_egress(egress, problems, removal_failures) + problems.extend(removal_failures) + for name in ("access.log", "cache.log"): + try: + data, pattern = redact_key_shaped(read_log(egress.spool_dir / name)) + if pattern: + self.leaks.append(f"{egress.job_id}/{name} ({pattern} pattern)") + problems.append(f"a key-shaped string was found in {name}") + with open_log_dir(egress.log_dir) as dir_fd: + write_new(dir_fd, name, data) + except KeyLeakError: + self.leaks.append(f"{egress.job_id}/{name}") + problems.append(f"a key-shaped string was found in {name}") + except BenchmarkValidationError as exc: + problems.append(f"{name} could not be collected: {exc}") + except (OSError, MemoryError) as exc: + problems.append(f"{name} could not be collected: {type(exc).__name__}") + finally: + try: + egress.staging.cleanup() + except (OSError, MemoryError) as exc: + problems.append(f"private log cleanup failed: {type(exc).__name__}") + + collected: dict[str, Any] = { + "ok": not problems, + "problems": problems, + "state_before_stop": before, + "state_after_stop": after, + } + + def encode_record() -> bytes: + return ( + scanned_json_bytes( + collected, where="collection diagnostics", indent=2, sort_keys=True + ) + + b"\n" + ) + + try: + data = encode_record() + except Exception as exc: # noqa: BLE001 - retry without unscannable state or diagnostics + if isinstance(exc, KeyLeakError): + self.leaks.append(f"{egress.job_id}/collected.json") + reason = "a key-shaped string was found in collection diagnostics" + else: + reason = f"collection diagnostics could not be scanned: {type(exc).__name__}" + problems = [*removal_failures, reason] + collected.update(ok=False, problems=problems, state_before_stop={}, state_after_stop={}) + data = None + + try: + if data is None: + data = encode_record() + with open_log_dir(egress.log_dir) as dir_fd: + write_new(dir_fd, "collected.json", data, mode=0o644) + if not problems: + try: + pending_collection(self.config.out_dir, egress.job_id).unlink() + except OSError as exc: + problems.append( + f"could not clear the collection marker: {type(exc).__name__}" + ) + collected.update(ok=False, problems=problems) + write_new(dir_fd, "collected.json", encode_record(), mode=0o644) + except KeyLeakError: + self.leaks.append(f"{egress.job_id}/collected.json") + problems.append("a key-shaped string was found during collection publication") + except Exception as exc: # noqa: BLE001 - preserve removal IDs on publication failure + problems.append(f"collection could not be completed: {type(exc).__name__}") + return problems + + async def _stop_egress( + self, egress: Egress, problems: list[str], removal_failures: list[str] + ) -> tuple[dict[str, Any], dict[str, Any]]: + before = await self._state(egress.proxy_id, problems, "before") + if before and (not before.get("Running") or before.get("OOMKilled")): + problems.append( + f"the proxy ended before our stop (exit {before.get('ExitCode')}, " + f"OOMKilled {before.get('OOMKilled')})" + ) + try: + await self.run("stop", "-t", "5", egress.proxy_id) + except Exception as exc: # noqa: BLE001 + problems.append(f"docker stop of the proxy failed: {exc}") + after = await self._state(egress.proxy_id, problems, "after") + if after and after.get("Running"): + problems.append("the proxy was still running after our stop") + elif after and (after.get("ExitCode") != 0 or after.get("OOMKilled")): + problems.append( + f"the proxy exited {after.get('ExitCode')} after our stop " + f"(OOMKilled {after.get('OOMKilled')}): its log may be partial" + ) + for args in (["rm", "-f", egress.proxy_id], ["network", "rm", egress.network_id]): + try: + await self.run(*args) + except Exception: # noqa: BLE001 - report the ID independently of daemon output + removal_failures.append( + f"docker {' '.join(args[:2])} {redact_key_shaped_text(args[-1])} failed" + ) + return before, after + + +class ContainerLauncher: + """Implements host.Launcher: each job's worker in its own hardened, keyless container.""" + + def __init__( + self, sandbox: Sandbox, probe: ProbeFn | None = None, control: ControlFn | None = None + ) -> None: + from benchmarks.agentic.probe import control_probe, isolation_probe + + self.sandbox = sandbox + self._probe: ProbeFn = probe or isolation_probe + self._control: ControlFn = control or control_probe + self._egresses: list[Egress] = [] + self._worker_ids: dict[str, str] = {} + + def supports(self, family: ModelFamily) -> bool: + return family.api in KNOWN_APIS # scripted, and every api make_client builds + + def worker_create_argv(self, job: WorkerJob) -> list[str]: + """Configure the stopped worker, including the program that will read host frames.""" + family, config = job.family, self.sandbox.config + env = worker_env(family) + mounts = ["type=tmpfs,dst=/cache/mcp-python-docs,tmpfs-mode=1777"] + if job.system.id == "python-docs": + index = "/cache/mcp-python-docs/index.db" + mounts.append(f"type=bind,src={config.index_path},dst={index},readonly") + if family.api == "scripted": + script = str(family.raw["script"]) + mounts.append(f"type=bind,src={script},dst={script},readonly") + name = self.sandbox.worker_name(job.job_id) + return self.sandbox.container_argv( + name=name, + network=f"{name}-net", + env=env, + mounts=mounts, + argv=["python", "-m", "benchmarks", "agentic-worker"], + create_only=True, + ) + + def command(self, job: WorkerJob) -> tuple[list[str], dict[str, str]]: + return ["docker", "start", "-ai", self._worker_ids[job.job_id]], self.sandbox.env + + def bootstrap_frame(self, job: WorkerJob) -> dict[str, Any] | None: + """The live worker's one key (none for Ollama), read now, after the gate and probes.""" + family = job.family + if family.api == "scripted": + return None + if family.provider in LIVE_LATCH_ENV: + return {"type": "bootstrap", "env": {}} + keys_file = self.sandbox.config.keys_file + name = PROVIDER_API_KEY_ENV[family.provider] + if keys_file is None: + raise BenchmarkValidationError( + f"model family {family.id!r} needs a keys file for {name}" + ) + return {"type": "bootstrap", "env": {name: read_key(keys_file, name)}} + + async def prepare(self, jobs: Sequence[WorkerJob]) -> None: + """Verify, run the control probe once, then open and probe every job's egress.""" + await self.sandbox.verify(self.sandbox) + index = self.sandbox.config.index_path + if any(job.system.id == "python-docs" for job in jobs) and not index.is_file(): + raise BenchmarkValidationError(f"python-docs requires a local index file at {index}") + await self._control(self.sandbox) # writes probe/control.json + for job in jobs: + allow = allowlist(job.family, job.system.id) + egress = await self.sandbox.open_egress(job.job_id, allow) + self._egresses.append(egress) + try: + await self._probe( + self.sandbox, + egress, + job_id=job.job_id, + family=job.family, + system_id=job.system.id, + ) + except KeyLeakError: + self.sandbox.leaks.append(f"{job.job_id}/probe") + raise + + # Own every stopped worker before reading keys or letting any supervisor start one. + for job in jobs: + argv = self.worker_create_argv(job) + self._worker_ids[job.job_id] = await self.sandbox.create_resource( + self.sandbox.worker_name(job.job_id), *argv[1:] + ) + + # Validate all required keys after isolation and before any worker can spend. + for job in jobs: + self.bootstrap_frame(job) + + async def stop_worker(self, job: WorkerJob) -> None: + """Remove a surviving worker only if this invocation created it.""" + await self._remove_worker(job.job_id) + + async def _remove_worker(self, job_id: str) -> None: + if (container_id := self._worker_ids.get(job_id)) is not None: + await self.sandbox.remove_container(container_id) + del self._worker_ids[job_id] + + async def close(self) -> list[str]: + problems: list[str] = [] + interrupted: asyncio.CancelledError | None = None + + def removal_failure(command: str, resource_id: str, exc: Exception) -> str: + detail = ( + redact_key_shaped_text(str(exc)) + if isinstance(exc, BenchmarkValidationError) + else type(exc).__name__ + ) + return f"{command} {redact_key_shaped_text(resource_id)} failed: {detail}" + + # Partial prepare and spawn failures can leave workers without a supervisor. + for job_id, worker_id in list(self._worker_ids.items()): + try: + await self._remove_worker(job_id) + except Exception as exc: # noqa: BLE001 - continue releasing the other resources + problems.append(removal_failure(f"{job_id}: docker rm -f", worker_id, exc)) + for egress in self._egresses: + try: + issues = await self.sandbox.close_egress(egress) + except (Exception, asyncio.CancelledError) as exc: # noqa: BLE001 + # Collection may have stopped on either side of the removal commands. + # Report both IDs for recovery without echoing the unverified exception. + if isinstance(exc, asyncio.CancelledError) and interrupted is None: + interrupted = exc + if isinstance(exc, KeyLeakError): + self.sandbox.leaks.append(f"{egress.job_id}/collection") + issues = [ + f"collection failed ({type(exc).__name__}); check proxy " + f"{redact_key_shaped_text(egress.proxy_id)} and network " + f"{redact_key_shaped_text(egress.network_id)}" + ] + problems.extend(f"{egress.job_id}: {p}" for p in issues) + if (outside_id := self.sandbox.outside_id) is not None: + try: + await self.sandbox.run("network", "rm", outside_id) + self.sandbox.outside_id = None + except Exception as exc: # noqa: BLE001 + problems.append(removal_failure("docker network rm", outside_id, exc)) + if self.sandbox.leaks: + leak = KeyLeakError( + "key-shaped strings were detected during proxy collection: " + + ", ".join(self.sandbox.leaks) + + (f"; other problems: {'; '.join(problems)}" if problems else "") + ) + if interrupted is None: + raise leak + add_cleanup_cause(interrupted, leak) + elif interrupted is not None: + add_cleanup_cause(interrupted, BenchmarkValidationError("; ".join(problems))) + if interrupted is not None: + raise interrupted + return problems diff --git a/benchmarks/agentic/schemas.py b/benchmarks/agentic/schemas.py index 1c439cd0..5ffa891c 100644 --- a/benchmarks/agentic/schemas.py +++ b/benchmarks/agentic/schemas.py @@ -43,6 +43,22 @@ def to_openai_responses(tools: Sequence[ToolSpec]) -> list[dict[str, Any]]: ] +def to_openai_chat(tools: Sequence[ToolSpec]) -> list[dict[str, Any]]: + """Chat Completions tools (Ollama's OpenAI-compatible endpoint), ``strict`` explicitly false.""" + return [ + { + "type": "function", + "function": { + "name": t.name, + "description": t.description, + "parameters": t.input_schema, + "strict": False, + }, + } + for t in tools + ] + + def _reduce(schema: Any, path: str, dropped: list[str]) -> Any: if not isinstance(schema, dict): return schema diff --git a/benchmarks/agentic/types.py b/benchmarks/agentic/types.py index fdbcd84d..9a2ce23f 100644 --- a/benchmarks/agentic/types.py +++ b/benchmarks/agentic/types.py @@ -2,6 +2,7 @@ from __future__ import annotations +from collections.abc import Callable from dataclasses import dataclass from typing import Any, Literal, Protocol @@ -103,18 +104,32 @@ def __init__( class ModelClient(Protocol): provider: str model_id: str + api: str def request_params(self) -> dict[str, Any]: """Every setting sent except system, tools and messages.""" raise NotImplementedError - def rendered_bytes(self, conv: Conversation, start: int) -> int: - """UTF-8 bytes of the provider-rendered request. + def rendered_bytes( + self, + conv: Conversation, + start: int, + *, + check_content: Callable[[bytes], None] | None = None, + ) -> int: + """Validate outgoing content and return its provider-rendered UTF-8 byte count. System, tools and ``entries[start:]`` when ``start == 0``, else ``entries[start:]`` only. + Check decoded strings and rendered JSON, including native replay, for key shapes. + The loop calls this with ``start == 0`` before every spend reservation. + ``check_content`` is an optional worker-local literal check, with no SDK auth. """ raise NotImplementedError async def call(self, conv: Conversation) -> ModelTurn: - """One HTTP request; raises :class:`ProviderCallError`.""" + """One HTTP request; raises :class:`ProviderCallError`. + + Response content is untrusted. Normal adapters return it with usage so the + loop can settle the request before checking arguments and native replay. + """ raise NotImplementedError diff --git a/benchmarks/agentic/usage.py b/benchmarks/agentic/usage.py index 82b4368e..47689caf 100644 --- a/benchmarks/agentic/usage.py +++ b/benchmarks/agentic/usage.py @@ -51,6 +51,14 @@ def openai_buckets(usage: Mapping[str, Any]) -> Buckets: ) +def ollama_buckets(usage: Mapping[str, Any]) -> Buckets: + """Chat Completions usage: cached tokens are nested inside the prompt tokens.""" + cached = _count(usage.get("prompt_tokens_details"), "cached_tokens") + return _buckets( + _count(usage, "prompt_tokens") - cached, 0, cached, _count(usage, "completion_tokens"), 0 + ) + + def gemini_buckets(usage: Mapping[str, Any]) -> Buckets: cached = _count(usage, "cached_content_token_count") thoughts = _count(usage, "thoughts_token_count") diff --git a/benchmarks/agentic/worker.py b/benchmarks/agentic/worker.py index 7e07bd78..78ecbb48 100644 --- a/benchmarks/agentic/worker.py +++ b/benchmarks/agentic/worker.py @@ -14,28 +14,63 @@ import hashlib import io import os +import shutil import sys import threading from collections import deque +from collections.abc import Callable, Mapping from contextlib import AsyncExitStack, suppress from dataclasses import asdict from importlib.metadata import version from typing import Any -from benchmarks.adapters.guard import PROVIDER_API_KEY_ENV +from benchmarks.adapters.guard import PAID_KEY_ENVS, PROVIDER_API_KEY_ENV from benchmarks.agentic.bridge import Bridge, SystemSpec, open_bridge, system_spec_from_raw +from benchmarks.agentic.cleanup import add_safe_cleanup_cause, settle from benchmarks.agentic.ledger import Outcome -from benchmarks.agentic.protocol import KeyLeakError, encode_frame, read_frame +from benchmarks.agentic.protocol import ( + WORKER_FRAME_LIMIT_EXIT, + WORKER_LEAK_REASON, + KeyLeakError, + encode_frame, + find_frame_too_large, + find_key_leak, + read_frame, + read_frame_fd, + scanned_json_bytes, +) from benchmarks.agentic.types import Buckets, ToolSpec from benchmarks.model_matrix import model_family_from_raw from benchmarks.runner import BenchmarkValidationError MAX_RERUNS = 2 +#: The type of the private first frame that carries a live worker's one key (ruling A1). +BOOTSTRAP = "bootstrap" _REDACTED = b"[redacted]" #: A trajectory that ended in one of these leaves the MCP server unusable: reopen it. _REOPEN_AFTER = frozenset({"mcp_protocol_crash", "cap_tool_timeout"}) +def apply_bootstrap(frame: Mapping[str, Any]) -> None: + """Put the bootstrap frame's one paid key in this process's environment, in memory only. + + ``env`` holds at most one name, a paid key's. Anything else is refused, naming the + variables and never a value. + """ + env = frame.get("env") + names = sorted(str(name) for name in env) if isinstance(env, Mapping) else [] + if ( + not isinstance(env, Mapping) + or len(env) > 1 + or not set(names) <= set(PAID_KEY_ENVS) + or not all(isinstance(value, str) and value for value in env.values()) + ): + raise BenchmarkValidationError( + f"a bootstrap frame may set at most one paid key, got {names}" + ) + os.environ.update(env) + + def _write_all(fd: int, data: bytes) -> None: while data: data = data[os.write(fd, data) :] @@ -79,11 +114,15 @@ def __init__( def send(self, message: dict[str, Any]) -> None: """Write one frame; refuse a frame that holds any of the worker's secrets.""" - frame = encode_frame(message) - if any(secret in frame for secret in self._secrets): - raise KeyLeakError("own key found in output") + frame = encode_frame(message, where="worker frame") + self.check_content(frame) _write_all(self._fd, frame) + def check_content(self, content: bytes) -> None: + """Worker-local literal check; callers supply content, never SDK auth or argv.""" + if any(secret in content for secret in self._secrets): + raise KeyLeakError("own key found in output") + def close(self) -> None: """Drain the redactor: every byte written so far reaches the sink. Restores nothing.""" sys.stdout.flush() @@ -130,6 +169,7 @@ class _HostLedger: def __init__(self, channel: ProtocolChannel, reader: asyncio.StreamReader) -> None: self._channel, self._reader = channel, reader + self.check_failure: Callable[[], None] | None = None async def request(self, message: dict[str, Any]) -> dict[str, Any]: self._channel.send(message) @@ -147,6 +187,8 @@ async def reserve( output_bound: int, kind: str = "model_call", ) -> str | None: + if self.check_failure is not None: + self.check_failure() reply = await self.request( { "type": "reserve", @@ -157,6 +199,8 @@ async def reserve( "kind": kind, } ) + if self.check_failure is not None: + self.check_failure() return reply["unit_id"] if reply.get("type") == "grant" else None async def settle(self, unit_id: str, *, outcome: Outcome, buckets: Buckets | None) -> None: @@ -171,10 +215,17 @@ async def settle(self, unit_id: str, *, outcome: Outcome, buckets: Buckets | Non def _converted(provider: str, tools: list[ToolSpec]) -> tuple[list[dict[str, Any]], list[str]]: - from benchmarks.agentic.schemas import to_anthropic, to_gemini, to_openai_responses + from benchmarks.agentic.schemas import ( + to_anthropic, + to_gemini, + to_openai_chat, + to_openai_responses, + ) if provider == "google": return to_gemini(tools) + if provider == "ollama": + return to_openai_chat(tools), [] if provider == "openai": return to_openai_responses(tools), [] return to_anthropic(tools), [] @@ -190,7 +241,12 @@ def _index_sha256() -> str | None: return hashlib.file_digest(file, "sha256").hexdigest() -def _system_info(system: SystemSpec, provider: str, bridge: Bridge | None) -> dict[str, Any]: +def _system_info( + system: SystemSpec, + provider: str, + bridge: Bridge | None, + model_limits: dict[str, Any] | None = None, +) -> dict[str, Any]: from benchmarks.agentic.schemas import schemas_sha256 tools_raw = bridge.tools_raw if bridge else [] @@ -205,46 +261,92 @@ def _system_info(system: SystemSpec, provider: str, bridge: Bridge | None) -> di "gemini_dropped": dropped, "index_sha256": _index_sha256() if system.id == "python-docs" else None, "client_versions": _client_versions(), + "fetch_extraction": _fetch_extraction() if system.id == "docs-fetch" else None, + "model_limits": model_limits, } +def _fetch_extraction() -> str: + """readabilipy uses Readability.js only when node is on PATH (design §5.1).""" + return "readability-js" if shutil.which("node") else "pure-python" + + def _client_versions() -> dict[str, str]: """Installed versions, read from metadata: no SDK is imported.""" return {name: version(name) for name in ("anthropic", "openai", "google-genai", "mcp")} -async def _open(stack: AsyncExitStack, system: SystemSpec) -> Bridge | None: +async def _open( + stack: AsyncExitStack, + system: SystemSpec, + *, + check_content: Callable[[bytes], None] | None = None, +) -> Bridge | None: if system.transport == "none": return None - return await stack.enter_async_context(open_bridge(system)) + return await stack.enter_async_context(open_bridge(system, check_content=check_content)) -async def _close(stack: AsyncExitStack) -> None: +async def _close(stack: AsyncExitStack, pending: BaseException | None = None) -> None: try: await stack.aclose() - except Exception as exc: # noqa: BLE001 - a dead server may fail its own shutdown + except BaseException as exc: + if leak := find_key_leak(exc): + raise leak + if not isinstance(exc, Exception): + raise + if pending is not None: + if leak := find_key_leak(pending): + raise leak + if not isinstance(pending, Exception): + raise pending from exc + if frame := find_frame_too_large(pending): + raise frame + if frame := find_frame_too_large(exc): + raise frame print(f"closing the MCP bridge failed: {exc!r}", file=sys.stderr) -async def _run_job(channel: ProtocolChannel, reader: asyncio.StreamReader) -> int: +async def _run_job( + channel: ProtocolChannel, + reader: asyncio.StreamReader, + first: dict[str, Any] | None = None, + *, + bootstrapped: bool = False, +) -> int: # Imported here, after protect_output: the provider SDKs load behind the redactor. - from benchmarks.agentic.clients import make_client + from benchmarks.agentic.clients import fetch_model_limits, make_client from benchmarks.agentic.loop import Caps, TrajectoryDiscarded, run_trajectory - job = await read_frame(reader) + job = first if first is not None else await read_frame(reader) if job is None or job.get("type") != "job": raise BenchmarkValidationError("the host sent no job") + scanned_json_bytes(job, where="worker job", check_content=channel.check_content) family = model_family_from_raw(job["family"]) system = system_spec_from_raw(job["system"]) caps = Caps(**job["caps"]) + if family.api != "scripted" and not bootstrapped: + raise BenchmarkValidationError("a live job needs its key bootstrap frame first") client = make_client(family, timeout_s=caps.model_call_timeout_s) + # Model-limit discovery is also an outgoing provider request, before the loop. + scanned_json_bytes( + client.request_params(), + where="outgoing provider settings", + check_content=channel.check_content, + ) + execution = {"provider": client.provider, "model_id": client.model_id, "api": client.api} + # One free models GET per live worker, outside the ledger (round-2 ruling D10). + limits = None if family.api == "scripted" else await fetch_model_limits(client) host = _HostLedger(channel, reader) queue = deque((item, 1) for item in job["trajectories"]) seen: set[str] = set() stack = AsyncExitStack() try: - bridge = await _open(stack, system) - channel.send(_system_info(system, family.provider, bridge)) + bridge = await _open(stack, system, check_content=channel.check_content) + if bridge is not None: + bridge.check_content = channel.check_content + host.check_failure = bridge.raise_if_failed + channel.send(_system_info(system, family.provider, bridge, limits)) while queue: item, attempt = queue.popleft() ident = {"corpus_id": item["corpus_id"], "repeat": item["repeat"]} @@ -257,12 +359,15 @@ async def _run_job(channel: ProtocolChannel, reader: asyncio.StreamReader) -> in ledger=host, caps=caps, seen_tool_args=seen, + check_content=channel.check_content, ) except TrajectoryDiscarded as discarded: + if bridge is not None: + bridge.raise_if_failed() await host.request( { "type": "discarded", - "record": discarded.record, + "record": {**discarded.record, "execution": execution}, **ident, "reason": discarded.reason, "attempt": attempt, @@ -291,48 +396,91 @@ async def _run_job(channel: ProtocolChannel, reader: asyncio.StreamReader) -> in } ) continue + if bridge is not None: + bridge.raise_if_failed() + record["execution"] = execution trajectory = {"type": "trajectory", "record": record, **ident, "attempt": attempt} await host.request(trajectory) if bridge is not None and (record["error"] or {}).get("category") in _REOPEN_AFTER: await _close(stack) stack = AsyncExitStack() - bridge = await _open(stack, system) + bridge = await _open(stack, system, check_content=channel.check_content) + if bridge is not None: + bridge.check_content = channel.check_content + host.check_failure = bridge.raise_if_failed if bridge is not None else None finally: - await _close(stack) # the MCP server exits and drops its copy of fd 2 + await _close(stack, sys.exception()) # the MCP server exits and drops its copy of fd 2 channel.send({"type": "done"}) return 0 def _report(channel: ProtocolChannel, reason: str, code: int) -> int: - try: - channel.send({"type": "error", "reason": reason}) - except KeyLeakError: - channel.send({"type": "error", "reason": "own key found in output"}) - return 3 + with suppress(OSError): + try: + channel.send({"type": "error", "reason": reason}) + except KeyLeakError: + code = 3 + with suppress(KeyLeakError): + channel.send({"type": "error", "reason": WORKER_LEAK_REASON}) return code -async def run_worker(channel: ProtocolChannel, reader: asyncio.StreamReader) -> int: +async def run_worker( + channel: ProtocolChannel, + reader: asyncio.StreamReader, + first: dict[str, Any] | None = None, + *, + bootstrapped: bool = False, +) -> int: + # SDK task groups cancel the task that opened them when their reader fails. + # Keep that cancellation inside the one job, distinct from our caller's + # cancellation. wait() observes completion without propagating child cancellation. + job = asyncio.create_task(_run_job(channel, reader, first, bootstrapped=bootstrapped)) + try: + await asyncio.wait((job,)) + except asyncio.CancelledError as interrupt: + job.cancel() + await settle(job) # drain the owned SDK tasks/process even on repeated interrupts + try: + job.result() + except BaseException as failure: + add_safe_cleanup_cause(interrupt, failure) + raise try: - return await _run_job(channel, reader) - except KeyLeakError: - return _report(channel, "own key found in output", 3) - except Exception as exc: # noqa: BLE001 - every failure is reported to the host + return job.result() + except BaseException as exc: # task groups may combine a leak with cancellation + if find_key_leak(exc) is not None: + return _report(channel, WORKER_LEAK_REASON, 3) + if frame := find_frame_too_large(exc): + return _report(channel, f"FrameTooLarge: {frame}", WORKER_FRAME_LIMIT_EXIT) + if not isinstance(exc, Exception): + raise return _report(channel, f"{type(exc).__name__}: {exc}", 2) -async def _serve(channel: ProtocolChannel) -> int: +async def _serve( + channel: ProtocolChannel, first: dict[str, Any] | None = None, *, bootstrapped: bool = False +) -> int: reader = asyncio.StreamReader() await asyncio.get_running_loop().connect_read_pipe( lambda: asyncio.StreamReaderProtocol(reader), sys.stdin ) - return await run_worker(channel, reader) + return await run_worker(channel, reader, first, bootstrapped=bootstrapped) def main_worker() -> int: - """``python -m benchmarks agentic-worker``: protect output first, then run the job.""" + """``python -m benchmarks agentic-worker``: the key bootstrap, output protection, the job. + + The first frame is read before anything else, so a bootstrap key is in the environment + when protect_output collects the secrets it redacts, and before any SDK is imported. + """ + first = read_frame_fd(0) + bootstrapped = False + if first is not None and first.get("type") == BOOTSTRAP: + apply_bootstrap(first) + first, bootstrapped = None, True channel = protect_output() try: - return asyncio.run(_serve(channel)) + return asyncio.run(_serve(channel, first, bootstrapped=bootstrapped)) finally: channel.close() diff --git a/benchmarks/model_matrix.py b/benchmarks/model_matrix.py index 464ea4a3..fcb24ea7 100644 --- a/benchmarks/model_matrix.py +++ b/benchmarks/model_matrix.py @@ -26,9 +26,7 @@ from pathlib import Path from typing import Any -import yaml - -from benchmarks.runner import _SAFE_ID, BenchmarkValidationError, Competitor +from benchmarks.runner import _SAFE_ID, BenchmarkValidationError, Competitor, _load_yaml_mapping #: Label for tokens counted by the benchmark's own methodology tokenizer #: (Claude token counting after client-side rewrap, per @@ -110,16 +108,10 @@ def load_model_matrix(path: Path) -> ModelMatrix: by ``benchmarks.runner``) on any structural problem, so callers can rely on one exception type across the benchmark's YAML-config surface. """ - if not path.exists(): - raise BenchmarkValidationError(f"model matrix file does not exist: {path}") - with path.open("r", encoding="utf-8") as file: - try: - data = yaml.safe_load(file) - except yaml.YAMLError as exc: - raise BenchmarkValidationError(f"model matrix file is not valid YAML: {exc}") from exc - if not isinstance(data, dict): - raise BenchmarkValidationError("model matrix file must contain a YAML mapping") + return model_matrix_from_mapping(_load_yaml_mapping(path, "model matrix")) + +def model_matrix_from_mapping(data: dict[str, Any]) -> ModelMatrix: token_label = data.get("methodology_token_label") if not isinstance(token_label, str) or not token_label.strip(): raise BenchmarkValidationError( diff --git a/benchmarks/runner.py b/benchmarks/runner.py index f14593c6..2815bdee 100644 --- a/benchmarks/runner.py +++ b/benchmarks/runner.py @@ -211,6 +211,10 @@ def _load_yaml_mapping(path: Path, label: str) -> dict[str, Any]: data = yaml.safe_load(file) except yaml.YAMLError as exc: raise BenchmarkValidationError(f"{label} file is not valid YAML: {exc}") from exc + return _require_yaml_mapping(data, label) + + +def _require_yaml_mapping(data: Any, label: str) -> dict[str, Any]: if not isinstance(data, dict): raise BenchmarkValidationError(f"{label} file must contain a YAML mapping") return data diff --git a/benchmarks/sandbox/Dockerfile b/benchmarks/sandbox/Dockerfile new file mode 100644 index 00000000..d2d9ca61 --- /dev/null +++ b/benchmarks/sandbox/Dockerfile @@ -0,0 +1,17 @@ +FROM python:3.14.10-slim-trixie@sha256:930e1abba7c4e8f96ed93e8012c35d174d7732752731bbd5e8e757d7ec6f3966 +COPY --from=ghcr.io/astral-sh/uv:0.13.4@sha256:9f130421e930bfbdc563c00740466603f8723158e90297d07957c2294640262b /uv /uvx /bin/ +ENV UV_COMPILE_BYTECODE=1 UV_LINK_MODE=copy UV_PYTHON_DOWNLOADS=0 PYTHONDONTWRITEBYTECODE=1 +WORKDIR /app +# The build context is `git archive HEAD`: exactly the run commit, nothing untracked. +COPY . /app +RUN uv sync --locked --no-editable \ + && uv venv /opt/fetch --python /usr/local/bin/python3.14 \ + && uv pip install --python /opt/fetch/bin/python --require-hashes --no-deps \ + -r benchmarks/sandbox/fetch-requirements.txt \ + && ln -s /opt/fetch/bin/mcp-server-fetch /usr/local/bin/mcp-server-fetch \ + && mkdir -p /cache/mcp-python-docs \ + && command -v cat \ + && ! command -v node \ + && useradd --uid 10001 --no-create-home --shell /usr/sbin/nologin bench +ENV PATH=/app/.venv/bin:$PATH +USER 10001:10001 diff --git a/benchmarks/sandbox/fetch-requirements.txt b/benchmarks/sandbox/fetch-requirements.txt new file mode 100644 index 00000000..384951c0 --- /dev/null +++ b/benchmarks/sandbox/fetch-requirements.txt @@ -0,0 +1,1142 @@ +# This file was autogenerated by uv via the following command: +# uv pip compile - --universal --python-version 3.14 --generate-hashes --exclude-newer 2026-10-22T00:00:00Z -o benchmarks/sandbox/fetch-requirements.txt +annotated-types==0.8.0 \ + --hash=sha256:13b2beaad985e05e2d6407ee4c4f35590b11f8d693a258a561055cac8f64cab7 \ + --hash=sha256:f072f4d804ea359e4eaf198b1af7a8b0943881a87f31bb764f8bf219bb9419e0 + # via pydantic +anyio==4.15.1 \ + --hash=sha256:6152fdbbf9a77fdec97731721bebf7c4c44f7c29b424b0065826173efc7ed101 \ + --hash=sha256:9f28306018cbd6d329e64a36d58256edff76dd996fe423bc957326e578b82a94 + # via + # httpx + # httpx2 + # mcp + # sse-starlette + # starlette +attrs==26.1.0 \ + --hash=sha256:c647aa4a12dfbad9333ca4e71fe62ddc36f4e63b2d260a37a8b83d2f043ac309 \ + --hash=sha256:d03ceb89cb322a8fd706d4fb91940737b6642aa36998fe130a9bc96c985eff32 + # via + # jsonschema + # referencing +beautifulsoup4==4.15.0 \ + --hash=sha256:288e3ca7d54b06f2ac191970bc275c1939cb46d450b255bf6718b04aa37ab4f7 \ + --hash=sha256:d6f88de62e1d4e38ecb1077eb9724cd0eff29d2a08ca16a401e9b9e93f117cf9 + # via + # markdownify + # readabilipy +certifi==2026.10.19 \ + --hash=sha256:035c1e85572b141bf1c3a3eff0e33a8eb74917522f2559075ff8d2fea780a1ae \ + --hash=sha256:42d35340cc5b9ba78e818ddbff0c5b1c2b779de448a340fd1b989f5fa8670e1b + # via + # httpcore + # httpx + # requests +cffi==2.1.1 ; platform_python_implementation != 'PyPy' \ + --hash=sha256:046bfc24911b37851ee1b51aab8bffe713d89c68c6a057b09484ce9fd5f69b4e \ + --hash=sha256:06c72bb76605a4b0cd0aad6930b69d4baf7dd5d806cfc409b824191099700e66 \ + --hash=sha256:0beceaabe56af686895136a2de78db54ecd8e4046b236b8fd6d6cb61389e9bf2 \ + --hash=sha256:154852545011f779917b11c78db2358d095da62a9a172b78ad0a583ee5adc0d0 \ + --hash=sha256:194cffa889098ced9976c3fc6340305e43f6303657d298da55366907c05c22d6 \ + --hash=sha256:19ee6127ee34de7d83ce3d371ebc5ed91addbdcc39f9ab15ce4eb35a4e534971 \ + --hash=sha256:1a18a57b58cfb21fc28d72e876acf10eaed67a1ed96226f92af4df681d571c4c \ + --hash=sha256:1aa5645c30469b09530c4ebca77ebf8f17618293c58f8549cb1a543a50236e7d \ + --hash=sha256:1dea0e4d7d4f11f619fe8c1d76caf49e24405b4b5743c0e3be16a500ecd930c9 \ + --hash=sha256:208f941bb9d18e768138677f0a6d2ce01f590df56043dda1df1535ac57c88517 \ + --hash=sha256:210019b6c7cf07f081b4c54635c8cf744377001350e29cc0f81c4377b4797735 \ + --hash=sha256:246fa40ce8645a614ff682e0b70f37134e460eaf93a775e0cbe3cca585a67a80 \ + --hash=sha256:25792eac27877609e7bb06d42ff88278a6624fff2ba9bbb523c09616b117e80f \ + --hash=sha256:27350daa11d4f10c540e6e89dada4c54feb7256ad03e9a4dc075ebad7ba360d1 \ + --hash=sha256:28907ab9bfb6aa13184cfc17c6b8e1023c5ab6fd7076d8c20a35e59fe04f8f29 \ + --hash=sha256:2ae64be792b8966f2c69538199728b290e34726562896df1e5dc8ffd8d8188e8 \ + --hash=sha256:31348097ff5bbe827ccc41795d4dd099d9f0625e7def00ee653c137a490c2a6c \ + --hash=sha256:3143d81e29e1e20a9ce10901ec369012947876596f75a222235965f2b7ae832e \ + --hash=sha256:3222ba5d678f80a030e6afbcc33dc1ae5cb45facabb61cee2c7016b8432fde48 \ + --hash=sha256:3311ed60d36f83378794e1009ac6258bafbf81f7888b4caa7b35a521e3f95813 \ + --hash=sha256:334644fbac4eff73d985a17a91226df55d0f394160c4cfb880e084c8f7161cac \ + --hash=sha256:34e261f78cb6ceaaa36f42f2613f4380d94d9c759a9c73c769ee6e0247364632 \ + --hash=sha256:363e05fa78e15116c3c32c210ee36884fd6b9afa6d440e47112c3bd511d64cb6 \ + --hash=sha256:398aff33cee2767e3e781d2554c54bd0dff386bb437581e0d8011fde1a942ec1 \ + --hash=sha256:3d22a20b1fb1632cc72c22f95f7b0d2961c3e1c235f245ba4c606c4771035659 \ + --hash=sha256:42a494cee34437f05546455144f2b5d9ac09b1face62bcfce597d2e521066688 \ + --hash=sha256:42e2f76b9455f5a9a844f770bf3e200ed3da0e15f5df3db9c31fe80b04b3d004 \ + --hash=sha256:42f6930c31dc7f50732c9ae793c2786c7b6b044195967bbdde40bb9be81c4cc0 \ + --hash=sha256:456a61fa52d579ebf9df2e9552ead5129855dbaff6c1e5a9b1bc408809bdc062 \ + --hash=sha256:471cee653ae88de62096552e6d24ccb4a5adb8c8c9f10b5054d0122c15bf2779 \ + --hash=sha256:49cbc70e6542d4ccccb936558d1064a8012541e78f821f955cff24e357776c94 \ + --hash=sha256:4a7c934f7360e8cd64fe9efadcbd10c7c6364f531e432b9a4bf5ccbc9e0e8b50 \ + --hash=sha256:4be96343e422f2dfcd12ab5c9f5aebe03f82f737c6bffeca6830b3875cb44aab \ + --hash=sha256:4f42141fc14250de6dde5ee7ea4432be017252d91f19c5ad043c084cea629cac \ + --hash=sha256:507a24c282e0f42f8ed737cf048572cbf580468da5555764a8331735e9c736b6 \ + --hash=sha256:51b31d1c98274844cfd7838ce00bfc27c7423a4dc00fc0772fc3331c2cc90676 \ + --hash=sha256:58acb8ab8e295e6c5ea12f888cbb13cf21511ef2a3303a23f4325c29d17fe5c1 \ + --hash=sha256:5a59cc1c4442bc3d5c703bf720b51138d0bfc173618807c9ee2490a7541dd3d9 \ + --hash=sha256:5bb4e7ea95dcd6a014a6fef62e62467d67d8e582326443f3d68e71d6320a9fcf \ + --hash=sha256:5c58fe613dc5e5336357eff555824a314d8e43282600435c8d1cb6a7a2fedd13 \ + --hash=sha256:5e7cecbaadb83884793e05828cee59b210b24583b9c7425d0ba6a754fe22eb4e \ + --hash=sha256:616f097f2fe415bc92a247f02e11f634e1f9e9a83d327e3c915c15089c87869e \ + --hash=sha256:63bbfd5ded17c4840ac07cd8f1c21ba9d9708141f840b324f422f41b207e3973 \ + --hash=sha256:64faea20f4e2613363a1a9b9c7dd73058f3ecd00133a511e72ad7c511658f527 \ + --hash=sha256:661c298b4821edebead0c91edd2b00374d67ad7c5a1f7a91d4442633b79d6a72 \ + --hash=sha256:68e62fe11f30d5ca8289242866f0a5291402d8529ca2178ab8afc5c9694ae890 \ + --hash=sha256:6a8dddef476fab96d066d578fc88526767b836ab5ab21754e1d5bf3879c31c7c \ + --hash=sha256:6e192623c49c94421616a5778fba35cf0d5a8d000650c1967ef4448ee5cdd990 \ + --hash=sha256:7225e4514edb64eb6740324353e0da0711954fd8d7da4576755b1c6e09b697cd \ + --hash=sha256:75f80557d1389eddbd0de2681f6a390a0c5338c31ddaa821381c203fc3fd50d9 \ + --hash=sha256:770de9db11e84213beec501cfcaa013b019820ca881e03344dea5844f7876d94 \ + --hash=sha256:7750c6449dff7864bb9bb27ddfb0267756189201a3afc911d82b3caacd70dfc3 \ + --hash=sha256:7bde5e4cc5c10140859842b9d383af292b22639a4dffb725314baf45968cef80 \ + --hash=sha256:7ce713ace7c0e4520535b42b77eaa742c16dab813978064913e5a3cf82973b41 \ + --hash=sha256:7da0c5eff80f0197f3b3d1232ec5a682a9325f4ae9016a78f5f5ca35f9ced1f5 \ + --hash=sha256:7dbb61fe3a7699468030f71bbe5f8a0e326a151daa91beb11a6fc1f980c55e1c \ + --hash=sha256:811bd1e21d32de12efca32393a0ab3f5133b54fce9bd44b8bd77ab07da14bf6a \ + --hash=sha256:8ef53b2de9bcb9197d31854256575d59dbac0cba72ac627bb291ef5eceb74be4 \ + --hash=sha256:937c0052c05a31ca1daf18de3158eed4dbfcb9cc107adbea227728d647be701e \ + --hash=sha256:9d2055050ea716bd38b7f7f1579c275386646b4894c155a3e2f3cd62ed41b7c6 \ + --hash=sha256:9f8d177621de5cb38ee3e731eda45d421db093ec0739f46a5594babda7987a98 \ + --hash=sha256:a2d7755bef5a12ed488f4ef1f1b69ee9191d7396083b755a5d2295f6edb4768b \ + --hash=sha256:a48d62ab9d6f4f98c983223a547af44be6ca3691074c31cecced6facd3ba2dc1 \ + --hash=sha256:a4f00aa42f75d6e4595e8866e748cc1705adc0cddfeb2ca86d0d03993d63ba03 \ + --hash=sha256:a6e721d4b0e45d5b65e87534470e67b18dcd092c83f68fba09f152b9cbc061af \ + --hash=sha256:a730a083190634c65cca36ba5f489531576ebd79bcd5c8e172130f6453127231 \ + --hash=sha256:a931079504ecc49efed7744c476a5c343a92fabf66dec2db95edb1b2fdc770e2 \ + --hash=sha256:aa9511c62d14da7aacc9b4bf51f3f697a621e83b2d6919008243c3aad168eea3 \ + --hash=sha256:ab36d55f9ed2d067327667c2fea18dda018eb628dd6347aa01dda6cf1f5d3836 \ + --hash=sha256:ad2c86c495b899d862ea0f4b42891b8713a3bd45dd4105c7fd51c2a72f39f3a5 \ + --hash=sha256:aeae0e330c9f6acd681f647d46cefd30c29f93e3392882e792e82080c9691399 \ + --hash=sha256:b0431303acaea1089ad4b3e9ce4e6518193def1118d4073ca848635ee4ea2e96 \ + --hash=sha256:b5bdfd1c873d4e093aabc0ca84c4ca6dbc4f752afb5c86f146d9742580c9da2e \ + --hash=sha256:baed1e86cc735622097354b9d1281406caf42ff42a886d29faa8e8d1630333be \ + --hash=sha256:c1453022f490d2459a11819d83ad1d586e9ff65a12ac3e705ffebd46d3685dcf \ + --hash=sha256:c26608d2222fb1e94487e4a387d85f13eb55d5ed725cb25a0c589ac4ee60e7bc \ + --hash=sha256:c7659f22557c5a0bc4855cd635f55edec690cc008a40768527762cb9fb263455 \ + --hash=sha256:c8c69575568085ba0b1b10c0249d779a214aea6f6522e949a0fc9fb0fcb449d0 \ + --hash=sha256:c8d2c9fd1f2d16f780d15127abb050d13d1a76c03a4bd87d7e4980e45e511e12 \ + --hash=sha256:ca82be1a1d406ecfe1d25dc16cb33488e5a16bf4438c9fb590484ea29d92478b \ + --hash=sha256:cc572dace3f60ef98d7b12ff411d20f5362feb31a0439eab0085bbfd349982d7 \ + --hash=sha256:d18e5ac0f2f03f4f518d3e23db0f0cad7faa1da8620e9c09461d443bbf6e6692 \ + --hash=sha256:d28630f5854ab07ab1fd4aba756de52326c82e6be15d414b12793f1975048b54 \ + --hash=sha256:d9c275eaacd24aa73f94ffd6de08fc3f932424d8b6c376f4bed7cde376fe7bc3 \ + --hash=sha256:da0e573f9f97159390c89d9f1a9e41908b66d408cc5b58d08cf3847d844c531b \ + --hash=sha256:dd31f52ea1086513bb9df30f8fcee9b8918323ae067a3d5b78bc826a000712be \ + --hash=sha256:dddad92b554513a31f272570678ba307fb9f618f05e3d4a5eacafff9eae03e1d \ + --hash=sha256:df423d40ee8654634421812bc3b196da3f9bd7d32929da813f8394c4348a5358 \ + --hash=sha256:df913725b79db7bcf03448f36b7bf8815363417d5b58deecf9305e3e30f0f21a \ + --hash=sha256:e0bcb7e0f677f543555d2adff3bf19c05f66cdb4796e5ff602442ab2fe3c4ef7 \ + --hash=sha256:e2d65b31f36619cda3999b78b2aa9632e76b78448e7a56fc4240824200e7c4fc \ + --hash=sha256:e6e8cff14d6fb0be70a09c0bdc58096f501952d04624ebf867e0e56da2df8960 \ + --hash=sha256:f16c709686a78c727bbbf059f92b0bf41c6fc60deec706d2dc19f529175a6125 \ + --hash=sha256:f24fb43132a4c6b4cb4eb029492919b2db645be6808d738f244fd146c03c32cb \ + --hash=sha256:f53e442b08449d42821fa4a4fba000095af9f62742a500f978a9f557ec44339a \ + --hash=sha256:f5cfbc5fe74540d335175b656c725d74d90e3730c626d92575eea35029d9afaa \ + --hash=sha256:f81b3b8f3d4e343550fa4baa0e479bba9f2d29ce9c2e9b51d1ce1718d7442fcf \ + --hash=sha256:f8ec5e643a9a937f64e1999eb9f75d072263751912dc5cd06d3c85f8f44be7c3 \ + --hash=sha256:fb92203a88b3d3053034db775110081c49d28be6551923805e039924093761e4 \ + --hash=sha256:fcd22650c908d7b7da162bbfaab594a1227a15d1643a98c68b122ac642fa2264 + # via cryptography +charset-normalizer==3.5.2 \ + --hash=sha256:01077390b03f7988f11d700a2194e69b119741a86b1a638b1db88891e3eced8e \ + --hash=sha256:01b0c0d2262a9e28e8484a278c7e1b5d650e3ac8cf2683d2967e25899f208bdf \ + --hash=sha256:04851f73ae72b8413dddadb16a49dfee95263553741fd42d546f7d66907e6be5 \ + --hash=sha256:0521c5665880b33d603717defa76c094048900010897909952397feb3039da56 \ + --hash=sha256:0774bf9bf620249fee3e0b8b9fd3065de213be30f3aa94ce2494b3b638949e26 \ + --hash=sha256:0891b9d3903c5571c03771ca669a4b0ec5618ca722a5c957d3d29cd4e5062848 \ + --hash=sha256:0c951d5e6dd9c2ff60609476752bee49da4206adde960ebc247766937f72e718 \ + --hash=sha256:0fed1d06615f022ee3b13caf5e8b180cfea32bb2c5aded8a9d44277afc040f93 \ + --hash=sha256:114e4d0c92d618409ed82a99e22b5c5e768fe995f2973f78265f4524f49d4640 \ + --hash=sha256:11912e4bb14baae7c5d8791aa55ba0a3a03ec6729073307b0f57270abaa713d3 \ + --hash=sha256:11a4d68a6ecda3292cb1e50239e111543ba5d709bb62a6b4ea1afcfa729d8875 \ + --hash=sha256:124fbf1a8ff966d87ae05bb8bd45a71f966055ed8bba320d0c7cf450bc5f4d0e \ + --hash=sha256:1461ac396c4fdb983a675f20aa555624f0ee18ac83d832b9244ffff3d8055275 \ + --hash=sha256:1503bccbeb36d5527790c3930327704c39af22de3112f1b1666a9f3ce15ee204 \ + --hash=sha256:15bb4005af6320d259dc7593ca84a38d7fe06a421dbcf7b910ae23979101e787 \ + --hash=sha256:15c44f7edfd477b06f517a5cc317fc1707edb9de2c865f43d4b6513907473234 \ + --hash=sha256:16fa0eccf81304b79c5cd87f9271c3b85dd9dd99245e4422ae9c0dd45e0f99d3 \ + --hash=sha256:183b88127acdb4fabe59d951ab424faf1af7b63cdbb5f776186c1ea2ffcaed98 \ + --hash=sha256:195c26fb65950f8fce54e26349852b7bdd7c5f120aeefbcc440b8a20faaed4a3 \ + --hash=sha256:1afb975bd5d68d5ce9f6b6d44fdf2f7e34b895a35e95708a7a91b20a3b51d187 \ + --hash=sha256:1b4cbc7c3491ccb4aa17fcd8165649d01cf39f76de1696da8631b5f71b85401d \ + --hash=sha256:1bc0baf5ef96b6ede57d47f4b8fe4d9d84019c3bfcbeb20a41edc6a6ee341f1f \ + --hash=sha256:1c50fe28bbc2ced33386f298650d91218076c05420e6cbd790b913adc41659e7 \ + --hash=sha256:1db38f4c5496827c1a501846d64d14c3b80c7e6714e406cd7dc36a9899fa1011 \ + --hash=sha256:211d5a3eb6af8f513b8d4ca19a8c1b7accab1b5f0d3175f9826b03c1a920dc1f \ + --hash=sha256:23851fb4e1b85ed3f6c2a27b777cdfe2e19fb5b38429a8faf38c7542b7665869 \ + --hash=sha256:254eb48b9fa5ee9898a3c445825a1f340fe53712a098904b39b0bddba8ea3cb1 \ + --hash=sha256:2625388c6c754520c37abaf3b41eb34d1cc4a373f457898f08606c8e362b891d \ + --hash=sha256:281cb91036248400f4cc957495cccd44c275c2e0c5854f7e45ac5cf7dc193847 \ + --hash=sha256:28a15fdad492a99b6eccfaaed66ef3f74050680545ea61ec8b2f4c538f1f1320 \ + --hash=sha256:28b4f0d66fb834ff90f28209ac7bce77868c45d8c93e26f906709d9b7c2e1af9 \ + --hash=sha256:2a925889534b3748302dae5dead07cc13480de1dac3aea80a941b729b471ef93 \ + --hash=sha256:2b7b3bbfb4fe8ef40600792d762fbaa9057559f9d3fad209525b7a22b99e91fd \ + --hash=sha256:2c9ad19a6cfcd5ea5c0d41161d22f9df1dcc277e9bef2751391334546a314c00 \ + --hash=sha256:2cc961b171b3f3440f410489ab3573e86aea8736134ebbb40ea1338b7f0831bc \ + --hash=sha256:2ce45c6627b22c47e390bc91a41c3d13032192e699fa0bea96e9671b373d69b0 \ + --hash=sha256:2e06a3a98f916dd41d27f3105e02e7a40181c98c94b9158733d03a6f80506c09 \ + --hash=sha256:304d5463e65a35d7bb0850550e0780395395f6fcf452f04db7d5ca7cecc425ac \ + --hash=sha256:304d8e4d493af723536393eee0c689eb7813f4a474c8b479dee63f1fdd98f621 \ + --hash=sha256:30fcd120b732aa79317f08dee04d7de0847822e4cf7ee0e9f445bb958832252c \ + --hash=sha256:31f3930700408d211f13378ccbe1c40845d8da54bd0681fac3a9b5aae81c7aa8 \ + --hash=sha256:34276fd796040bf0993ab33a369aa572e6979c7aab225a88893667ad8eac8f7a \ + --hash=sha256:355ad8011081dec5412240c087a9a0c9d4d5039f3ed11a3f13e18c2b29b56c51 \ + --hash=sha256:38a873987f3be698494da8b2e3085e29da02da7b633dce73e79c699a113d7bf0 \ + --hash=sha256:39de2a259fc954455c57274dc94c79d5842774e1247a016aff30bc0efed0f4ef \ + --hash=sha256:3d14b50de6bf4d0edf857a9386836846f982b8f524e188e2e68b96d702bcf4aa \ + --hash=sha256:3d21b8b13c7592db2ac5e544a6d83187b995257472b0c9e8351b6d507ae37ed6 \ + --hash=sha256:3d31298449090ab8d47b7b1b2a555ff73cac7ed438a08b7ac160980c7ebed649 \ + --hash=sha256:3ddacd27458c45bdacd6bd6db644bfb730efbf9e830310186e3045c9c5be8fb2 \ + --hash=sha256:3df041de8887954562c9b261cba85ca0e9ded74048daf125f45edcfaa4832229 \ + --hash=sha256:40ab6bffa02ae10a0581e6c198be7d2d8ca5c2a0c64e4ed3465d766df457573e \ + --hash=sha256:4275811936e2f06feff5e598fb42a1b7ae852da8e39605211892b56b81a34efd \ + --hash=sha256:443eae2bf318abeaf6f15d785138f71fd6de770e99a92158b8b814265e079115 \ + --hash=sha256:447441e76ec720b15e64418d32e092297340387053047c7c694f579efb0ee1d9 \ + --hash=sha256:4495c5002a7b28557e7e222e77e0b661183e432b7d6d2e788101e3f240e05b8c \ + --hash=sha256:44bd4fbb29dfbeba60e7d2bd000c59e4b21ddb3cc53912b14048d37092706d7c \ + --hash=sha256:4685902cf26edf013ed7a3da0f426ebba7a00ebb9541386d835afbf002c11cab \ + --hash=sha256:498dc3188ca05a68231ac3fdbfc7f57eb67e1343c30e0fea17f8218c1599b253 \ + --hash=sha256:4c2b5031f63e331e3839b40aed2dd6f191e9c07edbde303e7876846ea1946995 \ + --hash=sha256:4d48f2d08b9de5864e2c8744d4461b862fb149a18274abc8b698c45975573438 \ + --hash=sha256:4f87960d57feabfb618e4e0af6e7371645fa26a277860739d6e5d6e0012c92f0 \ + --hash=sha256:50e3adfb96fc189eb27b1cf62d3b598b89b4bb0420d93a3d3e42e137409011be \ + --hash=sha256:51cf45226a9b588d0d2b4880c62d686934b63ab0bd79ca23ab0e9762eb27441b \ + --hash=sha256:52aa6992700996af31f375de0c6bacd402b0097fe40b53c426b9f51a90ebabc7 \ + --hash=sha256:55ea99acb17b9325618de155a0cd6a2e8f5d10be008113e1d433bbb58db543b2 \ + --hash=sha256:56bc200a365efb37383b7852e4cc5898d3b2da5987289b543956cf8cad71018a \ + --hash=sha256:588461c2e8384d309bd63e5826019b6977bc66d629b99ac8737bb795d7b2cb5a \ + --hash=sha256:58ca3755ee7ff7f59b57789ec9833c9de9ea275405cdd240eda1f193112e398a \ + --hash=sha256:58f361dcbab699cf8f42db3f47c8e7fd1036f138c23a5d08de9fde5f425a730c \ + --hash=sha256:598a11a2c7ebaa5334bf698bf29568c9c390abac6a154d8170fedecd1cea38c5 \ + --hash=sha256:59f63901b0031c3136cf64704dcb21de0bbae62ce2c9529bc39d27665463de37 \ + --hash=sha256:5cde776b7cc66e4f6c99612cea4aa7269aa65863f7a15841b2c264f103822f4e \ + --hash=sha256:5e2b6b57e9733d39f0c9fd3185efa6b8e29652c4cd8fe94180272cf6ed9a78c4 \ + --hash=sha256:5fb29fb8cd1a46c27a1bf9613ad5ec2599310d46b4025d9556404a6b6a292800 \ + --hash=sha256:6045373d5a89a5ec71afde535db987ca28e76dfa276c2d4c818265b375d4b055 \ + --hash=sha256:619799369eeef6366ed3e8755a5670f4f2f0fb6b30a0fd7264dc0fdc2357058e \ + --hash=sha256:62588a277bfb59def052abd940703fa35107152bf479781a878617d60faf8fb5 \ + --hash=sha256:62603db9a7caa0802eaa28c1c46fecd7b3a263a774069c24c3c28c302448721c \ + --hash=sha256:65cd72beeeca9d3aaea1201e5923859f308f952f9c71de93f06063c79f0f7a3b \ + --hash=sha256:68eb192d85ab8e5f6ec69c2bc6ac0179fbf04a5ac1569d12fbef74883fe102d0 \ + --hash=sha256:6bd128f206a7752ae1f2ab6c61bf8a24ba28913a10df8b14c2637b973ff97a80 \ + --hash=sha256:6be488a102b8cf28d0391d8c4ba7748938ae28b78ad901f8585520fca33ead1a \ + --hash=sha256:7218e8f32b0956cfcd048fd42d9d5779809745ca1d86113ca56f66e7ae1549c4 \ + --hash=sha256:7441d755b7ab94f8d4eb3e43ec05482d760842fd263d003a99102d742cd835e2 \ + --hash=sha256:749e97e1b32313717a565abbe321bc2190bc8b35f1a67e4cdbc7c56c8d8ffe58 \ + --hash=sha256:75a3ceed0724d625d64b86ca20aba182e4df462e04c2414fc941c0f523f06aac \ + --hash=sha256:780fbe7cab297b81dad9fb8dc5eb003c0468ffb0d9e5f65068c53a34661a96bc \ + --hash=sha256:78456a747de8dc58360ffa581f30a002baf5aa28cb262536545e91f113ed7639 \ + --hash=sha256:7967d08cf06dee78443b874f98c98036f624f3a4e73e11f9f64f5be4d25393cf \ + --hash=sha256:7a881931aa470808df94a8c380eed2bbbc76cd9dc622310f99665658c821eb6d \ + --hash=sha256:7dcd882da75ef9adf94903b1e3b9419e8aa8fb4c7396822b834b9ef7fb96954f \ + --hash=sha256:7e841fb9010836c992c9f12fcbd43a831de93a5f726fc1ccd8ca1d0268c5014c \ + --hash=sha256:7fdde2c9fd9e3eca40631e024664cf2584272cc8f96308cbe5fdfc930f51d8bc \ + --hash=sha256:8024d00c3faf3fc0c16e07a69f4405e8eac7cc0ab15f65fe6cf43827c4cf72b4 \ + --hash=sha256:80d02b6f04e92601a081dd97b23d3128033098bff5d35d392ddcc0476ea11253 \ + --hash=sha256:838dcc90063569a0448120554591a1d6c4a4ffe11babf048908793154ab86ade \ + --hash=sha256:849df64e889b2e17230d58410a03dba311a65b163508fd33679b2b737d4b7858 \ + --hash=sha256:87475fabc8d9996fd9c27debb395e642e8c838d78a00b6e932227a0e06b81e26 \ + --hash=sha256:87e50a3e7cb90af586b6c5faf23e302a970415ac73bd7bd90a515a04b427ef96 \ + --hash=sha256:89b53f3cda69831909888e0494f4fa0bcd3537e3e138dabeb620bd6ad946bae8 \ + --hash=sha256:8a893cc101149f80a653f82062ebc95b34525a2614382e1da5458fe7c6997249 \ + --hash=sha256:8b2bfab86aa71ae13aa41a6a26aab338e0db2b8bc75434b05aea89e011ff35a4 \ + --hash=sha256:8d86d6fc60743dc916eb79e2eb1ec4818e21e427731543af40a3021851174a13 \ + --hash=sha256:915563965d418f986e7e145accc592eae9e1a1be3566ff98a05d7a9ec42a76e1 \ + --hash=sha256:92888bb3187c5ba50500b00b3b310c9f2c651709d28036077680cb5255450a03 \ + --hash=sha256:93223adc95033dd47133a46ccfc316a0139176fd79085762e27202ec56018f03 \ + --hash=sha256:9373ad13ef0d2c0fb761e04e55bfdee5a08b52cef2c882c8fbe9935b1517152e \ + --hash=sha256:9409a8bf35cf78353942504b24a57de3d75b708997a1e4bd8db71ac8633ce364 \ + --hash=sha256:9b7f416ff0978e2f2249330527f0ad6fa02f4932e6199692d3b52da2048c19e4 \ + --hash=sha256:9bde855991b7e362c146535e3136a50bfaffc0487d38b33ca7e5edefc6e23849 \ + --hash=sha256:9cae88599c7219005d879f98e5ed53341e9a122af585e1091200358a3003d2a0 \ + --hash=sha256:9cf9b1a857e25c4baceeb3624e92a56df3668f398c4acba74e174d81fb4d1d3a \ + --hash=sha256:9f56f72050826f63dcee7a7f55b0a77168cb3bfc553fd405e7f8f9ece75a4036 \ + --hash=sha256:a090bb2c68df85450502e3e20d665e3a5af9c65a84d6508ed477badd49166fd3 \ + --hash=sha256:a192e2c40070d92c3ccf777e3a5c4ff515573cd2bb7ed0c537fdadbbec5bbf21 \ + --hash=sha256:a19a731138fc27d5682277d3b9df22855cea1239bce7fcec5f78f42ef2d1f3c3 \ + --hash=sha256:a66c3bc5ab1f0ff2164fc9965ddd611ff0802173f4b9d24554c563f6ab7e1d6e \ + --hash=sha256:a815775b6c38d4e0ff7bcffbeba67feded90202bb6a226b8dd35f1c855217413 \ + --hash=sha256:a89012d6d5476ee112d20d998570ed58df2260a852afb1758809cd6900411d21 \ + --hash=sha256:ae4f5fea5b8b8ccff88238cc8569303e5ee95efae67fa62922a311397a71f346 \ + --hash=sha256:b6856554c4f44d79fc2307d5768854310a8f0096e501c75637542c82292b0429 \ + --hash=sha256:b6b751274acb69d77b3323d6b7dbaa3c7fdfc1eb829b7eb61d262f32e1af9685 \ + --hash=sha256:b736353c0a625bbd5fcec108576e2385db3496f4f771f785ff32e108d3c3bc45 \ + --hash=sha256:b7fd005a73d9e657273b7a10dc71a9e03c8fb9ee6999798d6918ce095b81ac7f \ + --hash=sha256:b91363207bd9dc966a691e959bb47f64b30f7ac4b072be9968b366982f7db77c \ + --hash=sha256:ba0b1d2620edf869789c3879223f52bf2afc5d31b3cb47cc57b3a12c05e2aa9d \ + --hash=sha256:bbbfc8e28816f19d7c0f1816664980c0a9875d01b27cdf8eedddb639d9e108ad \ + --hash=sha256:bd16aabe4a02a297c23417aa17ac6299dbd8c49f673bcd645b4929b11f5a4400 \ + --hash=sha256:c0afc6800ba57ccc350374c5bd6150419915d95ce93cdbab2d783d75eaf30ecb \ + --hash=sha256:c6708715abcf3c73b99508253e961a9967f02fe536532834149574eda6de0d1c \ + --hash=sha256:c7c9ab723cde841fefb34efbad91e87f00a674b1fe1cd0784fde742bf2c154dc \ + --hash=sha256:c8f3d67aeaf55f017982b73683f0e7342ba2f6635a78f69ce89ebb26aa411e5c \ + --hash=sha256:c9790464842f85f437dbbb54417eda1e0e6bfc52dd8d22d6fd1c994b73b2dc74 \ + --hash=sha256:ca403d7e4798f525fdfc78e258820419cbbd0f0ecbab9de7840e3c017cf6b8cf \ + --hash=sha256:d008d90a7f2471519aef0c90dfbe73b3e6e4d5e66ac48e19154c17e89e98b604 \ + --hash=sha256:d19fbd981a488e22cd04883659ca6b08f50b5974f9fd7c95655ef6a043e5893f \ + --hash=sha256:d1befeed746d247c81127bb14de9dc3d30edb6e5976d34f83f86ed262b1d9105 \ + --hash=sha256:d2374b62878abb00cd8309b32af6c0b715cd02dec0ca74ef12e5069bdc64144a \ + --hash=sha256:d376bbd28b3a8999db1a103b3b388aee6f1ddeb3e51bc2172993efdcd86e064d \ + --hash=sha256:d4a7319f304a774bed22115bc891618e45f85065ab44ea6acd07d274e750519a \ + --hash=sha256:d6734d2ef8a50fbf8445c139477da401f50d62a0606bf00e20ec6d87773fefb1 \ + --hash=sha256:d760fe2a4d7c3b226cb9026d6a842868d52a7901bd98420e1baf14e80da85cf5 \ + --hash=sha256:d913de495d90407cd859d263bee2e5d1a4ed3eb6573c04e70d9ec619a7cbed7f \ + --hash=sha256:db19d07e2e0129e974a0e65d0064fc222a446cd5122c2fd4184d2af9fc734a9e \ + --hash=sha256:dca9ab98072a5a54ebacebdc45f53e645336b320c667410b061be1ca588ae709 \ + --hash=sha256:ddc7dacc8ece3a182e7f15cb862d1fd616b46d076cb1ae9dd232b2c38b655874 \ + --hash=sha256:ddf19c062bea7a0cc80f519243d2c01dd091be0cf952a0750d4ad576709559f5 \ + --hash=sha256:def79fa35ef0cef8d2accec024f4fdc7ead3012ff02f5215c783f39f03ef8cfc \ + --hash=sha256:df29a0a7107f7011e77f4eebdddec4c7331e24d787a0b21a46d63bdf7445da95 \ + --hash=sha256:e09a3942ecbdee5cce73ea9d42da82b81b72ac1bf031ce069b93b5adf4eac8cd \ + --hash=sha256:e242bb1c5e76e97dfa9e7f209a71e93a01d7f19ffdd5cfbb2e2d55b4f08f8ab0 \ + --hash=sha256:e243bd13217235fc7290c621941c3f5cc8b66e4872495be821d7436ba2fb838d \ + --hash=sha256:e2af3aad578aa6bd1384bcf4750fc285e5a9de53f40b7d41e5a0bf748edeb2b3 \ + --hash=sha256:e4e81e09c1578b8df602e3db08b0b3ea0a6947ad612f52bf8dc5ea8d47691f0c \ + --hash=sha256:e54da4baf05720032d527874d40b65fa4d7e5c6c6a43d0c3adbeffcaf275a2b3 \ + --hash=sha256:e80e6c2f55656b4824d72065abb4ddd6a525c74bd78a0aab5d9fc2cf4fb5af50 \ + --hash=sha256:ed2a239c0ea213acc1908150a3037257083c7c083128f1a4cec2ec4b97dca491 \ + --hash=sha256:ed905975ab14056a2e5eb1c376cb2e1ebc5396baf84163939c518556fccde9f5 \ + --hash=sha256:ee21e28f0430bd6dc9086c6e525d5e818a44a5ad19720c8a0ef766792f3eb5e5 \ + --hash=sha256:ee43c17b173d46a3212baa6ead3ae258eeabdae48c263a01ccf0218c366dd655 \ + --hash=sha256:ef4fcbf3327382cd4c9f540babd61248208af7b93eec4de397b4d5f58a09e288 \ + --hash=sha256:eff0ac9dbe711a4aee69bf04a83896aa9b85f19641264053a9f6d48573abb7dd \ + --hash=sha256:f0aa869112ef88429ae17820d99c3dd9504c9e9c671d3c246f3d7442cb051084 \ + --hash=sha256:f3c96f633825733f735c5a9cf21d21a257d8e1edf0b1cee0a064b9c424ca0f7d \ + --hash=sha256:f5833ad231be5eb6553de524a70f48d71b2c8563101750531e0b80184e175cd4 \ + --hash=sha256:f5ec61164adcec446f8969a3358ec3f9b26bbda3b9213e5586d219afa8df2915 \ + --hash=sha256:f7d486c83842422badd511868fd8a9a20e9407ace71564b6af47ce7e60a336c1 \ + --hash=sha256:fb9e68df06293761f9fe66ade60a9bc6d0f5e42b8acf2939a9158af86ab0e5bd \ + --hash=sha256:fc14a032f813bf5fe624d991960ea83e9715adc27e4c1830a2361eb1d02ac341 \ + --hash=sha256:fcff63213e8e6e47770541a4607175404f47cbb3ebea7b6058cc82d524a0e424 \ + --hash=sha256:fd1fbe0f116b6e55da77aca2c6ddcddcfac2186cbf78bdebf40fc156efca389d \ + --hash=sha256:fe9753dfee015c570d73df76f899f18444d41388bffcde097deba51c4fadbb9f + # via requests +click==8.5.0 ; sys_platform != 'emscripten' \ + --hash=sha256:255bc9599cf7748b4b1a446ccc735421bd08a2ae529a8b88597d3de5664ee360 \ + --hash=sha256:ba0d2089de75ea0310e2dde03160e6ca10009947fb95a182f9b54021bb272e34 + # via uvicorn +cryptography==50.0.2 \ + --hash=sha256:0ddc924c04591c2811ca024d62ecad4f7f6f08af8939c211438f48a16bd23602 \ + --hash=sha256:0ec5f09541743261e66e291b4a0cbf0fb2997aeaab6d9e9c740b9dba1b58d1c2 \ + --hash=sha256:0ecbc5652bdb6fc9eaf89a7d196e20941adfe812f43bc4ca05d9150496821047 \ + --hash=sha256:1981f1db4630889b9ef7803fadef12b056f428cb6b85c27ba57b774793b6093c \ + --hash=sha256:1ba34f04897fcdaa73f74145c25f3ec146fbd56593853e88adc2e811303c5f42 \ + --hash=sha256:241449bf940a5d27309bd317e6f9a2af6932113818bb2b8f5c59ddc7ef16da18 \ + --hash=sha256:25784ce8b9621c90c643efb9e1e2162ab3b0224cae446ad5e70e7fcb1ce18b51 \ + --hash=sha256:3dc4fd8058cea1644971207d530e1a03a184a805ffc8ebdddf0599d78a331b81 \ + --hash=sha256:4061c0079120205fb760c58acab6443e217307dcf05e3702cf970e0689972856 \ + --hash=sha256:4a20ce1e5cb4284a86692fdcba7cb8754185c6b2e5c56fcef3751cf451d3cdc2 \ + --hash=sha256:4e81d95e5bafc2d6e34e4bed780e53e4d5b9a2f928573428aa4d35fbec1eb0de \ + --hash=sha256:58a0c478eeca76fe5e07993c5a0703def34a6dc6a0cda4f5564639b33112ffe7 \ + --hash=sha256:58ddb5a8e3179d12f19e4ea34d2d32e9d63a4baa142c875c1eb59f41b7243acd \ + --hash=sha256:630ebfea3bf689d075f82316324ff7433dc447fe6bc1bfc76524b74b4a9567d2 \ + --hash=sha256:6f8700550aa1474a91e5dc07049c46f98b423b5b1ddd0483e0b51362eeeaf5be \ + --hash=sha256:78198641e5be9521beea5aa782bb551a58068d10e6eb04c9c680c1b69f2e7d45 \ + --hash=sha256:79def8d059362e7831389ed3be0ecdf58a89386e1271e35dd9f5af84e81bffd0 \ + --hash=sha256:7a8701d6b584d76e909e3d305b7d126b41439876a5aaf76cddc67fc230eafa2e \ + --hash=sha256:7afa5a6602a9f29af1f3a2965f831bae7c9d5d597b7cbb716d41ab3b7d89879c \ + --hash=sha256:7b46165bb56eb4704e2eaaf86f3c940d19154535d9b0ca7d6d590b04060e00d5 \ + --hash=sha256:7b75de3c8b3be1cdb1052747c929440c3eea46c1bc2cb8a6e3a48388e9b7b452 \ + --hash=sha256:7c6d0330c472d96f6a6afe24d80dfdf15176c33096f0a4397ae4c60f3dd3be48 \ + --hash=sha256:828d49b0ff5a0e3975865571c5d91dbbdd0d38d8289b249a163e9425413a5e05 \ + --hash=sha256:84f964e537f916e2cc85199e5a88742e964939b575ac8598b3f9d6cc416cdaf1 \ + --hash=sha256:85d0d9a31b9098e98534226d5686b47264b95e62ce459dc2e62fdfc809f9fe93 \ + --hash=sha256:87e9ce85beb6b328ba370cc6e6aea483c92617b4c95b1d33a49297eb662bfb04 \ + --hash=sha256:8c71ba2cd31fc93748c38e1b613200ff1c2665cbfd5341fe3a61cfde35a1430e \ + --hash=sha256:92e665960f25fcdc73725b9cec7a3824f279ba97a98653afe9ffac2e43668f67 \ + --hash=sha256:94e5e9f108ee10471288214d3d233fbfbb492840a8457eb85178d643ddeb32c7 \ + --hash=sha256:9c8402a82ea0dc4ceeab793db05f0fafa8ca139ca34fcde5df0f596103c74107 \ + --hash=sha256:9dab55f57c74c3cad24c323bacbbd04be4705ba6eb0d92e920b1fc4837ed5079 \ + --hash=sha256:a582ab2ae1d34f67112cadc86702774c9ea4374df6bca6afe672817203c99134 \ + --hash=sha256:a6557e5f38e065ca9fbdaf7cfc7435ecb1d113aa81a022d1b51921ee7432e227 \ + --hash=sha256:a9f7355e6fab51f6c369b86fb7571cffa05edee2c2121e0380a37fb9ac1cd5c1 \ + --hash=sha256:ab50ee449bf968271e820086f10a33d101dd060370abc10bcd22279be2656539 \ + --hash=sha256:ac9ed99d81760c62fe89d5f0815cdfa1ba9a35141cf30f1c2d044f04b4803d2e \ + --hash=sha256:b13478603dcd0a2479ff8e87e2c19a7d525734686fe3c49542472293a204212d \ + --hash=sha256:c423ab384a46c4dff7217b2ea5ba2e11cffdeab6441acd04cf65a369caf0366c \ + --hash=sha256:c5e67125c7dca78d199ec4e116aa93dbb83494808ecbb8211a2cb09b1bf41dbd \ + --hash=sha256:c71be1cbfa5cd9a41ee452acf1eccd82b2c05950358b106ec8ceb83411d1a020 \ + --hash=sha256:cbc8738fd8526d80f35cb3a40d41f41a2e7030bb3b18b09a6778ef63d291c2fd \ + --hash=sha256:ce47f66801c20ec6c6632453bb5960fe38939e9306970b48b3a5a26de7745d94 \ + --hash=sha256:d370b8d1dfcdf7130178137f6fbee6140774a1acc6cacefc4b42643ec11d0a3a \ + --hash=sha256:d38cdff612d06fa6a32840d5e1b1f7a27cee4a349aa9085d94a67789d6bfd408 \ + --hash=sha256:d8947001be83df1394050758ce0e745dd74fb134eef0a4b5124208dfc3a68c37 \ + --hash=sha256:deb9fde5c60e437ee4821bc9bc39ff31b42135c27e1dc61ef0a629389c1de62e \ + --hash=sha256:dfe9763530994147d9af1def057a5b9658b00e8f8fe8743d144d1e0911c2e454 \ + --hash=sha256:e105ab60406787da31fccc883fc0f733af1efd78f0136a4599692c4083a73d0c \ + --hash=sha256:e275096ea1e60cc595cda2836fd4a6c725d1125108b868be17f53684d164e2cc \ + --hash=sha256:edc3342adf8f697fc5f59c887a304356f147b397809440ed64e2fa6af2f50f37 \ + --hash=sha256:ee247f5c245c9a2fe7c8e2214e295918838e44e00a45a6718451e4004219e767 \ + --hash=sha256:eef4c2f3423810b3070ab391f85436d2f8bbfcb286ac15cbc73190b3563b1f1a \ + --hash=sha256:f21e8a22c8605750c7af886bab299a363721264061b4ac0a30efb73cfd58efc5 \ + --hash=sha256:f265528741e048bce55c3463ed721fb0aa45a5888d8add8cfeccb3035451bbdc \ + --hash=sha256:f2f9bd7f90c64fe89253f0a2c05e3c4856072660429ce8831b4235bf29403a67 \ + --hash=sha256:f785f6161f202ab04d8ca194158968798e480ca058943907972da5f12e2881e8 \ + --hash=sha256:f9f6143a8c75945eb960d9eb98905a441394abfa24afaae239d514ffb2586480 \ + --hash=sha256:fa8f5efb344d6908a1ce62f4a24e2e5780f825d6f53f5f50ec5ffacac72936cb \ + --hash=sha256:fdd28f912fccfec1846a94e2e1e8f9b0012f557f0c46fe4f3eb0d7a87afcf90b + # via pyjwt +h11==0.16.0 \ + --hash=sha256:4e35b956cf45792e4caa5885e69fba00bdbc6ffafbfa020300e549b208ee5ff1 \ + --hash=sha256:63cf8bbe7522de3bf65932fda1d9c2772064ffb3dae62d55932da54b31cb6c86 + # via + # httpcore + # httpcore2 + # uvicorn +html5lib==1.1 \ + --hash=sha256:0d78f8fde1c230e99fe37986a60526d7049ed4bf8a9fadbad5f00e22e58e041d \ + --hash=sha256:b2e5b40261e20f354d198eae92afc10d750afb487ed5e50f9c4eaf07c184146f + # via readabilipy +httpcore==1.0.9 \ + --hash=sha256:2d400746a40668fc9dec9810239072b40b4484b640a8c38fd654a024c7a1bf55 \ + --hash=sha256:6e34463af53fd2ab5d807f399a9b45ea31c3dfa2276f15a2c3f00afff6e176e8 + # via httpx +httpcore2==2.16.0 ; sys_platform != 'emscripten' \ + --hash=sha256:5c4358319f2602d984ad93182c9fee5160f22e9da7babdda870a5e7c4e2dc34f \ + --hash=sha256:c72cd0413563b17e1cd8354677dff887466f8ec2551679759e93126534428643 + # via httpx2 +httpx==0.28.1 \ + --hash=sha256:75e98c5f16b0f35b567856f597f06ff2270a374470a5c2392242528e3e3e42fc \ + --hash=sha256:d909fcccc110f8c7faf814ca82a9a4d816bc5a6dbfea25d6591d6985b8ba59ad + # via mcp-server-fetch +httpx2==2.16.0 \ + --hash=sha256:0d54c98128e8f2ff7fbbde0fca8c359e5f032edeaaaac443cdb7f31f685bcd7f \ + --hash=sha256:fd2c5d7909e8d86fe92d53020c310ca0e4e431b838c207c5754b9bbf0308d49a + # via mcp +httpx2-jsfetch==1.0 ; sys_platform == 'emscripten' \ + --hash=sha256:70a0e3eabfef7cce5ad9c629f7d01ca05e418f586646f4ddf14782e4c1454c60 \ + --hash=sha256:cb916b707601e69a07721aabc8f3f6659be3a6893bc1ff5c6f9e02241df2da32 + # via httpx2 +idna==3.20 \ + --hash=sha256:a7db850025b95ded1eae8a46181a1a6c56c92c96f0e2b005d9ff8dc0210cab44 \ + --hash=sha256:ab7ae7122974553370f0bdb919e1a960b2cd1bc1ef0276416d896db81c14582c + # via + # anyio + # httpx + # httpx2 + # requests +jsonschema==4.26.0 \ + --hash=sha256:0c26707e2efad8aa1bfc5b7ce170f3fccc2e4918ff85989ba9ffa9facb2be326 \ + --hash=sha256:d489f15263b8d200f8387e64b4c3a75f06629559fb73deb8fdfb525f2dab50ce + # via mcp +jsonschema-specifications==2025.9.1 \ + --hash=sha256:98802fee3a11ee76ecaca44429fda8a41bff98b00a0f2838151b113f210cc6fe \ + --hash=sha256:b540987f239e745613c7a9176f3edb72b832a4ac465cf02712288397832b5e8d + # via jsonschema +lxml==6.1.3 \ + --hash=sha256:032a0a97eed428bd143c75a11118238546424ceb2fa311cca5f073aa44658dc4 \ + --hash=sha256:05f5bce9af14fd1506997594bd81cee6d9c6b58ea80a39c058327aa6371ed9e9 \ + --hash=sha256:0794e04ba343852c6d78e996c58ef4b8e579b4ecc72f8df0d4058bf843b4c96e \ + --hash=sha256:0ab2467e405e748d93495fb5568e74044802b8d3ff2b2a1607c3f78c6e982de5 \ + --hash=sha256:0bf5a3e397df2ec4258eb5eea4c1ac6cf013ca1abd04a176903bff20a70021fe \ + --hash=sha256:0c0710ac085a157b593c38fbcacd950f15c4afa8e2057527185875ab302752bc \ + --hash=sha256:0dee106e9aa97fb00541b1ed7827070564d0549c3d3fba8920e6b20fd980f748 \ + --hash=sha256:0f17d83c48ee9dfd96abae3ac3e2108c76d2fc86ce96355e37b8da9f7f4ecc08 \ + --hash=sha256:0feebef8d0521188d0157f758356072e840173aa61ca45b8b3f87959ac283dd5 \ + --hash=sha256:13a620a3fcc20023f9e6ed5c383e00e826f1c2d5db554df2f67240760f9118e8 \ + --hash=sha256:13d22c0d57355366b393936acf6b98a5e0edeadddd3fccbc6a846c50a76b8741 \ + --hash=sha256:160fcf381f76c3aeac28a756bec44f48942a8f7245a87aa28e3a523b4d90cd87 \ + --hash=sha256:16148acd77ed1d8836a56db883af2f5eed720f9723088110b16a0d08582130a6 \ + --hash=sha256:170773d8a3cdc76259065523ddd978c44f9806e28605f08812e8f86783e44ac6 \ + --hash=sha256:18293f8a8d8b6a8e71ef37706b659e3846a4261232158167b1ddf35f6994f633 \ + --hash=sha256:18a4db52b5a7b53a3540b0b0f4123319334621ee8083d496de314d0bf06ff59a \ + --hash=sha256:1a635e837b50a1819bebfedaac5916498ea024120969da8790500148fb0a894d \ + --hash=sha256:1aeca87830c4fe649dcf93fe2b059525b71c72587f21be4ae4af7103082a79fa \ + --hash=sha256:1b7c37339d7e75cab9a123a04248e243cefefb302ad6db566ea0c77cbcde421e \ + --hash=sha256:1beb0f9909b26cee938df9ba56b15252a84429b1fc30ce6fca161390b9789a70 \ + --hash=sha256:20384c2bbcbf87180c8c61eb60869699c1ec0cd09b62cfd13804022d860b0867 \ + --hash=sha256:20428910dae17a1a93152a3ff2c0441d2f4932992c0797d65651dd0561f1792f \ + --hash=sha256:207dfc3d47cf0e575e643bbc140dacc8863b39abaa1e5307cd64c7f2365b8a12 \ + --hash=sha256:209c3ccbfe35a04ac6d24f0611f9d1cbf8025d49991b14acd935236234d6c156 \ + --hash=sha256:2123e5aa075ac20d23c7af489255efd129cbfe190dbe88fd42598cc9df3199b6 \ + --hash=sha256:21402998e4b78e7cce237d2788841aaa21ac9a4d1574d04dc2d12ee41ae807b5 \ + --hash=sha256:2221e88679d1351e9a40aaee54bc65679b9795bbd0160bc3d5e36b163344eb75 \ + --hash=sha256:22eec57e26c418cde02c051ce9914a365e52a7f135a565c6f0480242aeebab48 \ + --hash=sha256:23c366231259cd75ad06495174701afb3fcb36a92917fa47de2d1f1bd9d95739 \ + --hash=sha256:25f4118c438f96bb466e83108506d03d5c31b1bd2387e83e5b070bda6ded9c37 \ + --hash=sha256:28a23fefdb345b2d4d0ff2860571b5ff9a89a28b6a120f720e8fb0324d346626 \ + --hash=sha256:290f66b97ede0e552e1cb44a0fd8a74f9753ee635b50830a0b122fb72788d015 \ + --hash=sha256:2b9b1325ca1c2a9a2dbb6eb913ae563313f2082ae60b03210f7e83ee80712274 \ + --hash=sha256:2bec13085dc8ef48a3fe62f7dfcacfeda2c785cdf19cc8eeda2bb9ed081da165 \ + --hash=sha256:2cae5d5c90a62d9139c512a0cb1aad1d182b022b5740daea2617eb5bf7fc658e \ + --hash=sha256:2e01125896585139453cab8cb235893644d8815d7509520da95ae3ee8d1c1f79 \ + --hash=sha256:2e62c569ec7531b679b184cbfe335c501c1d13c4b363560013019962eb630e6d \ + --hash=sha256:2f5b2a2b9811b853b39bfa41367c6d78747b8e3e80e07fc5a24aae295c1a4d7d \ + --hash=sha256:302f72413251c03f671e063c9414bed5dc8c927069e5abb69245521e51a4e81b \ + --hash=sha256:32a409be3190b088f960ac92bfedfbef2f86c49ff940765e1548177592d20026 \ + --hash=sha256:33cadd956b667997e4de1635fce9541f2e8ede2038fcde8cf55aa14d571d1bad \ + --hash=sha256:379f8a75cf6eb7eef0af074b55f49ab73b868388a98de14646abcdfa4564bb11 \ + --hash=sha256:3847e71a78cbbc1aff955dbbbaf2fff12153f611d3162c5beaa3395636cbc2f9 \ + --hash=sha256:38fc4e4e4e084e0bd491949482527d406788045c546d4f8789e93fc527b91385 \ + --hash=sha256:3a27ac6c780c8b8a1cd231b58407634cafc1c4cc28cd6c7141362df0f36351e7 \ + --hash=sha256:3a48093cdb058a93af842ede9703520e810b05dcd0fc6d7190a06376c3bfb6bd \ + --hash=sha256:3e42265103fb385d8642a78672edf376c6f7e1d3598a7a4f9cb1278f2f6b5f6f \ + --hash=sha256:3e9a00d1c2c30936f7add097c41afc5da6556c580909104aafd382cac92a855c \ + --hash=sha256:40983eabefd13da003e68170928c7acc011f0d095eefce5871a3c71c9385fb9a \ + --hash=sha256:40bcbd9f94166ffe925811e730607385cec959f42fb1bb7dad83748680465221 \ + --hash=sha256:41096ec0740a58dad03d3ae0c7486d306d20becefb13ceb1649835ab3eb64167 \ + --hash=sha256:415e3a115c0d510e329020012834d1c0aa1c581ee53a218603e38abbc1dea70a \ + --hash=sha256:41e2d428110b408e963b6fb18f9bbf1f5c027b56bd4b498d54556476c0aeb1c3 \ + --hash=sha256:424aa5657141d306ba9ad1baab4b2c0a0719040075ee6c66aee9bb2dea2b5054 \ + --hash=sha256:42632b4024ab24a6b488f559ac851312509888b6b80ae2aa11cf29a646a0d245 \ + --hash=sha256:45222d94ddd511536f3b2f7d9deae3b2339b4ce0f075f1ca25703b07cad9dd21 \ + --hash=sha256:4736e6c87e603146d8949d8501da621ad20c31015060d3fcf95ace2859f3e3e6 \ + --hash=sha256:48542c9acba9ff9450bd18d871d2c2c8787fdb283572b623d206f1b927cd7d9e \ + --hash=sha256:49fbc2682a9306135b7ec49e93f97f9c26689b9b7f96ed2742d8d6497e994d13 \ + --hash=sha256:4a579dfb9c835f8ab47f4b8ed33440cbc75b806b73297208e6ec2a33e903740b \ + --hash=sha256:4b061064b4a2fe8598a466d723d43dbcd5a610a5d5cfe02fb6226f5c17349f75 \ + --hash=sha256:4e11e885e0704be185867fcf71b904d8f65d7d6877bc121f69870b0d0479ba7b \ + --hash=sha256:4f4db7c7e954d289d71878938348b3d91b904a3e8210a11939359fb758a58e7d \ + --hash=sha256:527195c188d7d0af748cd48d220ab8cdc5cb99be3d49ac4d9be7324d8abf9bc0 \ + --hash=sha256:53258656846f5c48996b882fb4b135885e088a3ad3d96b4bc0530f95124d1f69 \ + --hash=sha256:545ccc14fb05485f48b4439ec35beb16d5b5280eb6c81c658bd4707a2a119414 \ + --hash=sha256:5609efdb0d3c95499c00046bc53648b3482ec2175b5503d6e611b3f0555dc71d \ + --hash=sha256:5929d9df5e7e3379183be0e21f7d559618a5b61cb63280df6164019242e337ed \ + --hash=sha256:5a143e6207579de8baeded4eaac9134413200359f1969d636f0bfb98ee8c3c8f \ + --hash=sha256:5a721a98c649855963811b59b55755b30566e7f7fc40bdc9803d66dee9f811cf \ + --hash=sha256:5cffe18571ccc51d742cd08cbb3f8b756de9311d18c7ea98f5d92f37b8fb60c2 \ + --hash=sha256:5d12669a2c419b0e8dc423d23dea24bb82f6f9cb829f32e04674b0ba40322a7c \ + --hash=sha256:5d582042c69857c364e8153de6e18e0da9b7b515a6a8113caf69a6ec8e0520f2 \ + --hash=sha256:61116cec57ed69aebc70f37a545eec095339bb829efbdabcfb97c51e9536e158 \ + --hash=sha256:611a51e61c92f62345a50b0035df6fc0d678f9299f33728826d831598862f59d \ + --hash=sha256:623c8799c17128753c65699f1c3aa32402657393a9ad6db09ed8b98ddf76611d \ + --hash=sha256:6374e9e382e5a98c9c5e66d41b357b470da1c54bce30f17f9dc4bcc58436cc1c \ + --hash=sha256:66299564c046bc7e0cc5de5106601eae907e9fa5904cd68a323380a8502f7861 \ + --hash=sha256:69cafd61aea04ebb3502c93c2aaa568b12931ca0802231e0b5de76bf8b6e74bd \ + --hash=sha256:6a406d0b3cb207b0fa460ed4dc93e866f44f105da0169361cb18ff998a44c7f0 \ + --hash=sha256:6ba4fe5bfbef6811a8e49b3719cde373ad399006c0c1ac184b7297116ecbba5d \ + --hash=sha256:6cd11e7550d89e551a87dcec30f04b1fca32e86b68708aa01a4daa455d8605e5 \ + --hash=sha256:6e1eb8a4cbffd5553680ad96be6680e364710656eced73d1dc90ec489df599a3 \ + --hash=sha256:6ea2f13dce778ca072ccee598bca46a092ce192e8fd907b6c1f0e52c800529a0 \ + --hash=sha256:71532ebf30be0048a45559b4fab15333fbaaf9042f658e878d918ecd0cf09805 \ + --hash=sha256:73fc05988ed20809450474ba760a87c8ad4e455fc09783c02195e56ec634b41a \ + --hash=sha256:75cc6569e86be5785b6188ef1642670c6adbc984e81ec35e224842ecd9eefcc8 \ + --hash=sha256:773062aec2f2e56b2b22d37054123f0de8a22a4688a0c3376c3fe42685f975cf \ + --hash=sha256:7ae4949f212a53b007dbc355884fda122545c5764a54256c9217e419a62a6559 \ + --hash=sha256:7b2bb7d703bed7ac893bf7f40d97b5d9279d35d2ce460624ca28929eab0d5a3d \ + --hash=sha256:7d0f5976aa2701996f759b30172925829867547bb073af0ae67d1307a0f0262c \ + --hash=sha256:7d5a748d12dd9b535e0a130f60dae9ddf0adafbabe61e7864f55c7436c84547a \ + --hash=sha256:7dd624c1eaa629ad44b59a1a0145fdf2d67895592dce94c9358b938b3d075e65 \ + --hash=sha256:7f75b9b9fec2a9c6b18095c81865580e795b1441c429e42d22fcc82a77f40039 \ + --hash=sha256:83e3a51e7933db700a0da0db31849db3a24022d9970da9bb73001e1d0326fd92 \ + --hash=sha256:8499d464de86fab0f102313cce32a9bed9ab1f06ec813cf025cb790964fbb765 \ + --hash=sha256:869dfcd4d381cb0ea87085cc4f011b9171b494ef21e76ad8665f6d5e2d1dc8a1 \ + --hash=sha256:8753b8d51dbc86fd335ee31fcf7f3658e9f5c016d4edfb23f76ad295f4b8c9d0 \ + --hash=sha256:887c021d9a977cff89cb273047c1352997b772a8908a25c21836861f69b92be1 \ + --hash=sha256:88e719b9437f148f7e1465df845c758dd1598618cbea3a2fd1e61a715542f2b2 \ + --hash=sha256:8a330c0ee5fa318c7b5cbbaad882baeca3f570357e7eb25ab34bf31008150758 \ + --hash=sha256:8db38ff3fb7aee7d6a82ae4da2eef1178656fe1216841fbd24870062a9d60473 \ + --hash=sha256:8e49a646acfab83c68974f4aa1d0a2acca9e88d7d627ae0fc13201b14b76d310 \ + --hash=sha256:909f4e927bb051f7740d6367285fc60cdcfdaf0258c2dba4ff5ba7eadadc250c \ + --hash=sha256:90f709b9accab6b2e4d14f5c8718203877a0486bcb3afd74d8b539ecd1e961d4 \ + --hash=sha256:92d96586376fb79a33474797186bf993250152ee5c32650b67db78d54b92e6f3 \ + --hash=sha256:93476b6514b373fc6ca67d26c442784f7807c86f00635bfe79f935c3eab2af17 \ + --hash=sha256:97acecb11cbc411473f15b8d780df06d7a9f3a2aad9aca78364f56640c8fb70e \ + --hash=sha256:97ce49699d87ebf8aad631b55d65b33219a4f1bfefbbf5bff19dc9af160aeaf9 \ + --hash=sha256:9bde9ae026a55b9a192078dfa6e27dd0ca4a050171ab6272e92f97b757dfdf48 \ + --hash=sha256:9e67324961ac9bbe616cce5100514d2e34d88665aeb07071e8b16eac55d06d94 \ + --hash=sha256:9efe56a68179f3adc4de41861c9358931db03837c48dd5e1c78077b84dd07f3a \ + --hash=sha256:a1932d7ce78a561367512c594fe66eac2b2ec9b9264cfd9b5f950622f4a116e2 \ + --hash=sha256:a1cec0f99b9b914d39176347a93b7610dc09324491aee1cbc57cd291a41a1d55 \ + --hash=sha256:a2e3f70673a1d5b82f38255f777d26cd855bf2092b1436c4867464a7892f9238 \ + --hash=sha256:a43b3bdf11e477dc7770609d3477316f974354dfc8425d596f64f471cc8daf6e \ + --hash=sha256:a5c18810318303ce9afb3f95e2ddb54834f96fa699a8600433fd5a93dcf44c56 \ + --hash=sha256:a7eb78ba28b187e1e9203a55c60fcf70df2d22cb205fe6d51b9383d6097419f0 \ + --hash=sha256:aa633613ff907ea91b9b0489a1f0da1b8725d8c6ccec6b77e8a1c9c235044bb0 \ + --hash=sha256:aa9fd1ee2a5dacfc41039ed49ffeeacfa75bafbd255b69f3b578e11897a0e623 \ + --hash=sha256:ace1d2c83b2bd24db5940600541140e87a325e119cb32d5fa9ad720d7e76648e \ + --hash=sha256:b1cc980905221a5d8b3c476330730b3adb40ff80add71ffbdb6215ba055656f1 \ + --hash=sha256:b37772102d44bb6628186accca3a121b1fa3a6b3d97518a8c29a5229ca4c0d0a \ + --hash=sha256:b3ff39654f0ce6ebd4db154211136dbe7e8157bcc3bed2344c87f32c7c6ecb6c \ + --hash=sha256:b477912f42c5c33405a10c759d22f80cf5af043ae02d95b9d8e5e5bc555739ed \ + --hash=sha256:b49638355ea3bebba70da783ccbc630fd72afa16bc46c54474bfa1f9a915bbc6 \ + --hash=sha256:b4fc6b03b9d9d90557274f571ab30e7fbbfc527955536935d96f98b6817a86e4 \ + --hash=sha256:b50343241eb69fd85f7791cf8bcc7b1c4729826b7d59ba2f6b27db29638fa745 \ + --hash=sha256:bc8dd3d9c93e70c3df974a201ac2958b6d77b465d813c51d1f15fa8e645763ae \ + --hash=sha256:be5346653c0b0e34be96869ff9dbeba23860156f89a2896a64c64fb419260cb6 \ + --hash=sha256:c00e26288784460885fe76e4d4b293573e0f791f52e6d60e27b42edf005922eb \ + --hash=sha256:c1b50797ac246bb2942a04b6c0f69af0667aba7cf7535f39bbb1b3208fd5d128 \ + --hash=sha256:c34ca1dc41bd86d9ff830d5bdf4e4a752bba6c54f7d2707027ce0eabd36084c9 \ + --hash=sha256:c55e71a9b1db1f107efb60da49c093689b74c5c31a708e5379e2fd9439d4fbb5 \ + --hash=sha256:c581b1d68b3845fb86c6b2983e755b29bf001461c59fa411d2c26a911b6559a9 \ + --hash=sha256:c59e4265608da6a041f54646ecc0c9ecdbb19aaf14c4c684bb6c2114998cc415 \ + --hash=sha256:c5e7ce578aa8a80910a72a8ca0bbea3baae10100827249001999726a788456d8 \ + --hash=sha256:c66f858b82497173f73366795fc6ee8171620e75a338506d6b2e7bc16f5fca11 \ + --hash=sha256:c6c0c13128a32eb04a51357e56a094e13aa8e6d3d1884de2e9ae923f6915e1a8 \ + --hash=sha256:c9389b3784b56c58d933b5e0aecdf28f901b073ff385358d8a7d40907f6e14b2 \ + --hash=sha256:ca0ec532ad2f5ba1e5ec120ac157769c57f01855b3d8bf37213f5d88abd9ba0a \ + --hash=sha256:cad7617727a96d189bd6f979d0fadf765198c7934e85f4edaba9bf3ad919a300 \ + --hash=sha256:cae82b5ca24b0c2beedb269f6e2a96f466acd926879ab00ae19f1a65cbf9ffb0 \ + --hash=sha256:cc669256d28736f7f3a149df5c380c50ace2692ba3e62203d10656fade4a2145 \ + --hash=sha256:ce1f220114959941170e22b8ad44279f6dee2dcef7591814d01ae805dc058889 \ + --hash=sha256:cfb398886a7eb4c719161c3efcff2a1248febc53a4d8e5072d2d8a87fed84ac9 \ + --hash=sha256:d077f21f4b16f0471353883748f126f62038760397c107bb9fad2ca94dc0dfb7 \ + --hash=sha256:d0c5c362bc94f1929dc7e96e715bbe7bd17037f802e6d8f0d1545df9133c0559 \ + --hash=sha256:d2765c18ce303149ee804b1f3dad11232726dd0a702d73a15cf19179ac8cc962 \ + --hash=sha256:d44442effeb8781f392340c5dc8c6716fba41dbeacb82fd4c0f09026fb5ff682 \ + --hash=sha256:d85dfab42dd672f87a7f76e9de7172962aee69fa12044f0d6e1a23cbd53fb80e \ + --hash=sha256:d97c5227621af74b111882a290b10f371780a38eef9d9e730408fba2259b52fb \ + --hash=sha256:d9a0d12846d6ce434fb3857918eef4315ec9b4769deb020c75828798614bfcfd \ + --hash=sha256:d9b3e7d71bf6acff341233417abbdface29c647e3113892d9aaedc02eb4aa2bc \ + --hash=sha256:da707f14ea3c35ee463d50acd596d6488e4b2b4ae7cf77a5bf93f55c023d63e8 \ + --hash=sha256:da85db328e507da922d586c3c7416ec360ec22e9cd9e0700691afacde0c81f53 \ + --hash=sha256:dc205732d593118cf701d986f40e9de7801bb2e371cb189ddbda9b7348f4d97e \ + --hash=sha256:dc3a44689eea43eab836e5c98a8ab015dc2419987d1ea6eafc7c590cdff86bed \ + --hash=sha256:dd5e90f34cffcfed97f36cf066325773d2b6021c60c29942e53a18b028501b1d \ + --hash=sha256:ddcf547bea2aee967d6a77779376a45e77e610e8465147a1f3d7e20d539d6e32 \ + --hash=sha256:e477aca0bc0d19f3b4ae9e4f2a1cfd687c31bf772d78734910658186b40b2477 \ + --hash=sha256:e8b17e23df3e827a69d25af70990ca2420e92668aaffaeeb3cd2351d7916a023 \ + --hash=sha256:e99e09ab7741f1281e2677f4c0058c7f5267d182530b09c87e4f6aa26adf3887 \ + --hash=sha256:ea2c01cdb16dc12156e455007c406dfaaece0c89aa4ba0e3b47586779f951d41 \ + --hash=sha256:ea6b1e9105b4b24a34c722432d9fb578f9ed83af21fa1abda639011e0f22bbb6 \ + --hash=sha256:ebd054ad1737a68fb7c5c073d405cef2b88bb824e294de3b4a4e995b47f0e376 \ + --hash=sha256:ec295280f4b37769256da025acf5890370355ac589c27e89caae0b5e9eedc702 \ + --hash=sha256:f6449672f9c93316deb5e2839e18931f468670e44d5bd9b1301a5a9655d45c07 \ + --hash=sha256:f683dc6300317700025e41d89a43e0276692ded16113a3c43eab704d605c58e5 \ + --hash=sha256:f6b9d2aad499c769ee8287609ab0e6de99d8bcea99c6e6c2e64945259fd52fb2 \ + --hash=sha256:f8b9c8ceebae6387d0dc77f7f4dbbfbfc962dba2efbfe6877486075a480726b4 \ + --hash=sha256:fad67b12ffe0f71e02b4932b04883cbc76a9072bbd30731409d3523cf058b011 \ + --hash=sha256:fbfb70ba01355251faf6b293171df49f73a88a1b6494db109ffea85442574458 \ + --hash=sha256:fe91993149523aa59941b9e3c90e2eb45f57ad014697aef6c8b13339a59c019e \ + --hash=sha256:febd35ef45f603c2d74b74655efdbf45e14f55fc0aef4ac82b663ca829b283e0 \ + --hash=sha256:ff88a92cafde90888511242d1c54afcc1a8adbb6dc0a88fa7f87e29e92400d4a + # via readabilipy +markdownify==1.2.3 \ + --hash=sha256:1a176f05522c8a2cb1dd3ab9d307dcdadbed5c26ae717855bfc42b3b6d38d937 \ + --hash=sha256:a189a0bedfd14009030fde5f85bb6f77c56897cb839b5c25315dd7d4e3e290ba + # via mcp-server-fetch +mcp==2.3.0 \ + --hash=sha256:8b147a50441cf059dc88c684e0aeed3687f0aa0f39c6cde7b90330effd2b34d8 \ + --hash=sha256:dd0c44c089d16453e8ae31a3877a0054d7a2314caaa81f5e0541b9b1734b2377 + # via mcp-server-fetch +mcp-server-fetch==2026.10.19 \ + --hash=sha256:3d16a5ebc68bf5a7dc8947ed4b1eaafb21a860f08a2503f05958e77bab427821 \ + --hash=sha256:bbdb6058496a7706584f351ef3e78eded14e153821edd69c34d3f2ba4d573e53 +mcp-types==2.3.0 \ + --hash=sha256:968efdbdaedfab06adae40d378a34395f1090c5921d4be3c9cde283aaf76d91d \ + --hash=sha256:d1e46549edb35ee19a94940fcee6d1addd7e589ab7ea92dda83f5d84781fc362 + # via mcp +opentelemetry-api==1.45.1 \ + --hash=sha256:aa38ed19bcc084ba42782a73255b3582283eced7ad6dddbd6695189e69adfb75 \ + --hash=sha256:b31553efa588ae44bc306f863c785c5333a9ecc091248c6ee68b4b6c87fdedfb + # via mcp +protego==0.7.0 \ + --hash=sha256:2c032d9736a1f4f0c4318f3558353ae34da5cd038f1a5e064ded7548df315e5a \ + --hash=sha256:944638aaee608f6c83fcad442695f3f9381a60be8d5007248f46b00f201fa5fc + # via mcp-server-fetch +pycparser==3.11 ; implementation_name != 'PyPy' and platform_python_implementation != 'PyPy' \ + --hash=sha256:51d5a8ba2be0bbe440b99d2112604c95bbbc3c2748a64260186c541e1729cd80 \ + --hash=sha256:d875f09c3507d00e1aba0eecc6dcadc1352f30fff09dc6bff2f1c2935e97c2bc + # via cffi +pydantic==2.14.1 \ + --hash=sha256:9195d967ec791692a04438115466764fb8b9a27b31f14a760437694f40d6b454 \ + --hash=sha256:94f478203dd03404682a1ada216965651dd74b1d2d5ffd62e00e0837caab5c26 + # via + # mcp + # mcp-server-fetch + # mcp-types +pydantic-core==2.50.1 \ + --hash=sha256:0036473f5583e6a60e50b8b21651511564277a3f05cc5dab8cf579f552cd5f6c \ + --hash=sha256:0048b6dddc8ef4b64fccaad878bd143b0c3882ea9936279dc11d613f6b7dd1bc \ + --hash=sha256:009634b83993777ddcd69cad0ffcace43dabde692109528e35f0fde91e386a8b \ + --hash=sha256:028e2f212273d4a39b1ec1e0de8166b1165a65fc0f1111452a9d94fc7c625c63 \ + --hash=sha256:062e891facce5ca296a1c37098e5e466780457f86413894b399f0cf22934f769 \ + --hash=sha256:06e01fbbfdb9be777b316a71b6c49efaf4a08b615d0a98d678cda3023f79d019 \ + --hash=sha256:06ead20d39ffd6f2f6f2a8f8a6de67ff8bb1b4f14a8a30e058502514ee2ac685 \ + --hash=sha256:0b3a6f334c6a2345ca15318ff894502a90012536404b37c844a976c76c846e0b \ + --hash=sha256:0c003c3b7f49debb893d2d85ae099ac5959c9839e2f330fadb1fcdf7a6594482 \ + --hash=sha256:131059670f1d2444269b8585cb888963994871932447c08b39ac6a51fcfef658 \ + --hash=sha256:132529c83901437ff642f585216831bf5fd7a91df66829907e155192ead62498 \ + --hash=sha256:17e722e156d0444ecaefbe640bdb60928752bf2013e2b7a11cdb099aaae19bec \ + --hash=sha256:1a9006395dece0e32e704c315eff8a00bede494f6108546cfc5539c89fef4f9a \ + --hash=sha256:1c8632d4ac04e6f91128fca584b3a8a507d81604c24eeaaad00d4be42765c32b \ + --hash=sha256:1c96fd793b73d1b92e65570132505498fe7b21eaef73cdf74e67e5dfba7ac9e4 \ + --hash=sha256:1cf41f1ae3fa155cf167a72689ad044bcc1e3c97e064123677149bdfb5dafc4a \ + --hash=sha256:1deeacb112d14d3f4fcb16b165f7dbaf76c70ba6e82f37ba042bdab51970a0b8 \ + --hash=sha256:1ef800dd7d85bcdadf4c3076e4c94e43939493558a3b69a1ea830c706d4617bb \ + --hash=sha256:1fa4c8bc12c1354c5550c0c35c1852c8c1901e89e06561724e03f8d0342e1f87 \ + --hash=sha256:2005207aafe1231315718bf6ed5d064a7300fb4772754af35ee72fc68159492e \ + --hash=sha256:23923ab9292c40da026330b1ecf4dc2618c8e86e0422e5d1fbf50d94d64ca4f8 \ + --hash=sha256:23edad659e8dbd8ca7e4e877fe6c81573abbdf215bd25a68b53e1272f58b80c7 \ + --hash=sha256:2ab756b72bd5054e4c7ef3ded331b35786cbd3cf931531a508f79a9537517064 \ + --hash=sha256:2cbd1b75b09e976ed0d6b6ca297675632ca35df86130088457cdc60ef36970ae \ + --hash=sha256:2cf91809d0721ab81592ba67bea7694821679c10b1a2e3c3460082b286c1918a \ + --hash=sha256:2df1ff41884de2bc4b307bafd7c40a691094fad2ff8e767e5b45a319257bcf4e \ + --hash=sha256:2eb75304506894a281d346220a4f7481a1b8729577c5ed2a05395991966a8396 \ + --hash=sha256:2eedf82ee4753cdab8e50044c6bd569577eebc3859b11fecf4eb9223761ff966 \ + --hash=sha256:30ddf019d082c117b5d309e5b86710c2a78909907ec1a9381feec3eec02eca0b \ + --hash=sha256:325c23f3e35cfbf0fe3486fa5f7260d1e45885173002d30a28ca019994124255 \ + --hash=sha256:32fad3a91e51b6d2039c572db04a5a873260b399f6bd62c3552671fa7a4a2899 \ + --hash=sha256:36c426eac0af8d1529ff8467e612b933346caec1fdc0d774f78f67a1a11e16c1 \ + --hash=sha256:3a5fce22f1e87d181e924e12da7d81cfe031fb3881a5ddf26ad28f141756ca43 \ + --hash=sha256:3aa9de446b793de2beb6fa2d9d0961803126c4e2a99c2f25ab59b9fd6ea125c0 \ + --hash=sha256:3e46a9eb0a0901dd6275e6b06ac3a464885ef350ec4121fe486869de8053e4bb \ + --hash=sha256:3fde4fdc6487a58d944ca87cf5adc95d5f266e872c19599f5f4c0a8a1b1f9f9f \ + --hash=sha256:409e0ea40ec30d9158f33574fd758e689f6045a0f2596701828c27816ca9687d \ + --hash=sha256:40f523349960fa30f3ea51404308ff50f9997a90df639590f47a057c1f32b415 \ + --hash=sha256:41bc8237121bd8dc8d888dfd6279fc166ffc88c1f1bf3a8bf00869680533ca4c \ + --hash=sha256:42b54c2c90ad348b5e3a85e03e715d572c1fde357ef104cdfe3b03b697a404ea \ + --hash=sha256:455a773617b5913bf5c20d0692e5787b119e52c4d40ea644ca31f5758fd31be2 \ + --hash=sha256:45b11cac094aa25725581d9304eee93c9028516b9ea80dd9e175e13a5a2c840e \ + --hash=sha256:45c6266d071c241f2a168d45bf8c54344f0effce35e7e6b73afdec11f3687568 \ + --hash=sha256:46b3301d3b5c886f77de7546e47274a5842c622ea2020b8c6524c6b66913b4a6 \ + --hash=sha256:476f6ed8e43cd1e0b460920e23571700872b284e77331cb30c4faf459cf48a4b \ + --hash=sha256:48569b0ade9edfbe065cad1d700175546592aebbb42f02adcebcc26e75b896fe \ + --hash=sha256:49c2cbb2397fe4d0987e84606e691af6cb87bc0ee1bd3e7b737f7e10b4c142f9 \ + --hash=sha256:4a53d13cdfbedbfa87f08b83c1a0a5efcc767d785a4b41934fa9cb672670493a \ + --hash=sha256:4be846f55c9477f5f3ddde8f2ce941137e16862a56d018ed885d422bb6ae02f2 \ + --hash=sha256:4df197990c15b5a37c5a277d131d9f2c67de6133f2e5dafd80d9bba4b99f46f9 \ + --hash=sha256:4e834f6a8e4ff772dcc34f58ef5504147a3ea5b0f4eeb13b0f8eb2ca75ac57f1 \ + --hash=sha256:57f51b31ff826e2859120cf4737c5a758a48d96f3e97da40ccee1796d58078ff \ + --hash=sha256:5958c72adb417c39b12ac87525ac60b0d73315fcdc59e21f44ee4a5e2512c9ef \ + --hash=sha256:5dfe41f232befddb9c4377f6cfc702b51595e2d78ed082672adf8758d2c4619f \ + --hash=sha256:5f3cae32fc46121f787cb2486de9cf95a8bf72aec5cc78f64c606fa1735a6ef5 \ + --hash=sha256:64f6047f62a6c5ae08d0a6afb035667aa2d97c3d20d69762e034c5ea144d92a5 \ + --hash=sha256:6a733778df2f7087ec1100ed0b41533e4f3001976e99570fa34f57c66e7f8e3e \ + --hash=sha256:6b20a4bffabdad0db2927ac034ae3b8a681b1f7a0182f3e60b479ad2fde21ebb \ + --hash=sha256:6dbcbee53bf17196a7f745aa9bf5a9603953a1e365b1f020be3207c676a3e7c4 \ + --hash=sha256:6ed4f3cef55164b026fefb41341b7754cc6b624c75dfe7142d2ecceb5ad21c87 \ + --hash=sha256:704075d10b74f2f3c6e15407c696d88701df35fc8953f434a431add0d0074db0 \ + --hash=sha256:739dc730e6be3bd5ec2f4ab5cfc7eb047cc45fc1497b3bafec74ff2ed07df597 \ + --hash=sha256:7456d699b13954e9c0164dcb267250a10ae0dfb03e6e26d6796ab0d46e189c84 \ + --hash=sha256:756d669f04e62ec4148ecfe22be6a4484d9b1181a6ef32e205ebfd200540858b \ + --hash=sha256:7689580e72a642ab5ec64d5f55b2e33636fa43b4ebe63c0c2c965ef307c7d1aa \ + --hash=sha256:76e2e83fa6ec8cdc972d438dafc2522b3a47bee4ec0ae668b29cfb1977ab5242 \ + --hash=sha256:7816e98acc08119dc0f340ab167048ecc54126316330c1f0caf7c6756c88e28f \ + --hash=sha256:79490e33c4c0fcb933bbbcfc3a62184d8803b99f535863dfbb925e1bcb6945ad \ + --hash=sha256:7f476456ac2bb0d937f75191494a09c83a30765fea4f70f3b404942fe25f6cdf \ + --hash=sha256:844b869f118e22a41a091bdcedda8a71bc1b0f62c38d1a0c3211cece47e1d8fc \ + --hash=sha256:84bc765b282a9d5b7fe0348b8648904f25a6a04b2139da52b1dd30c8ac3a2c8f \ + --hash=sha256:84f34323a61a365b4e9295de6028474754829aaddd59c7bf1a040e7487ef8f3c \ + --hash=sha256:8812592c85d0edf423f10eadcef42716d71e8219085ad9e85b775057b7306133 \ + --hash=sha256:88e492e8b9d0312e7dc13667c30222abf284dc3b79b5302b3607b41a5784ce61 \ + --hash=sha256:8a6791afa2245e6c6b180122d105941644f5bd410bb18623b408808cc41a3102 \ + --hash=sha256:8b4c3df25bd323bf1d36a648d563cf1fc69d717451569927151bdad7cad07a77 \ + --hash=sha256:8daa7ee75245d43ad7d747e5c9ecc1b1d06552f72b14887e9276f787d57375f4 \ + --hash=sha256:93ba4e9d8210d941c200431a56b2c0400b131865947903937ed3ec5404307d2e \ + --hash=sha256:94845ff54dc5193f228cab81b2662a04bfbb892e95bdc15edf7399000ce57d54 \ + --hash=sha256:94be440c03fede26969a5ce75468e0e6a9927a1b46d9b679ee8adc1b057b0350 \ + --hash=sha256:9572c1369e9c9da2d64a7b7992c786d90ff295abc93964cfe3125e4290768070 \ + --hash=sha256:983a662de2571cb2502fc8ff47b6770b03d025d2eb314c92f77b3f07c74720ed \ + --hash=sha256:992c3514ec891fa7858099183e4d64e6bd5a5d4ff452fae29df22faa77a006bb \ + --hash=sha256:99ba9bc2b8062ea0c326a990f7f00e6530c23579de66dd246e72c4cafef950a5 \ + --hash=sha256:9d1bed94af6a63835461f3cf7502058eb166c58c4778e11d0f433cfb1bd69e19 \ + --hash=sha256:9e4472072de0137ee0d8e72d6620e85939c271d2f90f6bbb4b15c24638b79f92 \ + --hash=sha256:a27c09d86600f1bf2fe3f37e1ae697faf3143931c09322cd799da94deee923b5 \ + --hash=sha256:a29a061fec0b4e2d714f277e70a3a18125ecff803f2fea6eade2f2e53711d112 \ + --hash=sha256:a3cda0e538208e5d722bbf3698b24f19c0a7d05bc8d5f8a7f9b121ea7fa243d9 \ + --hash=sha256:a44101320cfe99432db74237545a63057dc7a88dfe792cbcad0647f2af56cb81 \ + --hash=sha256:a4aaaa791bdae1c972a7e81765f4f3571c926b8e0b9b6e47346499fb80079665 \ + --hash=sha256:a51eee75939cf811ac09b278745a6cee7dc873ccfbc8b9af3cc88fe4b7ce25b5 \ + --hash=sha256:a7c58106de36ac6a56314182958de20db8d3a29dfd5db527192cc754e4f8e7fb \ + --hash=sha256:aa8224f10880d9bf1b5993988ba153d42a8b4f3f4f511f93b1f09c93ff613c72 \ + --hash=sha256:acbf31f37c53a5ac0c34706c80b4f5107ba20b05fdd3816124bf236ef0c57dd2 \ + --hash=sha256:adc06d218a1cadfd2ec4628424d7d79ce4eba69c2965e7e7b55106f0da5208c8 \ + --hash=sha256:ae28183297fb0d2b8dc46a1f01d51f5e45825fc5afe76a835a6cb7fb34821295 \ + --hash=sha256:b0135bcdcaa0f23573f286e4cb5e0fd2962700964ed13df085b85f2b97aeab9e \ + --hash=sha256:b087b1c5be7ac687cf22eabfe4b6b608d40df23610651e93611e1f49118baf84 \ + --hash=sha256:b0d955195bbbe489ad343fcc956eacea9357b79cb22192c66cacdefcbc14b32f \ + --hash=sha256:b281a3b0f0822618fe5e3e0d8a2048b6356b14388505dc9374ccffeb69989713 \ + --hash=sha256:b6d0c2183008c188e19f4906d426b293bdc4f67ab17df8e180fe16cda208fa71 \ + --hash=sha256:bbce99252ba3167b2b6277f1829d5bf4b43b754524bddf7f944707c3db7d2253 \ + --hash=sha256:bc1f08f68dac9f9e83845a8039880aba2ab553eb9b2259c3243a313182c253fe \ + --hash=sha256:bc94f474417604bd383d2cd445d071b07dd55fedceed3ce33407bf1fcc107290 \ + --hash=sha256:bed5163e03b98bc1fa2eb05d74c63d9c5c95d8ed6254985481640fbf5e237dea \ + --hash=sha256:c17799a62c142d61b8a3c51752a7cbc87fe2ad4ccfab10e628a77b405075c662 \ + --hash=sha256:c18db21573bd2c6489f9a544b7499f0df2853958c568e5e783536ee1f690af41 \ + --hash=sha256:c3ede305158e75510be50869b319550ab072008c13d64d4ab1e094fb286b6f44 \ + --hash=sha256:c516cc5367ca3448995d42cb994bf3f4c9002d2a7c22eac9622551269ad1b807 \ + --hash=sha256:c531166c42ea7bdfecc8c50049581f05dd1993b09cc7c52bb36a14e96deaec7d \ + --hash=sha256:c73622ef819328873b53109ee4f77ceb598bffedd02daf916102be3228866b78 \ + --hash=sha256:c8dce1f1e0e5358b682a6ad3fa5e31b31d4560997b8e61417e9217c8d60f8a0c \ + --hash=sha256:cb57f304525a5e3c13333b772bf9a473f36326e9c821b2e8e1b2fd36f80ae2c3 \ + --hash=sha256:ce8c25ca38cc0e3d7753ba180808de2c0c8cb24eae0df64491e40921454e9831 \ + --hash=sha256:ceff0acc940be2715bd6ad17b24c0e5304abf44f6efd0f81ee8499e640f9dc86 \ + --hash=sha256:cf356f70551d40374eaffb1aa63f1eb6d2006681cbd7a9faea173ce0f4dd7cd2 \ + --hash=sha256:d2d82aa62521c55ddfb000ae70f88cdd8de974078f6024e821dfe5addd0c818f \ + --hash=sha256:d32f3acc081cc3923386d88f422cde8892335e95f034e0104bb4cf9310d9915f \ + --hash=sha256:d4193206b6587047437f6f11d7e776df23e1c1e23af2a54d9347275614791e10 \ + --hash=sha256:d5c0e32fdbce7f1e8ef4d11f655694bf5f4175c757a9f1dc2be09b8864e5bcf5 \ + --hash=sha256:d5e062c01286d861fd6a1c4ff6e063547b3e713067f2df033c0ff97ac2ca006b \ + --hash=sha256:d8f9e8a6c4ab04b78d61f78627370d834eb004b2869dcb28cfffa647b4ea1980 \ + --hash=sha256:d939de9c82e2126f7f48a7e658f8a85ed46d57662d53f44c49b8895fe94a3eb7 \ + --hash=sha256:de531ce1e2a3364e8767878b58f4ff728a434b4fde089781fe30b1e08e2396e0 \ + --hash=sha256:e50d7b94baac6c7d09927fa5ca5800a0c7ee5015c7fcff65beb3a1931b5a6e09 \ + --hash=sha256:e5faeaee74a57d32b3ab3aebad2e348f06d3ba946fc5d28c1728455f00a3d13a \ + --hash=sha256:e6f0cc1bb9900dc558960894adeb30b0c083366fc1d69b856209fb2ca5c36fe5 \ + --hash=sha256:e8e1d6ce820aa23317e8209a86bd65a540973c12dc7552b48a4f6c8e9926815e \ + --hash=sha256:ed1e728b39a383c81035b2459cfcb35d99dfb01f7d6ebe3a913bc1cc5b81e459 \ + --hash=sha256:ee6db2fbed51a7991302e8fac498cd67e336246026d0dfa84cf5166ce1412760 \ + --hash=sha256:efbecf43d321f7b9281441f1f213f7c21c66988b0e06c2730ba13ed47a46bb08 \ + --hash=sha256:f2c634642694e6a0dad2ab1d375589fa671fd442edd5caf7d9737b8f6ca22906 \ + --hash=sha256:f3377c8c2b3ce898423c5e5dd94c7982e30aa7717a7e6ab2470b9de364963709 \ + --hash=sha256:f5187624823423e1d1b82b1072ac41dc837389e18d3d0572cc19bbee46cd550a \ + --hash=sha256:f77ac30b19221cd9bd3fcfa3d4614eff93140d0572ab730cded17b64adca05f3 \ + --hash=sha256:fe90228920fd8ff2be62622b6bb8a2b11acd65046d50c6b130614b5879605a20 + # via pydantic +pyjwt==2.15.1 \ + --hash=sha256:42d59d631f7768a1028a64c7ff581a9bf7519804daf91fc5b6c56e30eec5e193 \ + --hash=sha256:4f259e80cdfb6b3fc18a7de51fd1ef9ec79652f25019bae68975ca2468a34df8 + # via mcp +python-multipart==0.0.32 \ + --hash=sha256:be54b7f3fa167bb83e4fcd936b887b708f4e57fe75911c02aebf53efaf8d938e \ + --hash=sha256:ff6d3f776f16878c894e52e107296ffc890e913c611b1a4ec6c44e2821fe2e23 + # via mcp +pywin32==312 ; sys_platform == 'win32' \ + --hash=sha256:02ebca0f0242b75292e218065004310d6a477407c09fa449bfe4f6022bc0c0fc \ + --hash=sha256:17948aeadbdb091f0ced6ef0841620794e68327b94ee415571c1203594b7215c \ + --hash=sha256:3020656e34f1cf7faeb7bccd2b84653a607c6ff0c55ada85e6487d61716deabd \ + --hash=sha256:59aba5d5940842075343a5ddc6b11f1cdf0d1567fe745290359dfbcc7c2eb831 \ + --hash=sha256:5c1fbe4a937a73ae9297384a3da38518cbc694c68ad8a809b2e19acd350f03ed \ + --hash=sha256:5dbc35d2b5320dc07f25fa31269cfb767471002b17de5eb067d03da68c7cb2db \ + --hash=sha256:6017c58e12f6809fbb0555b75df144c2922a9ffd18e4b9b5afa863b6c1a9d950 \ + --hash=sha256:772235332b5d1024c696f11cea1ae4be7930f0a8b894bb43db14e3f435f1ff7e \ + --hash=sha256:7a27df850933d16a8eabfbaeb73d52b273e2da667f80d70b01a89d1f6828d02c \ + --hash=sha256:9fce94568364e0155e6dfb781ac5d95903be8baf28670632beab1b523f300daa \ + --hash=sha256:a4dd3a848290ef724347b19f301045831d8e802fa4464f491b98b1e0a081432e \ + --hash=sha256:a77a90fbb6881238d2ca9c6fd797b25817f3768fe78d214a90137ff055a75f5b \ + --hash=sha256:a8597d28f267b39074aef51fa593530082b39cbe5a074226096857b1fed2dfb9 \ + --hash=sha256:b2200a054ca6d6625c4842fc56a4976a4b47f96b73dbe5538c3f813a80359f47 \ + --hash=sha256:b457f6d628a47e8a7346ce22acb7e1a46a4a78b52e1d17e1af56871bd19a93bc \ + --hash=sha256:c2f03a0f73f804a13c2735b99392b0cd426bb4f2c4d0178e5ac966a0f21618d5 \ + --hash=sha256:c53e878d15a1c44788082bfe712a905433473aa38f86375b7cf8b45e3acbaaf9 \ + --hash=sha256:d11417d84412f859b722fad0841b3614459ed0047f7542d8362e77884f6b6e8a \ + --hash=sha256:d620900033cc7531e50727c3c8333091df5dd3ffe6d68cdca38c03f5821408d5 \ + --hash=sha256:dab4f65ac9c4e48400a2a0530c46c3c579cd5905ecd11b80692373915269208b \ + --hash=sha256:dc90147579a905b8635e1b0ec6514967dcb07e6e0d9c42f1477feef14cac23bb + # via mcp +readabilipy==0.3.0 \ + --hash=sha256:d106da0fad11d5fdfcde21f5c5385556bfa8ff0258483037d39ea6b1d6db3943 \ + --hash=sha256:e13313771216953935ac031db4234bdb9725413534bfb3c19dbd6caab0887ae0 + # via mcp-server-fetch +referencing==0.37.0 \ + --hash=sha256:381329a9f99628c9069361716891d34ad94af76e461dcb0335825aecc7692231 \ + --hash=sha256:44aefc3142c5b842538163acb373e24cce6632bd54bdb01b21ad5863489f50d8 + # via + # jsonschema + # jsonschema-specifications +regex==2026.9.29 \ + --hash=sha256:01000ddf0e3ffef97f2413ceb514f6313040106b6d18a03ee00a4fe35c1eb1db \ + --hash=sha256:0166844493626c5015c6088ee15c9ca2fd060ca15b7641d1657da6a58432ae33 \ + --hash=sha256:044265d77d94f5e3cb2fd72c76723807c429cb8c533e9d4672d0334a6f14f588 \ + --hash=sha256:0476e5bcbe6e1ba3d1c4cc7bbb1c3ba78e3b979b5c8a88d0a6a8cdd4992b8c84 \ + --hash=sha256:066d0e3dbfdd739bce2bf8c2a41dd16f73e3d8adc2eb06dd803a36a307f56075 \ + --hash=sha256:0b65c72739f981377c9c22e0c5c3cd7f42da7bd8a3c9209330fac772c7d893ed \ + --hash=sha256:0c992c19cd45058a4b92f68f139c93db168b48fb1f322c9a7cd620806afb6b51 \ + --hash=sha256:0cc63b5e47c12a48d90c7e9d7de6a035dd14f62868aaedbb4e0ff8ba2b8bfe7b \ + --hash=sha256:0dd8af32e9f7b56b7f95cc1fd79b23054c3bdc172392ae560acc24d57b7ffe71 \ + --hash=sha256:0def9fb6abac55492d6d51cddb7225d07d6f279e774e0adc08569a54a5fc8d46 \ + --hash=sha256:0fd2c901cc307a745ad4bc87f20060d7a0825a3371d1e93488af22e7a387f78f \ + --hash=sha256:1043aedf5917caa861bcb25a9c11460049656bdf0017a90a309fa8f255467725 \ + --hash=sha256:121a76a0985db80ceae9e171c337f8c927868e37d01b54e3ce87bc87f9c6a208 \ + --hash=sha256:143533cc4b6fbc5b95aca0a5b8d541088d374831593def000ec89322c220221d \ + --hash=sha256:14e953ff3607c92d7675bf79c4d4509ef6782aa8c08509f179f9b3d6d0679e86 \ + --hash=sha256:18ae8eed4526e35bdb754d61562b90bf5c00a67fdcf3cc1380dd59597486631b \ + --hash=sha256:19959129885356df0e97556856f77eb2888380dac18bed075a7c05c5128c618d \ + --hash=sha256:1ba8c6a416569ce0d37e83e28a254a61dc99a419084dfb6476cea02d997f74fa \ + --hash=sha256:1c2a0026062abcc321a53db4a185ceba0b59a66b5d37b0808917a88b55a5257f \ + --hash=sha256:1d9fe8091b2e89d470df68a9331111ed008ae8aae6bf1e8e1fba4086a495c84e \ + --hash=sha256:2089fe39c406784d90101c726755ffa1497bb74638fd434300d2b88006186de8 \ + --hash=sha256:23ae6fdad9e63e54038f5ef78aba2933faca61e24d432786589e737bc5522ebb \ + --hash=sha256:26ec4ccce55aa533fbd603d08911b01101a8fcfec987845ac3ae2c7087b2bde3 \ + --hash=sha256:2f7f7aa47b229f2b39a2ae2596d2ad5625d77b5eb9856fac2dab3eb506cdd0a0 \ + --hash=sha256:31b003f9a070335e2a8233ee9b14a3ca8e6d792012ae011f741bf0aaf11744c5 \ + --hash=sha256:32ab11df9677ca80bcbb5fe4eb1da9109a5019239a054836efc6fa1c64e683cf \ + --hash=sha256:33026515aebc0e70d1c89978e53e8d695d35d9e472f8d5b34465ba3c74028650 \ + --hash=sha256:34b6925af9853bf461950e6508910f179fd6e9b1a7ec8548e069606b7e51a26b \ + --hash=sha256:352cf115a810b357caa35193ab656ecf5ef41056855e82f292c99e8514f8d954 \ + --hash=sha256:39ab5894d971f9ac68baa6eca5c50387db579cfcacf36ae8df3feceb1815e6d0 \ + --hash=sha256:3a21a9509d0ee88e7a70e1ad228cd2f0e0fd1e187458db132e8a8d18c97daf9d \ + --hash=sha256:3c5c2ef13797466aa64170cbb66ad98a32351dd4127694cea7199f80f213750d \ + --hash=sha256:3e778bfccd63075167709136afbc251c1f683758d5bf49c803c60ac3f894ce6b \ + --hash=sha256:3f1e6cb402a89457582cd696f982559217d13484a193202c394015297968c86d \ + --hash=sha256:42e82e578c904445d4c8a35b8f28052cf567593215fa5db06266fbc6f77aaa2e \ + --hash=sha256:4408b2b27a95ca8cc48b7411945753773353b5c93b307754781086c99d3a576f \ + --hash=sha256:446654b29bfaa30500d80947eda42cef1449dc8a87f4e3cf061cc8485d3a1f0b \ + --hash=sha256:45010bcfe66df41522d56c9b6114e87ecc597a08970ff6a2ced24415c141ae5f \ + --hash=sha256:49ee178ca31c94621294bf9b8b676a92a2e6bba8af0529591753719e57edb621 \ + --hash=sha256:4d7d93613b01b0199961330e49cfc52d479b3d5776c56c691db31130c0a07d91 \ + --hash=sha256:4fb41211d2333eb930a51e0546a65999761cf1f572a4da56ef9b8a62966c06f2 \ + --hash=sha256:4fe97894d1b306c919b4e50def1e6f6c522f4d03a7283811f4d108f1ce5d3ac2 \ + --hash=sha256:554bffadcbcb6d5f4e5fb10a61cc52084b9a63d1dab5f10bcd2c4343972e8e2c \ + --hash=sha256:59b49507f47479e299a9e1bc41b5cb83a7afda0540625f1dbae886615978acbf \ + --hash=sha256:5eeb8edc6110d9194a4d0d54610f64c37a31c605b5dbb7e407fc6ec7fa34a4a1 \ + --hash=sha256:612b709381c0355b70d89cdb51b7f670591ed5cbbc0e3b5337488019dc667b65 \ + --hash=sha256:61956f074ecd123f55adca68ee3eab46e6a07ad3f8e64e6db95dfacb444f55c4 \ + --hash=sha256:6398d5145689503412cc1748895242598d8846b8967b851133b20dc2ed1e21e8 \ + --hash=sha256:65b408d8fcb273e3499e7ef2ce796810da1becd208c7fb4373692a242d79d461 \ + --hash=sha256:686ac5350fceae63830bb98805fcb8039325bf4c06d9f6f048ff65229d5bffa5 \ + --hash=sha256:6a1a824fbed817e0a891103886b68f063b1e83cc51bc97192a90a60195a9291f \ + --hash=sha256:6abb75ab16bc3281714a5b99548a2225db70dba1f995f6d7f7419b76eb5a8fbe \ + --hash=sha256:6f7121a8914ed13fcfe2099f895341bfb789f004d4c5a0bdece8fa667da10849 \ + --hash=sha256:7020ed44df30b3aa492c00ee3b52d0548c1f30c2c6c5bb13ae897680900d3413 \ + --hash=sha256:720537c7ea6f80dc61913184edb0ce2497a306b39ef19f28505b322553d52bdb \ + --hash=sha256:724184b4aafed865e4f13ca313fdcb43024300c028ec67319cfa16847d84685e \ + --hash=sha256:7c03031610e3e6ed1768a2b7a8fc84637c1257b50c5eacaf094c6e17a84fc563 \ + --hash=sha256:80a5ea3b4fd9d6a5b9a44f7976a9acaaab35aa3c1f6b29e5bd857dfabaded223 \ + --hash=sha256:80c7cadd3fd2bfde5df8aa0787e315812cad0c313a753095d02f4c2b6c01677b \ + --hash=sha256:80ea96f5c1a30bf09007d48466521d9c294bebe197c708c3359096e3e3691632 \ + --hash=sha256:864e9b87ac33c3fb9fb4ad48166d4fdb579c351d5c77deb0d34bccb36a775cd9 \ + --hash=sha256:87fb80cbe3557e27e7b28b995c2b2eedf689b8886f941ab93e0e288f0976518a \ + --hash=sha256:8873c4a11c50b9989168881aeb3f08859f469d809941866aa1feefd8be5431f6 \ + --hash=sha256:888d60953908dcf761aa320c3e390ab8556efbdb551ace63921de90f6ae0848d \ + --hash=sha256:8b5fcc4771732191b2b7d1dd68d8f0353f47f8d90b6150f6dce58bf1112442cb \ + --hash=sha256:8f39588af4731c8923c26810eb3b33f76f17633985e40f59c3cd45a33805a895 \ + --hash=sha256:9173db3be74a35cb6731701094b98120f7ee4876a287882a59cdea1fa7da342f \ + --hash=sha256:92f05c9c42bde5785dc48770bc2194d9f7442544156f951e19cd31b096cec562 \ + --hash=sha256:951733b1bbdb71e377cec567b409f1a7881b47cfcad84121aa74cb575fa425ea \ + --hash=sha256:957bb708e8057ab1649ba566456429d691ec9b90d1c9ad1af1ba7ffbbeaf05f2 \ + --hash=sha256:9916fda742cd4eede63b286f58c06718324265d727ce0856eb1aac86d0d150d6 \ + --hash=sha256:9e1d3a4cb7993b708f0ada8d0c84590efd853f169e7147d2202c9da503180242 \ + --hash=sha256:9e4482589065c8ecd761cff522dcd85f2d39e62f551e37e025d1c7d54772def3 \ + --hash=sha256:a5300757f8a68f5b6cc33f57338d72a0e3589c5cc9ad5f8504ea06f028be582a \ + --hash=sha256:a540abfab208e1b7ef2df231c40ef3b6cbb30a0aad6204e9b6a81c10a6794628 \ + --hash=sha256:a5758353650079898dc1b2b0e95aa51fa23a30d020e06f62c430dd08ee56cdd8 \ + --hash=sha256:a64b85a4760337cfefdb27d42da6ed8b58e8cde3f2d57b6ef43e76ef6ea9ef47 \ + --hash=sha256:a655d34b2a6943af32401f3d94f72e9d731f6ad16285815550bf2b4ee69d420a \ + --hash=sha256:a714befaacbd10092ffe4cea0d3c5f008fb9efe9bc322c715bcdfdee414b9a3d \ + --hash=sha256:a760da040b47767b4b873adfb7c3b691e9ba2fc60f113f9d0b88f1a62f323e85 \ + --hash=sha256:addd736a0547d553283adaf4e05d7104e7f2c7b0b092e9b4d28756825f14531f \ + --hash=sha256:ae4613d7d9dda60fcba95f846cc6f808017f1843f392cf9daad14a6534493d71 \ + --hash=sha256:b11b589e00095ec69cf79841a76360f9b079e95b0368a25b5ebb951ab0c157ff \ + --hash=sha256:b3e445b66c80b4eb4234e855ce94d9adc183eedbd632816228d89930b91b2c5b \ + --hash=sha256:b7b893976e7fe42053da64f2aa27239c24252fd2ec6df471e1be197c0addc3b1 \ + --hash=sha256:b84f186a7f0536fe4ff9a9fa12d06d007b9b71d4b5352ddcc41f59ad6522a312 \ + --hash=sha256:b89efc38431793d28b7cd91227e2f952ad7c48df19132b17f43a5fec3c14143b \ + --hash=sha256:b97a38fb4c732b6832db6bf108963adbcd82ef1268ba2025dce390f45af75efa \ + --hash=sha256:b9d74e4eee9ddb64c2e92d5d61472c59c21684c059eb7b68767be9628e977859 \ + --hash=sha256:bb90e7177944b6684738c1fc36aabd2dd00d1de3be7dbe09f91e196f1bc0dc81 \ + --hash=sha256:bec37990e3d6121f29ecfb594bd8f1bf009e9f7926daba2e50e3b27d3892a783 \ + --hash=sha256:bf3c49863c23a1ad6da9c30351aed6cff8d5ddbeb63c5c8420ae54e98c7d0138 \ + --hash=sha256:bf48516e35cf848390ea68850aba53e7c333720d2945b4d2c25b69fc5171723f \ + --hash=sha256:bfc71e6d970419c1309b3640305298643e2a734cad3f7cfb6d2ddee4175ab53d \ + --hash=sha256:c0094897d7d01f184b2d7fe8c56c66d64efe01b31f4b7d34205b391387df1111 \ + --hash=sha256:c03c6eb6ece86dfdcbb34799efaa339b093132e1aceed491ba5e08fe06cdf699 \ + --hash=sha256:c1a9a6651197fbed6f0212591418b9def774fc3f8324f78d1bf0e6a63e5f8aa1 \ + --hash=sha256:c3589f40749acce747510bf5d589d54e376cb0930ea58b35effac97e5312b0c1 \ + --hash=sha256:c4e38dd8f39c43a91d2410ad2b85610701b0979342c3df1d69eaf8e838c757d8 \ + --hash=sha256:c6c8fabf1dafc1f1ddcbb67896d3f93efb092e8c4b6322d7389b944e76a484e5 \ + --hash=sha256:c90fcf7804ea0a54b896ce0f2b9565350220b8d4890fd0db461a476a4c687963 \ + --hash=sha256:c9b602fae1e00b7c035d661ce85575365719192a7b46784bd71cf64c68053aa0 \ + --hash=sha256:ccb64d887a9db1cd76dbc0f92051a1a478a2a67e7f56c62d915cb881d7734704 \ + --hash=sha256:d06fcdecc10fc7954d7c8f27a03c96055fe525274dc84a7b0dbdc3d6b9e03dab \ + --hash=sha256:d0c3082bf79bcd6a614d55916590ad4b8f93200e10b97f463ea5d9d07c9b5f23 \ + --hash=sha256:d49c18f1ea294cf4adde2e5ac256e98c82ea9d708462ce4bf799dffa7cfe8a2c \ + --hash=sha256:d60030baaa7bfbb02d650c126cdcddcb6e33dbff14d819434c8fa2fdcaeeeba5 \ + --hash=sha256:d7cab119d0df0b9413f106b4d7fc34f2872d3574ed3806fb48959c830b1537da \ + --hash=sha256:d9b77b25b4f395f92de6099ab08e8ae2bc7e51dfe157f22900902243a5cc90c7 \ + --hash=sha256:dabee8f4935e731fb46b2a3091bdda0d3d94b3bbfb907d2b4f12eefce4009619 \ + --hash=sha256:db5e82ba15c142425b8406690032df89e39cca4a2e8afbbb9a3d84edc2373ac3 \ + --hash=sha256:dc79d36d0618752265f0d575915bdc5c5130ecb9c9f6b3bcefeae32e4bdfafcf \ + --hash=sha256:ddfa987262763c3c22a8367d2a49c244b018a74c3a8e3ab1a864119ad45c5633 \ + --hash=sha256:e1172147d28d8fbcf8cb8d26c41506169f5ad8fe9ec969cb116835a19d4d8eca \ + --hash=sha256:e11edba5bc344a32b029a7af9d4b3173982dd79eeafa0b9dbd787364414b0509 \ + --hash=sha256:e2c89e9b762c57f59d5e99ee8b20202adb892e35f8d3485741340999ca55058e \ + --hash=sha256:e31f72490b7c12f7790e1e25c3afffd20503ee1bfb43461d7838b871ff244b19 \ + --hash=sha256:e8c65ef3862a8ad6e86492b6ed9327805dd66904c012bd3649dc67d822ed6c34 \ + --hash=sha256:ebb8912f565b8cdbbf27debfe00df04202c20e2f651b9e32767930c5eace3621 \ + --hash=sha256:ed511a0708e2297e1d6431e7fb217e3402791e491e02da800658ace4973df1bb \ + --hash=sha256:edf06545875f3efa31560d94121e95c7fd70d98b1dfedc0157097d79b13b52ea \ + --hash=sha256:f0fe9834e5aeccaf19a0d8feb296d66a24be1a7c9922002f842a682cd5abb787 \ + --hash=sha256:f1a0d5117230dd46b399a30a38afa44f79c99f3168988fdc4f425c3f928b39df \ + --hash=sha256:f37964e4a5e993d2fd45147741e9dff7f34a2d8c00ab94c4ea0514a4677f959e \ + --hash=sha256:f57dc6b8fef170f105d2cf5cdce254f47b137d7755086cf7050f47e16582abba \ + --hash=sha256:f93bc1c3486ef3747e07c9d7c1d0a147b8fbaab975f80e348aed6f71309dfaca \ + --hash=sha256:fb00027a09a8f9f08028b40dce4c933cf73e4833240ed356583fdc9cfa721566 \ + --hash=sha256:fb99cc9d45f48895d9d67f6a0b8a57f08d39c174d9f25ad97a313e0470267b1c \ + --hash=sha256:fdd88ed5e20b1bcdd234421e454962c971aa44b653bdb7f1ea9ef683e90fb649 \ + --hash=sha256:fe3fa1dd453ed5c7f5ea23a26218329790ed7197a99b90e94330e313959a7f52 + # via readabilipy +requests==2.34.2 \ + --hash=sha256:2a0d60c172f83ac6ab31e4554906c0f3b3588d37b5cb939b1c061f4907e278e0 \ + --hash=sha256:f288924cae4e29463698d6d60bc6a4da69c89185ad1e0bcc4104f584e960b9ed + # via mcp-server-fetch +rpds-py==2026.9.1 \ + --hash=sha256:00ba2d8c7dd4ee537978ddf4b3fbd712bef2d8751603f7f3146b3f4287768e25 \ + --hash=sha256:01445c8d194aa032a08e944f16567672da1c62dbdbefd8b6d0693032e290cf68 \ + --hash=sha256:028ad274ea951dac64491b5d1e65712a4aeabfdbdb9fccf797b57bd899b0c495 \ + --hash=sha256:0483515261947e4e8b8e1375bf7463e7eb6ccfb3d86e7b554d90cd5285f20f32 \ + --hash=sha256:068c37bba854ec2fe42f7365c640af11dd9895890ccbf2df5070d0c059bd7f96 \ + --hash=sha256:074a4d198bc34d9a8ea425114fc3ded6d11ec01f6a314a8db67454a5152d8834 \ + --hash=sha256:07deecbfce94c78473018bc7d10b337cc651d12df87a1eb2cb3e4024bc9c33d0 \ + --hash=sha256:08dae4a4095150a7c4545a1fb40b98e1ab1744fbc2770d92c977b9dadaa49ab6 \ + --hash=sha256:0da298fb372dc192610a4b9ecbc68a0cd8b675bbbd1fc519d01b41cfd658333e \ + --hash=sha256:0f045bb053c9057720d72c56dffe30dffdc05997b2897a827b9325f0ab6623fa \ + --hash=sha256:10e208f2425d973938afcd56e28a7c4be32e27b6a60b5d381f49fb9d8acf9759 \ + --hash=sha256:136a1c3fe4402b7008bc81cb62ee538481795b61a7e83df88dff3b3f02b726ff \ + --hash=sha256:159a7aab5c5e8b112c8830f54717ce56da1252ebdbb526f5be2df2309280b9e7 \ + --hash=sha256:172e47169583f46ce118cbec68e6795d0da0f4606b488b6434f8276bca0a058c \ + --hash=sha256:1c2d1f6da5128eabf34e963d7163a818846075a52568250d006c4c953b40f903 \ + --hash=sha256:1d55198263bb51f557550c6ed2e6d1cb6a6fed6eb5c9120b741c5926bef8a45d \ + --hash=sha256:1d77b649e6f7cdf12ca5c2a98dad0ad37f9ea9b6f960408a92f0cb12bb3d04d9 \ + --hash=sha256:1e8d4d79d828299bf44a55db22a9388ab967b49d17132c88eab0f4360b48da8e \ + --hash=sha256:22ffd29a63d71fb1b81552c21f2c2b734949b7ac751a9be70675a939a900839b \ + --hash=sha256:2693b2728bbcc48d09a981a356954b0c47c53ff25b545856f28a889ea619f69a \ + --hash=sha256:270bdcdaac5d5b6f73c5e22e7e135c7f2a50e789f71d9e241d5be8d90026e19a \ + --hash=sha256:2711d29b653b3bce48a63d18b9c6b53274669e6d6c4094dddeb4d9a0e45128b2 \ + --hash=sha256:2c16ab111bc27c646ba8aa005d0527754edc538ebb636f0b1bf8e244b48d1945 \ + --hash=sha256:306ee1850d8105b5baf977e78d45fcadd12c1a54678d614c9baf217708446e91 \ + --hash=sha256:3231c4c0e521dafa5be0c9f114ee2c2ad46650836f2d72caa86801950c3e7044 \ + --hash=sha256:3890a6aa36e6baa53d5258a2a25d3ef8b37ad165a6ab27a892d7c3e3a432cd69 \ + --hash=sha256:3a72c11530d71abfb66c8d7696a2f86c43e63fca8b948f1a784ac490f4ec688e \ + --hash=sha256:3b5a6f40f0a1486b4b36c888123afc67acdbd9f33235927acf5ff295429a0ba3 \ + --hash=sha256:3c91c210ae7645626c608400e3519b4a642f837cce09ca830db3beb2e9f274d4 \ + --hash=sha256:3cd182d7291d29b92c521a0069d9c01ba6193628a9a105531d11b40a6d731a33 \ + --hash=sha256:3e524c7874ac72884d28e16dd5b8d839fd09e0fe76b020d3fbca23212a7b8c52 \ + --hash=sha256:3e93b2cd69a9830be33e03945cd7cda940a0a8bfcfbff41d6144f0cb0d3d8bd9 \ + --hash=sha256:3edae8c5ddfdb6985d49ae9d150516e5076888879022f91a26c2de9276ce0bdb \ + --hash=sha256:3f0e9ac28fc067d4d34b88ae43c48e9489455c97fee9633d851f7eeed5a05d35 \ + --hash=sha256:42e75466f83cd43f6026c81eab74246efb2bdadafb307b85700632d06c68f299 \ + --hash=sha256:44b32a7c4f0da3d28af31c259e38ddcff096f855e205ed0671d02fcf44f1ea1c \ + --hash=sha256:457866b85daf5034296666168b84a69e0b2e89dc4f1af102b46f6448a60b9063 \ + --hash=sha256:45bc6bccf78b20fd834237d18db64965d7ee68ba7f60440a26c7ab71e7b8d51a \ + --hash=sha256:46d80bc76b51a6c24f9944368c28d38b8bcbcea1da4f2f8d3ebc31a67e8c6ec6 \ + --hash=sha256:4793ef7f78268b124b73fa933440f01d258bbae01de9fa53e9080c9ab0425a12 \ + --hash=sha256:492e5e428cbe126221611f47e068f01660352feec4ad18bc0f5ea9b2ae88fb14 \ + --hash=sha256:4b26b03d9d2658ee2fa234f8f4f19f38a09773fe5261028025032e26d4d35af0 \ + --hash=sha256:4c0d2cb595a420b34d5086db0add011e26e2c09d6a024afbac4228bf8f863a30 \ + --hash=sha256:4cfaf02209061880210819934de2f4f6aa83dc04dafe6770276acc240a56da31 \ + --hash=sha256:501909f2e4a1e2dee528ef766fe3c469060ebc17e54a8383d404ba07a81a6f02 \ + --hash=sha256:50906f5aea24b5a865cbd0a589698288631d9f3a54c3a937c83aefa95a0d14af \ + --hash=sha256:54ac2158a6f96cfbabff0b2eedaf94b90c5ec7ca8317fcadc61e1c2b2e0ff6ef \ + --hash=sha256:56c6952a9b15047466d0c2347c446a761d4527f89976156341e68f0ce5cc08b0 \ + --hash=sha256:56cd8b3f77d7b6812f533b662186a1f28316931166ddc00fb893b1b0db7e9888 \ + --hash=sha256:57492a550a1d88d29d003247e5f78dd8cf04a701fac0e4c8db8745a6d2504e0a \ + --hash=sha256:5943980471829f6de242a20b109de3111ba6b77e3af0ffc587028ac854b05e6c \ + --hash=sha256:5c6ee90dee3e85e055ddfd502d611643d9b0fd94c818220bda84ec3dacd9b27b \ + --hash=sha256:5c90e7fa02e8f5de0d10c17595c568ada48c5302e749462c0ea1a4c362111a86 \ + --hash=sha256:5ce8943f79c2210f7abcc28e86367b03b28d95027fd01c46d2472373ae70c86f \ + --hash=sha256:617f59cde379b4f648a09797b7f683d04b90a46344cddab85639da5aff0f5531 \ + --hash=sha256:6307a0da524939decb8ca4a3933b8ab62525794411d6984fca6726e732804af6 \ + --hash=sha256:684fd492fff4fead00587544e059be2bbcb6f93454f21fa2a91b66fc7508be82 \ + --hash=sha256:6b5b393eda5ea42cca1c1a6665f2a4882b4fd5d1777e41ce0545a107fb008c9d \ + --hash=sha256:6b723eb406dec5bc9ec516c73ab9c3239a3284e017f7eb89ee2b3258bd504fb7 \ + --hash=sha256:6b9bf3135b4ad5981df9a73d71a35272d650a2985ae9c2746357b24d59de2448 \ + --hash=sha256:6beb738155fe8ab8091afdfa5a3226b21c2b1593f1e50ebb90eb25b44dbc0391 \ + --hash=sha256:6c0dbbcc19735fe5f8b0a54c07659d154a9e69f47e15d0a6ab7299215daf62cb \ + --hash=sha256:6cdc537c8633d7fd92a82e2e0d2ab74320a3f63d5e59fb9cf08711e08fe151c4 \ + --hash=sha256:6eae33003518fd4cb4f83a218d5371469dd3001aa3b87128c005b07762f7fe5e \ + --hash=sha256:740d0a99cf9de0b17a3943388e9294a59becf75e7c43421f387bd3c7a9901f7c \ + --hash=sha256:75c38c50ab9aca840225d9a9a3810bf11d04bd5c1f186cabbb8aee56db3e9b15 \ + --hash=sha256:761fdae6728ceb99ab182fad2f0cc1e262f610834dc891aea1d1a2a2e634776f \ + --hash=sha256:7664419f27db41d4f1c43a78dccda7dd6e8ef2428df3ee01d0c2a07a6b071297 \ + --hash=sha256:76d3af9732d2dab69f28179b40ba2d87e2f1d5824b4a694780aa787d685e8f36 \ + --hash=sha256:78326f4cb4427a56ba4996c0762b63be45f06b85f086526420d2b3a66e40f84d \ + --hash=sha256:7868b85224291c6cb6759f9b5adb9745f486d226f62b16a614dd5a2a5ab2b35b \ + --hash=sha256:815d26356930846a40c7bc1366e7b1b0320ab8a063e66c11298a208bed0fd237 \ + --hash=sha256:8171b44a054e5c67fd748ada04187f1250bf35b95f85e52ab64bcf3331a923bb \ + --hash=sha256:821b2755db9194409254012f429c56643416fb96ef9be090be82ec8826b7f477 \ + --hash=sha256:837c6b305e26fe0f75b15c92cf3b2ba29e0ae19dc40b1c557b026cb426347d0c \ + --hash=sha256:839dde845559254f34885267c6878f60d61d5205180226d976fe488d45fa128e \ + --hash=sha256:84a6ecc0c940169190d2c23bd969debd48c94dbc855acd60188a68d71d421608 \ + --hash=sha256:8601470267d938bcb7f3ab1a336100af51a4fd5b6ed030ef52461bb3ef5e7e07 \ + --hash=sha256:88b5268892fde430d5531f95bc560b6efbbd67c929662c586afd729a96e7461c \ + --hash=sha256:8aa5dda18d39b6143eb24809d158f9252c88f402749b6f1b62a506cc7d96cc35 \ + --hash=sha256:926bdd3e3b5998ddf70cc64bc8cf57209571f9044542913afb673799fec77dd0 \ + --hash=sha256:96beca19ec79de272e8668585380ff9092c47077c1d7a1e098e00bbd921f4785 \ + --hash=sha256:9a0460d43603d1fd9ef59c30278531e15d78581721ddb538fa560aa7817ea4ad \ + --hash=sha256:a03d57b86d2a51d0a66c92177e2be154ad015f357791d306e714569999cdb4cc \ + --hash=sha256:a36b70596407634ca82d4b989a3729074a008537a0522e4c8046a67c729103e9 \ + --hash=sha256:a3a52a3ba86436ab3aef510fbe21512abc2ddd1993005dfe50514bd2284ef025 \ + --hash=sha256:a3dbc5ed9514908d5046107d7b1346bde71eea61de6e0e4919c19354f97e769f \ + --hash=sha256:a431156bb41865fc14cd5d79bb9d7bbed83110b0159e34e62ae30951f96c0009 \ + --hash=sha256:a575404ebc9cf2e91edd32eaf570ec1430eb900d4f56724ba7dd4bc1fc9c176d \ + --hash=sha256:a5cf77eb04f20b720be95265a3e00eb2a14814074255cc27069c551b2db53118 \ + --hash=sha256:a8763f20692da7df39b0afdd1ba3042b004c50a45994f76c2d9a25641f7673db \ + --hash=sha256:ab4b2fda7c2b542f7f9d886cc6a838c5079d2b76f72e6081411faba11adde2c9 \ + --hash=sha256:addeda51556dac7c1a2f14cda62db8b621cd12afba3091d03a96c72932387eab \ + --hash=sha256:b242c27c8f836305a4a72df9cdd564386ac57b807bd252a063223331c9316b37 \ + --hash=sha256:b4f062343e7ad3fa94f2c66e5ae667dee47ee74dd41a9057c4fbe163236a123d \ + --hash=sha256:b5b8b0753718d258fd454283fbd57e14545d3b40583fa672e27cb4f987626bcc \ + --hash=sha256:be3e47e2d91aa3942ff9bf4077a505226005abfc39b6f7554a91c1b9393986b9 \ + --hash=sha256:befc2d6a953e563f8a7bfd87a42c22ebf8a3e980dcb7b6a4d17b70b0e914e8a3 \ + --hash=sha256:bf35d0568abda97233239ce32896d3ad53fccc537832c104e30c94aa5fb93569 \ + --hash=sha256:c933c6678c6f116ff8af47a4c6db0868b8ace74af0343016c0ef00f00272ea69 \ + --hash=sha256:c9d1aca01f49170fdcf5c92761b1fafe97f554b721ca4570c5949fff778f0d4b \ + --hash=sha256:cdeaa99ce822dca76cfb1b993e9120c5ea212f2eb66d48950ad63c349668a018 \ + --hash=sha256:ce4d4f52e2a4324396caddbd45a97d8d7be5f42edd25d2355282a9c34f9b2f7f \ + --hash=sha256:d1028417bb44037eb3069c1009bd7b7277212876cda22fbe565b0bca9fab6d2c \ + --hash=sha256:d151e148117294133bf8af7eeace085e7e87432db15ab6adf640330298a47f6f \ + --hash=sha256:d7841166b7fa64c9c56404617ae4341448847482d45933b13135d26c130519e5 \ + --hash=sha256:d7fca4eb6df565e2a928f1c7dad92d27db8f9df0f449e76423ed5d7e713ed445 \ + --hash=sha256:d95a354e02393eada6d7351184671aced9d4cce109dabf927cb7aa99624352a1 \ + --hash=sha256:d9edf30457d74eebfd76b045535e36f1cd89062566a128a0db2145ca042d787e \ + --hash=sha256:dbc2673f9223d420c91145599b3ba45a8a50c207d1976908e5fb5ddb0c9b9429 \ + --hash=sha256:e01b3c878c8641913e688edd1b3f08658c6783d29cf6b826bd3c0d1ae7a1ffaa \ + --hash=sha256:e21c1429e205828ea886a2293a4a2c8e01f4c25d9893ca330e97a6cf73f52e7b \ + --hash=sha256:e43d4a1f673e8a1cbd8533e809e02b4bf9d4f2280269bb640436556312121250 \ + --hash=sha256:e6d198bad4e49dd6732fbd636e2fc5c082f45c8cad0b4acb756b00c82c76072e \ + --hash=sha256:e6ea1cda8d8c688278430e4268a42f5e5da3bdd74578dfadc0820c3f1766ce83 \ + --hash=sha256:ea394a937f17a54c51239348bdbe2e3518124c8d4a8951ba04a311d3095bd18f \ + --hash=sha256:eac2f5dbafd585dfe31f86a23ebf0d3ba480a9d49ebc87947267b5608d4ea0cd \ + --hash=sha256:eb61be926bb81567c1f48bdc8aa22b9855048dc2efd53871f9f7e6e9a5632346 \ + --hash=sha256:eba5d173f7d5708b22a93815017a4611873ed54db9f268077c0dd1ed99cfc858 \ + --hash=sha256:ec450527cbf485e13c8d3602a54f428ab0432fdade0ede75efd74b735421c871 \ + --hash=sha256:eef6a03b0b6d08d0835ccfa8ec8d1bc70525e3801387567137b50c557695e6da \ + --hash=sha256:ef0d8c843e2827d6c120ab4687e9423fb1d893db1df27b7c1506615bcb9734a0 \ + --hash=sha256:ef6b65b03247c54692ad4fd9ee97cb772781927db72e3cb05e70b3db6d1ff14f \ + --hash=sha256:f3d6ed6a98cfd19155996605474982cc470d7601746a6439078f1a5a3fa8b050 \ + --hash=sha256:fce4b85234a0cbad67bf8e6e1201ee815d172c9aebad75f25645bc4d834f8e31 \ + --hash=sha256:fda1d96e542c37b6c804547dbf489c129fe7c97183a76a5ec275909ba1a063df \ + --hash=sha256:fdcd198979b4ecffcc1beba366a7fbcf4eb41243691a82fe52ceb0b902f09c12 \ + --hash=sha256:fe5ad0664ec772b02c45859041aa17655709cced7a31005817fbbbd988c25567 + # via + # jsonschema + # referencing +six==1.17.0 \ + --hash=sha256:4721f391ed90541fddacab5acf947aa0d3dc7d27b2e1e8eda2be8970586c3274 \ + --hash=sha256:ff70335d468e7eb6ec65b95b99d3a2836546063f63acc5171de367e834932a81 + # via + # html5lib + # markdownify +socksio==1.0.0 \ + --hash=sha256:95dc1f15f9b34e8d7b16f06d74b8ccf48f609af32ab33c608d08761c5dcbb1f3 \ + --hash=sha256:f88beb3da5b5c38b9890469de67d0cb0f9d494b78b106ca1845f96c10b91c4ac + # via httpx +soupsieve==3.0.3 \ + --hash=sha256:7dcf6022eed0399eb9934a75e020148f7a2024c37b7dfcd3cf2c5505d69c364e \ + --hash=sha256:fa30e3ba4809cb81ce1f3209f2fbe3e779fc445f0439bc147a0d7c4601743f21 + # via beautifulsoup4 +sse-starlette==3.5.0 \ + --hash=sha256:3e6e1070df3f0f5d9cea81496de92dbb72f6721871d99748ece67441dd8b7997 \ + --hash=sha256:75de713aa8a9441513cc283220826da079d982770965b951e9437720e8bafdb2 + # via mcp +starlette==1.9.0 \ + --hash=sha256:3d931de246ed870e35ce605974440816ef895e592f255d1396cfdf191d4c4318 \ + --hash=sha256:fd3f159936e882d06c1108f84688f7cda2cf85fc6a592a50edbd175e882c2ddc + # via + # mcp + # sse-starlette +truststore==0.10.5 ; sys_platform != 'emscripten' \ + --hash=sha256:30d36967ccaded5cbb38d602c433f53600036c79d502f4533a49b60a03bbefcd \ + --hash=sha256:9aaaedaefaf06d8b206278cf8b5012bc897f485a874503501e12d776df78951c + # via + # httpcore2 + # httpx2 +typing-extensions==4.16.0 \ + --hash=sha256:481caa481374e813c1b176ada14e97f1f67a4539ce9cfeb3f350d78d6370c2e8 \ + --hash=sha256:dc983d19a509c94dba722ee6abd33940f7c05a89e243c47e907eb4db6f1a43e5 + # via + # anyio + # beautifulsoup4 + # mcp + # mcp-types + # opentelemetry-api + # pydantic + # pydantic-core + # typing-inspection +typing-inspection==0.4.4 \ + --hash=sha256:547274fa6b0a561ccf549cc9524b999a578e737d015d8709d021f9d0d13bea47 \ + --hash=sha256:65b8397ba37ccbce054456aaccddfc91e6e3083c92824df348d96ca832f3f147 + # via + # mcp + # pydantic +urllib3==2.8.0 \ + --hash=sha256:0cf3cae568d36aa9576b28dfb35f11328f1cb974ca7647d9475ebb86c75ac6e3 \ + --hash=sha256:63bf2ead4c879426ebf22ef2a781eeb4aa3b4ae798a0435506f8687fd5bb9b63 + # via requests +uvicorn==0.54.0 ; sys_platform != 'emscripten' \ + --hash=sha256:505bdb0f318731d45f1f712071fc781a8981f6847a31c902c9f5e652d4f67faf \ + --hash=sha256:a2e33cbfaa0306f8e6b0c13e0cb89d7d7a2da3e62b90c66e18c33d9807b28620 + # via mcp +webencodings==0.6.1 \ + --hash=sha256:565f9ad031c702dae404e27a099e3e09186a3ab1b9520f06d215502b651fd910 \ + --hash=sha256:7fab6269c8bf237c657876b52058ccb182e861518d1c695c1a9aaa8c1c105d5b + # via html5lib diff --git a/benchmarks/sandbox/run.sh b/benchmarks/sandbox/run.sh new file mode 100755 index 00000000..cfd58f90 --- /dev/null +++ b/benchmarks/sandbox/run.sh @@ -0,0 +1,35 @@ +#!/usr/bin/env bash +# Build the sandbox image from HEAD, pull the pinned proxy, then run agentic-run in containers. +# A dry run unless the operator adds the live flag. IMAGE=sha256:... skips the build (the +# air-gapped arm). +# KEYS_FILE (default .env.local) is read only by the container launcher, one key per worker, +# into a bootstrap frame on that worker's stdin. +set -euo pipefail +for name in ANTHROPIC_API_KEY OPENAI_API_KEY GOOGLE_API_KEY; do + if [[ -n ${!name:-} ]]; then + echo "run.sh: unset $name before starting the sandbox" >&2 + exit 2 + fi +done +cd "$(git rev-parse --show-toplevel)" +for tool in git docker uv cat; do + command -v "$tool" >/dev/null || { echo "run.sh: $tool not found" >&2; exit 2; } +done +sandbox_docker() { + uv run --locked python -c ' +import os, sys +from benchmarks.agentic.sandbox import cli_env +os.execvpe("docker", ["docker", *sys.argv[1:]], cli_env(os.environ)) +' "$@" +} +if [ -z "${IMAGE:-}" ]; then + iid=$(mktemp) + trap 'rm -f "$iid"' EXIT + git archive --format=tar HEAD | sandbox_docker build --file benchmarks/sandbox/Dockerfile \ + --label "org.opencontainers.image.revision=$(git rev-parse HEAD)" --iidfile "$iid" - + IMAGE=$(cat "$iid"); rm -f "$iid"; trap - EXIT + sandbox_docker pull "$(uv run --locked python -c 'from benchmarks.agentic.sandbox import SQUID_IMAGE; print(SQUID_IMAGE)')" +fi +echo "run.sh: image $IMAGE" >&2 +exec uv run --locked python -m benchmarks agentic-run --launcher container --image "$IMAGE" \ + --keys-file "${KEYS_FILE:-.env.local}" "$@" diff --git a/docs/benchmarks/AGENTIC-BENCHMARK-DESIGN.md b/docs/benchmarks/AGENTIC-BENCHMARK-DESIGN.md index 3ef6585e..55f11321 100644 --- a/docs/benchmarks/AGENTIC-BENCHMARK-DESIGN.md +++ b/docs/benchmarks/AGENTIC-BENCHMARK-DESIGN.md @@ -265,6 +265,57 @@ came from. Container settings: key value and fails the step if the key appears. On the host, the harness also scans every artifact for key-shaped strings (each provider's key prefixes) and fails the run on a match. +- Before each model-call spend reservation, the shared trajectory loop checks the + complete provider-rendered conversation, including native replay. MCP results + are checked before canonicalization and truncation, and again after rendering; + errors are checked before retry or publication. A match aborts with a clean + diagnostic and no transcript, without another provider call or reservation. + The worker reuses its private literal-key check alongside the key-shape scans, + including keys embedded in longer tokens or without a provider shape. Only a + checker callback reaches the content renderers and MCP bridge; the key stays + in the worker. Every tool call in a turn is checked before the first dispatch, + after settling the returned provider usage. Native function arguments are + checked both raw and as decoded JSON strings, including scalars, invalid + arguments and values hidden by duplicate object keys; replay keeps the raw + argument string. One frame-bounded, non-overlapping scan checks quoted strings + independently of document validity, including trailing text and the decodable + prefix of an unfinished string. Each token is decoded with the standard library; + incomplete or invalid escapes fail closed after checking their completed prefix. + The scan does not parse document structure or retry from interior quotes. + Integer conversion and nesting-limit failures during adapter normalization keep + the raw argument as invalid input so the loop can settle returned usage first. + JSON argument strings are limited to 64 nested objects/arrays, counting the root, + before decoding, so accepted arguments fit recursive transcript serialization + and MCP validation on supported Pythons. Deeper arguments follow the same invalid + input path, retaining exact native replay and evidence; the content scan still + checks the entire string, including values shadowed by duplicate object keys. + A content failure does not replace known usage with a lost worker charge. + Both the full MCP envelope and the truncated result are checked. Gemini + content scanning includes the SDK's ASCII JSON escaping before reservation. + Provider settings also pass the worker's check before free model-limit discovery. + Private credential bootstrap frames and SDK authentication headers are outside + this content boundary. +- When the host recognizes a credential failure, it immediately stops fresh grants + across the invocation, including reservations waiting on another unit's provider + lock. Already granted units still settle or recover, and teardown and log + scrubbing finish before the original failure is reported. This stop does not + persist into a later invocation. + The host retains the recognized failure across sibling cleanup and attaches + redacted diagnostics from any storage errors. Operator interrupts take precedence. +- An MCP stdio reply above the frame limit aborts the run before the SDK closes + its connection. The worker settles any known usage. The host stops new grants + and withholds subsequent trajectory reports while it cleans up the workers. + Credential failures take precedence over frame-limit errors. Ordinary MCP + protocol errors keep their documented trajectory behavior. + SDK reader failures can cancel their own job while it awaits a host grant or + settlement reply. The worker drains that job and reports the recognized failure. + An external cancellation instead cancels and drains the owned job, then propagates + the original interrupt, including when the SDK has also recognized a failure. +- On protocol EOF the host waits for the owned worker's terminal status, up to + five seconds or the configured silence timeout, whichever is shorter. Status + 3 reports a credential failure. Status 4 reports a frame-limit failure even + if the host cannot read the final error frame. The host uses its ordinary + loss accounting for other worker deaths and timeouts. ### 7.4 Air-gapped arm (**Call**) diff --git a/docs/benchmarks/SANDBOX-RUNBOOK.md b/docs/benchmarks/SANDBOX-RUNBOOK.md new file mode 100644 index 00000000..33ee0270 --- /dev/null +++ b/docs/benchmarks/SANDBOX-RUNBOOK.md @@ -0,0 +1,313 @@ +# Agentic benchmark sandbox: operator runbook + +How the maintainer runs the agentic benchmark in its sandbox (design §§7.2–7.4, §12, §14). +Every live call in this runbook is the maintainer's, after PR 4 merges. An implementer never +runs one. Every `run.sh` command names its models with `--models`. + +`benchmarks/sandbox/run.sh` builds the worker image from `git archive HEAD`, pulls the +pinned Squid image, and runs `agentic-run --launcher container`. It is a dry run unless you +add `--live`. + +## 1. Prerequisites + +- Docker Desktop 4.96.1 or newer (Engine 28.0 or newer), with the context `desktop-linux`. + The sandbox refuses any daemon that is not a local `unix://` socket, including a + `DOCKER_HOST` that points elsewhere. +- No `proxies` key in `~/.docker/config.json`. The docker CLI would put those proxy + variables into every new container, and the isolation probe then refuses the run. +- The docs index built for 3.10–3.14 (CONTRIBUTING §3): + `uv run python-docs-mcp-server build-index --versions 3.10,3.11,3.12,3.13,3.14`. +- A keys file, mode 600, outside any commit (`.env.local` by default, which `.gitignore` + covers): one `NAME=VALUE` line per provider key. `chmod 600 .env.local`. +- Use a new, empty output directory outside the checkout for each run (for example, + `"$HOME/benchmark-runs/smoke"`). The host writes evidence before it checks the tree. +- A clean checkout: the image must hold exactly the commit you run. `run.sh` builds from + `HEAD`, and the launcher refuses a dirty tree or an image built from another commit. + +## 2. Where keys live + +- The host creates each stopped worker by ID after all isolation probes pass. It attaches + stdin to that ID with `docker start -ai` and removes the same ID on teardown. +- A key exists in the host process's memory during validation and bootstrap, and in the + environment of the one worker process that uses it. +- The host reads the one key a worker needs from the keys file after the authorization + gate and after every isolation probe passed. It checks every planned key before starting + any worker, then rereads the matching key for each launch. It writes the key as a bootstrap frame on + that worker's stdin, before the job frame. The worker puts it in its own environment, in + memory, before it protects its output or imports any SDK. +- A key is never in a container's environment or config (`docker inspect`), never in the + docker CLI's environment (`ps -E`), never in argv, and never in any file but the keys + file. The host's own environment never holds one. +- This is a recorded departure from design §7.3, which passed keys with `--env-file` + (#200, ruling A1): Docker stores `-e` and `--env-file` values in the container config. + +MCP stdout replies are checked for literal worker credentials and key-shaped strings +before JSON-RPC parsing, result conversion or tool output-schema validation can drop +fields. This includes malformed replies, error details, tool listings and handshake +data. A detected credential ends the worker with exit 3 and stops new grants across +the run; already granted calls still settle and clean diagnostics are retained. +Task-group and chained exceptions cannot turn that detection into a scored MCP crash. +Clean replies keep the SDK's normal validation outcomes, including malformed +structure or trailing text whose strings can be inspected. Quoted fields are +checked independently of JSON structure, including duplicate fields and unfinished +strings. Broken escapes with an uninspectable suffix fail closed using the same +credential-failure path; no such content is replayed or published. Tool arguments +use this same bounded scan after returned provider usage has settled; integer and +nesting-limit errors are retained as invalid raw arguments, without losing usage. +Each stdout line is limited to 64 MiB, with no queued reply buffer, and subprocess +shutdown remains bounded. + +A reply with invalid text encoding stops the run after the worker checks its readable prefix. + +## 3. Dry run + +```bash +benchmarks/sandbox/run.sh --models claude-sonnet-5-5,gpt-6.1-sol,gemini-3.8-flash \ + --corpus docs/benchmarks/corpus.yml --out +``` + +It builds the image, plans every cell and writes the plan, and opens no ledger and no +container. + +For dry and live runs, `agentic-run` plans from the same corpus, manifest, matrix and +price snapshot bytes that it copies to `snapshots/`. A key-shaped CLI argument or YAML +input stops the command with exit code 3 before it writes snapshots or opens the ledger. +The check includes YAML comments and decoded scalars, even values a merge or duplicate +key overrides. + +## 4. Order of the first live calls + +#200 ruling 4, as amended by round-2 ruling D10: + +1. the keyless docker test (section 5), before any live call; +2. the ~$1 smoke run (section 6), once PR 4 is merged. It checks the plumbing and the model + limits (`run-summary.json` `model_limits_mismatch`) and produces no reported number; +3. G1, after PR 5; +4. the pilot (section 7). + +G1 still gates the pilot and every reported number. + +## 5. Keyless docker test + +```bash +IID=$(mktemp) +git archive --format=tar HEAD | docker build --file benchmarks/sandbox/Dockerfile \ + --label "org.opencontainers.image.revision=$(git rev-parse HEAD)" --iidfile "$IID" - +docker pull "$(uv run --locked python -c 'from benchmarks.agentic.sandbox import SQUID_IMAGE; print(SQUID_IMAGE)')" +BENCHMARK_DOCKER_TESTS=1 BENCHMARK_SANDBOX_IMAGE="$(cat "$IID")" \ + uv run --locked pytest tests/benchmarks/test_agentic_sandbox_docker.py -q +``` + +It uses scripted models only, with no key and no provider call, on a clean checkout. + +### Docker Desktop results + +First run: 2026-11-04, Docker Desktop on Apple silicon (context `desktop-linux`, Engine +29.9.2), worker image built from `05e2ff8`, Squid image by its pinned digest. Result: +7 passed, and no container or network with the run label remained. + +| Behaviour (#200 record) | Result | +|---|---| +| Internal-network reach to the Mac | None. From a job's internal network, `host.docker.internal` and `gateway.docker.internal` do not resolve (`gaierror`), and the Mac's LAN address (192.168.1.28) gives `OSError`, on the canary port and on 11434. The canary never saw the probe's token. | +| The control probe | A container on the outside network reached the host canary through `host.docker.internal`, so the silent canary above is meaningful. | +| DNS on internal networks | `pypi.org` does not resolve (`gaierror`). The strict DNS check passed: **no #200 ruling 5 fallback was needed.** | +| `--ipv6=false` on Desktop | Honoured: `EnableIPv6` is false. The isolated gateway mode assigns no IPAM gateway address, so the probe has no gateway to try. | +| `host.docker.internal` against a 127.0.0.1 bind | Reachable through the proxy: a service bound to the Mac's 127.0.0.1 only answered 200 to a GET through an egress allowing it. Ollama's default bind should work for the air-gapped arm; ruling 7's `OLLAMA_HOST=0.0.0.0` fallback stays for the case where the probe's Ollama check fails. | +| Large attached worker output | A trajectory frame over 150,000 bytes round-tripped intact with the original `docker run -i` launcher and again on November 4 with `docker create` followed by `docker start -ai`. | +| Attach with `--log-driver none` | Works: every worker frame and reply passed over the attached stdin and stdout. | +| Squid writing to the bind mount | The #200 run produced `access.log` and `cache.log` (mode 640) on the mounted volume, with one access-log line per connection attempt. | +| Squid's exit after `docker stop` | Exit code 0, `Running` false, "Exiting normally", within `shutdown_lifetime`. | +| IP literal whose PTR names an allowed host | Denied: a `CONNECT 127.0.0.1:443` through an egress allowing `localhost:443` got 403 and logged `TCP_DENIED_ABORTED` (the probe closes after reading the status line). | +| Proxies in the docker CLI config | A `config.json` with `proxies` makes the CLI inject `HTTPS_PROXY` into the probe container, and the isolation probe refuses the run, naming it. | + +Two observations for the owner: + +- The image tagged `6.6-24.04_edge` at the pinned digest runs **Squid 6.14** + ("Starting Squid Cache version 6.14"), not 6.6. Every directive used here works, and the + exit status after SIGTERM is 0. +- Squid's ICMP `pinger` helper cannot start without `NET_RAW` (`cache.log`: "Unable to + open any ICMP sockets"). The proxy runs normally without it. + +## 6. Smoke run (design §14) + +One question, k = 1, every system: + +```bash +benchmarks/sandbox/run.sh --models claude-sonnet-5-5,gpt-6.1-sol,gemini-3.8-flash \ + --corpus docs/benchmarks/corpus.yml --questions --repeats 1 --out --live +``` + +The run shows each provider's spend, cap, remaining budget and estimate, and starts only +after you type `yes` at the terminal. It refuses under `CI`. Then read +`run-summary.json` `model_limits_mismatch` and correct `docs/benchmarks/model-matrix.yml` +by hand in a docs PR if it lists anything. + +## 7. Pilot + +The 10 fixed questions, k = 3, every system: + +```bash +benchmarks/sandbox/run.sh --models claude-sonnet-5-5,gpt-6.1-sol,gemini-3.8-flash \ + --corpus docs/benchmarks/corpus.yml --questions <10 ids> --repeats 3 --out --live +``` + +That is 90 trajectories per provider, the most a run may plan without a reference run. + +## 8. Full run + +```bash +benchmarks/sandbox/run.sh --models claude-sonnet-5-5,gpt-6.1-sol,gemini-3.8-flash \ + --corpus docs/benchmarks/corpus.yml --out --reference-run --live +``` + +The full-run gate scales the pilot's cost and time per logical cell (every attempt of a +cell included) by 1.25. It refuses a provider whose estimate is over its remaining cap and +a model whose time is over 24 hours. When it refuses, choose fewer repeats or fewer +questions before you run, and disclose that choice with the results. + +Each scored or discarded transcript records `execution.provider`, `execution.model_id` +and `execution.api` from the client instantiated by the worker. A reference must prove +all three agree with its saved model matrix and the requested family. Scripted responses +cannot supply live rates. Older pilots without executed identity are rejected; rerun the +pilot to obtain auditable evidence rather than adding an API label to old transcripts. +Local Ollama timing references need the same identity evidence, even though they are +unmetered. Grant waits remain excluded, and discarded attempts count toward cost and time. + +The host retains a `transcript_inventory` in `run-summary.json`: the SHA256 of each exact +published scored or discarded JSON file, its relative path and its immutable cell, +question, system, family, provider, model, repeat and trajectory-attempt coordinates. +The reference reader checks these against the same captured bytes it parses before +using any timing or charges. Replacing a single file from another pilot, including one +with the same run label, fails closed. Missing inventories, missing files, extra files +and changed bytes are refused with an inventory or SHA256 diagnostic. Produce a new +pilot with the current runner for older evidence; adding hashes after a restore cannot +establish which bytes the host originally published. Copying a complete intact pilot +to another directory and regenerating scoring, token or report artifacts remain supported. +This is a consistency check for partial restores or edits, without signing infrastructure; +deliberately forging the entire unsigned evidence bundle is outside its scope. + +Every actual model-call attempt must have a unique `unit_id`. For metered providers, +that ID must join to exactly one reservation and settlement in the summary's `run_id`, +with the same provider, family/system job and model. Execution identity establishes the +API; a recorded request model must agree too. Outcomes, usage, booked charges and summary +balances must reconcile, including retries and discarded trajectories. Mixed pilot +channels, missing attempt IDs and contradictory accounting are refused before estimation. +This checks consistency using existing producer IDs; it does not require signed records. +Local calls have no spend events, and opening recovery settlements for older pending units +remain part of `spent_before`, outside the current pilot's rate. + +Reference summaries, matrices, scored and discarded transcripts, and ledger JSONL are +scanned as raw bytes and decoded values before validation can quote them. YAML values +hidden by aliases or merge overrides and overwritten JSON values are included. Both dry +and live runs validate an explicit `--reference-run`; a key-shaped value stops the CLI +with exit 3 before confirmation or any provider call, with no key in the diagnostic. + +## 9. Artifacts + +- `egress/summary.json`: the C1 evidence, read by PR 5. +- `egress//` holds the public `squid.conf`, the scanned `access.log` and `cache.log`, + and `collected.json` with the stop state and collection result. +- `probe/.json` and `probe/control.json`: the isolation probe records. +- `sandbox.json`: the image, its revision, the proxy image, the engine version, and the + docker context and endpoint. +- `airgap/checks.json` (the C3 evidence, read by PR 5) and `airgap/records.jsonl` (every + check round). +- `ollama.json`: the Ollama version, the model's digest and details, and its context. + +Worker stderr stays in an unlinked file until teardown. The host publishes a scrubbed +snapshot in the run directory after stopping the worker. A snapshot over 8 MiB fails +the run and leaves that worker without a public stderr log. The ledger still accounts +for its open reservation. + +Squid writes to a job-specific temporary spool outside the run directory. Its parent is +mode 0700. Docker Desktop mounts only the writable child directory (mode 0777) and the +read-only config file. The probe reads the private access log and scans its record before +publishing the exact prefix used to separate probe traffic from query traffic. + +At close, the runner reads only regular `access.log` and `cache.log` files without +following symlinks. Each file has an 8 MiB limit on its logical size, including sparse +regions. If a log exceeds the limit or changes size during the read, the runner refuses +to publish it. Each public log appears by atomic rename after its key scan. A key +match fails the run even if writing the scrubbed log fails. The runner removes the private +spool on teardown. A `probe/.collection-pending` marker means collection is +incomplete or failed and C1 cannot pass, even if some public files are present. + +If a Docker state field or other collection diagnostic contains a key-shaped string, +`collected.json` records a failed collection and omits the state details. The runner +continues closing the remaining jobs and the outside network. Check the reported +resource IDs if a removal failed, even when the runner could not publish the record. + +The last four access-log fields record the client status (`%>Hs`), result (`%Ss`), +hierarchy (`%Sh`), and next-hop HTTP status (`% benchmarks/sandbox/run.sh --models gemma4-12b --systems python-docs,no-docs \ + --corpus docs/benchmarks/corpus.yml --questions <5 ids> --repeats 1 --out --live + ``` + + If tool calls fail often, stop and report: design §14 names `gemma4:e4b` or a stronger + machine. +7. Run the arm with all 50 questions, k = 3, a new `--out`, and + `--reference-run ` to check the 24-hour window. If the model changes, + run its smoke sample first and use that directory as the reference. + +If the probe's Ollama check fails, set `OLLAMA_HOST=0.0.0.0:11434` for this arm only, +while the Mac is offline, and revert it afterwards (#200 ruling 7). + +## 11. Cleanup + +```bash +docker ps -a --filter label=org.python-docs-mcp.benchmark-run= +docker network ls --filter label=org.python-docs-mcp.benchmark-run= +``` + +The first managed SIGTERM or SIGHUP stops the run. Docker management commands have +their own process group and do not read terminal input, so a later foreground signal +does not interrupt rollback. Worker cleanup failures are reported on stderr with the +job ID. + +After cleanup both lists should be empty. A run ID can be reused. If a resource remains, +match its full container or network ID, or the exact invocation-specific +`org.python-docs-mcp.benchmark-resource` label from the cleanup diagnostic, to the +stopped invocation before removing it by ID. diff --git a/docs/benchmarks/agentic-manifest.yml b/docs/benchmarks/agentic-manifest.yml index eb7d41e6..98d1a841 100644 --- a/docs/benchmarks/agentic-manifest.yml +++ b/docs/benchmarks/agentic-manifest.yml @@ -11,7 +11,9 @@ # - adapter: `mcp-stdio` (a stdio MCP server) or `none` (no tools). # - command: argv of the server; "{python}" is replaced by the worker's # interpreter at spawn. -# - env: variables set for the server. +# - env: variables set for the server. The value "{egress}" is replaced by the +# run's egress proxy URL (BENCHMARK_EGRESS_URL in the sandbox), and the +# variable is dropped when there is none. # - pass_env: variables copied from the worker's environment when present. # The server gets these two and the MCP SDK's default set, nothing else. schema_version: 1 @@ -24,16 +26,23 @@ competitors: env: # Never let a missing index trigger the server's network auto-build. PYTHON_DOCS_MCP_DISABLE_AUTO_INDEX: "1" + # lookup_package_docs reaches PyPI only through the egress proxy, which + # logs the attempt as denied (design section 5, C1). + HTTPS_PROXY: "{egress}" + HTTP_PROXY: "{egress}" pass_env: [HOME, XDG_CACHE_HOME] - id: docs-fetch name: mcp-server-fetch, limited to docs.python.org by the egress proxy adapter: mcp-stdio - # No flags: keep the robots.txt default (design section 5.1). Its version is - # pinned in PR 4's sandbox image. + # No flags: keep the robots.txt default (design section 5.1). The sandbox + # image installs mcp-server-fetch 2026.10.19 from the hashed + # benchmarks/sandbox/fetch-requirements.txt. command: [mcp-server-fetch] - env: {} - pass_env: [HOME, HTTPS_PROXY, HTTP_PROXY, NO_PROXY] + env: + HTTPS_PROXY: "{egress}" + HTTP_PROXY: "{egress}" + pass_env: [HOME] - id: no-docs name: No documentation tools (correctness floor) diff --git a/docs/benchmarks/model-matrix.yml b/docs/benchmarks/model-matrix.yml index ce9eff1a..68b4a9cf 100644 --- a/docs/benchmarks/model-matrix.yml +++ b/docs/benchmarks/model-matrix.yml @@ -61,8 +61,9 @@ model_families: Provider default effort; no sampling parameters (Claude 5.5 rejects them). Adaptive thinking is on by default and cannot be disabled; the documented default effort is `high`. - # Documented as "1M tokens". The exact integer needs the Models API, - # which PR 4's smoke run reads. + # Documented as "1M tokens". The exact integer needs the Models API: each + # live worker reads it at startup, and the smoke run's run-summary.json + # lists any difference under model_limits_mismatch. max_input_tokens: 1000000 # Documented maximum 128,000. max_output_tokens: 32768 @@ -143,6 +144,10 @@ model_families: seven tool schemas plus a docs result, and the OpenAI-compatible endpoint cannot change it per request). 12B fits the maintainer's 16 GB M1 Pro; 26B and 31B do not. + # The loop's per-call bounds need both; neither is ever sent to Ollama + # (Ollama defaults, no max_tokens) and the unit is never priced. + max_output_tokens: 32768 + framing_allowance_tokens: 256 headline_eligible: false headline_ineligibility_reason: >- No live benchmark run has been executed against this model family yet; diff --git a/docs/plans/2026-11-04-agentic-sandbox-runner.md b/docs/plans/2026-11-04-agentic-sandbox-runner.md index 8af88767..8363ae22 100644 --- a/docs/plans/2026-11-04-agentic-sandbox-runner.md +++ b/docs/plans/2026-11-04-agentic-sandbox-runner.md @@ -41,9 +41,9 @@ them. reads. **Tech Stack:** -- Python ≥ 3.12 on the host; the worker image runs CPython 3.14.8. +- Python ≥ 3.12 on the host; the worker image runs CPython 3.14.10. - Docker Desktop for Mac ≥ 4.96.1 (Engine ≥ 28.0, for the isolated - gateway mode); Squid 6.6 (`ubuntu/squid`); uv 0.13.4; `mcp-server-fetch` + gateway mode); Squid 6.14 (`ubuntu/squid`); uv 0.13.4; `mcp-server-fetch` 2026.10.19 in its own hashed venv inside the image. - `openai` 3.32.0 (already in the dev group) for Ollama's OpenAI-compatible endpoint. No new Python dependency. @@ -96,7 +96,7 @@ Executors read the design §7, the sandbox note and - **Egress (design §7.3):** - One Squid per job, on that job's internal network (`--internal --ipv6=false -o com.docker.network.bridge.gateway_mode_ipv4=isolated`) under the alias `egress`, and on one shared outside network per run. - Allowlist: the job's provider API host on 443 (none for scripted), plus `docs.python.org:443` for `docs-fetch`. The air-gapped arm allows only `host.docker.internal:11434`. Every allowlist ACL is `dstdomain -n`. No TLS interception. - - Squid writes its access log to a bind-mounted file with no rotation: one line per connection attempt (time, client, method, host, port, status, Squid result). + - Squid writes its access log to a bind-mounted file with no rotation: one line per connection attempt (time, client, method, host, port, client status, Squid result, hierarchy, peer status). - **Evidence for PR 5** (#199, owner question 9): - `/egress/summary.json` is `{"jobs": {job_id: {"hosts_allowed": [...], "hosts_denied": [...], "lookup_package_docs_attempts": n}}, "isolation_probe": "pass"|"fail"}`. - `/airgap/checks.json` is `{"all_passed": bool, "checks": n, "internet_hosts": [...]}`. @@ -104,11 +104,11 @@ Executors read the design §7, the sandbox note and - **Authorization gate** (round-2 ruling D9): `live.authorize_live` is the one host-side check for every live entry point. It runs before any key is read and before any keyed container starts. It refuses when `CI` is set to a truthy value, and it requires an interactive `yes`. - **One free request outside the ledger:** at startup, a live Anthropic or Gemini worker makes one models-retrieve GET (free, not billable) and reports `model_limits` (round-2 ruling D10). Every billable call keeps exactly one request per reserved unit. - **Pins** (sandbox note §A), unchanged without an owner ruling: - - `python:3.14.8-slim-trixie@sha256:fbecd461fc72d21b2143c6eaba25143738079154a6d0ea3da3aec724f50eed4a` + - `python:3.14.10-slim-trixie@sha256:930e1abba7c4e8f96ed93e8012c35d174d7732752731bbd5e8e757d7ec6f3966` - `ghcr.io/astral-sh/uv:0.13.4@sha256:9f130421e930bfbdc563c00740466603f8723158e90297d07957c2294640262b` - `ubuntu/squid:6.6-24.04_edge@sha256:8a3baed477e2c282ab8aa5edad442f69873246964f225c5c2ae8364b6610963c` - `mcp-server-fetch==2026.10.19`, every transitive package hash-pinned and published on or before 2026-10-21. - - The two young pins (the Python image and `mcp-server-fetch`) are re-checked at implementation time (#200 ruling). Before Task 7, the implementer also checks https://www.python.org/downloads/ for a CPython 3.14.9+ security fix. If one exists and is at least 14 days old, they raise it in the PR body instead of switching silently. + - The owner selected Python 3.14.10 under the security exception for CVE-2026-115557 and CVE-2026-114583. The sandbox research note records the release advisory and image digest. The fetch pin meets the 14-day rule. - **Platform:** Docker Desktop for Mac only (context `desktop-linux`), Engine ≥ 28.0. Podman and Colima are out of scope for round 1. - **Local daemon only** (round-3 item 4): `verify_image` refuses unless the active context's endpoint and any `DOCKER_HOST` are `unix://`. A bootstrap frame therefore never crosses a network to a remote daemon. - **Dependencies:** no change to `pyproject.toml` or `uv.lock`. `mcp-server-fetch` lives only in the image's `/opt/fetch` venv, from a hashed requirements file. @@ -601,8 +601,9 @@ async def test_a_failing_stop_worker_still_scrubs_the_log_and_settles_the_unit(t async def test_close_problems_fail_a_clean_run(tmp_path) -> None # tests/benchmarks/test_agentic_run.py (ledger-events.jsonl is written only by write_outcome) def test_every_reserve_event_names_its_job(tmp_path) -> None - # a scripted two-job run_agentic: every "reserve" event in the run's ledger-events.jsonl has job_id - # equal to the job that reserved it + # a scripted two-job run_agentic with two families of different providers (scripted-anthropic, + # scripted-openai): every "reserve" event in the run's ledger-events.jsonl has job_id equal to + # the job that reserved it, and that job's family belongs to the event's provider (amendment 5) # tests/benchmarks/test_agentic_ledger.py def test_reserve_events_without_job_id_still_load(tmp_path) -> None # Ledger.reserve without job_id writes job_id None; and a .jsonl whose reserve lines lack @@ -704,7 +705,7 @@ The Dockerfile is fixed copy. There is deliberately no `# syntax=` line, because that would pull an unpinned frontend image: ```dockerfile -FROM python:3.14.8-slim-trixie@sha256:fbecd461fc72d21b2143c6eaba25143738079154a6d0ea3da3aec724f50eed4a +FROM python:3.14.10-slim-trixie@sha256:930e1abba7c4e8f96ed93e8012c35d174d7732752731bbd5e8e757d7ec6f3966 COPY --from=ghcr.io/astral-sh/uv:0.13.4@sha256:9f130421e930bfbdc563c00740466603f8723158e90297d07957c2294640262b /uv /uvx /bin/ ENV UV_COMPILE_BYTECODE=1 UV_LINK_MODE=copy UV_PYTHON_DOWNLOADS=0 PYTHONDONTWRITEBYTECODE=1 WORKDIR /app @@ -771,8 +772,8 @@ Expected: `10001`, `/usr/bin/cat`, `/usr/local/bin/mcp-server-fetch`, `no-env-fi - Produces: - `EGRESS_ALIAS = "egress"`, `EGRESS_PORT = 3128`, `EGRESS_URL = "http://egress:3128"`, `LOG_DIR_IN_PROXY = "/var/log/squid-bench"`. - `PROVIDER_HOSTS = {"anthropic": (("api.anthropic.com", 443),), "openai": (("api.openai.com", 443),), "google": (("generativelanguage.googleapis.com", 443),), "ollama": (("host.docker.internal", 11434),)}` and `SYSTEM_HOSTS = {"docs-fetch": (("docs.python.org", 443),)}`. These are the pinned base URLs in `clients.py` (Anthropic, OpenAI, Gemini) and design §7.4. - - `allowlist(family: ModelFamily, system_id: str | None) -> tuple[tuple[str, int], ...]`: the provider's hosts unless `family.api == "scripted"`, plus `SYSTEM_HOSTS.get(system_id, ())`, in that order. - - `@dataclass(frozen=True) class ProxyEvent: at: str; client: str; method: str; host: str; port: int; status: int; result: str`, with property `allowed: bool` (`not result.startswith("TCP_DENIED")`) and property `target: str` (`f"{host}:{port}"`). + - `allowlist(family: ModelFamily, system_id: str | None) -> tuple[tuple[str, int], ...]`: the provider's hosts unless `family.api == "scripted"`, plus `SYSTEM_HOSTS.get(system_id, ())` for hosted jobs only, in that order. The air-gapped arm permits only local Ollama and the `python-docs` and `no-docs` systems. + - `ProxyEvent` records time, client, method, host, port, client status, result, hierarchy and next-hop HTTP status. Seven-field logs predate the last two fields. Its `target` property formats the requested host and port. - `parse_proxy_log(text: str) -> list[ProxyEvent]`. It needs every line to end with `\n`. It raises `BenchmarkValidationError` naming the line number on a malformed or unterminated line. - `FORBIDDEN_ENV = re.compile(r"(?i)^(?:\w*_proxy|ssl_cert_\w*|requests_ca_bundle)$")` and `forbidden_env_names(environ: Mapping[str, str]) -> list[str]` (sorted names, never values). @@ -844,7 +845,7 @@ cache deny all shutdown_lifetime 1 seconds httpd_suppress_version_string on logfile_rotate 0 -logformat bench %{%Y-%m-%dT%H:%M:%S}tg.%03tuZ %>a %rm %>rd %>rP %>Hs %Ss +logformat bench %{%Y-%m-%dT%H:%M:%S}tg.%03tuZ %>a %rm %>rd %>rP %>Hs %Ss %Sh % dict[str, str]`: the docker CLI allowlist in Global Constraints. It never holds a key. - `@dataclass(frozen=True) class SandboxConfig: image: str; run_id: str; out_dir: Path; index_path: Path; keys_file: Path | None; repo_commit: str`. `__post_init__` refuses an `image` that does not match `^sha256:[0-9a-f]{64}$`. - `@dataclass(frozen=True) class Egress: job_id: str; network: str; proxy: str; allow: tuple[tuple[str, int], ...]; log_dir: Path; gateways: tuple[str, ...]; inspect: dict[str, Any]`. - - `VerifyFn = Callable[[Sandbox], Awaitable[dict[str, str]]]`. + - `VerifyFn = Callable[["Sandbox"], Awaitable[dict[str, str]]]`, the forward reference quoted (amendment 4). - `async verify_image(sandbox: Sandbox, *, repo_root: Path = REPO_ROOT) -> dict[str, str]`, the real check, as a module function (`REPO_ROOT` is the checkout root, computed like `run._REPO_ROOT`). All of these must hold, checked before any container starts: - `docker context inspect --format '{{.Endpoints.docker.Host}}'` (the active context) gives an endpoint starting `unix://`, and `DOCKER_HOST`, when set in `cli_env`, also starts `unix://` (round-3 item 4); - `docker image inspect` gives `Id == config.image` and the label `org.opencontainers.image.revision == config.repo_commit`; + - `docker image inspect` on `SQUID_IMAGE` succeeds: the pinned proxy image is present locally (amendment 2); - `docker version` gives a server version ≥ `MIN_ENGINE`; - - `git -C status --porcelain` is empty (the only dirty-tree check; `run.sh` has none). + - `git -C status --porcelain --untracked-files=normal` is empty, so a global `status.showUntrackedFiles=no` cannot hide an untracked file (amendment 1; the only dirty-tree check; `run.sh` has none). It writes `out_dir/sandbox.json` (image, revision, proxy image, engine version, docker context and endpoint). - `class Sandbox(config, docker: DockerRun | None = None, verify: VerifyFn = verify_image)`. `verify` is the test seam (round-4 item 2): production keeps the real check, and tests that only need to reach `prepare` pass a stub, so they work on a dirty checkout. PR 5's tests use the same seam. - `async open_egress(job_id: str, allow) -> Egress`: @@ -927,11 +929,12 @@ git commit -m "feat(benchmarks): Squid config with lookup-free allowlists and a 4. Create `log_dir = out_dir/egress//` with `mkdir(parents=True)`, then `log_dir.chmod(0o777)`, because `mkdir(mode=...)` is cut by the umask and Squid's uid differs from the host user's (round-3 item 3). Write `squid.conf` into it, then `chmod(0o644)` it, so Squid running as `proxy` can read it under umask 077 (round-4 item 4). 5. Start the proxy: `docker run -d --pull never --name --label RUN_LABEL= --network --read-only --tmpfs /run --tmpfs /var/spool/squid --cap-drop ALL --security-opt no-new-privileges --user proxy --memory 256m --cpus 0.5 --entrypoint /usr/sbin/squid --mount type=bind,src=/squid.conf,dst=/etc/squid/squid.conf,readonly --mount type=bind,src=,dst=/var/log/squid-bench SQUID_IMAGE -N -f /etc/squid/squid.conf`. 6. Run `docker network connect --alias egress `. + On any failure after the internal network exists (step 3 onwards, the proxy `docker run` and `network connect` included), remove the proxy (`docker rm -f`) and the network, then raise (amendment 2). - `container_argv(*, name: str, network: str, env: Mapping[str, str], mounts: Sequence[str], argv: Sequence[str], interactive: bool = True) -> list[str]`: the full `docker run` argv with the Global Constraints hardening, `--log-driver none` included (`-i` only when `interactive`). `env` becomes `-e NAME=VALUE` and each mount a `--mount`, then the image ID, then `argv`. It has no key parameter. - `async close_egress(egress: Egress) -> list[str]`: 1. `docker inspect --format '{{json .State}}' `, before our stop (round-3 item 1). The proxy ended abnormally when it is no longer `Running` (it ended on its own, for example exit 137 from a kill or an OOM) or `OOMKilled` is true. 2. `docker stop -t 5 `. Squid closes its log within `shutdown_lifetime`, and the access log is already on the host. - 3. Inspect `State` again. It must show `ExitCode == 0` and `OOMKilled` false (round-4 item 1). A healthy Squid exits 0 within `shutdown_lifetime 1 seconds`, well inside `-t 5` (sandbox note §C, from the Squid 6.6 source). Any non-zero exit after our stop is abnormal, including 137 from `docker stop`'s forced kill of a hung Squid, because the log may then be partial even when it is well formed. + 3. Inspect `State` again. It must show `Running` false (amendment 7), `ExitCode == 0` and `OOMKilled` false (round-4 item 1). A healthy Squid exits 0 within `shutdown_lifetime 1 seconds`, well inside `-t 5` (sandbox note §C, from the Squid 6.14 source). Any non-zero exit after our stop is abnormal, including 137 from `docker stop`'s forced kill of a hung Squid, because the log may then be partial even when it is well formed. 4. Check the key shape of `access.log` and `cache.log` with `redact_key_shaped`, rewriting a file in place when a pattern is found. 5. `docker rm -f `, then `docker network rm `. 6. Write `egress//collected.json` as `{"ok": bool, "problems": [...], "state_before_stop": {...}, "state_after_stop": {...}}`. `ok` is false after any failed step or an abnormal end. @@ -977,8 +980,8 @@ async def test_internal_networks_are_ipv4_only_with_an_isolated_gateway(tmp_path async def test_prepare_builds_one_network_and_proxy_per_job_with_a_file_log(tmp_path, monkeypatch) -> None # verify stubbed; one outside network; per job one squid run with the conf and the log dir # bind-mounted, and one "network connect --alias egress"; egress//squid.conf == - # squid_conf(allowlist(...)); probe per job; with os.umask(0o077) in force, egress// is still - # mode 0o777 and egress//squid.conf is mode 0o644 + # squid_conf(allowlist(...)); probe per job; with os.umask(0o077) in force, set and restored by a + # fixture (amendment 8), egress// is still mode 0o777 and egress//squid.conf is mode 0o644 # The verify_image tests call the real check with FakeDocker and repo_root = a clean `git init` repo in tmp_path. async def test_prepare_refuses_a_daemon_that_is_not_local(tmp_path, monkeypatch) -> None # FakeDocker context endpoint "tcp://10.0.0.5:2376" -> refused; DOCKER_HOST=tcp://... with a unix @@ -1149,14 +1152,14 @@ makes C1 "not evaluable". ``` - `jobs` is keyed by `job_id` (`--`), with one entry per planned job. - - `hosts_allowed` and `hosts_denied` are sorted, unique `"host:port"` strings. They come from the query-time events: the access-log lines after the probe's verified `proxy_prefix`, split by `ProxyEvent.allowed`. Probe traffic never appears. + - `hosts_allowed` and `hosts_denied` are sorted, unique `"host:port"` strings. Only events after the verified `proxy_prefix` contribute. A reached target enters `hosts_allowed` and a request ACL denial enters `hosts_denied`. Unconfirmed attempts contribute to neither list. - `lookup_package_docs_attempts` counts the model's `lookup_package_docs` tool calls in that job's `transcripts/` and `discarded/` records (cells `----r`). - `isolation_probe` is `"pass"` only when all of these hold (round-2 rulings C5, C6; round-3 items 1, 2): - `probe/control.json` and every job's `probe/.json` passed; - every job's `collected.json` says `ok`, so no failed collection step and no abnormal proxy end; - - every job's `access.log` exists, parses, and starts with exactly its `proxy_prefix`; + - every job's `access.log` exists, parses, and starts with its nonempty `proxy_prefix`. Every event is a request ACL denial or a recognized attempt to a destination and method permitted for that job; - every `ok` settle in the run's ledger events is attributed: its `unit_id` matches a `reserve` event whose `job_id` is a planned job. An `ok` settle that cannot be attributed fails the evidence; - - every hosted live job (`arm == "hosted"`, `api != "scripted"`) with at least one attributed `ok` settle shows an allowed `PROVIDER_HOSTS` line after the prefix. The attribution comes from the ledger alone, so a worker that died before reporting its trajectory still counts. + - every hosted live job (`arm == "hosted"`, `api != "scripted"`) with at least one attributed `ok` settle shows an established tunnel to its provider after the prefix. The attribution comes from the ledger alone, so a worker that died before reporting its trajectory still counts. Otherwise it is `"fail"`. - Produces in `egress.py`: - `lookup_attempts(out_dir: Path, family_id: str, system_id: str) -> int`. @@ -1294,6 +1297,9 @@ def test_cli_container_launcher_defaults_to_a_dry_run(tmp_path, monkeypatch) -> # main([... "--launcher", "container", "--image", "sha256:" + "0" * 64]) prints dry_run true; # Sandbox is patched to fail on any docker call def test_cli_refuses_live_with_the_local_launcher() -> None +def test_cli_builds_the_production_sandbox_with_the_real_check(tmp_path, monkeypatch) -> None + # amendment 6: on the production CLI path, launcher.sandbox.verify is verify_image, and the + # sandbox and the run share one run_id ``` The existing scripted end-to-end tests stay unchanged: a run of scripted @@ -1676,11 +1682,23 @@ From #200 (round 1), as amended by the round-2 message on #200: - a network that keeps IPv6 is refused, with no fallback (Task 10); - sandbox note §§B.2 and B.3 are corrected. 15. **Round 4 (reviews of `32bbb17`):** - - after our stop the proxy must show `ExitCode == 0`, so a forced kill of a hung Squid (137) fails the collection; the Squid 6.6 source shows a graceful SIGTERM exits 0 (Task 10, sandbox note §C); + - after our stop the proxy must show `ExitCode == 0`, so a forced kill of a hung Squid (137) fails the collection; the Squid 6.14 source shows a graceful SIGTERM exits 0 (Task 10, sandbox note §C); - `Sandbox` takes an injectable `verify`, with the real `verify_image` as its default, and a test proves the real check refuses a dirty tree (Task 10); - the IPv6 refusal removes its network first (Task 10); - `squid.conf` is set to mode 0o644 (Task 10); - Task 10's abnormal-exit test asserts `collected.json` only; Task 12 owns the summary verdict; - the reserve-event test reads the run's `ledger-events.jsonl` in `test_agentic_run.py`, and old `.jsonl` lines without `job_id` still load (Task 5). +16. **Binding amendments on #200** (Fable round-4 Lows and Nits, owner-ruled, applied in PR 4): + 1. `verify_image` runs `git status --porcelain --untracked-files=normal` (Task 10). + 2. `open_egress` removes the proxy and the network on any failure after the internal network exists, then raises; `verify_image` inspects `SQUID_IMAGE` (Task 10). + 3. **PR 5 handoff:** grading jobs pass `job_id` on every reservation, and each grading invocation's evidence lives under `/grading/sandbox//`. + 4. The forward reference in `VerifyFn = Callable[["Sandbox"], ...]` is quoted (Task 10). + 5. `test_every_reserve_event_names_its_job` uses two families of different providers and checks each `job_id`'s family against the event's provider (Task 5). + 6. A CLI test asserts `sandbox.verify is verify_image` on the production path (Task 13). + 7. `close_egress` also requires `Running` to be false after the stop (Task 10). + 8. The umask test restores the umask in a fixture (Task 10). + +Where the implementation had to depart from this plan, each departure is recorded with its +cost under "Rulings" in the PR 4 body. No open question remains for this plan. diff --git a/docs/research/2026-11-04-benchmark-sandbox-tooling.md b/docs/research/2026-11-04-benchmark-sandbox-tooling.md index ddf66666..6db5869d 100644 --- a/docs/research/2026-11-04-benchmark-sandbox-tooling.md +++ b/docs/research/2026-11-04-benchmark-sandbox-tooling.md @@ -13,17 +13,21 @@ this note says "not documented" and names the check that settles it. | Item | Pin | Published | Source | |---|---|---|---| -| Python base image | `python:3.14.8-slim-trixie@sha256:fbecd461fc72d21b2143c6eaba25143738079154a6d0ea3da3aec724f50eed4a` (index; arm64 `sha256:eaecc1a821ac5f032c7cc29d6fdd2cca4199ca97f8d11ea79417e9f647dbd809`) | pushed 2026-10-21T08:09Z | https://hub.docker.com/v2/repositories/library/python/tags/3.14.8-slim-trixie | +| Python base image | `python:3.14.10-slim-trixie@sha256:930e1abba7c4e8f96ed93e8012c35d174d7732752731bbd5e8e757d7ec6f3966` (index; arm64 `sha256:29434a59c93070e470f84663e4289026e04644ea44b5220ef7e07d653318ca1f`) | pushed 2026-11-02T08:08Z | https://hub.docker.com/v2/repositories/library/python/tags/3.14.10-slim-trixie | | uv | `ghcr.io/astral-sh/uv:0.13.4@sha256:9f130421e930bfbdc563c00740466603f8723158e90297d07957c2294640262b` (index) | release 2026-10-20T15:24Z | https://github.com/astral-sh/uv/releases/tag/0.13.4 ; digest from the ghcr.io registry manifest | -| Squid proxy image | `ubuntu/squid:6.6-24.04_edge@sha256:8a3baed477e2c282ab8aa5edad442f69873246964f225c5c2ae8364b6610963c` (index; arm64 `sha256:2580be07409d64c1b5bff32d218649771a53616b06ef102bc3005e81534beccf`), Squid 6.6 | pushed 2026-05-07T21:56Z | https://hub.docker.com/v2/repositories/ubuntu/squid/tags/6.6-24.04_edge | +| Squid proxy image | `ubuntu/squid:6.6-24.04_edge@sha256:8a3baed477e2c282ab8aa5edad442f69873246964f225c5c2ae8364b6610963c` (index; arm64 `sha256:2580be07409d64c1b5bff32d218649771a53616b06ef102bc3005e81534beccf`), Squid 6.14 | pushed 2026-05-07T21:56Z | https://hub.docker.com/v2/repositories/ubuntu/squid/tags/6.6-24.04_edge | | `mcp-server-fetch` | `2026.10.19`, `requires_dist` includes `mcp<3,>=2.3` and `httpx[socks]>=0.27` | 2026-10-19T06:48Z | https://pypi.org/pypi/mcp-server-fetch/2026.10.19/json | | Docker Desktop (maintainer's machine) | 4.96.1, bundling Engine 29.9.2 | 2026-10-21 | https://docs.docker.com/desktop/release-notes/ | | Ollama | v0.40.8 is the newest release on or before 2026-10-21 (2026-10-21T16:20Z); v0.40.14 (2026-11-03) changes OpenAI-endpoint sampler defaults, see D.3 | as stated | https://github.com/ollama/ollama/releases/tag/v0.40.8 , https://github.com/ollama/ollama/releases/tag/v0.40.14 | Notes on the pins: -- `python:3.14-slim` now points at 3.14.10 (pushed 2026-11-02) and 3.14.9 - was pushed 2026-10-22: both are too new. 3.14.8 is exactly 14 days old. +- The Python pin uses the security exception to the 14-day rule. + Python 3.14.10 blocks compromised eMudhra keys in the SSL module + (CVE-2026-115557) and fixes link handling in tarfile (CVE-2026-114583). + [CPython release advisory](https://www.python.org/downloads/release/python-31410/). +- The pinned Squid image reports version 6.14 from `/usr/sbin/squid -v`. + The 6.6 in its registry tag is not the installed version. - The Squid image is Canonical's (Docker Hub "Verified Publisher"). There is no Docker Official Squid image. Its config runs `entrypoint.sh` as root (`User` is empty), which calls `make-ssl-cert` and needs root, so @@ -126,21 +130,23 @@ https://www.squid-cache.org/Versions/v6/cfgman/). (`buffered_logs` applies only to the daemon, tcp and udp modules). - `logformat` codes: `%tg` GMT time with a strftime argument, `%tu` sub-second milliseconds, `%>a` client IP, `%rm` method, `%>rd` request - domain, `%>rP` request port, `%>Hs` status sent, `%Ss` Squid result - (`TCP_DENIED`, `TCP_TUNNEL`, ...; https://wiki.squid-cache.org/SquidFaq/SquidLogs). + domain, `%>rP` request port, `%>Hs` status sent to the client, `%Ss` Squid result + (such as `TCP_DENIED` or `TCP_TUNNEL`), `%Sh` hierarchy code and `%= deadline: + return + time.sleep(0.01) + print( + json.dumps( + { + "jsonrpc": "2.0", + "method": "notifications/message", + "params": { + "level": "info", + "data": "orchard" if kind == "credential" else "x" * 2048, + }, + } + ), + flush=True, + ) + + +if __name__ == "__main__": + marker, kind = sys.argv[1:] + for line in sys.stdin: + request = json.loads(line) + if "id" not in request: + continue + print( + json.dumps( + { + "jsonrpc": "2.0", + "id": request["id"], + **response(request["method"], request.get("params", {}), "valid", "clean"), + } + ), + flush=True, + ) + if request["method"] == "tools/list": + threading.Thread(target=notify, args=(Path(marker), kind), daemon=True).start() diff --git a/tests/benchmarks/fixtures/agentic/model-matrix-local.yml b/tests/benchmarks/fixtures/agentic/model-matrix-local.yml new file mode 100644 index 00000000..b19b2a24 --- /dev/null +++ b/tests/benchmarks/fixtures/agentic/model-matrix-local.yml @@ -0,0 +1,54 @@ +# One scripted model family on the air-gapped arm, for the host offline-check tests. +# Provider ollama: its units are unmetered, never priced or booked. `script` is +# relative to this directory; plan_jobs makes it absolute. The two hosted scripted +# families are here only because every matrix must name an openai and a google +# family (benchmarks.model_matrix.REQUIRED_PROVIDERS); the tests never run them. +schema_version: 1 +methodology_token_label: "Claude Tokens (Normalized Payload)" + +model_families: + - id: scripted-local + provider: ollama + model_id: scripted-local-1 + api: scripted + arm: air-gapped + client: scripted + script: script-local.yml + token_count_method: claude_normalized_payload + latency_scope: request_dispatch_to_final_answer + max_output_tokens: 1024 + framing_allowance_tokens: 256 + headline_eligible: false + headline_ineligibility_reason: Test fixture with a scripted model; never a public result. + + - id: scripted-openai + provider: openai + model_id: scripted-2 + api: scripted + arm: hosted + client: scripted + script: script-openai.yml + token_count_method: claude_normalized_payload + latency_scope: request_dispatch_to_final_answer + max_input_tokens: 200000 + max_output_tokens: 1024 + output_cap_includes_reasoning: true + framing_allowance_tokens: 256 + headline_eligible: false + headline_ineligibility_reason: Test fixture with a scripted model; never a public result. + + - id: scripted-google + provider: google + model_id: scripted-3 + api: scripted + arm: hosted + client: scripted + script: script-google.yml + token_count_method: claude_normalized_payload + latency_scope: request_dispatch_to_final_answer + max_input_tokens: 200000 + max_output_tokens: 1024 + output_cap_includes_reasoning: true + framing_allowance_tokens: 256 + headline_eligible: false + headline_ineligibility_reason: Test fixture with a scripted model; never a public result. diff --git a/tests/benchmarks/fixtures/agentic/r13-scripted-live/README.md b/tests/benchmarks/fixtures/agentic/r13-scripted-live/README.md new file mode 100644 index 00000000..aad14a9d --- /dev/null +++ b/tests/benchmarks/fixtures/agentic/r13-scripted-live/README.md @@ -0,0 +1,14 @@ +# Owner's R13 pilot, replayed during R14 review + +These four reference inputs are byte-for-byte copies of the owner's saved +`r14-owner-legacy.mNWWhN/pilot` reproduction: summary, model matrix, +ledger events, and one scored transcript. The owner generated them on the +R13 checkout and replayed them unchanged against R14 (owner record +`r14-owner-record.md`, finding 4). + +The saved matrix claims `anthropic-messages`, while the response contains +`raw_response.scripted_step` and has no recorded executed API. R14 accepted +its simulated $0.002 per cell and reached paid confirmation for 91 +trajectories. The regression must reject these unchanged inputs before +confirmation. Absolute paths in this historical evidence are provenance; +the test never follows them or launches their commands. diff --git a/tests/benchmarks/fixtures/agentic/r13-scripted-live/ledger-events.jsonl b/tests/benchmarks/fixtures/agentic/r13-scripted-live/ledger-events.jsonl new file mode 100644 index 00000000..1fb4d549 --- /dev/null +++ b/tests/benchmarks/fixtures/agentic/r13-scripted-live/ledger-events.jsonl @@ -0,0 +1,2 @@ +{"at": "2026-11-04T11:57:04.196Z", "bound": "0.011274", "event": "reserve", "input_bound": 1034, "job_id": "scripted-anthropic--no-docs", "kind": "model_call", "model_id": "scripted-1", "output_bound": 1024, "provider": "anthropic", "run_id": "20261104T115702Z", "unit_id": "anthropic-ae497265ba2e47f8b1acd2feb3bb8887"} +{"actual": "0.002", "at": "2026-11-04T11:57:04.197Z", "booked": "0.002", "buckets": {"cache_write_input": 0, "cached_input": 0, "output": 100, "reasoning": 0, "uncached_input": 1000}, "event": "settle", "input_bound_exceeded": false, "outcome": "ok", "provider": "anthropic", "run_id": "20261104T115702Z", "unit_id": "anthropic-ae497265ba2e47f8b1acd2feb3bb8887"} diff --git a/tests/benchmarks/fixtures/agentic/r13-scripted-live/run-summary.json b/tests/benchmarks/fixtures/agentic/r13-scripted-live/run-summary.json new file mode 100644 index 00000000..0ba70d27 --- /dev/null +++ b/tests/benchmarks/fixtures/agentic/r13-scripted-live/run-summary.json @@ -0,0 +1,78 @@ +{ + "artifact_root": "/tmp/tmpix0pgw2w/run", + "competitors": [ + "no-docs--scripted-anthropic--r1" + ], + "completed_at": "2026-11-04T11:57:04Z", + "corpus_ids": [ + "SYN-EX-001" + ], + "corpus_path": "/private/var/folders/fg/qy05cq110zb7rzbcyt5tnkr40000gn/T/pdmcp-201.AJGNg8/r13int/tests/benchmarks/fixtures/corpus.sample.yml", + "correctness_denominator_cells": 1, + "discarded": [], + "dry_run": false, + "failed_cells": 0, + "failed_cells_included_in_correctness_denominator": true, + "families": { + "scripted-anthropic": { + "answer_turns": 1, + "failed_attempt_s": 0.0, + "first_started_at": "2026-11-04T11:57:04.195Z", + "grant_wait_s": 0.001, + "last_completed_at": "2026-11-04T11:57:04.197Z", + "output_cap_stops": 0, + "reruns": 0, + "retries": {}, + "retry_wait_s": 0.0, + "timeouts": 0, + "wall_s": 0.002 + } + }, + "ledger": { + "anthropic": { + "cap": "180", + "input_bound_exceeded": 0, + "spent_after": "0.002", + "spent_before": "0", + "stopped": null + }, + "google": { + "cap": "180", + "input_bound_exceeded": 0, + "spent_after": "0", + "spent_before": "0", + "stopped": null + }, + "openai": { + "cap": "65", + "input_bound_exceeded": 0, + "spent_after": "0", + "spent_before": "0", + "stopped": null + } + }, + "manifest_path": "/private/var/folders/fg/qy05cq110zb7rzbcyt5tnkr40000gn/T/pdmcp-201.AJGNg8/r13int/docs/benchmarks/agentic-manifest.yml", + "mode": "agentic", + "model_limits_mismatch": [], + "models": [ + "scripted-anthropic" + ], + "not_run": [], + "planned_cells": 1, + "price_snapshot": { + "captured_on": "2026-10-31", + "expires_on": null + }, + "repeats": 1, + "repo_commit": "a0108c311d3c665b257a21103dded84a98e0e4dd", + "run_id": "20261104T115702Z", + "scored_cells": 1, + "seed": 7, + "started_at": "2026-11-04T11:57:02Z", + "status": "completed", + "succeeded_cells": 1, + "systems": [ + "no-docs" + ], + "worker_errors": [] +} diff --git a/tests/benchmarks/fixtures/agentic/r13-scripted-live/snapshots/model-matrix.yml b/tests/benchmarks/fixtures/agentic/r13-scripted-live/snapshots/model-matrix.yml new file mode 100644 index 00000000..9384fb17 --- /dev/null +++ b/tests/benchmarks/fixtures/agentic/r13-scripted-live/snapshots/model-matrix.yml @@ -0,0 +1,51 @@ +methodology_token_label: Claude Tokens (Normalized Payload) +model_families: +- api: anthropic-messages + arm: hosted + client: scripted + framing_allowance_tokens: 256 + headline_eligible: false + headline_ineligibility_reason: Test fixture with a scripted model; never a public + result. + id: scripted-anthropic + latency_scope: request_dispatch_to_final_answer + max_input_tokens: 200000 + max_output_tokens: 1024 + model_id: scripted-1 + output_cap_includes_reasoning: true + provider: anthropic + script: /private/var/folders/fg/qy05cq110zb7rzbcyt5tnkr40000gn/T/pdmcp-201.AJGNg8/r13int/tests/benchmarks/fixtures/agentic/script-anthropic.yml + token_count_method: claude_normalized_payload +- api: scripted + arm: hosted + client: scripted + framing_allowance_tokens: 256 + headline_eligible: false + headline_ineligibility_reason: Test fixture with a scripted model; never a public + result. + id: scripted-openai + latency_scope: request_dispatch_to_final_answer + max_input_tokens: 200000 + max_output_tokens: 1024 + model_id: scripted-2 + output_cap_includes_reasoning: true + provider: openai + script: /private/var/folders/fg/qy05cq110zb7rzbcyt5tnkr40000gn/T/pdmcp-201.AJGNg8/r13int/tests/benchmarks/fixtures/agentic/script-openai.yml + token_count_method: claude_normalized_payload +- api: scripted + arm: hosted + client: scripted + framing_allowance_tokens: 256 + headline_eligible: false + headline_ineligibility_reason: Test fixture with a scripted model; never a public + result. + id: scripted-google + latency_scope: request_dispatch_to_final_answer + max_input_tokens: 200000 + max_output_tokens: 1024 + model_id: scripted-3 + output_cap_includes_reasoning: true + provider: google + script: /private/var/folders/fg/qy05cq110zb7rzbcyt5tnkr40000gn/T/pdmcp-201.AJGNg8/r13int/tests/benchmarks/fixtures/agentic/script-google.yml + token_count_method: claude_normalized_payload +schema_version: 1 diff --git a/tests/benchmarks/fixtures/agentic/r13-scripted-live/transcripts/no-docs--scripted-anthropic--r1/SYN-EX-001.json b/tests/benchmarks/fixtures/agentic/r13-scripted-live/transcripts/no-docs--scripted-anthropic--r1/SYN-EX-001.json new file mode 100644 index 00000000..373db7ed --- /dev/null +++ b/tests/benchmarks/fixtures/agentic/r13-scripted-live/transcripts/no-docs--scripted-anthropic--r1/SYN-EX-001.json @@ -0,0 +1,91 @@ +{ + "answer": "Scripted answer.", + "canonical_messages": [ + { + "content": "[SYNTHETIC FIXTURE] What does the fictional `synthstdlib.fixture_symbol_ex_1()` do in Python 3.13?", + "role": "user" + }, + { + "content": [ + { + "text": "Scripted answer.", + "type": "text" + } + ], + "role": "assistant" + } + ], + "competitor_id": "no-docs--scripted-anthropic--r1", + "completed_at": "2026-11-04T11:57:04.197Z", + "corpus_id": "SYN-EX-001", + "error": null, + "model_calls": [ + { + "attempts": [ + { + "outcome": "ok", + "status": null, + "unit_id": "anthropic-ae497265ba2e47f8b1acd2feb3bb8887", + "wait_ms": 1.068, + "wall_ms": 0.041 + } + ], + "buckets": { + "cache_write_input": 0, + "cached_input": 0, + "output": 100, + "reasoning": 0, + "uncached_input": 1000 + }, + "index": 0, + "input_bound": 1034, + "message_count": 1, + "output_bound": 1024, + "raw_response": { + "scripted_step": { + "text": "Scripted answer.", + "usage": { + "cache_creation_input_tokens": 0, + "cache_read_input_tokens": 0, + "input_tokens": 1000, + "output_tokens": 100 + } + } + }, + "raw_usage": { + "cache_creation_input_tokens": 0, + "cache_read_input_tokens": 0, + "input_tokens": 1000, + "output_tokens": 100 + }, + "reported_model": "scripted-1", + "request_params": { + "model": "scripted-1" + }, + "stop_reason": "end_turn", + "tool_calls_requested": 0, + "wall_ms": 0.041 + } + ], + "model_family_id": "scripted-anthropic", + "model_id": "scripted-1", + "provider": "anthropic", + "repeat": 1, + "started_at": "2026-11-04T11:57:04.195Z", + "status": "succeeded", + "system_id": "no-docs", + "system_prompt_sha256": "35a0b826e7fd8f16e5b9c369594962ebe51025c29c191335293af5a5385e5c9b", + "timing": { + "failed_attempt_ms": 0.0, + "grant_wait_ms": 1.068, + "model_ms": 0.041, + "overhead_ms": 0.482, + "retry_wait_ms": 0.0, + "tool_ms": 0.0, + "used_ms": 0.041, + "wall_ms": 1.592 + }, + "tool_calls": [], + "tool_model_key": "no-docs:anthropic/scripted-1", + "tools_sha256": "4f53cda18c2baa0c0354bb5f9a3ecbe5ed12ab4d8e11ba873c2f11161202b945" +} diff --git a/tests/benchmarks/fixtures/agentic/raw_result_server.py b/tests/benchmarks/fixtures/agentic/raw_result_server.py new file mode 100644 index 00000000..645219ff --- /dev/null +++ b/tests/benchmarks/fixtures/agentic/raw_result_server.py @@ -0,0 +1,103 @@ +"""Synthetic MCP JSON-RPC peer: deliberately bypass server-side result validation.""" + +import json +import sys +import time + + +def token(kind): + return { + "literal": "synthetic_bootstrap_opaque", + "bound-shaped": "AIza" + "q" * 35, + "lexical": "AIza" + "q" * 35, + "clean": "clean-value", + }[kind] + + +def response(method, params, case, value): + if method == "initialize": + result = { + "protocolVersion": params["protocolVersion"], + "capabilities": {"tools": {}}, + "serverInfo": {"name": "synthetic", "version": "1"}, + } + if case == "handshake": + result["discarded"] = value + return {"result": result} + if method == "tools/list": + result = { + "tools": [ + { + "name": "search_docs", + "inputSchema": {"type": "object"}, + "outputSchema": {"type": "object", "required": ["answer"]}, + } + ] + } + if case == "listing": + result["discarded"] = value + return {"result": result} + result = {"content": [{"type": "text", "text": "safe"}]} + if case == "missing-structured": + result["content"][0]["text"] = value + elif case == "invalid-structured": + result["structuredContent"] = {"hidden": value} + elif case == "malformed-content": + result["content"] = [{"type": "unknown", "hidden": value}] + elif case in ("dropped-field", "escaped-field"): + result["discarded"] = value + elif case == "error-result": + result.update(isError=True, discarded=value) + elif case == "rpc-error": + return {"error": {"code": -32603, "message": "clean error", "data": {"hidden": value}}} + elif case == "dropped-error": + return {"error": {"code": -32603, "message": "clean error", "discarded": value}} + elif case == "malformed-envelope": + return {"result": ["invalid result", {"hidden": value}]} + elif case == "rpc-clean": + return {"error": {"code": -32603, "message": "clean error"}} + elif case == "valid": + result["structuredContent"] = {"answer": "clean answer"} + return {"result": result} + + +if __name__ == "__main__": + case, kind = sys.argv[1:] + # The literal deliberately has no lexical-key match; its exact bytes matter. + value = ( + "prefix" + token(kind) + "-suffix" if kind in ("literal", "bound-shaped") else token(kind) + ) + print("synthetic server diagnostic retained", file=sys.stderr, flush=True) + for line in sys.stdin: + request = json.loads(line) + if "id" not in request: + continue + if case == "wait" and request["method"] == "tools/call": + time.sleep(30) # Cancellation must stop only this owned subprocess. + if case == "oversize" and request["method"] == "tools/call": + print("x" * 2048, flush=True) + continue + message = { + "jsonrpc": "2.0", + "id": request["id"], + **response(request["method"], request.get("params", {}), case, value), + } + encoded = json.dumps(message) + if case == "escaped-field": + encoded = encoded.replace(token(kind), "".join(f"\\u{ord(c):04x}" for c in token(kind))) + if ( + case in ("trailing-encoded", "unfinished-encoded", "broken-encoded", "truncated-utf8") + and request["method"] == "tools/call" + ): + # Complete envelope, then a string with a single encoded character. + hidden = value.replace(token(kind)[0], f"\\u{ord(token(kind)[0]):04x}", 1) + encoded += ' "note":"' + hidden + if case == "truncated-utf8": + sys.stdout.buffer.write((encoded + '" ').encode() + b"\xe2\x82") + sys.stdout.buffer.flush() + break + if case == "trailing-encoded": + encoded += '"' + elif case == "broken-encoded": + encoded += "\\u00" + print(encoded, flush=True) diff --git a/tests/benchmarks/fixtures/agentic/script-local.yml b/tests/benchmarks/fixtures/agentic/script-local.yml new file mode 100644 index 00000000..7bd15d69 --- /dev/null +++ b/tests/benchmarks/fixtures/agentic/script-local.yml @@ -0,0 +1,7 @@ +# Scripted air-gapped model: one answer per trajectory, usage in the Chat Completions +# shape Ollama reports. +steps: + - text: "Scripted local answer." + usage: + prompt_tokens: 1000 + completion_tokens: 100 diff --git a/tests/benchmarks/test_agentic_airgap.py b/tests/benchmarks/test_agentic_airgap.py new file mode 100644 index 00000000..bf6411a6 --- /dev/null +++ b/tests/benchmarks/test_agentic_airgap.py @@ -0,0 +1,444 @@ +"""The air-gapped arm: host offline checks, the Ollama preflight and the C3 evidence. + +No test touches the network or a real Ollama: connects, routes and HTTP are all fakes. +""" + +from __future__ import annotations + +import json +from collections.abc import Callable +from pathlib import Path +from typing import Any + +import pytest + +from benchmarks.__main__ import main +from benchmarks.agentic.airgap import ( + MIN_OLLAMA, + REQUIRED_CONTEXT, + AirGapWatch, + default_routes, + host_offline_checks, + ollama_preflight, + write_airgap_evidence, +) +from benchmarks.agentic.egress import allowlist +from benchmarks.agentic.protocol import KeyLeakError +from benchmarks.agentic.run import run_agentic +from benchmarks.model_matrix import load_model_matrix +from benchmarks.runner import BenchmarkValidationError +from tests.benchmarks.test_agentic_egress import PROBE_LINES, PYPI_LINE, _evidence, _lines +from tests.benchmarks.test_agentic_run import ( + COMMITTED_MATRIX, + _cli, + _config, + _container, + _EveryFamily, + _live_config, +) + +FIX = Path(__file__).parent / "fixtures" / "agentic" + + +@pytest.mark.parametrize( + "system,text,expected", + [ + ( + "Darwin", + "Routing tables\n\nInternet:\nDestination Gateway Flags Netif\n" + "127.0.0.1 127.0.0.1 UH lo0\n", + [], + ), + ( + "Darwin", + "Internet6:\ndefault fe80::%utun0 UGcIg utun0\n", + ["default fe80::%utun0 UGcIg utun0"], + ), + ( + "Linux", + "Iface\tDestination\tGateway\neth0\t00000000\t0100A8C0\n", + ["eth0\t00000000\t0100A8C0"], + ), + ( + "Linux", + "00000000000000000000000000000000 00 00000000000000000000000000000000 00 " + "fe800000000000000000000000000001 00000400 00000001 00000000 00000003 eth0\n" + "00000000000000000000000000000000 00 00000000000000000000000000000000 00 " + "00000000000000000000000000000000 ffffffff 00000001 00000001 00200200 lo\n", + [ + "00000000000000000000000000000000 00 00000000000000000000000000000000 00 " + "fe800000000000000000000000000001 00000400 00000001 00000000 00000003 eth0" + ], + ), + ], +) +def test_default_routes_on_macos_and_linux(system: str, text: str, expected: list[str]) -> None: + assert default_routes(system=system, read=lambda: text) == expected + + +class _Conn: + def close(self) -> None: + return None + + +def _connect(reachable: set[str]) -> Callable[..., Any]: + def connect(address: tuple[str, int], timeout: float) -> _Conn: + if address[0] in reachable: + return _Conn() + raise OSError(51, "Network is unreachable") + + return connect + + +def test_offline_checks_need_both_a_name_and_an_address_to_fail() -> None: + checks = host_offline_checks(connect=_connect({"1.1.1.1"}), routes=lambda: []) + by_name = {c["check"]: c for c in checks} + assert by_name["outside_connect:pypi.org"]["passed"] is True # DNS is down + assert by_name["outside_connect:1.1.1.1"]["passed"] is False # but IP still works + assert by_name["no_default_route"]["passed"] is True + assert all("at" in c for c in checks) + offline = host_offline_checks(connect=_connect(set()), routes=lambda: ["default x UGScg en0"]) + route = {c["check"]: c for c in offline}["no_default_route"] + assert route["passed"] is False and route["detail"] == ["default x UGScg en0"] + + +@pytest.mark.parametrize("output", ["", "permission denied"]) +def test_unrecognized_netstat_output_cannot_certify_an_offline_host(output: str) -> None: + checks = host_offline_checks( + connect=_connect(set()), routes=lambda: default_routes(system="Darwin", read=lambda: output) + ) + route = next(check for check in checks if check["check"] == "no_default_route") + assert route["passed"] is False + + +def test_failed_netstat_is_a_failed_offline_check( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + netstat = tmp_path / "netstat" + netstat.write_text("#!/bin/sh\nexit 7\n") + netstat.chmod(0o700) + monkeypatch.setenv("PATH", str(tmp_path)) + checks = host_offline_checks( + connect=_connect(set()), routes=lambda: default_routes(system="Darwin") + ) + route = next(check for check in checks if check["check"] == "no_default_route") + assert route["passed"] is False + assert "7" in str(route["detail"]) + + +def test_gemma_cli_defaults_to_the_two_offline_systems( + tmp_path: Path, capsys: pytest.CaptureFixture[str] +) -> None: + args = _cli( + tmp_path, + "--launcher", + "container", + "--image", + "sha256:" + "0" * 64, + "--matrix", + str(COMMITTED_MATRIX), + "--models", + "gemma4-12b", + "--index", + str(tmp_path / "index"), + ) + assert main(args) == 0 + assert set(json.loads(capsys.readouterr().out)["systems"]) == {"python-docs", "no-docs"} + + +def test_air_gapped_run_refuses_an_explicit_online_system(tmp_path: Path) -> None: + config = _live_config(tmp_path, models=("gemma4-12b",), systems=("python-docs", "docs-fetch")) + with pytest.raises(BenchmarkValidationError, match="docs-fetch"): + run_agentic( + config, launcher=_EveryFamily(), confirm=lambda _: pytest.fail("confirmation reached") + ) + assert not config.out_dir.exists() + + +def test_air_gapped_run_refuses_a_hosted_provider_in_a_custom_matrix(tmp_path: Path) -> None: + matrix = tmp_path / "matrix.yml" + matrix.write_text(COMMITTED_MATRIX.read_text().replace("arm: hosted", "arm: air-gapped")) + config = _live_config(tmp_path, matrix_path=matrix, models=("gpt-6.1-sol",), dry_run=True) + with pytest.raises(BenchmarkValidationError, match="Ollama"): + run_agentic(config, launcher=_EveryFamily()) + + +def test_air_gapped_proxy_never_adds_a_system_upstream() -> None: + gemma = next( + f for f in load_model_matrix(COMMITTED_MATRIX).model_families if f.id == "gemma4-12b" + ) + assert allowlist(gemma, "docs-fetch") == (("host.docker.internal", 11434),) + + +def _ollama(version: str = "0.40.14", context: int = REQUIRED_CONTEXT, present: bool = True): + calls: list[tuple[str, Any]] = [] + tags = [ + { + "name": "gemma4:12b", + "model": "gemma4:12b", + "digest": "c7597fc90b86", + "details": {"format": "mlx"}, + } + ] + + def fetch(url: str, body: bytes | None) -> dict[str, Any]: + calls.append((url, None if body is None else json.loads(body))) + path = url.removeprefix("http://127.0.0.1:11434") + if path == "/api/version": + return {"version": version} + if path == "/api/tags": + return {"models": tags if present else []} + if path == "/api/generate": + return {"model": "gemma4:12b", "response": "", "done": True} + if path == "/api/ps": + return { + "models": [{"name": "gemma4:12b", "model": "gemma4:12b", "context_length": context}] + } + if path == "/api/show": + return {"parameters": "stop ", "model_info": {}} + raise AssertionError(url) + + return fetch, calls + + +def test_ollama_preflight_requires_the_32768_context() -> None: + fetch, _ = _ollama(context=4096) + with pytest.raises(BenchmarkValidationError, match="4096"): + ollama_preflight("gemma4:12b", fetch=fetch) + fetch, calls = _ollama() + record = ollama_preflight("gemma4:12b", fetch=fetch) + assert record["context_length"] == 32_768 and record["version"] == "0.40.14" + assert ( + "http://127.0.0.1:11434/api/generate", + {"model": "gemma4:12b", "prompt": "", "keep_alive": "60m"}, + ) in calls + assert record["parameters"] == "stop " + + +def test_ollama_preflight_refuses_a_version_before_0_40_14() -> None: + assert MIN_OLLAMA == (0, 40, 14) + fetch, calls = _ollama(version="0.40.8") + with pytest.raises(BenchmarkValidationError, match="0.40.8"): + ollama_preflight("gemma4:12b", fetch=fetch) + assert [url for url, _ in calls] == ["http://127.0.0.1:11434/api/version"] # nothing loaded + fetch, _ = _ollama(present=False) + with pytest.raises(BenchmarkValidationError, match="gemma4:12b"): + ollama_preflight("gemma4:12b", fetch=fetch) + + +def test_ollama_preflight_records_the_reported_digest() -> None: + fetch, _ = _ollama() + record = ollama_preflight("gemma4:12b", fetch=fetch) + assert record["digest"] == "c7597fc90b86" and record["details"] == {"format": "mlx"} + assert record["model"] == "gemma4:12b" + + +def _local_config(tmp_path: Path, **overrides: Any) -> Any: + values: dict[str, Any] = { + "matrix_path": FIX / "model-matrix-local.yml", + "models": ("scripted-local",), + "systems": ("no-docs",), + "questions": ("SYN-EX-001", "SYN-EX-002"), + "repeats": 1, + } + return _config(tmp_path, **(values | overrides)) + + +def _counting(fail_on: int | None = None) -> tuple[Callable[[], list[dict[str, Any]]], list[int]]: + rounds: list[int] = [] + + def checks() -> list[dict[str, Any]]: + rounds.append(len(rounds) + 1) + passed = len(rounds) != fail_on + return [ + {"check": "outside_connect:pypi.org", "passed": True, "detail": "", "at": "t"}, + {"check": "no_default_route", "passed": passed, "detail": [], "at": "t"}, + ] + + return checks, rounds + + +def test_the_arm_checks_the_host_before_each_trajectory_and_after_the_last(tmp_path: Path) -> None: + checks, rounds = _counting() + summary = run_agentic(_local_config(tmp_path), offline_checks=checks) + assert summary["status"] == "completed" and summary["succeeded_cells"] == 2 + assert rounds == [1, 2, 3, 4] # before the first, after each of 2 trajectories, after the last + assert summary["airgap"] == {"checks": 4, "broken": False} + records = (tmp_path / "run" / "airgap" / "records.jsonl").read_text().splitlines() + whens = [json.loads(line)["when"] for line in records] + assert len(whens) == 8 # two records per round + rounds_seen = list(dict.fromkeys(whens)) + assert rounds_seen[0] == "before_first" and rounds_seen[-1] == "after_last" + assert sorted(rounds_seen[1:-1]) == [ + "after no-docs--scripted-local--r1/SYN-EX-001", + "after no-docs--scripted-local--r1/SYN-EX-002", + ] + + +def test_the_first_failed_check_stops_the_arm(tmp_path: Path) -> None: + checks, rounds = _counting(fail_on=2) + with pytest.raises(BenchmarkValidationError, match="no_default_route"): + run_agentic(_local_config(tmp_path), offline_checks=checks) + summary = json.loads((tmp_path / "run" / "run-summary.json").read_text()) + assert summary["status"] == "aborted" and "no_default_route" in summary["abort_reason"] + assert summary["airgap"] == {"checks": 2, "broken": True} + last = json.loads((tmp_path / "run" / "airgap" / "records.jsonl").read_text().splitlines()[-1]) + assert last["passed"] is False and last["check"] == "no_default_route" + + +def test_a_hosted_run_makes_no_offline_check(tmp_path: Path) -> None: + def never() -> list[dict[str, Any]]: + raise AssertionError("a hosted run is online") + + config = _config(tmp_path, models=("scripted-anthropic",), systems=("no-docs",), repeats=1) + summary = run_agentic(config, offline_checks=never) + assert summary["status"] == "completed" and "airgap" not in summary + + +@pytest.mark.parametrize( + ("kind", "partial"), + [ + ("transcripts", b'{"tool_calls":'), + ("discarded", b'{"tool_calls":[null]}'), + ("transcripts", b"{}"), + ], +) +def test_partial_record_preserves_abort_and_evidence( + tmp_path: Path, kind: str, partial: bytes, monkeypatch: pytest.MonkeyPatch +) -> None: + config = _local_config(tmp_path, systems=("no-docs", "python-docs")) + out = config.out_dir + launcher, _ = _container(tmp_path) + aborted = OSError("trajectory write interrupted") + + async def interrupted(jobs: Any, **kwargs: Any) -> None: + for job in jobs: + _evidence(out, job.job_id, log=_lines(*PROBE_LINES, PYPI_LINE)) + cell = out / kind / "no-docs--scripted-local--r1" + cell.mkdir(parents=True) + (cell / "SYN-EX-001.json").write_bytes(partial) + good = out / "transcripts" / "python-docs--scripted-local--r1" + good.mkdir(parents=True) + (good / "SYN-EX-001.json").write_text('{"tool_calls":[{"tool":"lookup_package_docs"}]}') + raise aborted + + monkeypatch.setattr("benchmarks.agentic.run.run_jobs", interrupted) + checks, _ = _counting() + with pytest.raises(OSError) as raised: + run_agentic(config, launcher=launcher, offline_checks=checks) + assert raised.value is aborted + summary = json.loads((out / "run-summary.json").read_text()) + assert (summary["status"], summary["abort_reason"]) == ( + "aborted", + "OSError: trajectory write interrupted", + ) + c1 = json.loads((out / "egress" / "summary.json").read_text()) + assert c1["isolation_probe"] == "fail" + assert c1["jobs"]["scripted-local--no-docs"] == { + "hosts_allowed": [], + "hosts_denied": ["pypi.org:443"], + "lookup_package_docs_attempts": 0, + } + assert c1["jobs"]["scripted-local--python-docs"]["lookup_package_docs_attempts"] == 1 + assert json.loads((out / "airgap" / "checks.json").read_text()) == { + "checks": 1, + "internet_hosts": [], + "all_passed": False, + } + + +# --- C3 evidence: airgap/checks.json (#199, owner question 9) ----------------------------------- + +GEMMA = "gemma4-12b--python-docs" + + +def _egress_summary(out: Path, allowed: list[str], *, probe: str = "pass") -> None: + jobs = { + GEMMA: { + "hosts_allowed": allowed, + "hosts_denied": ["pypi.org:443"], + "lookup_package_docs_attempts": 1, + } + } + (out / "egress").mkdir(parents=True, exist_ok=True) + summary = {"jobs": jobs, "isolation_probe": probe} + (out / "egress" / "summary.json").write_text(json.dumps(summary)) + + +async def test_airgap_checks_reject_an_escaped_mapping_key(tmp_path: Path) -> None: + key = "AIza" + "g" * 35 + record = {"check": "routes", "passed": True, "observed": [{"\n" + key: 1}]} + watch = AirGapWatch(tmp_path, lambda: [record]) + with pytest.raises(KeyLeakError) as caught: + await watch.check("before_first") + assert key not in str(caught.value) + assert all(key.encode() not in p.read_bytes() for p in tmp_path.rglob("*.jsonl")) + + +def test_airgap_evidence_refuses_an_escaped_host(tmp_path: Path) -> None: + key = "AIza" + "g" * 35 + _egress_summary(tmp_path, ["é" + key]) + with pytest.raises(KeyLeakError) as caught: + write_airgap_evidence(tmp_path, rounds=1, broken=False, job_ids=[GEMMA]) + assert key not in str(caught.value) + assert not (tmp_path / "airgap" / "checks.json").exists() + + +def test_airgap_evidence_has_exactly_the_bound_keys(tmp_path: Path) -> None: + _egress_summary(tmp_path, ["host.docker.internal:11434"]) + result = write_airgap_evidence(tmp_path, rounds=4, broken=False, job_ids=[GEMMA]) + written = json.loads((tmp_path / "airgap" / "checks.json").read_text()) + assert written == result and set(written) == {"all_passed", "checks", "internet_hosts"} + + +def test_a_denied_pypi_attempt_keeps_all_passed_true(tmp_path: Path) -> None: + _egress_summary(tmp_path, ["host.docker.internal:11434"]) + result = write_airgap_evidence(tmp_path, rounds=4, broken=False, job_ids=[GEMMA]) + assert result == {"all_passed": True, "checks": 4, "internet_hosts": []} + + +def test_a_reached_internet_host_fails_the_evidence(tmp_path: Path) -> None: + _egress_summary(tmp_path, ["pypi.org:443", "host.docker.internal:11434"]) + result = write_airgap_evidence(tmp_path, rounds=4, broken=False, job_ids=[GEMMA]) + assert result == {"all_passed": False, "checks": 4, "internet_hosts": ["pypi.org:443"]} + + +def test_missing_egress_evidence_or_a_failed_probe_fails_the_evidence(tmp_path: Path) -> None: + result = write_airgap_evidence(tmp_path, rounds=4, broken=False, job_ids=[GEMMA]) + assert result == {"all_passed": False, "checks": 4, "internet_hosts": []} + _egress_summary(tmp_path / "p", ["host.docker.internal:11434"], probe="fail") + result = write_airgap_evidence(tmp_path / "p", rounds=4, broken=False, job_ids=[GEMMA]) + assert result["all_passed"] is False + _egress_summary(tmp_path / "b", ["host.docker.internal:11434"]) + assert write_airgap_evidence(tmp_path / "b", rounds=4, broken=True, job_ids=[GEMMA]) == { + "all_passed": False, + "checks": 4, + "internet_hosts": [], + } + _egress_summary(tmp_path / "z", ["host.docker.internal:11434"]) + result = write_airgap_evidence(tmp_path / "z", rounds=0, broken=False, job_ids=[GEMMA]) + assert result["all_passed"] is False # no round ran: nothing shows the host was offline + + +@pytest.mark.parametrize("entry", [{}, {"hosts_allowed": ""}, {"hosts_allowed": {}}]) +def test_c3_requires_a_host_list_for_each_job(tmp_path: Path, entry: dict[str, Any]) -> None: + _egress_summary(tmp_path, []) + path = tmp_path / "egress" / "summary.json" + path.write_text(json.dumps({"isolation_probe": "pass", "jobs": {GEMMA: entry}})) + assert not write_airgap_evidence(tmp_path, rounds=1, broken=False, job_ids=[GEMMA])[ + "all_passed" + ] + + +def test_missing_job_does_not_hide_another_jobs_external_connection(tmp_path: Path) -> None: + _egress_summary(tmp_path, ["pypi.org:443"]) + checks = write_airgap_evidence(tmp_path, rounds=1, broken=False, job_ids=["missing", GEMMA]) + assert checks == {"all_passed": False, "checks": 1, "internet_hosts": ["pypi.org:443"]} + + +def test_an_air_gapped_run_writes_checks_json_even_when_aborted(tmp_path: Path) -> None: + checks, _ = _counting(fail_on=2) + with pytest.raises(BenchmarkValidationError): + run_agentic(_local_config(tmp_path), offline_checks=checks) + written = json.loads((tmp_path / "run" / "airgap" / "checks.json").read_text()) + assert written == {"all_passed": False, "checks": 2, "internet_hosts": []} diff --git a/tests/benchmarks/test_agentic_argument_content.py b/tests/benchmarks/test_agentic_argument_content.py new file mode 100644 index 00000000..1f61b544 --- /dev/null +++ b/tests/benchmarks/test_agentic_argument_content.py @@ -0,0 +1,322 @@ +"""Real adapter argument replay with synthetic credentials and recording SDK transports.""" + +from __future__ import annotations + +import json +from unittest.mock import Mock + +import pytest +from mcp.types import CallToolResult, TextContent + +from benchmarks.agentic.loop import Caps +from benchmarks.agentic.protocol import KEY_SHAPED, KeyLeakError +from benchmarks.agentic.types import Buckets +from benchmarks.agentic.worker import ProtocolChannel +from tests.benchmarks.test_agentic_clients import ( + OPENAI_CALL, + OPENAI_MESSAGE, + Recorder, + _chat_completion, + _ok, + _ollama, + _openai, + _openai_response, + _tool_call, +) +from tests.benchmarks.test_agentic_outgoing import RecordingLedger, _bridge, _close, _run + + +def _argument_client(provider, arguments, name="search_docs", *, safe_first=False): + calls = [(name, arguments)] + if safe_first: + calls.insert(0, ("search_docs", '{"query":"json"}')) + if provider == "openai": + first = _openai_response( + [ + {**OPENAI_CALL, "call_id": f"call_{i}", "name": tool, "arguments": args} + for i, (tool, args) in enumerate(calls) + ] + ) + recorder = Recorder(_ok(first), _ok(_openai_response([OPENAI_MESSAGE]))) + return _openai(recorder), recorder + first = _chat_completion( + { + "role": "assistant", + "tool_calls": [ + _tool_call(tool, args, f"call_{i}") for i, (tool, args) in enumerate(calls) + ], + }, + "tool_calls", + ) + recorder = Recorder(_ok(first), _ok(_chat_completion({"role": "assistant", "content": "done"}))) + return _ollama(recorder), recorder + + +CASES = [ + "array", + "scalar", + "object", + "duplicate", + "nested-duplicate", + "duplicate-array", + "duplicate-name", + "malformed", + "unfinished", + "unfinished-slash", + "unfinished-unicode", + "unfinished-quotes", + "broken-escape", + "raw-invalid", + "name", + "later-name", + "later-object", +] + + +@pytest.mark.parametrize("provider", ["openai", "ollama"]) +@pytest.mark.parametrize("mode", ["opaque-literal", "shaped-literal", "lexical"]) +@pytest.mark.parametrize("case", CASES) +async def test_arguments_stop_before_dispatch_or_second_grant_with_first_usage_settled( + provider, mode, case +): + literal = "synthetic_bootstrap_opaque" if mode == "opaque-literal" else "sk-proj-" + "g" * 60 + value = literal if mode == "lexical" else "prefix" + literal + "-suffix" + if mode != "lexical": + assert KEY_SHAPED.search(value) is None + encoded = json.dumps(value).replace("s", r"\u0073") + name = value if case in ("name", "later-name") else "search_docs" + arguments = { + "array": f"[{encoded}]", + "scalar": encoded, + "object": f'{{"query":{encoded}}}', + "duplicate": f'{{"query":{encoded},"query":"json"}}', + "nested-duplicate": f'{{"query":{{"value":{encoded},"value":"json"}}}}', + "duplicate-array": f'[{{"query":{encoded},"query":"json"}}]', + "duplicate-name": f'{{{encoded}:"first",{encoded}:"second"}}', + "malformed": f'{{"query":{encoded},', + "raw-invalid": "not-json " + value, + }.get(case, '{"query":"json"}') + if case.startswith("unfinished") or case == "broken-escape": + # Only one encoded character, with a completed harmless marker before damage. + prefix = ('"' if mode == "lexical" else '"prefix') + literal.replace( + literal[0], f"\\u{ord(literal[0]):04x}", 1 + ) + tail = { + "unfinished": "-suffix", + "unfinished-slash": "-suffix\\", + "unfinished-unicode": "-suffix\\u00", + "unfinished-quotes": "-suffix", + "broken-escape": '-suffix\\x20"}', + }[case] + if case == "unfinished-quotes": + # Interior escaped quotes must not restart the scan on every suffix. + prefix = prefix[0] + r'\"' * 8192 + prefix[1:] + if mode == "lexical": + tail = tail.replace("-suffix", " ") + arguments = '{"query":' + prefix + tail + if case == "later-object": + arguments = f'{{"query":{encoded}}}' + client, recorder = _argument_client( + provider, arguments, name, safe_first=case.startswith("later-") + ) + if provider == "openai" and case.startswith("unfinished"): + body = json.loads(recorder.responses[0].content) + body.update(status="incomplete", incomplete_details={"reason": "max_output_tokens"}) + recorder.responses[0] = _ok(body) + # The bound credential also authenticates the first SDK request. Content checks must + # never compare against auth headers or attach the callback to the HTTP transport. + if provider == "openai": + client._sdk.api_key = literal + channel = ProtocolChannel(-1, (literal.encode(),), -1, Mock(), (Mock(), Mock())) + ledger = RecordingLedger() + bridge, dispatch = _bridge(CallToolResult(content=[TextContent(type="text", text="safe")])) + try: + with pytest.raises(KeyLeakError) as caught: + await _run( + client, + bridge, + ledger, + check_content=None if mode == "lexical" else channel.check_content, + ) + assert literal not in str(caught.value) + assert len(recorder.seen) == len(ledger.reserves) == len(ledger.settles) == 1 + expected = ( + Buckets(500, 300, 200, 50, 40) if provider == "openai" else Buckets(120, 0, 0, 30) + ) + assert ledger.settles == [{"unit_id": "1", "outcome": "ok", "buckets": expected}] + dispatch.assert_not_awaited() + assert literal.encode() not in recorder.seen[0].content + finally: + await _close(client) + + +@pytest.mark.parametrize("provider", ["openai", "ollama"]) +@pytest.mark.parametrize( + "arguments,valid", + [ + ('{"query":"js\\u006fn"}', True), + ('{"query":"old","query":"json"}', True), + ('["ordinary"]', False), + ('"ordinary"', False), + ("42", False), + ("true", False), + ("null", False), + ('{"query":"ordinary",', False), + ('{"query":"ord\\u0069nary', False), + ], +) +async def test_safe_arguments_keep_native_replay_dispatch_and_billing(provider, arguments, valid): + client, recorder = _argument_client(provider, arguments) + channel = ProtocolChannel(-1, (b"synthetic_bootstrap_opaque",), -1, Mock(), (Mock(), Mock())) + ledger = RecordingLedger() + bridge, dispatch = _bridge(CallToolResult(content=[TextContent(type="text", text="safe")])) + try: + record = await _run(client, bridge, ledger, check_content=channel.check_content) + assert record["status"] == "succeeded" + assert len(recorder.seen) == len(ledger.reserves) == len(ledger.settles) == 2 + if valid: + dispatch.assert_awaited_once_with("search_docs", {"query": "json"}) + else: + dispatch.assert_not_awaited() + assert record["tool_calls"][0]["is_error"] is True + body = recorder.body(1) + replay = ( + next(item for item in body["input"] if item.get("type") == "function_call") + if provider == "openai" + else body["messages"][2]["tool_calls"][0]["function"] + ) + assert replay["arguments"] == arguments + finally: + await _close(client) + + +@pytest.mark.parametrize("provider", ["openai", "ollama"]) +@pytest.mark.parametrize("usage", [True, False]) +async def test_argument_rejection_settles_even_when_usage_absent_or_model_cap_reached( + provider, usage +): + literal = "synthetic_bootstrap_opaque" + arguments = '["prefix\\u0073ynthetic_bootstrap_opaque-suffix"]' + client, recorder = _argument_client(provider, arguments) + if not usage: + body = json.loads(recorder.responses[0].content) + body.pop("usage") + recorder.responses[0] = _ok(body) + channel = ProtocolChannel(-1, (literal.encode(),), -1, Mock(), (Mock(), Mock())) + ledger = RecordingLedger() + try: + with pytest.raises(KeyLeakError): + await _run( + client, None, ledger, caps=Caps(model_calls=1), check_content=channel.check_content + ) + assert len(recorder.seen) == len(ledger.reserves) == len(ledger.settles) == 1 + assert ledger.settles[0]["outcome"] == ("ok" if usage else "no_usage") + assert (ledger.settles[0]["buckets"] is not None) is usage + finally: + await _close(client) + + +@pytest.mark.parametrize("provider", ["openai", "ollama"]) +@pytest.mark.parametrize("case", ["integer-limit", "nesting-limit"]) +async def test_argument_normalization_limits_keep_known_usage_and_safe_continuation(provider, case): + arguments = ( + '{"query":' + "7" * 4301 + "}" + if case == "integer-limit" + else '{"query":' + "[" * 20000 + "0" + "]" * 20000 + "}" + ) + client, recorder = _argument_client(provider, arguments) + ledger = RecordingLedger() + bridge, dispatch = _bridge(CallToolResult(content=[TextContent(type="text", text="safe")])) + channel = ProtocolChannel(-1, (b"synthetic_bootstrap_opaque",), -1, Mock(), (Mock(), Mock())) + try: + record = await _run(client, bridge, ledger, check_content=channel.check_content) + assert record["status"] == "succeeded" + assert len(recorder.seen) == len(ledger.reserves) == len(ledger.settles) == 2 + expected = ( + Buckets(500, 300, 200, 50, 40) if provider == "openai" else Buckets(120, 0, 0, 30) + ) + assert ledger.settles[0] == {"unit_id": "1", "outcome": "ok", "buckets": expected} + assert record["tool_calls"][0]["is_error"] is True + assert record["tool_calls"][0]["raw_arguments"] == arguments + dispatch.assert_not_awaited() + finally: + await _close(client) + + +@pytest.mark.parametrize("provider", ["openai", "ollama"]) +@pytest.mark.parametrize("arguments", ['{"query":"ordinary\\', '{"query":"ordinary\\u00']) +async def test_uninspectable_argument_suffix_stops_after_honest_settlement(provider, arguments): + client, recorder = _argument_client(provider, arguments) + ledger = RecordingLedger() + try: + with pytest.raises(KeyLeakError, match="uninspectable JSON string"): + await _run(client, None, ledger) + assert len(recorder.seen) == len(ledger.reserves) == len(ledger.settles) == 1 + assert ledger.settles[0]["outcome"] == "ok" + finally: + await _close(client) + + +@pytest.mark.parametrize("provider", ["openai", "ollama"]) +async def test_argument_inspection_budget_fails_closed_after_settlement(monkeypatch, provider): + from benchmarks.agentic import clients, protocol + + monkeypatch.setattr(clients, "MAX_FRAME_BYTES", 64) + monkeypatch.setattr(protocol, "MAX_FRAME_BYTES", 64) + client, recorder = _argument_client(provider, '{"query":"' + "x" * 65 + '"}') + ledger = RecordingLedger() + try: + with pytest.raises(KeyLeakError, match="content inspection limit"): + await _run(client, None, ledger) + assert len(recorder.seen) == len(ledger.reserves) == len(ledger.settles) == 1 + assert ledger.settles[0]["outcome"] == "ok" + finally: + await _close(client) + + +@pytest.mark.parametrize("provider", ["openai", "ollama"]) +async def test_safe_escaped_quotes_and_unicode_keep_dispatch_and_native_replay(provider): + query = 'quote: " slash: \\ emoji: 😀' + arguments = json.dumps({"query": query}) + client, recorder = _argument_client(provider, arguments) + bridge, dispatch = _bridge(CallToolResult(content=[TextContent(type="text", text="safe")])) + ledger = RecordingLedger() + try: + record = await _run(client, bridge, ledger) + assert record["status"] == "succeeded" + dispatch.assert_awaited_once_with("search_docs", {"query": query}) + assert len(recorder.seen) == len(ledger.settles) == 2 + finally: + await _close(client) + + +@pytest.mark.parametrize("provider", ["openai", "ollama"]) +async def test_decoded_scalar_keeps_rendered_key_boundary_check(provider): + marker = "AIza" + "g" * 35 + value = "\0xxx" + marker + assert KEY_SHAPED.search(value) is None + arguments = json.dumps(value).replace("A", r"\u0041", 1) + assert KEY_SHAPED.search(arguments) is None + client, recorder = _argument_client(provider, arguments) + ledger = RecordingLedger() + try: + with pytest.raises(KeyLeakError): + await _run(client, None, ledger) + assert len(recorder.seen) == len(ledger.reserves) == len(ledger.settles) == 1 + finally: + await _close(client) + + +async def test_unbalanced_prefix_cannot_hide_a_replayed_argument(): + client, recorder = _argument_client("openai", r'x"{"query":"pre\u006frchard-suffix"}') + ledger = RecordingLedger() + bridge, dispatch = _bridge(CallToolResult(content=[TextContent(type="text", text="safe")])) + channel = ProtocolChannel(-1, (b"orchard",), -1, None, ()) + try: + with pytest.raises(KeyLeakError): + await _run(client, bridge, ledger, check_content=channel.check_content) + assert len(recorder.seen) == len(ledger.reserves) == len(ledger.settles) == 1 + assert ledger.settles[0]["outcome"] == "ok" + dispatch.assert_not_awaited() + finally: + await _close(client) diff --git a/tests/benchmarks/test_agentic_argument_depth.py b/tests/benchmarks/test_agentic_argument_depth.py new file mode 100644 index 00000000..49813e80 --- /dev/null +++ b/tests/benchmarks/test_agentic_argument_depth.py @@ -0,0 +1,201 @@ +"""Bound argument normalization before recursive transcript/MCP serialization; no network.""" + +from __future__ import annotations + +import asyncio +import json +from pathlib import Path +from unittest.mock import AsyncMock + +import pytest +from mcp.types import CallToolResult, TextContent + +from benchmarks.agentic import clients, worker +from benchmarks.agentic.bridge import open_bridge +from benchmarks.agentic.protocol import KEY_SHAPED, KeyLeakError, encode_frame +from benchmarks.agentic.types import Buckets +from tests.benchmarks.test_agentic_argument_content import _argument_client +from tests.benchmarks.test_agentic_host import NO_DOCS, _family +from tests.benchmarks.test_agentic_mcp_boundary import _system +from tests.benchmarks.test_agentic_outgoing import RecordingLedger, _bridge, _close, _run + + +def _arguments(depth, shape, leaf='"ordinary"'): + """Build JSON text with exactly depth containers, without recursive fixture code.""" + opens, closes = [], [] + for index in range(depth - 1): + array = shape == "array" or (shape == "mixed" and index % 2 == 0) + opens.append("[" if array else '{"value":') + closes.append("]" if array else "}") + return '{ "query": ' + "".join(opens) + leaf + "".join(reversed(closes)) + " }" + + +def _native_arguments(provider, payload, *, response=False): + if provider == "openai": + items = payload["output" if response else "input"] + return next(item["arguments"] for item in items if item.get("type") == "function_call") + message = payload["choices"][0]["message"] if response else next( + item for item in payload["messages"] if item.get("tool_calls") + ) + return message["tool_calls"][0]["function"]["arguments"] + + +@pytest.mark.parametrize("provider", ["openai", "ollama"]) +@pytest.mark.parametrize("shape", ["array", "object", "mixed"]) +@pytest.mark.parametrize("depth", [65, 1100, 9500]) +@pytest.mark.parametrize("shadowed", [False, True]) +async def test_deep_sdk_arguments_keep_usage_evidence_and_invalid_argument_continuation( + provider, shape, depth, shadowed +): + arguments = _arguments(depth, shape) + if shadowed: + arguments = arguments[:-2] + ', "query":"safe" }' + client, recorder = _argument_client(provider, arguments) + ledger = RecordingLedger() + bridge, dispatch = _bridge(CallToolResult(content=[TextContent(type="text", text="safe")])) + channel = worker.ProtocolChannel(-1, (), -1, None, ()) + try: + record = await _run(client, bridge, ledger, check_content=channel.check_content) + assert record["status"] == "succeeded" + assert len(recorder.seen) == len(ledger.reserves) == len(ledger.settles) == 2 + expected = ( + Buckets(500, 300, 200, 50, 40) if provider == "openai" else Buckets(120, 0, 0, 30) + ) + assert ledger.settles[0] == {"unit_id": "1", "outcome": "ok", "buckets": expected} + call = record["tool_calls"][0] + assert call["is_error"] is True + assert call["arguments"] == {} + assert call["raw_arguments"] == arguments + raw_response = record["model_calls"][0]["raw_response"] + assert _native_arguments(provider, raw_response, response=True) == arguments + assert _native_arguments(provider, recorder.body(1)) == arguments + # Exercise publication, which previously failed before a score could be produced. + encode_frame({"type": "trajectory", "record": record}, where="test trajectory") + dispatch.assert_not_awaited() + finally: + await _close(client) + + +@pytest.mark.parametrize("provider", ["openai", "ollama"]) +@pytest.mark.parametrize("shape", ["array", "object", "mixed"]) +@pytest.mark.parametrize("depth", [1, 16, 64]) +async def test_reasonable_argument_depth_completes_real_mcp_validation_and_publication( + provider, shape, depth +): + # Brackets, escaped quotes and backslashes inside strings must not count as containers. + arguments = _arguments(depth, shape, json.dumps('ordinary [ { \\ " ] }' * 80)) + client, recorder = _argument_client(provider, arguments) + ledger = RecordingLedger() + try: + async with open_bridge(_system("valid", "clean")) as bridge: + record = await _run(client, bridge, ledger) + assert record["status"] == "succeeded" + call = record["tool_calls"][0] + assert call["arguments"] == json.loads(arguments) + assert call["raw_arguments"] is None + assert call["is_error"] is False + assert call["result"] == '{"answer":"clean answer"}' + assert _native_arguments(provider, recorder.body(1)) == arguments + encode_frame({"type": "trajectory", "record": record}, where="test trajectory") + finally: + await _close(client) + + +@pytest.mark.parametrize("provider", ["openai", "ollama"]) +@pytest.mark.parametrize("depth", [64, 65, 1100]) +@pytest.mark.parametrize("kind", ["opaque", "shaped"]) +@pytest.mark.parametrize("shadowed", [False, True]) +async def test_deep_and_near_limit_arguments_scan_encoded_content_even_when_shadowed( + provider, depth, kind, shadowed +): + marker = "orchard" if kind == "opaque" else "AIza" + "g" * 35 + encoded = json.dumps(marker).replace(marker[0], f"\\u{ord(marker[0]):04x}", 1) + arguments = _arguments(depth, "mixed", encoded) + if shadowed: + arguments = arguments[:-2] + ', "query":"safe" }' + assert KEY_SHAPED.search(arguments) is None + client, recorder = _argument_client(provider, arguments, safe_first=True) + ledger = RecordingLedger() + bridge, dispatch = _bridge(CallToolResult(content=[TextContent(type="text", text="safe")])) + literals = (marker.encode(),) if kind == "opaque" else () + channel = worker.ProtocolChannel(-1, literals, -1, None, ()) + try: + with pytest.raises(KeyLeakError): + await _run(client, bridge, ledger, check_content=channel.check_content) + assert len(recorder.seen) == len(ledger.reserves) == len(ledger.settles) == 1 + assert ledger.settles[0]["outcome"] == "ok" + dispatch.assert_not_awaited() + finally: + await _close(client) + + +async def _run_sdk_worker(client, monkeypatch): + reader = asyncio.StreamReader() + messages = [] + + class Channel: + check_content = worker.ProtocolChannel(-1, (), -1, None, ()).check_content + + def send(self, message): + encode_frame(message, where="test worker report") + messages.append(message) + if message["type"] == "reserve": + reader.feed_data(encode_frame({"type": "grant", "unit_id": str(len(messages))})) + elif message["type"] in ("settle", "trajectory", "discarded"): + reader.feed_data(encode_frame({"type": "ack"})) + + job = { + "type": "job", + "family": _family(Path("unused")).raw, # scripted limits: no models endpoint + "system": NO_DOCS.raw, + "caps": {}, + "trajectories": [{"corpus_id": "Q1", "repeat": 1, "prompt": "ordinary"}], + } + monkeypatch.setattr(clients, "make_client", lambda *args, **kwargs: client) + return await worker.run_worker(Channel(), reader, job), messages + + +@pytest.mark.parametrize("provider", ["openai", "ollama"]) +async def test_sdk_accepted_depth_keeps_worker_alive_and_publishes_a_trajectory( + monkeypatch, provider +): + client, recorder = _argument_client(provider, _arguments(1100, "array")) + try: + status, messages = await _run_sdk_worker(client, monkeypatch) + assert status == 0, [m for m in messages if m["type"] == "error"] + assert messages[-1] == {"type": "done"} + assert len(recorder.seen) == 2 + assert [m["outcome"] for m in messages if m["type"] == "settle"] == ["ok", "ok"] + trajectories = [m["record"] for m in messages if m["type"] == "trajectory"] + assert len(trajectories) == 1 + assert trajectories[0]["status"] == "succeeded" + assert trajectories[0]["tool_calls"][0]["raw_arguments"] == _arguments(1100, "array") + finally: + await _close(client) + + +@pytest.mark.parametrize("provider", ["openai", "ollama"]) +@pytest.mark.parametrize("arguments", [r'{"query":"\ud800"}', r'{"\udfff":"value"}']) +async def test_unpaired_surrogate_stops_worker_after_one_correct_settlement( + monkeypatch, provider, arguments +): + client, recorder = _argument_client(provider, arguments, safe_first=True) + bridge, dispatch = _bridge(CallToolResult(content=[])) + monkeypatch.setattr(worker, "_open", AsyncMock(return_value=bridge)) + try: + status, messages = await _run_sdk_worker(client, monkeypatch) + assert status == 3 + assert messages[-1] == {"type": "error", "reason": worker.WORKER_LEAK_REASON} + assert len(recorder.seen) == 1 + dispatch.assert_not_awaited() + assert [m["type"] for m in messages if m["type"] != "system_info"] == [ + "reserve", "settle", "error" + ] + settlement = next(m for m in messages if m["type"] == "settle") + expected = ( + Buckets(500, 300, 200, 50, 40) if provider == "openai" else Buckets(120, 0, 0, 30) + ) + assert settlement["outcome"] == "ok" + assert Buckets(**settlement["buckets"]) == expected + finally: + await _close(client) diff --git a/tests/benchmarks/test_agentic_bridge.py b/tests/benchmarks/test_agentic_bridge.py index 0a0d16c7..39d14945 100644 --- a/tests/benchmarks/test_agentic_bridge.py +++ b/tests/benchmarks/test_agentic_bridge.py @@ -15,9 +15,11 @@ canonical_text, load_systems, open_bridge, + server_env, system_spec_from_raw, truncate_utf8, ) +from benchmarks.agentic.protocol import KeyLeakError from tests.test_mcp_get_docs_cache_smoke import _create_contentful_json_index from tests.test_stdio_smoke import _isolated_cache_env @@ -56,6 +58,14 @@ def test_canonical_text_prefers_compact_structured_content() -> None: assert canonical_text(r) == '{"a":"é","b":[1,2]}' +def test_structured_tool_result_refuses_a_key_before_converting_to_text() -> None: + key = "AIza" + "g" * 35 + result = CallToolResult(content=[], structured_content={"extra": [{"\n" + key: True}]}) + with pytest.raises(KeyLeakError) as caught: + canonical_text(result) + assert key not in str(caught.value) + + def test_canonical_text_joins_text_blocks_and_marks_other_blocks() -> None: r = CallToolResult( content=[ @@ -84,10 +94,15 @@ def test_load_systems_reads_the_committed_manifest() -> None: systems = {s.id: s for s in load_systems(AGENTIC_MANIFEST_PATH)} assert set(systems) == {"python-docs", "docs-fetch", "no-docs"} assert systems["python-docs"].command == ("{python}", "-m", "mcp_server_python_docs", "serve") - assert systems["python-docs"].env == {"PYTHON_DOCS_MCP_DISABLE_AUTO_INDEX": "1"} + assert systems["python-docs"].env == { + "PYTHON_DOCS_MCP_DISABLE_AUTO_INDEX": "1", + "HTTPS_PROXY": "{egress}", + "HTTP_PROXY": "{egress}", + } assert systems["python-docs"].pass_env == ("HOME", "XDG_CACHE_HOME") assert systems["docs-fetch"].command == ("mcp-server-fetch",) - assert systems["docs-fetch"].pass_env == ("HOME", "HTTPS_PROXY", "HTTP_PROXY", "NO_PROXY") + assert systems["docs-fetch"].env == {"HTTPS_PROXY": "{egress}", "HTTP_PROXY": "{egress}"} + assert systems["docs-fetch"].pass_env == ("HOME",) assert systems["no-docs"].transport == "none" assert all(system_spec_from_raw(s.raw) == s for s in systems.values()) @@ -208,3 +223,28 @@ async def test_server_env_holds_only_the_listed_variables(monkeypatch: pytest.Mo text = (await bridge.call("env_names", {})).text assert '"MARKER"' in text and '"HOME"' in text assert "ANTHROPIC_API_KEY" not in text + + +def _committed(system_id: str) -> SystemSpec: + return {s.id: s for s in load_systems(AGENTIC_MANIFEST_PATH)}[system_id] + + +@pytest.mark.parametrize("system_id", ["python-docs", "docs-fetch"]) +def test_server_env_points_both_proxy_variables_at_the_egress(system_id: str) -> None: + env = server_env(_committed(system_id), {"BENCHMARK_EGRESS_URL": "http://egress:3128"}) + assert env["HTTPS_PROXY"] == env["HTTP_PROXY"] == "http://egress:3128" + if system_id == "python-docs": + assert env["PYTHON_DOCS_MCP_DISABLE_AUTO_INDEX"] == "1" + + +@pytest.mark.parametrize("system_id", ["python-docs", "docs-fetch"]) +def test_server_env_drops_the_proxy_variables_without_an_egress(system_id: str) -> None: + env = server_env(_committed(system_id), {"HOME": "/tmp"}) + assert "HTTPS_PROXY" not in env and "HTTP_PROXY" not in env + assert "{egress}" not in env.values() and env["HOME"] == "/tmp" + + +def test_no_worker_proxy_variable_reaches_an_mcp_server() -> None: + environ = {"HTTPS_PROXY": "socks5://x:1", "ALL_PROXY": "socks5://x:1", "HOME": "/tmp"} + env = server_env(_committed("docs-fetch"), environ) + assert not [name for name in env if name.upper().endswith("_PROXY")] diff --git a/tests/benchmarks/test_agentic_cleanup_failure.py b/tests/benchmarks/test_agentic_cleanup_failure.py new file mode 100644 index 00000000..7c8925be --- /dev/null +++ b/tests/benchmarks/test_agentic_cleanup_failure.py @@ -0,0 +1,381 @@ +"""Recognized worker credential failures survive real asynchronous teardown.""" + +import asyncio +import errno +import json +import os +import subprocess +import sys +import traceback +from pathlib import Path +from typing import Any + +import pytest + +from benchmarks.__main__ import main +from benchmarks.adapters.guard import PROVIDER_API_KEY_ENV +from benchmarks.agentic import host +from benchmarks.agentic.cleanup import finish +from benchmarks.agentic.host import LocalLauncher, WorkerJob, run_jobs +from benchmarks.agentic.ledger import Ledger +from benchmarks.agentic.protocol import WORKER_LEAK_REASON, KeyLeakError +from benchmarks.agentic.sandbox import _rollback +from benchmarks.runner import BenchmarkValidationError +from tests.benchmarks.test_agentic_host import ( + ANSWER, + REPO_ROOT, + SYNTHETIC_KEY, + D, + Host, + _job, + _reserve_frame, +) +from tests.benchmarks.test_agentic_run import _cli_args + + +def _worker_code(*, leak: bool = True, reason: str = WORKER_LEAK_REASON) -> str: + # A separate isolated interpreter writes raw wire frames, bypassing output guards. + return ( + "import json, os, sys\n" + "def read():\n" + " n = int.from_bytes(sys.stdin.buffer.read(8), 'big')\n" + " return json.loads(sys.stdin.buffer.read(n))\n" + "def send(value):\n" + " body = json.dumps(value).encode()\n" + " os.write(1, len(body).to_bytes(8, 'big') + body)\n" + "assert read()['type'] == 'job'\n" + f"send({_reserve_frame(1024)!r})\n" + "assert read()['type'] == 'grant'\n" + "os.write(2, b'clean worker stderr\\n')\n" + + (f"send({{'type': 'error', 'reason': {reason!r}}})\n" if leak else "") + + f"sys.exit({3 if leak and reason == WORKER_LEAK_REASON else 2})\n" + ) + + +def _storage_error(secret: str = "") -> OSError: + error = OSError(errno.ENOSPC, "artifact volume full") + if secret: + error.__cause__ = RuntimeError("daemon response: " + secret) + error.add_note("collection note: " + secret) + return error + + +def _assert_safe_chain(error: BaseException, raw: BaseException) -> str: + seen: set[int] = set() + stack = [error] + while stack: + item = stack.pop() + if id(item) in seen: + continue + seen.add(id(item)) + assert item is not raw + assert SYNTHETIC_KEY not in str(item) + assert SYNTHETIC_KEY not in "\n".join(getattr(item, "__notes__", [])) + stack.extend(e for e in (item.__cause__, item.__context__) if e is not None) + if isinstance(item, BaseExceptionGroup): + stack.extend(item.exceptions) + trace = "".join(traceback.format_exception(error)) + assert SYNTHETIC_KEY not in trace + return trace + + +@pytest.mark.parametrize("secret", ["", SYNTHETIC_KEY], ids=["clean", "credential-chain"]) +async def test_finish_keeps_original_leak_and_only_safe_cleanup_diagnostics(secret: str) -> None: + original = KeyLeakError("recognized worker credential failure") + failure = _storage_error(secret) + prior = BenchmarkValidationError("earlier cleanup failed") + original.__cause__ = prior + + async def fail() -> None: + await asyncio.sleep(0) + raise failure + + with pytest.raises(KeyLeakError) as caught: + try: + raise original + finally: + await finish(fail(), original) + assert caught.value is original + trace = _assert_safe_chain(caught.value, failure) + assert "OSError" in trace and "artifact volume full" in trace + assert "earlier cleanup failed" in trace and "cleanup" in trace + if secret: + assert "daemon response" in trace and "collection note" in trace + assert "[redacted]" in trace + + +@pytest.mark.parametrize("boundary", ["publish", "close", "problems"]) +@pytest.mark.parametrize("secret", ["", SYNTHETIC_KEY], ids=["clean", "credential-chain"]) +async def test_recognized_frame_survives_async_cleanup_and_settles( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, boundary: str, secret: str +) -> None: + for name in PROVIDER_API_KEY_ENV.values(): + monkeypatch.delenv(name, raising=False) + h = Host(tmp_path) + job = _job(tmp_path, [ANSWER], job_id="recognized-leak") + service = h.service(job.family) + failure = _storage_error(secret) + captures, processes, anchors, pending = [], [], [], [] + original_reserve = service.reserve + original_spawn = asyncio.create_subprocess_exec + original_anchor = host._start_anchor + original_snapshot = host._scrubbed_snapshot + observed: list[KeyLeakError] = [] + + async def reserve(**kwargs: Any) -> str | None: + unit = await original_reserve(**kwargs) + if unit is not None: + # Queued while the worker holds the only in-flight provider unit. + pending.append(asyncio.create_task(original_reserve(**kwargs))) + return unit + + async def spawn(*args: Any, **kwargs: Any) -> asyncio.subprocess.Process: + proc = await original_spawn(*args, **kwargs) + processes.append(proc) + return proc + + def anchor() -> Any: + proc = original_anchor() + anchors.append(proc) + return proc + + def snapshot(log: Any) -> Any: + captures.append(log) + return original_snapshot(log) + + async def observe_finish(operation: Any, unwinding: BaseException | None = None) -> Any: + if isinstance(unwinding, KeyLeakError): + observed.append(unwinding) + return await finish(operation, unwinding) + + class Launcher(LocalLauncher): + stopped = closed = False + + def command(self, job: WorkerJob) -> tuple[list[str], dict[str, str]]: + return [sys.executable, "-I", "-c", _worker_code()], {} + + async def stop_worker(self, job: WorkerJob) -> None: + self.stopped = True + assert pending + assert not pending[0].done() # settlement releases the provider lock later + + async def close(self) -> list[str]: + await asyncio.sleep(0) # exercise a real awaited close, after settlement + self.closed = True + assert await asyncio.wait_for(pending[0], 2) is None + if boundary == "close": + raise failure + return ["outside network removal failed: " + secret] if boundary == "problems" else [] + + def publish(data: bytes, path: Path) -> None: + assert data == b"clean worker stderr\n" + raise failure + + monkeypatch.setattr(service, "reserve", reserve) + monkeypatch.setattr(asyncio, "create_subprocess_exec", spawn) + monkeypatch.setattr(host, "_start_anchor", anchor) + monkeypatch.setattr(host, "_scrubbed_snapshot", snapshot) + monkeypatch.setattr(host, "finish", observe_finish) + if boundary == "publish": + monkeypatch.setattr(host, "_publish_worker_log", publish) + launcher = Launcher() + try: + with pytest.raises(KeyLeakError) as caught: + await run_jobs( + [job], + launcher=launcher, + ledger=service, + on_message=h.on_message, + log_dir=tmp_path / "logs", + cwd=REPO_ROOT, + ) + assert caught.value is observed[0] + trace = _assert_safe_chain(caught.value, failure) + assert WORKER_LEAK_REASON in str(caught.value) + assert ( + "outside network removal failed" if boundary == "problems" else "artifact volume full" + ) in trace + assert launcher.stopped and launcher.closed + assert captures and all(log.closed for log in captures) + assert processes and all(proc.returncode is not None for proc in processes) + assert anchors and all( + proc.returncode is not None and proc.stdin.closed for proc in anchors + ) + events = h.ledger.invocation_events() + assert [event["event"] for event in events] == ["reserve", "settle"] + assert events[1]["outcome"] == "worker_lost" + assert D(events[1]["booked"]) == 2 * D(events[0]["bound"]) + before = h.ledger.spent("anthropic") + assert ( + await original_reserve( + provider="anthropic", + model_id=job.family.model_id, + input_bound=1000, + output_bound=1024, + ) + is None + ) + assert h.ledger.spent("anthropic") == before + assert h.ledger.invocation_events() == events + log_path = tmp_path / "logs" / f"{job.job_id}.stderr.log" + assert ( + not log_path.exists() + if boundary == "publish" + else (log_path.read_bytes() == b"clean worker stderr\n") + ) + finally: + for task in pending: + task.cancel() + await asyncio.gather(*pending, return_exceptions=True) + h.ledger.close() + reopened = Ledger.open(tmp_path / "ledger", run_id="after-failure") + try: + assert reopened.spent("anthropic") == before + finally: + reopened.close() + + +async def test_rollback_keeps_recognized_leak_with_cleanup_diagnostics() -> None: + original = KeyLeakError("setup credential failure") + failure = _storage_error(SYNTHETIC_KEY) + + async def remove() -> None: + await asyncio.sleep(0) + raise failure + + with pytest.raises(KeyLeakError) as caught: + await _rollback(remove(), original) + assert caught.value is original + assert "artifact volume full" in _assert_safe_chain(caught.value, failure) + + +async def test_unprintable_cleanup_does_not_replace_recognized_leak( + monkeypatch: pytest.MonkeyPatch, +) -> None: + original = KeyLeakError("recognized worker credential failure") + + class BrokenError(Exception): + def __str__(self) -> str: + raise ValueError("formatting failed " + SYNTHETIC_KEY) + + async def fail() -> None: + raise BrokenError() + + def broken_format(*args: Any, **kwargs: Any) -> Any: + raise ValueError("formatting failed " + SYNTHETIC_KEY) + + with monkeypatch.context() as formatting: + formatting.setattr(traceback, "format_exception", broken_format) + with pytest.raises(KeyLeakError) as caught: + await finish(fail(), original) + assert caught.value is original + assert "could not safely report BrokenError" in str(original.__cause__) + assert SYNTHETIC_KEY not in "".join(traceback.format_exception(original)) + + +@pytest.mark.parametrize("pending_leak", [False, True]) +async def test_finish_waits_through_repeated_cancellation_before_cleanup_failure( + pending_leak: bool, +) -> None: + stopping, release = asyncio.Event(), asyncio.Event() + pending = ( + KeyLeakError("recognized credential failure") + if pending_leak + else asyncio.CancelledError("first signal") + ) + failure = _storage_error() + + async def remove() -> None: + stopping.set() + await release.wait() + raise failure + + task = asyncio.create_task(finish(remove(), pending)) + await stopping.wait() + task.cancel("later signal") + await asyncio.sleep(0) + task.cancel("last signal") + await asyncio.sleep(0) + assert not task.done() + release.set() + with pytest.raises(asyncio.CancelledError) as caught: + await task + if pending_leak: + assert str(caught.value) == "later signal" + else: + assert caught.value is pending + assert caught.value.__cause__ is failure + + +def test_keyboard_interrupt_during_cleanup_keeps_its_precedence() -> None: + # asyncio treats KeyboardInterrupt specially. Exercise it in an owned interpreter + # so pytest's own event loop and signal handling remain outside the reproduction. + code = ( + "import asyncio, sys\n" + f"sys.path.insert(0, {str(REPO_ROOT)!r})\n" + "from benchmarks.agentic.cleanup import finish\n" + "from benchmarks.agentic.protocol import KeyLeakError\n" + "interrupt = KeyboardInterrupt('operator interrupt')\n" + "async def remove():\n" + " await asyncio.sleep(0)\n" + " raise interrupt\n" + "try:\n" + " asyncio.run(finish(remove(), KeyLeakError('recognized credential failure')))\n" + "except KeyboardInterrupt as caught:\n" + " assert caught is interrupt\n" + "else:\n" + " raise AssertionError('operator interrupt was replaced')\n" + ) + proc = subprocess.run( + [sys.executable, "-I", "-c", code], env={}, capture_output=True, text=True, timeout=10 + ) + assert proc.returncode == 0, proc.stderr + + +@pytest.mark.parametrize("leak", [False, True]) +def test_cli_recognized_frame_and_clean_stderr_publication_failure( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str], leak: bool +) -> None: + for name in PROVIDER_API_KEY_ENV.values(): + monkeypatch.delenv(name, raising=False) + monkeypatch.setattr( + LocalLauncher, + "command", + lambda self, job: ([sys.executable, "-I", "-c", _worker_code(leak=leak)], {}), + ) + replace = os.replace + + def no_space(src: Any, dst: Any, **kwargs: Any) -> None: + if str(dst).endswith(".stderr.log"): + raise _storage_error() + replace(src, dst, **kwargs) + + monkeypatch.setattr(os, "replace", no_space) + args = [*_cli_args(tmp_path), "--models", "scripted-anthropic", "--systems", "no-docs"] + if leak: + with pytest.raises(SystemExit) as caught: + main(args) + assert caught.value.code == 3 + else: + with pytest.raises(OSError, match="artifact volume full") as caught: + main(args) + assert caught.value.errno == errno.ENOSPC + output = capsys.readouterr() + assert "artifact volume full" in output.err + assert SYNTHETIC_KEY not in output.err and output.out == "" + summary = json.loads((tmp_path / "run" / "run-summary.json").read_text()) + assert summary["status"] == "aborted" + assert summary["abort_reason"].startswith("KeyLeakError:" if leak else "OSError:") + events = [ + json.loads(line) + for line in (tmp_path / "ledger" / "anthropic.jsonl").read_text().splitlines() + ] + reserve, settle = (event for event in events if event["event"] in ("reserve", "settle")) + assert settle["outcome"] == "worker_lost" + assert D(settle["booked"]) == 2 * D(reserve["bound"]) + assert not list((tmp_path / "run" / "logs").glob("*")) + reopened = Ledger.open(tmp_path / "ledger", run_id="after-cli") + try: + assert reopened.spent("anthropic") == D(settle["booked"]) + finally: + reopened.close() diff --git a/tests/benchmarks/test_agentic_clients.py b/tests/benchmarks/test_agentic_clients.py index 56ebc97e..67fd9c73 100644 --- a/tests/benchmarks/test_agentic_clients.py +++ b/tests/benchmarks/test_agentic_clients.py @@ -9,7 +9,7 @@ import json from collections.abc import Callable from dataclasses import replace -from datetime import UTC, datetime, timedelta +from datetime import UTC, datetime, timedelta, tzinfo from email.utils import format_datetime from pathlib import Path from typing import Any @@ -20,19 +20,29 @@ import pytest import yaml -from benchmarks.adapters.guard import PAID_KEY_ENVS, PROVIDER_API_KEY_ENV, LiveProviderDisabledError +from benchmarks.adapters.guard import ( + PAID_KEY_ENVS, + PROVIDER_API_KEY_ENV, + LiveProviderDisabledError, + require_live_environment, +) +from benchmarks.agentic import clients from benchmarks.agentic.clients import ( AnthropicClient, GeminiClient, + OllamaChatClient, OpenAIResponsesClient, ScriptedClient, anthropic_sdk, + fetch_model_limits, gemini_sdk, make_client, + ollama_sdk, openai_sdk, parse_retry_after, tool_arguments, ) +from benchmarks.agentic.protocol import KeyLeakError from benchmarks.agentic.types import ( Buckets, Conversation, @@ -367,11 +377,27 @@ def test_tool_arguments(value: Any, expected: tuple[dict[str, Any], str | None]) assert tool_arguments(value) == expected -def test_parse_retry_after_accepts_an_http_date() -> None: - when = format_datetime(datetime.now(UTC) + timedelta(seconds=30), usegmt=True) - value = parse_retry_after({"retry-after": when}) - assert value is not None and 28 < value <= 30 - past = format_datetime(datetime.now(UTC) - timedelta(seconds=30), usegmt=True) +@pytest.mark.parametrize("serialized", [True, False]) +def test_raw_tool_arguments_refuse_a_key_before_becoming_transcript_text(serialized: bool) -> None: + key = "AIza" + "g" * 35 + arguments = ["\n" + key] + with pytest.raises(KeyLeakError) as caught: + tool_arguments(json.dumps(arguments) if serialized else arguments) + assert key not in str(caught.value) + + +def test_parse_retry_after_accepts_an_http_date(monkeypatch: pytest.MonkeyPatch) -> None: + now = datetime(2026, 11, 4, 12, 0, 0, tzinfo=UTC) + + class Frozen(datetime): + @classmethod + def now(cls, tz: tzinfo | None = None) -> datetime: + return now + + monkeypatch.setattr(clients, "datetime", Frozen) + when = format_datetime(now + timedelta(seconds=30), usegmt=True) + assert parse_retry_after({"retry-after": when}) == 30.0 + past = format_datetime(now - timedelta(seconds=30), usegmt=True) assert parse_retry_after({"retry-after": past}) == 0 assert parse_retry_after({"retry-after": "soon"}) is None assert parse_retry_after({}) is None @@ -610,12 +636,48 @@ def test_make_client_refuses_a_second_paid_key(monkeypatch: pytest.MonkeyPatch) assert "not-a-real-key" not in str(caught.value) -def test_make_client_refuses_the_ollama_api_until_pr_4(monkeypatch: pytest.MonkeyPatch) -> None: +def test_make_client_builds_the_ollama_client_through_the_guard( + monkeypatch: pytest.MonkeyPatch, +) -> None: + _clear_keys(monkeypatch) + monkeypatch.delenv("OLLAMA_BASE_URL", raising=False) + family = _matrix_family("gemma4-12b") + with pytest.raises(LiveProviderDisabledError): + make_client(family, timeout_s=600) + monkeypatch.setenv("BENCHMARK_LIVE_PROVIDERS_ENABLED", "1") + monkeypatch.setenv("OLLAMA_BASE_URL", "http://host.docker.internal:11434/v1") + client = make_client(family, timeout_s=600) # builds an SDK object; sends nothing + assert isinstance(client, OllamaChatClient) and client.provider == "ollama" + assert client.model_id == "gemma4:12b" + monkeypatch.setenv("ANTHROPIC_API_KEY", "not-a-real-key") + with pytest.raises(BenchmarkValidationError, match="ANTHROPIC_API_KEY") as caught: + make_client(family, timeout_s=600) + assert "not-a-real-key" not in str(caught.value) + + +def test_make_client_refuses_an_ollama_base_url_that_is_not_http( + monkeypatch: pytest.MonkeyPatch, +) -> None: _clear_keys(monkeypatch) - with pytest.raises(BenchmarkValidationError, match="openai-chat-completions"): + monkeypatch.setenv("BENCHMARK_LIVE_PROVIDERS_ENABLED", "1") + monkeypatch.setenv("OLLAMA_BASE_URL", "file:///etc/passwd") + with pytest.raises(BenchmarkValidationError, match="OLLAMA_BASE_URL"): make_client(_matrix_family("gemma4-12b"), timeout_s=600) +def test_ollama_needs_the_live_flag_and_its_base_url(monkeypatch: pytest.MonkeyPatch) -> None: + _clear_keys(monkeypatch) + monkeypatch.delenv("OLLAMA_BASE_URL", raising=False) + monkeypatch.setenv("BENCHMARK_LIVE_PROVIDERS_ENABLED", "1") + with pytest.raises(LiveProviderDisabledError, match="OLLAMA_BASE_URL"): + require_live_environment("ollama") + monkeypatch.setenv("OLLAMA_BASE_URL", "http://127.0.0.1:11434/v1") + require_live_environment("ollama") # no key is read: none is set + monkeypatch.delenv("BENCHMARK_LIVE_PROVIDERS_ENABLED") + with pytest.raises(LiveProviderDisabledError): + require_live_environment("ollama") + + def test_make_client_refuses_a_provider_that_does_not_match_its_api( monkeypatch: pytest.MonkeyPatch, ) -> None: @@ -846,3 +908,230 @@ def test_a_ca_variable_cannot_swap_a_clients_trust_store( # No transport is injected and nothing is patched; no request is made. monkeypatch.setenv("SSL_CERT_FILE", "/nonexistent/ca.pem") build("test-key", 30) + + +LIVE_HOSTS = [ + ("claude-sonnet-5-5", "api.anthropic.com"), + ("gpt-6.1-sol", "api.openai.com"), + ("gemini-3.8-flash", "generativelanguage.googleapis.com"), +] + + +def _proxy_url(proxy: Any) -> str | None: + """A route's proxy as its URL string, whether given as a string or a proxy object.""" + if proxy is None or isinstance(proxy, str): + return proxy + return str(getattr(proxy, "url", proxy)) + + +@pytest.mark.parametrize("family_id,host", LIVE_HOSTS) +async def test_the_egress_proxy_carries_every_call( + monkeypatch: pytest.MonkeyPatch, family_id: str, host: str +) -> None: + # As test_a_proxy_variable_cannot_steer_a_call, with the sandbox's explicit egress proxy + # set beside two hostile proxy variables: only the egress route may carry the call. + _clear_keys(monkeypatch) + family = _matrix_family(family_id) + monkeypatch.setenv("BENCHMARK_LIVE_PROVIDERS_ENABLED", "1") + monkeypatch.setenv(PROVIDER_API_KEY_ENV[family.provider], "not-a-real-key") + monkeypatch.setenv("BENCHMARK_EGRESS_URL", "http://egress:3128") + monkeypatch.setenv("HTTPS_PROXY", "http://proxy.invalid:3128") + monkeypatch.setenv("ALL_PROXY", "socks5://proxy.invalid:1080") + kind = httpx if family.provider == "google" else httpx2 + recorder = _recorder( + family.provider, _response(family.provider, 200, OK_BODIES[family.provider]) + ) + routes: list[Any] = [] + + def transport(**kwargs: Any) -> Any: + def handle(request: Any) -> Any: + routes.append(kwargs.get("proxy")) + return recorder(request) + + return kind.MockTransport(handle) + + for module in (kind, kind._client, anthropic._base_client): + monkeypatch.setattr(module, "AsyncHTTPTransport", transport) + await make_client(family, timeout_s=30).call(_conv()) + assert [_proxy_url(p) for p in routes] == ["http://egress:3128"] + assert [r.url.host for r in recorder.seen] == [host] + + +@pytest.mark.parametrize( + "value", + [ + "socks5://egress:1080", + "http://u:p@egress:3128", + "http://egress:3128/x", + "egress:3128", + "https://egress:3128", + ], +) +def test_a_malformed_egress_url_is_refused(monkeypatch: pytest.MonkeyPatch, value: str) -> None: + _clear_keys(monkeypatch) + monkeypatch.setenv("BENCHMARK_LIVE_PROVIDERS_ENABLED", "1") + monkeypatch.setenv("ANTHROPIC_API_KEY", "not-a-real-key") + monkeypatch.setenv("BENCHMARK_EGRESS_URL", value) + with pytest.raises(BenchmarkValidationError, match="BENCHMARK_EGRESS_URL") as caught: + make_client(_matrix_family("claude-sonnet-5-5"), timeout_s=30) + assert "u:p" not in str(caught.value) + + +@pytest.mark.parametrize("build", [anthropic_sdk, openai_sdk, gemini_sdk]) +def test_a_ca_variable_cannot_swap_the_proxy_routes_trust_store( + monkeypatch: pytest.MonkeyPatch, build: Callable[..., Any] +) -> None: + # As test_a_ca_variable_cannot_swap_a_clients_trust_store, for the proxy route. + monkeypatch.setenv("SSL_CERT_FILE", "/nonexistent/ca.pem") + build("test-key", 30, proxy="http://egress:3128") + + +def _chat_completion(message: dict[str, Any], finish: str = "stop") -> dict[str, Any]: + return { + "id": "chatcmpl-1", + "object": "chat.completion", + "created": 0, + "model": "gemma4:12b", + "choices": [{"index": 0, "message": message, "finish_reason": finish}], + "usage": {"prompt_tokens": 120, "completion_tokens": 30, "total_tokens": 150}, + } + + +def _ollama(recorder: Recorder) -> OllamaChatClient: + sdk = ollama_sdk("http://127.0.0.1:11434/v1", 600, transport=recorder.transport()) + return OllamaChatClient(sdk, "gemma4:12b") + + +def _tool_call(name: str, arguments: str, call_id: str | None) -> dict[str, Any]: + call = {"type": "function", "function": {"name": name, "arguments": arguments}} + return call if call_id is None else {"id": call_id, **call} + + +async def test_ollama_client_round_trips_a_tool_call() -> None: + first = { + "role": "assistant", + "content": None, + "tool_calls": [_tool_call("search_docs", '{"query": "json"}', "call_abc")], + } + recorder = Recorder( + _ok(_chat_completion(first, "tool_calls")), + _ok(_chat_completion({"role": "assistant", "content": "The answer."})), + ) + client = _ollama(recorder) + conv = _conv() + turn = await client.call(conv) + body = recorder.body(0) + assert body["model"] == "gemma4:12b" + assert body["messages"][0] == {"role": "system", "content": "system prompt"} + assert body["messages"][1] == {"role": "user", "content": "q?"} + assert body["tools"] == [ + { + "type": "function", + "function": { + "name": "search_docs", + "description": TOOLS[0].description, + "parameters": TOOLS[0].input_schema, + "strict": False, + }, + } + ] + for name in ("max_tokens", "max_completion_tokens", "tool_choice", "temperature", "top_p"): + assert name not in body + assert turn.tool_calls == (ToolCall("call_abc", "search_docs", {"query": "json"}),) + assert turn.stop_reason == "tool_calls" and turn.reported_model == "gemma4:12b" + assert turn.buckets == Buckets(120, 0, 0, 30, 0) + assert client.request_params() == {"model": "gemma4:12b"} + conv.entries += [turn, ToolResults((ToolResult("call_abc", "search_docs", "result", False),))] + answer = await client.call(conv) + messages = recorder.body(1)["messages"] + assert messages[2]["role"] == "assistant" + assert messages[2]["tool_calls"][0]["id"] == "call_abc" + assert messages[3] == {"role": "tool", "tool_call_id": "call_abc", "content": "result"} + assert answer.text == "The answer." and answer.tool_calls == () + + +async def test_ollama_tool_calls_without_ids_pair_by_position() -> None: + first = { + "role": "assistant", + "content": "", + "tool_calls": [ + _tool_call("search_docs", '{"query": "a"}', None), + _tool_call("search_docs", '{"query": "b"}', None), + ], + } + recorder = Recorder( + _ok(_chat_completion(first, "tool_calls")), + _ok(_chat_completion({"role": "assistant", "content": "ok"})), + ) + client = _ollama(recorder) + conv = _conv() + turn = await client.call(conv) + assert [c.id for c in turn.tool_calls] == ["call_1", "call_2"] + results = tuple(ToolResult(c.id, c.name, f"r{c.id}", False) for c in turn.tool_calls) + conv.entries += [turn, ToolResults(results)] + await client.call(conv) + messages = recorder.body(1)["messages"] + assert [c["id"] for c in messages[2]["tool_calls"]] == ["call_1", "call_2"] + assert [(m["role"], m["tool_call_id"]) for m in messages[3:]] == [ + ("tool", "call_1"), + ("tool", "call_2"), + ] + + +@pytest.mark.parametrize("status", [200, 500]) +async def test_ollama_client_sends_one_request_per_call(status: int) -> None: + body = _chat_completion({"role": "assistant", "content": "ok"}) if status == 200 else {} + recorder = Recorder(_ok(body, status), _ok(body, status)) + sdk = ollama_sdk("http://127.0.0.1:11434/v1", 600, transport=recorder.transport()) + assert sdk.max_retries == 0 + client = OllamaChatClient(sdk, "gemma4:12b") + if status == 200: + await client.call(_conv()) + else: + with pytest.raises(ProviderCallError): + await client.call(_conv()) + assert len(recorder.seen) == 1 + + +ANTHROPIC_MODEL_INFO = { + "id": "claude-sonnet-5-5", + "type": "model", + "display_name": "Claude Sonnet 5.5", + "created_at": "2026-09-01T00:00:00Z", + "lifecycle": "active", + "max_input_tokens": 1_000_000, + "max_tokens": 128_000, +} +GEMINI_MODEL = { + "name": "models/gemini-3.8-flash", + "inputTokenLimit": 1_048_576, + "outputTokenLimit": 65_536, +} + + +@pytest.mark.parametrize("family_id", ["claude-sonnet-5-5", "gemini-3.8-flash"]) +async def test_fetch_model_limits_makes_one_free_get(family_id: str) -> None: + if family_id == "claude-sonnet-5-5": + recorder: Recorder = Recorder(_ok(ANTHROPIC_MODEL_INFO)) + client: Any = _anthropic(recorder) + expected = {"max_input_tokens": 1_000_000, "max_tokens": 128_000} + else: + recorder = GeminiRecorder(_gemini_ok(GEMINI_MODEL)) + client = _gemini(recorder) # type: ignore[arg-type] + expected = {"max_input_tokens": 1_048_576, "max_tokens": 65_536} + assert await fetch_model_limits(client) == expected + assert [r.method for r in recorder.seen] == ["GET"] + assert recorder.seen[0].url.path.endswith(f"/models/{family_id}") + + +async def test_fetch_model_limits_skips_providers_that_report_none() -> None: + recorder = Recorder() # no response queued: any request would fail the test + assert await fetch_model_limits(_openai(recorder)) is None + assert await fetch_model_limits(_ollama(recorder)) is None + assert recorder.seen == [] + + +async def test_fetch_model_limits_records_an_error_without_raising() -> None: + recorder = Recorder(_ok(ERROR_BODY, 500)) + assert await fetch_model_limits(_anthropic(recorder)) == {"error": "InternalServerError"} + assert len(recorder.seen) == 1 diff --git a/tests/benchmarks/test_agentic_egress.py b/tests/benchmarks/test_agentic_egress.py new file mode 100644 index 00000000..c5f01a64 --- /dev/null +++ b/tests/benchmarks/test_agentic_egress.py @@ -0,0 +1,478 @@ +"""Egress policy: allowlists, the Squid config, the proxy log and the C1 evidence (design §7.3).""" + +from __future__ import annotations + +import json +from pathlib import Path +from typing import Any + +import pytest + +from benchmarks.agentic.airgap import write_airgap_evidence +from benchmarks.agentic.egress import ( + EGRESS_URL, + ProxyEvent, + allowlist, + forbidden_env_names, + lookup_attempts, + parse_proxy_log, + squid_conf, + write_egress_summary, +) +from benchmarks.model_matrix import ModelFamily, load_model_matrix +from benchmarks.runner import BenchmarkValidationError + +REPO_ROOT = Path(__file__).resolve().parents[2] +FIX = Path(__file__).parent / "fixtures" / "agentic" +FAMILIES: dict[str, ModelFamily] = { + f.id: f + for path in (REPO_ROOT / "docs" / "benchmarks" / "model-matrix.yml", FIX / "model-matrix.yml") + for f in load_model_matrix(path).model_families +} +TUNNEL = "2026-11-04T10:00:00.123Z 172.20.0.3 CONNECT api.anthropic.com 443 200 TCP_TUNNEL\n" +DENIED = "2026-11-04T10:00:01.004Z 172.20.0.3 CONNECT example.com 443 403 TCP_DENIED\n" + + +@pytest.mark.parametrize( + "family_id,system_id,expected", + [ + ("claude-sonnet-5-5", "python-docs", (("api.anthropic.com", 443),)), + ("gpt-6.1-sol", "docs-fetch", (("api.openai.com", 443), ("docs.python.org", 443))), + ("gemma4-12b", "python-docs", (("host.docker.internal", 11434),)), + ("scripted-anthropic", "no-docs", ()), + ], +) +def test_allowlist_per_job( + family_id: str, system_id: str, expected: tuple[tuple[str, int], ...] +) -> None: + assert allowlist(FAMILIES[family_id], system_id) == expected + + +def test_parse_proxy_log_reads_tunnels_and_denials() -> None: + tunnel, denied = parse_proxy_log(TUNNEL + DENIED) + assert tunnel == ProxyEvent( + "2026-11-04T10:00:00.123Z", + "172.20.0.3", + "CONNECT", + "api.anthropic.com", + 443, + 200, + "TCP_TUNNEL", + ) + assert tunnel.allowed and tunnel.target == "api.anthropic.com:443" + assert not denied.allowed and denied.target == "example.com:443" and denied.status == 403 + assert parse_proxy_log("") == [] + assert EGRESS_URL == "http://egress:3128" + + +@pytest.mark.parametrize( + "text,line", + [ + (TUNNEL + "garbage\n", 2), + (TUNNEL + DENIED.rstrip("\n"), 2), # unterminated: the proxy died mid-write + ("2026-11-04T10:00:00.123Z 172.20.0.3 CONNECT a.example 4x3 200 TCP_TUNNEL\n", 1), + ], +) +def test_parse_proxy_log_rejects_a_malformed_or_unterminated_line(text: str, line: int) -> None: + with pytest.raises(BenchmarkValidationError, match=f"line {line}"): + parse_proxy_log(text) + + +def test_forbidden_env_names_match_every_case() -> None: + names = [ + "HTTPS_PROXY", + "http_proxy", + "ALL_PROXY", + "NO_PROXY", + "SSL_CERT_FILE", + "SSL_CERT_DIR", + "REQUESTS_CA_BUNDLE", + ] + environ = {name: "user:secret@x" for name in names} | {"PATH": "/bin", "PROXY_NOTE": "x"} + assert forbidden_env_names(environ) == sorted(names) + assert forbidden_env_names({"PATH": "/bin", "PROXY_NOTE": "x"}) == [] + + +SQUID_TEMPLATE = """\ +http_port 3128 +visible_hostname egress +pid_filename none +cache deny all +shutdown_lifetime 1 seconds +httpd_suppress_version_string on +logfile_rotate 0 +logformat bench %{%Y-%m-%dT%H:%M:%S}tg.%03tuZ %>a %rm %>rd %>rP %>Hs %Ss %Sh % None: + conf = squid_conf([("api.anthropic.com", 443), ("host.docker.internal", 11434)]) + assert conf == SQUID_TEMPLATE + + +def test_squid_conf_with_no_host_denies_everything() -> None: + conf = squid_conf([]) + assert "http_access allow" not in conf and "acl " not in conf + assert conf.endswith("http_access deny all\n") + + +def test_every_allowlist_acl_disables_lookups() -> None: + conf = squid_conf([("api.openai.com", 443), ("docs.python.org", 443), ("h.invalid", 8080)]) + acls = [line.split() for line in conf.splitlines() if line.startswith("acl ")] + domains = [acl for acl in acls if acl[2] == "dstdomain"] + assert len(domains) == 3 and all(acl[3] == "-n" for acl in domains) + assert not [acl for acl in acls if acl[2] in ("dst", "dstdom_regex", "dst_as")] + (access_log,) = [line for line in conf.splitlines() if line.startswith("access_log ")] + assert access_log.split()[1].startswith("stdio:/var/log/squid-bench/") + assert "rotate=0" in access_log.split() and "logfile_rotate 0" in conf.splitlines() + + +# --- C1 evidence: egress/summary.json (#199, owner question 9) ---------------------------------- + +PROBE_LINES = [ + "2026-11-04T10:00:00.001Z 172.30.0.2 CONNECT example.com 443 403 TCP_DENIED", + "2026-11-04T10:00:00.002Z 172.30.0.2 GET host.docker.internal 50000 403 TCP_DENIED", +] +ANTHROPIC_LINE = "2026-11-04T10:00:05.000Z 172.30.0.3 CONNECT api.anthropic.com 443 200 TCP_TUNNEL" +PYPI_LINE = "2026-11-04T10:00:06.000Z 172.30.0.3 CONNECT pypi.org 443 403 TCP_DENIED" +CLAUDE = "claude-sonnet-5-5--python-docs" +SCRIPTED = "scripted-anthropic--no-docs" + + +def _jobs() -> list[Any]: + from tests.benchmarks.test_agentic_sandbox import _job + + return [_job("claude-sonnet-5-5", "python-docs"), _job("scripted-anthropic", "no-docs")] + + +def _evidence( + out: Path, + job_id: str, + *, + log: str | None, + prefix: list[str] = PROBE_LINES, + probe_passed: bool = True, + ok: bool = True, +) -> None: + log_dir = out / "egress" / job_id + log_dir.mkdir(parents=True, exist_ok=True) + if log is not None: + (log_dir / "access.log").write_text(log, encoding="utf-8") + (log_dir / "collected.json").write_text(json.dumps({"ok": ok, "problems": []})) + (out / "probe").mkdir(exist_ok=True) + probe = {"passed": probe_passed, "failed": [], "proxy_prefix": prefix} + (out / "probe" / f"{job_id}.json").write_text(json.dumps(probe)) + (out / "probe" / "control.json").write_text(json.dumps({"passed": True})) + + +def _lines(*lines: str) -> str: + return "".join(f"{line}\n" for line in lines) + + +def _ok_settle(job_id: str | None, unit: str = "anthropic-1") -> list[dict[str, Any]]: + return [ + {"event": "reserve", "unit_id": unit, "provider": "anthropic", "job_id": job_id}, + {"event": "settle", "unit_id": unit, "provider": "anthropic", "outcome": "ok"}, + ] + + +def _clean_run(tmp_path: Path) -> Path: + out = tmp_path / "run" + _evidence(out, CLAUDE, log=_lines(*PROBE_LINES, ANTHROPIC_LINE, PYPI_LINE)) + _evidence(out, SCRIPTED, log=_lines(*PROBE_LINES)) + return out + + +def test_egress_summary_has_exactly_the_bound_keys(tmp_path: Path) -> None: + out = _clean_run(tmp_path) + summary = write_egress_summary(out, _jobs(), _ok_settle(CLAUDE)) + written = json.loads((out / "egress" / "summary.json").read_text()) + assert written == summary + assert set(written) == {"jobs", "isolation_probe"} + assert set(written["jobs"]) == {CLAUDE, SCRIPTED} + assert all( + set(j) == {"hosts_allowed", "hosts_denied", "lookup_package_docs_attempts"} + for j in written["jobs"].values() + ) + assert written["isolation_probe"] == "pass" + + +def test_probe_lines_never_reach_the_summary(tmp_path: Path) -> None: + out = _clean_run(tmp_path) + jobs = write_egress_summary(out, _jobs(), _ok_settle(CLAUDE))["jobs"] + assert jobs[CLAUDE]["hosts_allowed"] == ["api.anthropic.com:443"] + assert jobs[CLAUDE]["hosts_denied"] == ["pypi.org:443"] + assert jobs[SCRIPTED] == { + "hosts_allowed": [], + "hosts_denied": [], + "lookup_package_docs_attempts": 0, + } + + +@pytest.mark.parametrize( + "log", + [ + _lines(*PROBE_LINES, ANTHROPIC_LINE) + PYPI_LINE, # unterminated last line + _lines(PYPI_LINE, *PROBE_LINES, ANTHROPIC_LINE), # a line before the probe's prefix + _lines(PROBE_LINES[1], ANTHROPIC_LINE), # the prefix lost a line + ], +) +def test_a_truncated_or_reprefixed_log_invalidates_the_evidence(tmp_path: Path, log: str) -> None: + out = _clean_run(tmp_path) + (out / "egress" / CLAUDE / "access.log").write_text(log, encoding="utf-8") + assert write_egress_summary(out, _jobs(), _ok_settle(CLAUDE))["isolation_probe"] == "fail" + + +def test_a_dangling_pending_marker_blocks_complete_evidence(tmp_path: Path) -> None: + out = _clean_run(tmp_path) + (out / "probe" / f"{CLAUDE}.collection-pending").symlink_to(tmp_path / "absent") + assert write_egress_summary(out, _jobs(), _ok_settle(CLAUDE))["isolation_probe"] == "fail" + + +def test_a_missing_log_invalidates_the_evidence(tmp_path: Path) -> None: + out = _clean_run(tmp_path) + (out / "egress" / SCRIPTED / "access.log").unlink() + assert write_egress_summary(out, _jobs(), _ok_settle(CLAUDE))["isolation_probe"] == "fail" + out = _clean_run(tmp_path / "linked") + access = out / "egress" / SCRIPTED / "access.log" + access.unlink() + access.symlink_to(out / "egress" / CLAUDE / "access.log") # a link is never followed + assert write_egress_summary(out, _jobs(), _ok_settle(CLAUDE))["isolation_probe"] == "fail" + + +async def test_c1_refuses_a_link_to_a_complete_job_directory(tmp_path: Path) -> None: + from tests.benchmarks.test_agentic_sandbox import FakeDocker, _opened + + sandbox, egress = await _opened(tmp_path, FakeDocker(), CLAUDE) + out = sandbox.config.out_dir + _evidence(out, CLAUDE, log=_lines(*PROBE_LINES, ANTHROPIC_LINE)) + (egress.spool_dir / "access.log").write_text(_lines(*PROBE_LINES, ANTHROPIC_LINE)) + _evidence(out, SCRIPTED, log=_lines(*PROBE_LINES)) + assert await sandbox.close_egress(egress) == [] + assert write_egress_summary(out, _jobs(), _ok_settle(CLAUDE))["isolation_probe"] == "pass" + job_dir = out / "egress" / CLAUDE + moved = job_dir.rename(tmp_path / "copied-logs") + job_dir.symlink_to(moved) + assert write_egress_summary(out, _jobs(), _ok_settle(CLAUDE))["isolation_probe"] == "fail" + + +@pytest.mark.parametrize("status", ["503 TCP_MISS", "204 TCP_TUNNEL"]) +def test_failed_provider_connect_is_not_evidence_of_a_billed_connection( + tmp_path: Path, status: str +) -> None: + out = _clean_run(tmp_path) + failed = ANTHROPIC_LINE.replace("200 TCP_TUNNEL", status) + (out / "egress" / CLAUDE / "access.log").write_text(_lines(*PROBE_LINES, failed, PYPI_LINE)) + summary = write_egress_summary(out, _jobs(), _ok_settle(CLAUDE)) + assert summary["isolation_probe"] == "fail" + assert summary["jobs"][CLAUDE]["hosts_allowed"] == [] + assert summary["jobs"][CLAUDE]["hosts_denied"] == ["pypi.org:443"] + + +@pytest.mark.parametrize( + "attempt,isolated", + [ + ("CONNECT docs.python.org 443 503 NONE_NONE", False), + ("POST host.docker.internal 11434 503 TCP_MISS", True), + ("POST host.docker.internal 11434 0 TCP_MISS_ABORTED", True), + ("POST host.docker.internal 11434 200 TCP_MISS_ABORTED", True), + ("POST host.docker.internal 11434 302 TCP_MISS_TIMEDOUT_ABORTED", True), + ("POST external.invalid 11434 200 TCP_MISS_ABORTED", False), + ], +) +@pytest.mark.parametrize("successful_retry", [False, True]) +def test_legacy_failed_attempts_only_preserve_isolation_for_the_permitted_target( + tmp_path: Path, attempt: str, isolated: bool, successful_retry: bool +) -> None: + from tests.benchmarks.test_agentic_sandbox import _job + + job = _job("gemma4-12b", "python-docs") + ollama = "2026-11-04T10:00:04.001Z 172.30.0.3 POST host.docker.internal 11434 200 TCP_MISS" + failed = f"2026-11-04T10:00:05.000Z 172.30.0.3 {attempt}" + retry = [ollama] if successful_retry else [] + _evidence(tmp_path, job.job_id, log=_lines(*PROBE_LINES, failed, *retry)) + summary = write_egress_summary(tmp_path, [job], []) + checks = write_airgap_evidence(tmp_path, rounds=1, broken=False, job_ids=[job.job_id]) + assert checks == {"all_passed": isolated, "checks": 1, "internet_hosts": []} + assert summary["isolation_probe"] == ("pass" if isolated else "fail") + assert summary["jobs"][job.job_id]["hosts_allowed"] == ( + ["host.docker.internal:11434"] if successful_retry else [] + ) + assert summary["jobs"][job.job_id]["hosts_denied"] == [] + + +# These fields come from the pinned Squid 6.14 proxy, including "-" for no peer reply. +CURRENT_PREFIX = [line + " HIER_NONE -" for line in PROBE_LINES] +LOCAL = "host.docker.internal:11434" + + +@pytest.mark.parametrize( + "attempt,passed,reached,denied", + [ + ("POST host.docker.internal 11434 500 TCP_MISS HIER_DIRECT 500", True, [LOCAL], []), + ("POST host.docker.internal 11434 500 TCP_MISS_ABORTED HIER_DIRECT 500", True, [LOCAL], []), + ("POST host.docker.internal 11434 0 TCP_MISS_ABORTED HIER_DIRECT -", True, [], []), + ("POST host.docker.internal 11434 0 TCP_MISS_TIMEDOUT_ABORTED HIER_DIRECT -", True, [], []), + ("POST host.docker.internal 11434 503 TCP_MISS_ABORTED HIER_DIRECT -", True, [], []), + ("POST host.docker.internal 11434 503 TCP_MISS HIER_NONE -", True, [], []), + ("CONNECT pypi.org 443 403 TCP_DENIED_ABORTED HIER_NONE -", True, [], ["pypi.org:443"]), + ("POST outside.invalid 11434 0 TCP_MISS_ABORTED HIER_DIRECT -", False, [], []), + ( + "POST outside.invalid 11434 500 TCP_MISS HIER_DIRECT 500", + False, + ["outside.invalid:11434"], + [], + ), + ("CONNECT outside.invalid 443 200 TCP_DENIED HIER_NONE -", False, [], []), + ("CONNECT outside.invalid 443 403 TCP_DENIED_BOGUS HIER_NONE -", False, [], []), + ("CONNECT outside.invalid 443 403 TCP_DENIED_REPLY HIER_DIRECT 403", False, [], []), + ("POST host.docker.internal 11434 0 TCP_MISS_BOGUS HIER_DIRECT -", False, [], []), + ("POST host.docker.internal 11434 500 TCP_MISS UNKNOWN 500", False, [], []), + ("POST host.docker.internal 11434 500 TCP_MISS HIER_NONE 500", False, [], []), + ("POST host.docker.internal 11434 500 TCP_MISS HIER_DIRECT garbage", False, [], []), + ("POST host.docker.internal 11434 500 TCP_MISS HIER_DIRECT", False, [], []), + ("POST host.docker.internal 11434 200 TCP_MISS", False, [], []), # format changed mid-log + ], +) +def test_airgap_query_evidence( + tmp_path: Path, attempt: str, passed: bool, reached: list[str], denied: list[str] +) -> None: + from tests.benchmarks.test_agentic_sandbox import _job + + job = _job("gemma4-12b", "python-docs") + query = f"2026-11-04T10:00:05.000Z 172.30.0.3 {attempt}" + _evidence(tmp_path, job.job_id, prefix=CURRENT_PREFIX, log=_lines(*CURRENT_PREFIX, query)) + summary = write_egress_summary(tmp_path, [job], []) + entry = summary["jobs"][job.job_id] + assert summary["isolation_probe"] == ("pass" if passed else "fail") + assert entry["hosts_allowed"] == reached + assert entry["hosts_denied"] == denied + assert write_airgap_evidence(tmp_path, rounds=1, broken=False, job_ids=[job.job_id]) == { + "all_passed": passed, + "checks": 1, + "internet_hosts": [host for host in reached if host != LOCAL], + } + + +@pytest.mark.parametrize( + "reply,passed", + [ + ("200 TCP_TUNNEL HIER_DIRECT -", True), + ("200 TCP_TUNNEL_ABORTED HIER_DIRECT -", True), + ("503 TCP_MISS_ABORTED HIER_DIRECT -", False), + ("503 NONE_NONE HIER_NONE -", False), + ("200 TCP_TUNNEL HIER_NONE -", False), + ("204 TCP_TUNNEL HIER_DIRECT -", False), + ], +) +def test_billing_needs_an_established_provider_tunnel( + tmp_path: Path, reply: str, passed: bool +) -> None: + query = f"2026-11-04T10:00:05.000Z 172.30.0.3 CONNECT api.anthropic.com 443 {reply}" + _evidence(tmp_path, CLAUDE, prefix=CURRENT_PREFIX, log=_lines(*CURRENT_PREFIX, query)) + summary = write_egress_summary(tmp_path, [_jobs()[0]], _ok_settle(CLAUDE)) + assert summary["isolation_probe"] == ("pass" if passed else "fail") + assert summary["jobs"][CLAUDE]["hosts_allowed"] == (["api.anthropic.com:443"] if passed else []) + + +def test_an_empty_probe_prefix_is_not_evidence(tmp_path: Path) -> None: + _evidence(tmp_path, SCRIPTED, prefix=[], log="") + assert write_egress_summary(tmp_path, [_jobs()[1]], [])["isolation_probe"] == "fail" + + +@pytest.mark.parametrize("record", ["control", SCRIPTED]) +def test_a_non_object_probe_fails_the_evidence(tmp_path: Path, record: str) -> None: + out = _clean_run(tmp_path) + (out / "probe" / f"{record}.json").write_text("[]") + assert write_egress_summary(out, _jobs(), [])["isolation_probe"] == "fail" + + +async def test_no_false_clean_when_collection_failed_or_the_provider_never_appears( + tmp_path: Path, +) -> None: + from tests.benchmarks.test_agentic_sandbox import RUNNING, FakeDocker, _sandbox + + # (a) A forced kill after our stop: the log is well formed but may be partial. + killed = {"Running": False, "ExitCode": 137, "OOMKilled": False} + sandbox = _sandbox(tmp_path, FakeDocker(states=(RUNNING, killed))) + egress = await sandbox.open_egress(CLAUDE, (("api.anthropic.com", 443),)) + (egress.spool_dir / "access.log").write_text(_lines(*PROBE_LINES, ANTHROPIC_LINE)) + (egress.spool_dir / "cache.log").write_text("squid\n") + await sandbox.close_egress(egress) + out = tmp_path / "run" + _evidence(out, SCRIPTED, log=_lines(*PROBE_LINES)) + probe = {"passed": True, "proxy_prefix": PROBE_LINES} + (out / "probe" / f"{CLAUDE}.json").write_text(json.dumps(probe)) + assert json.loads((egress.log_dir / "collected.json").read_text())["ok"] is False + assert write_egress_summary(out, _jobs(), _ok_settle(CLAUDE))["isolation_probe"] == "fail" + # (b) A hosted job billed an ok call, but its log shows no provider host. + out = tmp_path / "b" / "run" + _evidence(out, CLAUDE, log=_lines(*PROBE_LINES, PYPI_LINE)) + _evidence(out, SCRIPTED, log=_lines(*PROBE_LINES)) + assert write_egress_summary(out, _jobs(), _ok_settle(CLAUDE))["isolation_probe"] == "fail" + assert write_egress_summary(out, _jobs(), [])["isolation_probe"] == "pass" # nothing billed + + +def test_an_ok_settle_from_a_worker_that_died_early_fails_the_evidence(tmp_path: Path) -> None: + # No transcript or discarded record for the job: the ledger alone attributes the settle. + out = tmp_path / "run" + _evidence(out, CLAUDE, log=_lines(*PROBE_LINES)) + _evidence(out, SCRIPTED, log=_lines(*PROBE_LINES)) + assert not (out / "transcripts").exists() + assert write_egress_summary(out, _jobs(), _ok_settle(CLAUDE))["isolation_probe"] == "fail" + + +@pytest.mark.parametrize("job_id", [None, "gpt-6.1-sol--python-docs"]) +def test_an_unattributed_ok_settle_fails_the_evidence(tmp_path: Path, job_id: str | None) -> None: + out = _clean_run(tmp_path) + events = _ok_settle(CLAUDE) + _ok_settle(job_id, unit="anthropic-2") + assert write_egress_summary(out, _jobs(), events)["isolation_probe"] == "fail" + + +def test_a_failed_probe_or_control_fails_the_evidence(tmp_path: Path) -> None: + out = _clean_run(tmp_path) + (out / "probe" / "control.json").write_text(json.dumps({"passed": False})) + assert write_egress_summary(out, _jobs(), _ok_settle(CLAUDE))["isolation_probe"] == "fail" + out = _clean_run(tmp_path / "p") + (out / "probe" / f"{SCRIPTED}.json").unlink() + assert write_egress_summary(out, _jobs(), _ok_settle(CLAUDE))["isolation_probe"] == "fail" + + +def _record(path: Path, tools: list[str]) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(json.dumps({"tool_calls": [{"tool": tool} for tool in tools]})) + + +def test_lookup_attempts_count_scored_and_discarded_records(tmp_path: Path) -> None: + out = tmp_path / "run" + lookup = "lookup_package_docs" + _record(out / "transcripts" / "python-docs--m--r1" / "EX-001.json", [lookup, "x", lookup]) + _record(out / "discarded" / "python-docs--m--r2" / "EX-002--attempt1.json", [lookup]) + _record(out / "transcripts" / "docs-fetch--m--r1" / "EX-001.json", [lookup]) + _record(out / "transcripts" / "python-docs--m-b--r1" / "EX-001.json", [lookup]) + assert lookup_attempts(out, "m", "python-docs") == 3 + assert lookup_attempts(out, "m", "no-docs") == 0 + + +@pytest.mark.parametrize( + "prefix", + ["- -", "2026-02-31T10:00:00.123Z 172.30.0.3", "2026-11-04T10:00:00.123Z invalid-client"], +) +def test_malformed_log_identity_cannot_corroborate_a_billed_call( + tmp_path: Path, prefix: str +) -> None: + line = f"{prefix} CONNECT api.anthropic.com 443 200 TCP_TUNNEL HIER_DIRECT -" + probe = [f"{event} HIER_NONE -" for event in PROBE_LINES] + _evidence(tmp_path, CLAUDE, log=_lines(*probe, line), prefix=probe) + summary = write_egress_summary(tmp_path, [_jobs()[0]], _ok_settle(CLAUDE)) + assert summary["isolation_probe"] == "fail" + assert summary["jobs"][CLAUDE]["hosts_allowed"] == [] diff --git a/tests/benchmarks/test_agentic_frame_failure.py b/tests/benchmarks/test_agentic_frame_failure.py new file mode 100644 index 00000000..9b4ab8ac --- /dev/null +++ b/tests/benchmarks/test_agentic_frame_failure.py @@ -0,0 +1,448 @@ +"""Frame limits abort the harness before another dispatch or scored publication.""" + +import asyncio +import json +import sys +from contextlib import AsyncExitStack +from unittest.mock import AsyncMock, Mock + +import pytest +from mcp.types import CallToolResult + +from benchmarks.adapters.guard import PROVIDER_API_KEY_ENV +from benchmarks.agentic import clients, loop, worker +from benchmarks.agentic.bridge import Bridge +from benchmarks.agentic.cleanup import finish +from benchmarks.agentic.host import LocalLauncher, run_jobs +from benchmarks.agentic.mcp_stdio import ReplyGuard +from benchmarks.agentic.protocol import ( + WORKER_FRAME_LIMIT_EXIT, + FrameTooLarge, + KeyLeakError, + encode_frame, +) +from tests.benchmarks.test_agentic_host import ( + ANSWER, + REPO_ROOT, + Host, + _fake_host_processes, + _job, + _reserve_frame, +) +from tests.benchmarks.test_agentic_loop import TOOL +from tests.benchmarks.test_agentic_mcp_boundary import _system + + +@pytest.fixture +def host(tmp_path, monkeypatch): + for name in PROVIDER_API_KEY_ENV.values(): + monkeypatch.delenv(name, raising=False) + value = Host(tmp_path) + yield value + value.ledger.close() + + +async def test_oversized_stdio_reply_aborts_real_worker_and_host(tmp_path, monkeypatch, host): + calls, outcome = tmp_path / "calls", tmp_path / "outcome.json" + program = tmp_path / "worker.py" + program.write_text(f""" +import sys +sys.path.insert(0, {str(REPO_ROOT)!r}) +import json +from pathlib import Path +from benchmarks.agentic import clients, mcp_stdio, worker +mcp_stdio.MAX_FRAME_BYTES = 512 +original_call = clients.ScriptedClient.call +async def call(self, conv): + with Path({str(calls)!r}).open('a') as file: + file.write('provider\\n') + return await original_call(self, conv) +clients.ScriptedClient.call = call +processes = [] +create = mcp_stdio._create_platform_compatible_process +async def capture(**kwargs): + process = await create(**kwargs) + processes.append(process) + return process +mcp_stdio._create_platform_compatible_process = capture +code = worker.main_worker() +Path({str(outcome)!r}).write_text(json.dumps({{ + 'code': code, 'children': [p.returncode for p in processes]}})) +raise SystemExit(code) +""") + job = _job(tmp_path, [TOOL, ANSWER, ANSWER], system=_system("oversize", "clean")) + monkeypatch.setattr( + LocalLauncher, "command", lambda self, job: ([sys.executable, "-I", str(program)], {}) + ) + stopped = AsyncMock() + monkeypatch.setattr(LocalLauncher, "stop_worker", stopped) + service = host.service(job.family) + async with asyncio.timeout(10): + with pytest.raises(FrameTooLarge, match="MCP stdio reply exceeds the frame limit"): + await run_jobs( + [job], + launcher=LocalLauncher(), + ledger=service, + on_message=host.on_message, + log_dir=tmp_path / "logs", + cwd=REPO_ROOT, + ) + assert calls.read_text().splitlines() == ["provider"] + result = json.loads(outcome.read_text()) + assert result["code"] == WORKER_FRAME_LIMIT_EXIT + assert len(result["children"]) == 1 and result["children"][0] is not None + stopped.assert_awaited_once() + assert [m["type"] for m in host.messages()] == ["system_info"] + events = host.ledger.invocation_events() + assert [e["event"] for e in events] == ["reserve", "settle"] + assert events[1]["outcome"] == "ok" # The known model usage was settled before MCP. + assert ( + await service.reserve( + provider=job.family.provider, + model_id=job.family.model_id, + input_bound=1, + output_bound=1, + ) + is None + ) + assert b"synthetic server diagnostic retained" in b"".join( + p.read_bytes() for p in (tmp_path / "logs").glob("*.log") + ) + + +@pytest.mark.parametrize("phase", ["before", "during", "after"]) +async def test_bridge_checks_frame_latch_at_each_call_boundary(phase): + guard = ReplyGuard() + failure = FrameTooLarge("synthetic frame limit") + + async def call(*args): + guard.failure = failure + if phase == "during": + raise ConnectionError("connection closed") + return CallToolResult(content=[]) + + session = Mock(call_tool=AsyncMock(side_effect=call)) + bridge = Bridge(session, {}, []) + bridge._reply_guard = guard + if phase == "before": + guard.failure = failure + with pytest.raises(FrameTooLarge) as caught: + await bridge.call("search_docs", {}) + assert caught.value is failure + assert session.call_tool.await_count == (0 if phase == "before" else 1) + + +@pytest.mark.parametrize("cleanup", ["ordinary", "credential", "interrupt"]) +async def test_frame_failure_cleanup_precedence(cleanup): + pending = FrameTooLarge("recognized frame limit") + error = { + "ordinary": RuntimeError("cleanup failed"), + "credential": KeyLeakError("synthetic credential failure"), + "interrupt": asyncio.CancelledError("operator interrupt"), + }[cleanup] + + async def fail(): + raise error + + expected = pending if cleanup == "ordinary" else error + with pytest.raises(type(expected)) as caught: + await finish(fail(), pending) + assert caught.value is expected + + +async def test_worker_close_propagates_grouped_frame_limit(): + stack = AsyncExitStack() + failure = FrameTooLarge("synthetic frame limit") + + async def close(): + raise ExceptionGroup("stdio teardown", [RuntimeError("clean"), failure]) + + stack.push_async_callback(close) + with pytest.raises(FrameTooLarge) as caught: + await worker._close(stack) + assert caught.value is failure + + +async def test_worker_frame_failure_survives_unprintable_cleanup(): + stack = AsyncExitStack() + pending = FrameTooLarge("recognized frame limit") + + class BrokenError(Exception): + def __repr__(self): + raise ValueError("broken diagnostic") + + async def close(): + raise BrokenError() + + stack.push_async_callback(close) + with pytest.raises(FrameTooLarge) as caught: + await worker._close(stack, pending) + assert caught.value is pending + + +@pytest.mark.parametrize("discarded", [False, True]) +async def test_worker_checks_latch_before_publishing_returned_record( + tmp_path, monkeypatch, discarded +): + job = _job(tmp_path, []) + guard = ReplyGuard() + bridge = Bridge(Mock(), {}, []) + bridge._reply_guard = guard + channel = Mock() + client = Mock(provider="anthropic", model_id="scripted-1", api="scripted") + client.request_params.return_value = {} + monkeypatch.setattr(clients, "make_client", Mock(return_value=client)) + monkeypatch.setattr(worker, "_open", AsyncMock(return_value=bridge)) + + async def trajectory(**kwargs): + guard.failure = FrameTooLarge("recognized before record publication") + if discarded: + raise loop.TrajectoryDiscarded("retries_exhausted", {}) + return {"error": {"category": "mcp_protocol_crash"}} + + run = AsyncMock(side_effect=trajectory) + monkeypatch.setattr(loop, "run_trajectory", run) + code = await worker.run_worker( + channel, + asyncio.StreamReader(), + { + "type": "job", + "family": job.family.raw, + "system": job.system.raw, + "caps": {}, + "trajectories": list(job.trajectories), + }, + ) + assert code == WORKER_FRAME_LIMIT_EXIT + assert run.await_count == 1 + sent = [call.args[0] for call in channel.send.call_args_list] + assert [m["type"] for m in sent] == ["system_info", "error"] + assert sent[-1]["reason"] == "FrameTooLarge: recognized before record publication" + + +@pytest.mark.parametrize("source", ["error", "header"]) +async def test_host_stops_grants_before_wait_or_teardown(host, tmp_path, monkeypatch, source): + job = _job(tmp_path, [ANSWER]) + service = host.service(job.family) + waiting, release = asyncio.Event(), asyncio.Event() + stdout = asyncio.StreamReader() + stdout.feed_data( + encode_frame({"type": "error", "reason": "FrameTooLarge: synthetic frame limit"}) + if source == "error" + else (513).to_bytes(8, "big") + ) + + async def wait(): + waiting.set() + await release.wait() + return 2 + + proc = Mock(stdin=Mock(drain=AsyncMock()), stdout=stdout, wait=wait) + _fake_host_processes(monkeypatch, AsyncMock(return_value=proc)) + task = asyncio.create_task( + run_jobs( + [job], + launcher=LocalLauncher(), + ledger=service, + on_message=host.on_message, + log_dir=tmp_path / "logs", + cwd=REPO_ROOT, + max_frame_bytes=512, + ) + ) + try: + await asyncio.wait_for(waiting.wait(), 2) + unit = await service.reserve( + provider=job.family.provider, + model_id=job.family.model_id, + input_bound=1, + output_bound=1, + ) + if unit is not None: # Clean up the failing pre-fix assertion's own reservation. + await service.settle(unit, outcome="worker_lost", buckets=None) + finally: + release.set() + with pytest.raises(FrameTooLarge): + await task + assert unit is None + assert host.ledger.invocation_events() == [] + + +async def test_frame_recognized_while_waiting_for_grant_prevents_model_dispatch(): + guard = ReplyGuard() + channel = Mock() + channel.check_content = Mock() + reader = asyncio.StreamReader() + ledger = worker._HostLedger(channel, reader) + ledger.check_failure = guard.raise_if_failed + failure = FrameTooLarge("synthetic frame limit") + + async def request(message): + guard.failure = failure + return {"type": "grant", "unit_id": "already-granted"} + + ledger.request = request + with pytest.raises(FrameTooLarge) as caught: + await ledger.reserve( + provider="anthropic", model_id="synthetic", input_bound=1, output_bound=1 + ) + assert caught.value is failure + + +@pytest.mark.parametrize("cleanup_error", [False, True]) +async def test_frame_failure_denies_sibling_grants_and_publications_during_teardown( + host, tmp_path, cleanup_error +): + boundary, response = tmp_path / "stopping", tmp_path / "reply.json" + record = {"type": "trajectory", "corpus_id": "Q1", "repeat": 1, "attempt": 1, "record": {}} + code = f""" +import os, sys, time, json +sys.path.insert(0, {str(REPO_ROOT)!r}) +from pathlib import Path +from benchmarks.agentic.protocol import encode_frame, read_frame_fd +job = read_frame_fd(0) +if job['job_id'] == 'oversize': + os.write(1, {encode_frame(_reserve_frame(1024))!r}) + assert read_frame_fd(0)['type'] == 'grant' + os.write(1, {encode_frame({"type": "error", "reason": "FrameTooLarge: synthetic limit"})!r}) +else: + deadline = time.monotonic() + 5 + while not Path({str(boundary)!r}).exists(): + assert time.monotonic() < deadline + time.sleep(0.01) + os.write(1, {encode_frame(record)!r}) + assert read_frame_fd(0)['type'] == 'ack' + os.write(1, {encode_frame(_reserve_frame(1024))!r}) + reply = read_frame_fd(0) + stage = Path({str(response.with_suffix(".tmp"))!r}) + stage.write_text(json.dumps(reply)) + stage.replace({str(response)!r}) +""" + + class Launcher(LocalLauncher): + def __init__(self): + self.stopped = [] + self.closed = False + + def command(self, job): + return [sys.executable, "-I", "-c", code], {} + + async def stop_worker(self, job): + self.stopped.append(job.job_id) + if job.job_id == "oversize": + boundary.touch() + async with asyncio.timeout(5): + while not response.exists(): + await asyncio.sleep(0.01) + if cleanup_error: + raise RuntimeError("worker removal diagnostic") + + async def close(self): + self.closed = True + if cleanup_error: + raise RuntimeError("launcher cleanup diagnostic") + return [] + + jobs = [_job(tmp_path, [ANSWER], job_id=name) for name in ("oversize", "sibling")] + service = host.service(jobs[0].family) + launcher = Launcher() + with pytest.raises(FrameTooLarge, match="synthetic limit"): + async with asyncio.timeout(10): + await run_jobs( + jobs, + launcher=launcher, + ledger=service, + on_message=host.on_message, + log_dir=tmp_path / "logs", + cwd=REPO_ROOT, + ) + assert sorted(launcher.stopped) == ["oversize", "sibling"] and launcher.closed + assert json.loads(response.read_text()) == {"type": "deny"} + assert host.messages() == [] + events = host.ledger.invocation_events() + assert [e["event"] for e in events] == ["reserve", "settle"] + assert events[1]["outcome"] == "worker_lost" + assert len(list((tmp_path / "logs").glob("*.log"))) == 2 + + +@pytest.mark.parametrize("credential", [False, True]) +async def test_frame_latch_never_masks_credential_or_interrupt(credential): + guard = ReplyGuard() + guard.failure = FrameTooLarge("synthetic limit") + failure = ( + KeyLeakError("synthetic credential failure") if credential else asyncio.CancelledError() + ) + bridge = Bridge(Mock(call_tool=AsyncMock(side_effect=failure)), {}, []) + + # The latch arrives during the SDK call, after the pre-dispatch check. + async def call(*args): + bridge._reply_guard = guard + raise failure + + bridge._session.call_tool.side_effect = call + with pytest.raises(type(failure)) as caught: + await bridge.call("search_docs", {}) + assert caught.value is failure + + +async def test_existing_credential_latch_keeps_its_precedence_on_sdk_cancellation(): + guard = ReplyGuard() + failure = KeyLeakError("recognized credential failure") + bridge = Bridge(Mock(), {}, []) + + async def call(*args): + guard.failure = failure + bridge._reply_guard = guard + raise asyncio.CancelledError() + + bridge._session.call_tool = AsyncMock(side_effect=call) + with pytest.raises(KeyLeakError) as caught: + await bridge.call("search_docs", {}) + assert caught.value is failure + + +async def test_worker_frame_error_survives_an_unread_error_frame(tmp_path, monkeypatch, host): + """A reporting worker can exit while the host still owes a reply to the prior frame.""" + job = _job(tmp_path, [TOOL]) + service = host.service(job.family) + processes = [] + spawn = asyncio.create_subprocess_exec + + async def start(*args, **kwargs): + process = await spawn(*args, **kwargs) + processes.append(process) + return process + + reserve = service.reserve + + async def delayed_grant(**kwargs): + await asyncio.wait_for(processes[0].wait(), 10) + return await reserve(**kwargs) + + class Launcher(LocalLauncher): + def command(self, job): + code = """ +import asyncio, sys +from benchmarks.agentic import worker +from benchmarks.agentic.protocol import FrameTooLarge +async def fail(channel, reader, *args, **kwargs): + channel.send({'type':'reserve', 'input_bound':100, 'output_bound':32}) + raise FrameTooLarge('synthetic reply limit') +worker._run_job = fail +sys.exit(worker.main_worker()) +""" + return [sys.executable, "-c", code], {} + + monkeypatch.setattr(asyncio, "create_subprocess_exec", start) + monkeypatch.setattr(service, "reserve", delayed_grant) + with pytest.raises(FrameTooLarge): + await run_jobs( + [job], + launcher=Launcher(), + ledger=service, + on_message=host.on_message, + log_dir=tmp_path / "logs", + cwd=REPO_ROOT, + ) + assert not host.messages(job.job_id) + assert [row["event"] for row in host.ledger.invocation_events()] == ["reserve", "settle"] diff --git a/tests/benchmarks/test_agentic_host.py b/tests/benchmarks/test_agentic_host.py index 0ee0cfdc..f6d7504c 100644 --- a/tests/benchmarks/test_agentic_host.py +++ b/tests/benchmarks/test_agentic_host.py @@ -6,27 +6,41 @@ from __future__ import annotations import asyncio +import io import json import os import signal import subprocess import sys +import tempfile import time -from dataclasses import replace +import traceback +from collections.abc import Sequence +from dataclasses import asdict, replace from decimal import Decimal from pathlib import Path -from typing import Any +from typing import Any, BinaryIO +from unittest.mock import AsyncMock, Mock import pytest import yaml import benchmarks.agentic.host as agentic_host +import benchmarks.agentic.worker as worker from benchmarks.adapters.guard import PAID_KEY_ENVS, PROVIDER_API_KEY_ENV from benchmarks.agentic.bridge import system_spec_from_raw from benchmarks.agentic.host import LocalLauncher, WorkerJob, refuse_host_keys, run_jobs from benchmarks.agentic.ledger import Ledger, LedgerService, ModelPrice, Rates, Tier from benchmarks.agentic.loop import HOSTED_CAPS, Caps -from benchmarks.agentic.protocol import FrameTooLarge, KeyLeakError, assert_no_key_shaped +from benchmarks.agentic.protocol import ( + WORKER_LEAK_REASON, + FrameTooLarge, + KeyLeakError, + assert_no_key_shaped, + encode_frame, + read_frame_fd, + redact_key_shaped, +) from benchmarks.model_matrix import ModelFamily, load_model_matrix, model_family_from_raw from benchmarks.runner import BenchmarkValidationError @@ -221,6 +235,10 @@ def test_local_launcher_passes_no_proxy_or_ca_variable( ("task-runner-" + "d" * 40, None), ("sk-ant-api03-" + "a" * 20, None), # too short for any key shape ("AIza" + "b" * 36, None), # a Google key is exactly 39 characters + ("bn" + "AIza" + "b" * 35, None), # a base64 run containing a key-shaped suffix + ("base64u0020" + "sk-proj-" + "c" * 40, None), + ("\\" + "x" * 10 + "AIza" + "g" * 35, None), # beyond the longest escape + (r"\x20" + "AIza" + "g" * 36, None), # the end boundary still applies ], ) def test_key_shaped_scan(text: str, pattern: str | None) -> None: @@ -234,6 +252,43 @@ def test_key_shaped_scan(text: str, pattern: str | None) -> None: assert_no_key_shaped(f"before {text} after", where="test frame") +@pytest.mark.parametrize( + "escape", + [ + r"\b", + r"\f", + r"\n", + r"\r", + r"\t", + r"\u000A", + r"\\u0020", + r"\x20", + r"\0", + r"\07", + r"\377", + r"\U00000020", + r"\N{SPACE}", + r"\a", + r"\v", + r"\e", + r"\N", + r"\_", + r"\L", + r"\P", + r"\\\\x00", + "\\" * 64 + "U00000020", + ], +) +def test_structured_escape_is_a_key_boundary_in_arbitrary_text(escape: str) -> None: + key = "sk-proj-" + "k" * 40 + prefix = "arbitrary text, no JSON required " + escape + for value in (prefix + key, (prefix + key).encode()): + with pytest.raises(KeyLeakError, match="openai"): + assert_no_key_shaped(value, where="test output") + expected = (prefix + "[redacted]").encode() + assert redact_key_shaped((prefix + key).encode()) == (expected, "openai") + + def test_random_base64_is_not_key_shaped() -> None: import base64 import random @@ -304,13 +359,13 @@ async def test_host_logs_and_artifacts_never_hold_a_workers_key(host: Host, tmp_ "import os, sys\n" "from benchmarks.agentic import worker\n" "real = worker.run_worker\n" - "async def leaky(channel, reader):\n" + "async def leaky(channel, reader, *args, **kwargs):\n" " key = os.environ['ANTHROPIC_API_KEY']\n" " print(key)\n" " sys.stderr.write(key + '\\n')\n" " sys.stderr.flush()\n" " os.write(2, key.encode() + b'\\n')\n" - " return await real(channel, reader)\n" + " return await real(channel, reader, *args, **kwargs)\n" "worker.run_worker = leaky\n" "sys.exit(worker.main_worker())\n" ) @@ -340,10 +395,10 @@ def command(self, job: WorkerJob) -> tuple[list[str], dict[str, str]]: "import os, sys\n" "from benchmarks.agentic import worker\n" "real = worker.run_worker\n" - "async def leaky(channel, reader):\n" + "async def leaky(channel, reader, *args, **kwargs):\n" " for name in ('ANTHROPIC_API_KEY', 'OPENAI_API_KEY', 'REF_API_KEY'):\n" " print(os.environ[name])\n" - " return await real(channel, reader)\n" + " return await real(channel, reader, *args, **kwargs)\n" "worker.run_worker = leaky\n" "sys.exit(worker.main_worker())\n" ) @@ -470,6 +525,99 @@ def command(self, job: WorkerJob) -> tuple[list[str], dict[str, str]]: return ([sys.executable, "-c", self.code] if job.job_id == "lost" else argv), env +@pytest.fixture +async def worker_stream(monkeypatch: pytest.MonkeyPatch) -> asyncio.StreamReader: + """Feed wire frames through supervision without creating or signalling any processes.""" + reader = asyncio.StreamReader() + proc = Mock(stdout=reader, wait=AsyncMock()) + proc.stdin.drain = AsyncMock() + monkeypatch.setattr(agentic_host, "_kill_group", Mock()) + monkeypatch.setattr(agentic_host, "_start_anchor", Mock()) + monkeypatch.setattr(agentic_host, "_reap", AsyncMock()) + monkeypatch.setattr(asyncio, "create_subprocess_exec", AsyncMock(return_value=proc)) + return reader + + +@pytest.mark.parametrize( + "kind,fields", + [ + ("discarded", {"corpus_id": "../other", "repeat": 1, "attempt": 1}), + ("trajectory", {"corpus_id": "Q1", "repeat": 2, "attempt": 1}), + ("trajectory", {"corpus_id": "Q1", "repeat": True, "attempt": 1}), + ("not_run", {"corpus_id": "Q1", "repeat": 1.0}), + ("trajectory", {"corpus_id": "Q1", "repeat": 1}), + ("discarded", {"corpus_id": "Q1", "repeat": 1, "attempt": 0}), + ("trajectory", {"corpus_id": "Q1", "repeat": 1, "attempt": 4}), + ("discarded", {"corpus_id": "Q1", "repeat": 1, "attempt": True}), + ("trajectory", {"corpus_id": "Q1", "repeat": 1, "attempt": 1.0}), + ("not_run", {"corpus_id": "Q1", "repeat": 1, "attempt": None}), + ], +) +async def test_unassigned_or_invalid_report_never_reaches_callback( + host: Host, + tmp_path: Path, + worker_stream: asyncio.StreamReader, + kind: str, + fields: dict[str, Any], +) -> None: + worker_stream.feed_data(encode_frame({"type": kind, "reason": "budget_stop", **fields})) + worker_stream.feed_eof() + with pytest.raises(BenchmarkValidationError): + await host.run([_job(tmp_path, [], count=1)]) + assert host.received == [] + + +@pytest.mark.parametrize("raw_only", [False, True]) +async def test_host_refuses_an_escaped_key_in_a_worker_frame( + host: Host, tmp_path: Path, worker_stream: asyncio.StreamReader, raw_only: bool +) -> None: + key = "AIza" + "g" * 35 + if raw_only: # The escaped A hides the key's end boundary in the decoded value. + body = ('{"type":"done","extra":"' + key + r'\u0041"}').encode() + worker_stream.feed_data(len(body).to_bytes(8, "big") + body) + else: + worker_stream.feed_data(encode_frame({"type": "done", "extra": [{"\n" + key: True}]})) + worker_stream.feed_eof() + with pytest.raises(KeyLeakError) as caught: + await host.run([_job(tmp_path, [], count=1)]) + assert key not in str(caught.value) + assert host.received == [] + + +def test_worker_checks_decoded_fields_before_sending(monkeypatch: pytest.MonkeyPatch) -> None: + write = Mock() + monkeypatch.setattr(worker, "_write_all", write) + key = "AIza" + "g" * 35 + channel = worker.ProtocolChannel(1, (), 2, Mock(), (Mock(), Mock())) + with pytest.raises(KeyLeakError) as caught: + channel.send({"answer": ["\n" + key]}) + assert key not in str(caught.value) + write.assert_not_called() + + +async def test_assigned_reports_reach_callback( + host: Host, tmp_path: Path, worker_stream: asyncio.StreamReader +) -> None: + job = _job(tmp_path, [], count=3) + frames = [ + {"type": "trajectory", "corpus_id": "Q1", "repeat": 1, "attempt": 1}, + { + "type": "discarded", + "corpus_id": "Q2", + "repeat": 1, + "attempt": 1, + "reason": "budget_stop", + }, + {"type": "not_run", "corpus_id": "Q3", "repeat": 1, "reason": "budget_stop"}, + {"type": "done"}, + ] + for frame in frames: + worker_stream.feed_data(encode_frame(frame)) + worker_stream.feed_eof() + await host.run([job]) + assert host.messages() == frames + + async def test_host_settles_a_lost_workers_unit_at_twice_its_bound_and_frees_the_provider( host: Host, tmp_path: Path ) -> None: @@ -551,6 +699,113 @@ async def test_a_key_shape_in_a_worker_log_is_redacted_before_the_run_stops( assert log.read_text() == "debug: token=[redacted]\n" +@pytest.mark.parametrize("indent", [None, 2], ids=["compact", "multiline"]) +@pytest.mark.parametrize("bytes_repr", [False, True]) +async def test_structured_worker_stderr_is_redacted_on_publication( + host: Host, tmp_path: Path, indent: int | None, bytes_repr: bool +) -> None: + key = "AIza" + "g" * 35 + detail = repr(b"\x00" + key.encode()) if bytes_repr else "failure\n" + key + line = json.dumps({"detail": detail}, indent=indent) + "\n" + code = ( + "import sys\nfrom benchmarks.agentic.worker import protect_output\n" + "channel = protect_output()\n" + f"sys.stderr.write({line!r})\nchannel.close()\n" + ) + with pytest.raises(KeyLeakError, match="google") as caught: + await host.run([_job(tmp_path, [], job_id="lost")], launcher=KeyedLauncher(code, "")) + assert key not in str(caught.value) + expected = line.replace(key, "[redacted]").encode() + assert (tmp_path / "logs/lost.stderr.log").read_bytes() == expected + + +@pytest.mark.parametrize("read_only", [False, True]) +async def test_raw_worker_stderr_is_private_before_publication( + host: Host, tmp_path: Path, read_only: bool +) -> None: + if read_only and os.geteuid() == 0: + pytest.skip("the read-only directory fixture requires unprivileged permissions") + log_dir = tmp_path / "logs" + log = log_dir / "lost.stderr.log" + links = tmp_path / "stderr-link-count" + code = ( + "import os\nfrom pathlib import Path\n" + f"os.write(2, {SYNTHETIC_KEY.encode()!r})\n" + f"Path({str(links)!r}).write_text(str(os.fstat(2).st_nlink))\n" + + _fake_worker(_reserve_frame(1024)) + ) + visible_at_stop = [] + + class Launcher(KeyedLauncher): + async def stop_worker(self, job: WorkerJob) -> None: + visible_at_stop.extend(log_dir.iterdir()) + if read_only: + log_dir.chmod(0o500) + + try: + with pytest.raises(KeyLeakError, match="anthropic") as error: + await host.run([_job(tmp_path, [ANSWER], job_id="lost")], launcher=Launcher(code, "")) + finally: + log_dir.chmod(0o700) + assert host.ledger.spent("anthropic") == 2 * D("0.002024") + assert SYNTHETIC_KEY not in "".join(traceback.format_exception(error.value)) + assert not visible_at_stop + assert links.read_text() == "0" + if read_only: + assert isinstance(error.value.__cause__, PermissionError) + assert not log.exists() + else: + assert log.read_text() == "[redacted]" + + +async def test_worker_log_publication_does_not_follow_path_collisions( + host: Host, tmp_path: Path +) -> None: + log_dir = tmp_path / "logs" + log_dir.mkdir() + log = log_dir / "lost.stderr.log" + target = tmp_path / "other-artifact" + target.write_bytes(b"keep me") + log.symlink_to(target) + legacy_stage = log_dir / (log.name + ".tmp") + legacy_stage.symlink_to(target) + code = f"import os\nos.write(2, {SYNTHETIC_KEY.encode()!r})" + with pytest.raises(KeyLeakError): + await host.run([_job(tmp_path, [], job_id="lost")], launcher=KeyedLauncher(code, "")) + assert target.read_bytes() == b"keep me" + assert legacy_stage.is_symlink() + assert not log.is_symlink() and log.read_text() == "[redacted]" + + +async def test_worker_log_redaction_cannot_expose_an_adjacent_key( + host: Host, tmp_path: Path +) -> None: + # The Google key acquires a token boundary when the adjacent Anthropic key is removed. + google = "AIza" + "g" * 35 + code = f"import os\nos.write(2, {(google + SYNTHETIC_KEY).encode()!r})" + with pytest.raises(KeyLeakError): + await host.run([_job(tmp_path, [], job_id="lost")], launcher=KeyedLauncher(code, "")) + assert google not in (tmp_path / "logs" / "lost.stderr.log").read_text() + + +async def test_oversized_worker_log_is_rejected_before_reading( + host: Host, tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + job = _job(tmp_path, [], job_id="lost") + code = ( + f"import os\nos.ftruncate(2, {agentic_host._MAX_LOG_BYTES + 1})\n" + + _fake_worker(_reserve_frame(1024)) + ) + pread = Mock(side_effect=AssertionError("oversized log read")) + monkeypatch.setattr(os, "pread", pread) + with pytest.raises(BenchmarkValidationError, match="scan limit") as error: + await host.run([job], launcher=KeyedLauncher(code, "")) + assert "lost.stderr.log" in "".join(traceback.format_exception(error.value)) + pread.assert_not_called() + assert not list((tmp_path / "logs").iterdir()) + assert host.ledger.spent("anthropic") == 2 * D("0.002024") + + async def test_a_line_logged_just_before_an_error_frame_reaches_the_log( host: Host, tmp_path: Path ) -> None: @@ -927,6 +1182,12 @@ async def wait(self) -> int: return 0 +def _worker_log(data: bytes) -> BinaryIO: + capture = tempfile.TemporaryFile(buffering=0) + capture.write(data) + return capture + + async def test_teardown_of_an_anchor_that_died_early(host: Host, tmp_path: Path) -> None: # Its group holds only a zombie, and macOS answers a group kill with EPERM. zombie = subprocess.Popen([sys.executable, "-c", "pass"], start_new_session=True) @@ -936,10 +1197,10 @@ async def test_teardown_of_an_anchor_that_died_early(host: Host, tmp_path: Path) time.sleep(0.01) try: log = tmp_path / "exited.stderr.log" - log.write_text("worker: done\n", encoding="utf-8") + capture = _worker_log(b"worker: done\n") service = host.service(_job(tmp_path, [ANSWER]).family) worker, anchor = _Exited(zombie.pid), zombie # the anchor died early - pattern = await agentic_host._teardown(worker, anchor, log, service, None) # type: ignore[arg-type] + pattern = await agentic_host._teardown(worker, anchor, log, service, None, capture) # type: ignore[arg-type] assert pattern is None and log.read_text() == "worker: done\n" finally: zombie.wait() @@ -966,44 +1227,73 @@ async def test_a_worker_that_never_exits_cannot_hang_its_teardown( provider="anthropic", model_id="scripted-1", input_bound=1000, output_bound=1024 ) log = tmp_path / "never-exits.stderr.log" - log.write_text("debug: sk-ant-api03-" + "z" * 90 + "\n", encoding="utf-8") + capture = _worker_log(f"debug: {SYNTHETIC_KEY}\n".encode()) async with asyncio.timeout(5): # the bound under test is 0.1 s worker, anchor = _Unending(group.pid), group - pattern = await agentic_host._teardown(worker, anchor, log, service, unit) # type: ignore[arg-type] + with pytest.raises(KeyLeakError, match="anthropic"): + await agentic_host._teardown(worker, anchor, log, service, unit, capture) # type: ignore[arg-type] assert group.wait(timeout=5) == -signal.SIGKILL - assert pattern is not None and log.read_text() == "debug: [redacted]\n" + assert log.read_text() == "debug: [redacted]\n" settles = [e for e in host.ledger.events("host-test") if e["event"] == "settle"] assert [(s["outcome"], D(s["booked"])) for s in settles] == [ ("worker_lost", 2 * D("0.002024")) ] +@pytest.mark.parametrize("failure", ["stage", "write", "close", "replace"]) async def test_a_failed_log_publish_still_settles_and_leaves_no_key( - host: Host, tmp_path: Path, monkeypatch: pytest.MonkeyPatch + host: Host, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, failure: str ) -> None: group = subprocess.Popen( [sys.executable, "-c", "import time; time.sleep(30)"], start_new_session=True ) - real_write = Path.write_bytes - - def full_disk(self: Path, data: bytes) -> int: - if self.name.endswith(".tmp"): # a partial copy, then the disk is full - real_write(self, data[:10]) - raise OSError(28, "No space left on device") - return real_write(self, data) - - monkeypatch.setattr(Path, "write_bytes", full_disk) + create_stage = tempfile.NamedTemporaryFile + storage_error = OSError(28, "No space left on device") + + def fail(*args: Any) -> None: + raise storage_error + + def full_disk(**kwargs: Any) -> Any: + if failure == "stage": + fail() + stage = create_stage(**kwargs) + write = stage.write + close = stage.file.close + + def partial_write(data: bytes) -> None: + assert SYNTHETIC_KEY.encode() not in data + write(data[:10]) + fail() + + def delayed_close() -> None: + if not stage.file.closed: + close() + fail() + + if failure == "write": + stage.write = partial_write + elif failure == "close": + stage.file.close = delayed_close + return stage + + monkeypatch.setattr(tempfile, "NamedTemporaryFile", full_disk) + if failure == "replace": + monkeypatch.setattr(os, "replace", fail) service = host.service(_job(tmp_path, [ANSWER]).family) unit = await service.reserve( provider="anthropic", model_id="scripted-1", input_bound=1000, output_bound=1024 ) log = tmp_path / "full.stderr.log" - log.write_text("debug: sk-ant-api03-" + "z" * 90 + "\n", encoding="utf-8") - retained = log.open("ab") # a writer that kept its descriptor through the teardown + capture = _worker_log(f"debug: {SYNTHETIC_KEY}\n".encode()) + # A writer that kept its descriptor through teardown. + retained = os.fdopen(os.dup(capture.fileno()), "wb") try: - with pytest.raises(OSError, match="No space left"): + with pytest.raises(KeyLeakError, match="anthropic") as error: worker, anchor = _Exited(group.pid), group - await agentic_host._teardown(worker, anchor, log, service, unit) # type: ignore[arg-type] + await agentic_host._teardown(worker, anchor, log, service, unit, capture) # type: ignore[arg-type] + assert error.value.__cause__ is storage_error + trace = "".join(traceback.format_exception(error.value)) + assert "No space left" in trace and SYNTHETIC_KEY not in trace retained.write(b"late: sk-ant-api03-" + b"z" * 90 + b"\n") finally: retained.close() @@ -1013,7 +1303,34 @@ def full_disk(self: Path, data: bytes) -> int: ("worker_lost", 2 * D("0.002024")) ] assert [path.name for path in tmp_path.glob("*.tmp")] == [] - assert not log.exists() or "sk-ant-api03-" not in log.read_text() + assert not log.exists() + + +def test_cli_reports_leak_and_storage_failure_after_worker_reservation( + host: Host, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str] +) -> None: + from benchmarks.__main__ import main + + job = _job(tmp_path, [], job_id="lost") + code = ( + f"import os\nos.write(2, {('private stderr: ' + SYNTHETIC_KEY).encode()!r})\n" + + _fake_worker(_reserve_frame(1024)) + ) + + def run(*args: Any, **kwargs: Any) -> None: + asyncio.run(host.run([job], launcher=LostLauncher(code))) + + monkeypatch.setattr("benchmarks.agentic.run.run_agentic", run) + monkeypatch.setattr(os, "replace", Mock(side_effect=PermissionError("artifact inaccessible"))) + with pytest.raises(SystemExit) as stopped: + main(["agentic-run", "--corpus", "unused", "--out", str(tmp_path)]) + assert stopped.value.code == 3 + output = capsys.readouterr() + assert not output.out and "anthropic" in output.err and "artifact inaccessible" in output.err + assert SYNTHETIC_KEY not in output.err and "private stderr" not in output.err + assert not list((tmp_path / "logs").iterdir()) + settles = [e for e in host.ledger.events("host-test") if e["event"] == "settle"] + assert [(e["outcome"], D(e["booked"])) for e in settles] == [("worker_lost", 2 * D("0.002024"))] async def test_host_aborts_the_run_when_a_worker_frame_holds_a_key_shaped_string( @@ -1064,3 +1381,867 @@ async def test_retries_exhausted_trajectory_is_rerun_at_most_twice( ("done", None), ] assert host.ledger.spent("anthropic") == 0 # every 429 books zero + + +def test_system_info_records_the_fetch_extraction_path(monkeypatch: pytest.MonkeyPatch) -> None: + fetch = system_spec_from_raw( + {"id": "docs-fetch", "adapter": "mcp-stdio", "command": ["mcp-server-fetch"]} + ) + monkeypatch.setattr(worker.shutil, "which", lambda name: None) + assert worker._system_info(fetch, "anthropic", None)["fetch_extraction"] == "pure-python" + monkeypatch.setattr(worker.shutil, "which", lambda name: "/usr/bin/node") + assert worker._system_info(fetch, "anthropic", None)["fetch_extraction"] == "readability-js" + assert worker._system_info(NO_DOCS, "anthropic", None)["fetch_extraction"] is None + + +# --- the launcher seam: prepare, key bootstrap, stop worker, close ------------------------------ + +SYNTHETIC_KEY = "sk-ant-api03-" + "a" * 90 + + +class RecordingLauncher: + """Wraps a launcher and logs every seam call to a shared list.""" + + def __init__( + self, + inner: Any = None, + *, + events: list[Any] | None = None, + bootstrap: dict[str, Any] | None = None, + prepare_error: Exception | None = None, + stop_error: Exception | None = None, + problems: Sequence[str] = (), + ) -> None: + self.inner = inner or LocalLauncher() + self.events = [] if events is None else events + self.bootstrap, self.prepare_error, self.stop_error = bootstrap, prepare_error, stop_error + self.problems = list(problems) + + def supports(self, family: ModelFamily) -> bool: + return self.inner.supports(family) + + def command(self, job: WorkerJob) -> tuple[list[str], dict[str, str]]: + self.events.append(("command", job.job_id)) + return self.inner.command(job) + + def bootstrap_frame(self, job: WorkerJob) -> dict[str, Any] | None: + self.events.append(("bootstrap", job.job_id)) + return None if self.bootstrap is None else dict(self.bootstrap) + + async def prepare(self, jobs: Sequence[WorkerJob]) -> None: + self.events.append(("prepare", [job.job_id for job in jobs])) + if self.prepare_error is not None: + raise self.prepare_error + + async def stop_worker(self, job: WorkerJob) -> None: + self.events.append(f"stop_worker:{job.job_id}") + if self.stop_error is not None: + raise self.stop_error + + async def close(self) -> list[str]: + self.events.append(("close",)) + return self.problems + + +def test_local_launcher_seam_defaults(tmp_path: Path) -> None: + job = _job(tmp_path, [ANSWER]) + launcher = LocalLauncher() + assert launcher.bootstrap_frame(job) is None + + async def seam() -> list[str]: + await launcher.prepare([job]) + await launcher.stop_worker(job) + return await launcher.close() + + assert asyncio.run(seam()) == [] + + +async def test_run_jobs_prepares_every_job_before_any_worker_starts( + host: Host, tmp_path: Path +) -> None: + jobs = [_job(tmp_path, [ANSWER], count=1, job_id=job_id) for job_id in ("a", "b")] + launcher = RecordingLauncher() + await host.run(jobs, launcher=launcher) + assert launcher.events[0] == ("prepare", ["a", "b"]) + assert {e for e in launcher.events if isinstance(e, tuple) and e[0] == "command"} == { + ("command", "a"), + ("command", "b"), + } + assert launcher.events[-1] == ("close",) + + +async def test_a_failed_prepare_starts_no_worker_and_still_closes( + host: Host, tmp_path: Path +) -> None: + launcher = RecordingLauncher(prepare_error=BenchmarkValidationError("probe failed")) + with pytest.raises(BenchmarkValidationError, match="probe failed"): + await host.run([_job(tmp_path, [ANSWER])], launcher=launcher) + assert [e for e in launcher.events if e[0] in ("command", "bootstrap")] == [] + assert launcher.events[-1] == ("close",) + + +async def test_supervise_writes_the_bootstrap_before_the_job_frame( + host: Host, tmp_path: Path +) -> None: + code = ( + "import json, sys\n" + "inp, out = sys.stdin.buffer, sys.stdout.buffer\n" + "def read():\n" + " return json.loads(inp.read(int.from_bytes(inp.read(8), 'big')))\n" + "types = [read()['type'], read()['type']]\n" + "body = json.dumps({'type': 'seen', 'types': types}).encode()\n" + "out.write(len(body).to_bytes(8, 'big') + body)\n" + "out.flush()\n" + ) + launcher = RecordingLauncher( + LostLauncher(code), bootstrap={"type": "bootstrap", "env": {}} + ) + await host.run([_job(tmp_path, [ANSWER], count=1, job_id="lost")], launcher=launcher) + seen = [m for m in host.messages("lost") if m["type"] == "seen"] + assert seen == [{"type": "seen", "types": ["bootstrap", "job"]}] + + +async def test_host_environ_is_unchanged_after_a_launch(host: Host, tmp_path: Path) -> None: + # A real worker takes the key from its bootstrap frame; the host never holds it. + before = dict(os.environ) + bootstrap = {"type": "bootstrap", "env": {"ANTHROPIC_API_KEY": SYNTHETIC_KEY}} + await host.run( + [_job(tmp_path, [ANSWER], count=1)], launcher=RecordingLauncher(bootstrap=bootstrap) + ) + assert dict(os.environ) == before + refuse_host_keys(os.environ) + assert [m["type"] for m in host.messages()] == ["system_info", "trajectory", "done"] + for path in (tmp_path / "logs").iterdir(): + assert SYNTHETIC_KEY not in path.read_text() + + +def test_bootstrap_key_is_redacted_from_worker_output() -> None: + code = ( + "import os, sys\n" + "from benchmarks.agentic.protocol import read_frame_fd\n" + "from benchmarks.agentic.worker import apply_bootstrap, protect_output\n" + "apply_bootstrap(read_frame_fd(0))\n" + "ch = protect_output()\n" + "key = os.environ['ANTHROPIC_API_KEY']\n" + "print(key)\n" + "sys.stderr.write(key + '\\n')\n" + "os.write(2, key.encode() + b'\\n')\n" + "ch.send({'type': 'done'})\n" + "ch.close()\n" + ) + env = {k: v for k, v in os.environ.items() if k not in PROVIDER_API_KEY_ENV.values()} + bootstrap = {"type": "bootstrap", "env": {"ANTHROPIC_API_KEY": SYNTHETIC_KEY}} + proc = subprocess.run( + [sys.executable, "-c", code], + cwd=REPO_ROOT, + input=encode_frame(bootstrap), + capture_output=True, + timeout=60, + env=env, + ) + assert proc.returncode == 0, proc.stderr + assert SYNTHETIC_KEY.encode() not in proc.stdout + proc.stderr + assert proc.stderr.count(b"[redacted]") == 3 + assert _frames(proc.stdout) == [{"type": "done"}] + + +async def test_worker_refuses_a_live_job_without_its_bootstrap( + monkeypatch: pytest.MonkeyPatch, +) -> None: + import benchmarks.agentic.clients as clients + + def never(*args: Any, **kwargs: Any) -> Any: + raise AssertionError("make_client must not be called") + + monkeypatch.setattr(clients, "make_client", never) + family = {f.id: f for f in load_model_matrix(MODEL_MATRIX_PATH).model_families}[ + "claude-sonnet-5-5" + ] + job = { + "type": "job", + "job_id": "claude-sonnet-5-5--no-docs", + "family": family.raw, + "system": NO_DOCS.raw, + "trajectories": [{"corpus_id": "Q1", "prompt": "q", "repeat": 1}], + "caps": asdict(HOSTED_CAPS), + } + with tempfile.TemporaryFile() as output: + channel = worker.ProtocolChannel(output.fileno(), (), -1, None, ()) + assert await worker.run_worker(channel, asyncio.StreamReader(), job) == 2 + output.seek(0) + error = read_frame_fd(output.fileno()) + assert error and error["type"] == "error" and "bootstrap" in error["reason"] + assert read_frame_fd(output.fileno()) is None + + +@pytest.mark.parametrize( + "env", + [ + {"HTTPS_PROXY": "http://elsewhere.invalid:3128"}, + {"ANTHROPIC_API_KEY": "not-a-real-key-1", "OPENAI_API_KEY": "not-a-real-key-2"}, + {"REF_API_KEY": "not-a-real-key-3"}, + ], +) +def test_a_bootstrap_with_a_foreign_or_second_variable_is_refused( + monkeypatch: pytest.MonkeyPatch, env: dict[str, str] +) -> None: + for name in env: + monkeypatch.delenv(name, raising=False) + with pytest.raises(BenchmarkValidationError) as caught: + worker.apply_bootstrap({"type": "bootstrap", "env": env}) + assert all(name in str(caught.value) for name in env) + assert "not-a-real-key" not in str(caught.value) and "elsewhere" not in str(caught.value) + assert all(name not in os.environ for name in env) + + +def test_read_frame_fd_reads_one_frame_and_leaves_the_next(tmp_path: Path) -> None: + read_fd, write_fd = os.pipe() + try: + os.write(write_fd, encode_frame({"type": "bootstrap"}) + encode_frame({"type": "job"})) + os.close(write_fd) + assert read_frame_fd(read_fd) == {"type": "bootstrap"} + assert read_frame_fd(read_fd) == {"type": "job"} + assert read_frame_fd(read_fd) is None + finally: + os.close(read_fd) + read_fd, write_fd = os.pipe() + try: + os.write(write_fd, (10**9).to_bytes(8, "big")) + os.close(write_fd) + with pytest.raises(FrameTooLarge): + read_frame_fd(read_fd, limit=1000) + finally: + os.close(read_fd) + + +def _settles_recorded(service: LedgerService, events: list[Any]) -> None: + real = service.settle + + async def settle(unit_id: str, **kwargs: Any) -> None: + events.append(f"settle:{kwargs['outcome']}") + await real(unit_id, **kwargs) + + service.settle = settle # type: ignore[method-assign] + + +async def _run_lost( + host: Host, tmp_path: Path, launcher: RecordingLauncher, job: WorkerJob +) -> None: + service = host.service(job.family) + _settles_recorded(service, launcher.events) + await run_jobs( + [job], + launcher=launcher, + ledger=service, + on_message=host.on_message, + log_dir=tmp_path / "logs", + cwd=REPO_ROOT, + ) + + +async def test_teardown_stops_the_worker_before_its_unit_is_settled( + host: Host, tmp_path: Path +) -> None: + launcher = RecordingLauncher(LostLauncher(_fake_worker(_reserve_frame(1024)))) + await _run_lost(host, tmp_path, launcher, _job(tmp_path, [ANSWER], job_id="lost")) + order = [e for e in launcher.events if isinstance(e, str)] + assert order == ["stop_worker:lost", "settle:worker_lost"] + assert host.ledger.spent("anthropic") == 2 * D("0.002024") + + +async def test_a_failing_stop_worker_still_scrubs_the_log_and_settles_the_unit( + host: Host, tmp_path: Path +) -> None: + leaky = ( + f"import sys\nsys.stderr.write('debug: {SYNTHETIC_KEY}\\n')\nsys.stderr.flush()\n" + + _fake_worker(_reserve_frame(1024)) + ) + launcher = RecordingLauncher( + LostLauncher(leaky), stop_error=RuntimeError("docker rm -f failed") + ) + with pytest.raises(KeyLeakError, match="anthropic") as error: + await _run_lost(host, tmp_path, launcher, _job(tmp_path, [ANSWER], job_id="lost")) + assert isinstance(error.value.__cause__, BenchmarkValidationError) + assert "RuntimeError: docker rm -f failed" in str(error.value.__cause__) + assert SYNTHETIC_KEY not in "".join(traceback.format_exception(error.value)) + log = tmp_path / "logs" / "lost.stderr.log" + assert not log.exists() or log.read_text() == "debug: [redacted]\n" + assert host.ledger.spent("anthropic") == 2 * D("0.002024") + assert [e for e in launcher.events if isinstance(e, str)] == [ + "stop_worker:lost", + "settle:worker_lost", + ] + assert launcher.events[-1] == ("close",) + + +@pytest.mark.parametrize("phase", ["spawn", "kill", "reap", "stop", "chained_stop"]) +async def test_cleanup_scrubs_and_accounts_even_with_a_broken_stderr( + host: Host, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, phase: str +) -> None: + granted, started = asyncio.Event(), asyncio.Event() + stopped = AsyncMock() + + async def spawn(*args: Any, stderr: Any, **kwargs: Any) -> Mock: + os.write(stderr.fileno(), f"debug: {SYNTHETIC_KEY}\n".encode()) + started.set() + if phase == "spawn": + await asyncio.Event().wait() + stdout = asyncio.StreamReader() + stdout.feed_data(encode_frame(_reserve_frame(1024))) + + def write(frame: bytes) -> None: + if _frames(frame)[0]["type"] == "grant": + granted.set() + + return Mock(stdin=Mock(write=write, drain=AsyncMock()), stdout=stdout, wait=AsyncMock()) + + class Launcher(LocalLauncher): + async def stop_worker(self, job: WorkerJob) -> None: + await stopped(job) + if phase == "chained_stop": + try: + raise ValueError(SYNTHETIC_KEY) + except ValueError as cause: + raise RuntimeError("removal failed") from cause + if phase == "stop": + raise RuntimeError(f"removal failed: {SYNTHETIC_KEY}") + + _fake_host_processes(monkeypatch, spawn) + if phase == "kill": + monkeypatch.setattr(agentic_host, "_kill_group", Mock(side_effect=OSError("kill failed"))) + if phase == "reap": + monkeypatch.setattr(agentic_host, "_reap", AsyncMock(side_effect=OSError("reap failed"))) + job = _job(tmp_path, [ANSWER], job_id="interrupted") + task = asyncio.create_task(host.run([job], launcher=Launcher())) + await asyncio.wait_for((started if phase == "spawn" else granted).wait(), 2) + broken = Mock(write=Mock(side_effect=BrokenPipeError("reader closed"))) + with monkeypatch.context() as stream: + stream.setattr(sys, "stderr", broken) + task.cancel("signal SIGTERM") + with pytest.raises(asyncio.CancelledError, match="signal SIGTERM") as error: + await task + log = tmp_path / "logs" / "interrupted.stderr.log" + assert log.read_text() == "debug: [redacted]\n" + stopped.assert_awaited_once_with(job) + trace = "".join(traceback.format_exception(error.value)) + assert SYNTHETIC_KEY not in trace + assert log.name in trace and "KeyLeakError" in trace + if phase in ("stop", "chained_stop"): + assert "removal failed" in trace + assert host.ledger.spent("anthropic") == (0 if phase == "spawn" else 2 * D("0.002024")) + + +@pytest.mark.parametrize("cancel_spawn", [False, True]) +async def test_parent_log_close_failure_still_cleans_the_spawned_worker( + host: Host, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, cancel_spawn: bool +) -> None: + opened = asyncio.Event() + log = tmp_path / "logs" / "interrupted.stderr.log" + create_capture = tempfile.TemporaryFile + + class FailingClose(io.FileIO): + def close(self) -> None: + super().close() + raise OSError("log close failed") + + def open_file(**kwargs: Any) -> FailingClose: + with create_capture(**kwargs) as capture: + return FailingClose(os.dup(capture.fileno()), "rb+") + + async def spawn(*args: Any, stderr: Any, **kwargs: Any) -> Mock: + os.write(stderr.fileno(), SYNTHETIC_KEY.encode()) + opened.set() + if cancel_spawn: + await asyncio.Event().wait() + stdout = asyncio.StreamReader() + stdout.feed_eof() + return Mock(stdin=Mock(drain=AsyncMock()), stdout=stdout, wait=AsyncMock()) + + _fake_host_processes(monkeypatch, spawn) + kill = Mock() + reap = AsyncMock() + monkeypatch.setattr(agentic_host, "_kill_group", kill) + monkeypatch.setattr(agentic_host, "_reap", reap) + monkeypatch.setattr(tempfile, "TemporaryFile", open_file) + launcher = RecordingLauncher() + job = _job(tmp_path, [ANSWER], job_id="interrupted") + task = asyncio.create_task(host.run([job], launcher=launcher)) + await asyncio.wait_for(opened.wait(), 2) + if cancel_spawn: + task.cancel("signal SIGTERM") + with pytest.raises((asyncio.CancelledError, OSError, KeyLeakError)) as error: + await task + kill.assert_called_once() + reap.assert_awaited_once() + assert "stop_worker:interrupted" in launcher.events + assert log.read_text() == "[redacted]" + trace = "".join(traceback.format_exception(error.value)) + assert "log close failed" in trace and SYNTHETIC_KEY not in trace + if cancel_spawn: + assert isinstance(error.value, asyncio.CancelledError) + assert str(error.value) == "signal SIGTERM" + + +async def test_unreadable_worker_log_is_not_published( + host: Host, tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + job = _job(tmp_path, [], job_id="lost") + code = f"import os\nos.write(2, {SYNTHETIC_KEY.encode()!r})" + monkeypatch.setattr(os, "pread", Mock(side_effect=OSError("read failed"))) + with pytest.raises(OSError, match="read failed"): + await host.run([job], launcher=KeyedLauncher(code, "")) + assert not list((tmp_path / "logs").iterdir()) + + +async def test_scrub_allocation_failure_leaves_no_log_and_settles( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + log = tmp_path / "worker.stderr.log" + capture = _worker_log(SYNTHETIC_KEY.encode()) + failure = MemoryError("redaction allocation failed") + monkeypatch.setattr(agentic_host, "redact_key_shaped", Mock(side_effect=failure)) + monkeypatch.setattr(agentic_host, "_kill_group", Mock()) + monkeypatch.setattr(agentic_host, "_reap", AsyncMock()) + ledger = Mock(settle=AsyncMock()) + with pytest.raises(MemoryError, match="redaction allocation failed") as error: + await agentic_host._teardown(None, Mock(), log, ledger, "reserved", capture) + assert error.value is failure + assert not log.exists() and not log.with_suffix(".log.tmp").exists() + ledger.settle.assert_awaited_once_with("reserved", outcome="worker_lost", buckets=None) + + +async def test_unformattable_removal_error_cannot_skip_scrub_or_settlement( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + log = tmp_path / "worker.stderr.log" + capture = _worker_log(SYNTHETIC_KEY.encode()) + monkeypatch.setattr(agentic_host, "_kill_group", Mock()) + monkeypatch.setattr(agentic_host, "_reap", AsyncMock()) + ledger = Mock(settle=AsyncMock()) + stop = AsyncMock(side_effect=RuntimeError(f"removal failed: {SYNTHETIC_KEY}")) + with monkeypatch.context() as formatting, pytest.raises(KeyLeakError) as error: + formatting.setattr(traceback, "format_exception", Mock(side_effect=MemoryError())) + await agentic_host._teardown(None, Mock(), log, ledger, "reserved", capture, stop) + assert log.read_text() == "[redacted]" + ledger.settle.assert_awaited_once_with("reserved", outcome="worker_lost", buckets=None) + trace = "".join(traceback.format_exception(error.value)) + assert log.name in trace and SYNTHETIC_KEY not in trace + + +async def test_close_problems_fail_a_clean_run(host: Host, tmp_path: Path) -> None: + launcher = RecordingLauncher(problems=["proxy pdmcp-x-proxy: exit 137"]) + with pytest.raises(BenchmarkValidationError, match="exit 137"): + await host.run([_job(tmp_path, [ANSWER], count=1)], launcher=launcher) + assert [m["type"] for m in host.messages()][-1] == "done" # the run itself completed + + +@pytest.mark.parametrize("boundary", ["spawn", "spawn_kill", "worker", "launcher"]) +async def test_host_cleanup_preserves_signal_and_waits_for_failure( + host: Host, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, boundary: str +) -> None: + running, removing, release = asyncio.Event(), asyncio.Event(), asyncio.Event() + failure = RuntimeError(f"{boundary} cleanup failed") + interrupted: list[asyncio.CancelledError] = [] + + async def until_cancelled(*args: Any, **kwargs: Any) -> None: + running.set() + try: + await asyncio.Event().wait() + except asyncio.CancelledError as exc: + interrupted.append(exc) + raise + + async def fail_cleanup(*args: Any) -> None: + removing.set() + await release.wait() + raise failure + + launcher = RecordingLauncher() + if boundary == "launcher": + monkeypatch.setattr(launcher, "prepare", until_cancelled) + monkeypatch.setattr(launcher, "close", fail_cleanup) + else: + monkeypatch.setattr(agentic_host, "_start_anchor", Mock(return_value=Mock(pid=object()))) + + async def reap(*args: Any) -> None: + if boundary == "spawn": + await fail_cleanup() + if boundary == "spawn_kill": + removing.set() + await release.wait() + + def kill(*args: Any) -> None: + if boundary == "spawn_kill": + removing.set() + raise failure + + monkeypatch.setattr(agentic_host, "_kill_group", kill) + monkeypatch.setattr(agentic_host, "_reap", reap) + proc = Mock(stdin=Mock(drain=until_cancelled), wait=AsyncMock(return_value=0)) + monkeypatch.setattr( + asyncio, + "create_subprocess_exec", + until_cancelled if boundary.startswith("spawn") else AsyncMock(return_value=proc), + ) + monkeypatch.setattr(launcher, "stop_worker", fail_cleanup) + + task = asyncio.create_task(host.run([_job(tmp_path, [ANSWER])], launcher=launcher)) + await asyncio.wait_for(running.wait(), 2) + task.cancel("signal SIGTERM") + await asyncio.wait_for(removing.wait(), 2) + task.cancel("signal SIGHUP") + await asyncio.sleep(0) + still_cleaning = not task.done() + release.set() + with pytest.raises(asyncio.CancelledError, match="signal SIGTERM") as error: + await task + assert still_cleaning + assert error.value is interrupted[0] + assert error.value.__cause__ is failure + + +def _fake_host_processes(monkeypatch: pytest.MonkeyPatch, spawn: Any) -> None: + monkeypatch.setattr(agentic_host, "_start_anchor", Mock(return_value=Mock(pid=object()))) + monkeypatch.setattr(agentic_host, "_kill_group", Mock()) + monkeypatch.setattr(agentic_host, "_reap", AsyncMock()) + monkeypatch.setattr(asyncio, "create_subprocess_exec", spawn) + + +@pytest.mark.parametrize("during_teardown", [False, True]) +async def test_cancelled_worker_reports_scrubbed_log_and_books_open_unit( + host: Host, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, during_teardown: bool +) -> None: + granted, stopping, release = asyncio.Event(), asyncio.Event(), asyncio.Event() + + async def spawn(*args: Any, stderr: Any, **kwargs: Any) -> Mock: + stderr.write(f"local debug: {SYNTHETIC_KEY}\n".encode()) + stdout = asyncio.StreamReader() + stdout.feed_data(encode_frame(_reserve_frame(1024))) + if during_teardown: + stdout.feed_eof() + + def write(frame: bytes) -> None: + if _frames(frame)[0]["type"] == "grant": + granted.set() + + return Mock(stdin=Mock(write=write, drain=AsyncMock()), stdout=stdout, wait=AsyncMock()) + + class Launcher(LocalLauncher): + async def stop_worker(self, job: WorkerJob) -> None: + stopping.set() + await release.wait() + + _fake_host_processes(monkeypatch, spawn) + job = _job(tmp_path, [ANSWER], job_id="interrupted") + task = asyncio.create_task(host.run([job], launcher=Launcher())) + await asyncio.wait_for((stopping if during_teardown else granted).wait(), 2) + task.cancel("signal SIGTERM") + await asyncio.wait_for(stopping.wait(), 2) + release.set() + with pytest.raises(asyncio.CancelledError, match="signal SIGTERM") as error: + await task + log = tmp_path / "logs" / "interrupted.stderr.log" + assert log.read_text() == "local debug: [redacted]\n" + assert host.ledger.spent("anthropic") == 2 * D("0.002024") + leak = error.value.__cause__ + assert isinstance(leak, KeyLeakError) + assert str(log) in str(leak) and "anthropic" in str(leak) + assert SYNTHETIC_KEY not in str(leak) and "local debug" not in str(leak) + + +@pytest.mark.parametrize("problem", ["stop", "leak"]) +async def test_later_worker_reports_cleanup_after_clean_sibling_cancellation( + host: Host, + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + capsys: pytest.CaptureFixture[str], + problem: str, +) -> None: + ready = {name: asyncio.Event() for name in ("first", "later")} + first_done, release = asyncio.Event(), asyncio.Event() + + async def spawn(*args: Any, stderr: Any, **kwargs: Any) -> Mock: + name = args[-1] + if name == "first": + supervisor = asyncio.current_task() + assert supervisor is not None + supervisor.add_done_callback(lambda _: first_done.set()) + elif problem == "leak": + stderr.write(f"local debug: {SYNTHETIC_KEY}\n".encode()) + ready[name].set() + return Mock(stdin=Mock(drain=AsyncMock()), stdout=asyncio.StreamReader(), wait=AsyncMock()) + + class Launcher(LocalLauncher): + def command(self, job: WorkerJob) -> tuple[list[str], dict[str, str]]: + return ["unused", job.job_id], {} + + async def stop_worker(self, job: WorkerJob) -> None: + if job.job_id == "later": + await release.wait() + if problem == "stop": + raise RuntimeError("worker removal failed") + + _fake_host_processes(monkeypatch, spawn) + jobs = [_job(tmp_path, [ANSWER], job_id=name) for name in ready] + task = asyncio.create_task(host.run(jobs, launcher=Launcher())) + for event in ready.values(): + await asyncio.wait_for(event.wait(), 2) + task.cancel("signal SIGTERM") + await asyncio.wait_for(first_done.wait(), 2) + assert not task.done() + release.set() + with pytest.raises(asyncio.CancelledError, match="signal SIGTERM"): + await task + stderr = capsys.readouterr().err + assert "later" in stderr + if problem == "leak": + log = tmp_path / "logs" / "later.stderr.log" + assert log.read_text() == "local debug: [redacted]\n" + assert "KeyLeakError" in stderr and "anthropic" in stderr and str(log) in stderr + assert SYNTHETIC_KEY not in stderr and "local debug" not in stderr + else: + assert "worker removal failed" in stderr + + +async def test_run_jobs_preserves_cancellation_while_draining_other_workers( + host: Host, tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + draining, release = asyncio.Event(), asyncio.Event() + original = asyncio.CancelledError("signal SIGTERM") + + async def supervise(job: WorkerJob, **kwargs: Any) -> None: + if job.job_id == "first": + raise original + try: + await asyncio.Event().wait() + finally: + draining.set() + await release.wait() + + monkeypatch.setattr(agentic_host, "_supervise", supervise) + jobs = [_job(tmp_path, [ANSWER], job_id=name) for name in ("first", "second")] + task = asyncio.create_task(host.run(jobs)) + await asyncio.wait_for(draining.wait(), 2) + task.cancel("signal SIGHUP") + await asyncio.sleep(0) + assert not task.done() + release.set() + with pytest.raises(asyncio.CancelledError, match="signal SIGTERM") as error: + await task + assert error.value is original + + +@pytest.mark.parametrize("during_prepare", [True, False]) +async def test_launcher_close_problems_are_the_cause_of_cancellation( + host: Host, tmp_path: Path, during_prepare: bool +) -> None: + started, closing, release = asyncio.Event(), asyncio.Event(), asyncio.Event() + + class Launcher(LocalLauncher): + async def prepare(self, jobs: Sequence[WorkerJob]) -> None: + if during_prepare: + started.set() + await asyncio.Event().wait() + + async def close(self) -> list[str]: + closing.set() + await release.wait() + return ["outside network removal failed"] + + task = asyncio.create_task( + run_jobs( + [], + launcher=Launcher(), + ledger=host.service(_job(tmp_path, [ANSWER]).family), + on_message=host.on_message, + log_dir=tmp_path, + cwd=tmp_path, + ) + ) + await asyncio.wait_for((started if during_prepare else closing).wait(), 2) + task.cancel("signal SIGTERM") + await asyncio.wait_for(closing.wait(), 2) + release.set() + with pytest.raises(asyncio.CancelledError, match="signal SIGTERM") as error: + await task + assert isinstance(error.value.__cause__, BenchmarkValidationError) + assert "outside network removal failed" in str(error.value.__cause__) + + +@pytest.mark.parametrize("provider", ["anthropic", "openai"]) +@pytest.mark.parametrize("failure", [WORKER_LEAK_REASON, "own key found in output", "decoded"]) +async def test_credential_failure_denies_sibling_grants_during_teardown( + host: Host, tmp_path: Path, provider: str, failure: str +) -> None: + """Real protocol workers reproduce the R15 sibling grant during removal.""" + boundary, response = tmp_path / "removing", tmp_path / "reply.json" + if failure == "decoded": + body = json.dumps({"type": "system_info", "note": SYNTHETIC_KEY}).replace( + "sk-ant", r"\u0073k-ant" + ).encode() + assert SYNTHETIC_KEY.encode() not in body + assert_no_key_shaped(body, where="encoded synthetic frame") + leak_frame = len(body).to_bytes(8, "big") + body + else: + leak_frame = encode_frame({"type": "error", "reason": failure}) + code = ( + "import json, os, sys, time\n" + "from pathlib import Path\n" + "from benchmarks.agentic.protocol import encode_frame, read_frame_fd\n" + "job = read_frame_fd(0)\n" + "if job['job_id'] == 'leak':\n" + f" os.write(1, {leak_frame!r})\n" + "else:\n" + " deadline = time.monotonic() + 5\n" + f" while not Path({str(boundary)!r}).exists():\n" + " assert time.monotonic() < deadline, 'teardown never started'\n" + " time.sleep(0.01)\n" + f" os.write(1, {encode_frame(_reserve_frame(1024))!r})\n" + " reply = read_frame_fd(0)\n" + f" stage = Path({str(response.with_suffix('.tmp'))!r})\n" + " stage.write_text(json.dumps(reply))\n" + f" stage.replace({str(response)!r})\n" + ) + + class Launcher(KeyedLauncher): + closed = False + + async def stop_worker(self, job: WorkerJob) -> None: + if job.job_id == "leak": + boundary.touch() + async with asyncio.timeout(5): + while not response.exists(): + await asyncio.sleep(0.01) + + async def close(self) -> list[str]: + self.closed = True + return [] + + jobs = [_job(tmp_path, [ANSWER], job_id=name) for name in ("leak", "sibling")] + jobs[1] = replace(jobs[1], family=replace(jobs[1].family, provider=provider)) + host.ledger.close() + host.ledger = Ledger.open( + tmp_path / "ledger", run_id="host-test", caps={"anthropic": D(180), "openai": D(65)} + ) + service = host.service(jobs[0].family) + launcher = Launcher(code, key="") + with pytest.raises(KeyLeakError) as error: + await run_jobs( + jobs, launcher=launcher, ledger=service, on_message=host.on_message, + log_dir=tmp_path / "logs", cwd=REPO_ROOT, + ) + assert launcher.closed + assert len(list((tmp_path / "logs").glob("*.stderr.log"))) == 2 + assert SYNTHETIC_KEY not in "".join(traceback.format_exception(error.value)) + assert json.loads(response.read_text()) == {"type": "deny"} + assert host.ledger.invocation_events() == [] + + +async def test_credential_failure_stops_grants_before_waiting_for_worker_exit( + host: Host, tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + waiting, release = asyncio.Event(), asyncio.Event() + job = _job(tmp_path, [ANSWER], job_id="leak") + service = host.service(job.family) + stdout = asyncio.StreamReader() + stdout.feed_data(encode_frame({"type": "error", "reason": WORKER_LEAK_REASON})) + + async def wait() -> int: + waiting.set() + await release.wait() + return 3 + + proc = Mock(stdin=Mock(drain=AsyncMock()), stdout=stdout, wait=wait) + _fake_host_processes(monkeypatch, AsyncMock(return_value=proc)) + task = asyncio.create_task(run_jobs( + [job], launcher=LocalLauncher(), ledger=service, on_message=host.on_message, + log_dir=tmp_path / "logs", cwd=REPO_ROOT, + )) + try: + await asyncio.wait_for(waiting.wait(), 2) + assert not task.done() + unit = await service.reserve( + provider="anthropic", model_id=job.family.model_id, input_bound=1000, output_bound=1024 + ) + finally: + release.set() + with pytest.raises(KeyLeakError, match=WORKER_LEAK_REASON): + await task + assert unit is None + assert host.ledger.invocation_events() == [] + + +@pytest.mark.parametrize("decoded", [False, True]) +async def test_protocol_failure_stops_grants_at_recognition_without_a_scheduling_gap( + host: Host, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, decoded: bool +) -> None: + job = _job(tmp_path, [ANSWER], job_id="leak") + service = host.service(job.family) + body = json.dumps({"type": "system_info", "note": SYNTHETIC_KEY}) + if decoded: + body = body.replace("sk-ant", r"\u0073k-ant") + assert_no_key_shaped(body, where="encoded synthetic frame") + stdout = asyncio.StreamReader() + stdout.feed_data(len(body.encode()).to_bytes(8, "big") + body.encode()) + proc = Mock(stdin=Mock(drain=AsyncMock()), stdout=stdout, wait=AsyncMock()) + _fake_host_processes(monkeypatch, AsyncMock(return_value=proc)) + real_read = agentic_host.read_frame + competing: list[asyncio.Task[str | None]] = [] + + async def read(*args: Any, **kwargs: Any) -> Any: + try: + return await real_read(*args, **kwargs) + except KeyLeakError: + # A sibling ready at recognition must not outrun the supervisor's stop. + competing.append(asyncio.create_task(service.reserve( + provider="anthropic", model_id=job.family.model_id, + input_bound=1000, output_bound=1024, + ))) + raise + + monkeypatch.setattr(agentic_host, "read_frame", read) + with pytest.raises(KeyLeakError, match="worker frame"): + await run_jobs( + [job], launcher=LocalLauncher(), ledger=service, on_message=host.on_message, + log_dir=tmp_path / "logs", cwd=REPO_ROOT, + ) + assert len(competing) == 1 + assert await competing[0] is None + assert host.ledger.invocation_events() == [] + + +@pytest.mark.parametrize("failure", ["log", "stop_worker", "diagnostic"]) +async def test_cleanup_credential_failure_stops_queued_grants_and_settles_open_unit( + host: Host, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, failure: str +) -> None: + service = host.service(_job(tmp_path, [ANSWER]).family) + unit = await service.reserve( + provider="anthropic", model_id="scripted-1", input_bound=1000, output_bound=1024 + ) + assert unit is not None + pending = asyncio.create_task(service.reserve( + provider="anthropic", model_id="scripted-1", input_bound=1000, output_bound=1024 + )) + await asyncio.sleep(0) + assert not pending.done() + monkeypatch.setattr(agentic_host, "_kill_group", Mock()) + monkeypatch.setattr(agentic_host, "_reap", AsyncMock()) + capture = _worker_log(SYNTHETIC_KEY.encode() if failure == "log" else b"clean") + log = tmp_path / "worker.stderr.log" + stop = AsyncMock() + if failure == "stop_worker": + stop.side_effect = KeyLeakError("synthetic credential failure in cleanup") + elif failure == "diagnostic": + stop.side_effect = RuntimeError(SYNTHETIC_KEY) + try: + with pytest.raises(KeyLeakError) as error: + await agentic_host._teardown(None, Mock(), log, service, unit, capture, stop) + assert await asyncio.wait_for(pending, 1) is None + assert host.ledger.spent("anthropic") == 2 * D("0.002024") + assert [e["event"] for e in host.ledger.invocation_events()] == ["reserve", "settle"] + assert log.read_text() == ("[redacted]" if failure == "log" else "clean") + assert SYNTHETIC_KEY not in "".join(traceback.format_exception(error.value)) + assert capture.closed + finally: + pending.cancel() + await asyncio.gather(pending, return_exceptions=True) diff --git a/tests/benchmarks/test_agentic_ledger.py b/tests/benchmarks/test_agentic_ledger.py index d7c165d3..f890c8f0 100644 --- a/tests/benchmarks/test_agentic_ledger.py +++ b/tests/benchmarks/test_agentic_ledger.py @@ -3,7 +3,9 @@ from __future__ import annotations import asyncio +import fcntl import json +import os import subprocess import sys from datetime import date @@ -16,6 +18,7 @@ from benchmarks.agentic.ledger import ( PROVIDER_CAPS, PROVIDER_MARGINS, + UNMETERED_PROVIDERS, Ledger, LedgerService, ModelPrice, @@ -27,8 +30,14 @@ load_price_snapshot, refuse_stale_snapshot, ) +from benchmarks.agentic.protocol import KeyLeakError from benchmarks.agentic.types import Buckets -from benchmarks.agentic.usage import anthropic_buckets, gemini_buckets, openai_buckets +from benchmarks.agentic.usage import ( + anthropic_buckets, + gemini_buckets, + ollama_buckets, + openai_buckets, +) from benchmarks.model_matrix import ModelFamily, load_model_matrix, model_family_from_raw from benchmarks.runner import BenchmarkValidationError @@ -341,6 +350,27 @@ def test_actual_above_bound_stops_the_provider_until_acknowledged(tmp_path: Path ledger.close() +def test_ledger_refuses_an_escaped_key_before_recording_a_reservation(tmp_path: Path) -> None: + key = "AIza" + "g" * 35 + ledger = _open(tmp_path, anthropic="10") + try: + with pytest.raises(KeyLeakError) as caught: + ledger.reserve( + "anthropic", + model_id="é" + key, + kind="model_call", + bound=D(1), + input_bound=1, + output_bound=1, + ) + assert key not in str(caught.value) + assert not (tmp_path / "anthropic.jsonl").exists() + assert ledger.invocation_events() == [] + assert _reserve(ledger, "anthropic", "1") + finally: + ledger.close() + + def test_ledger_files_hold_money_as_decimal_strings(tmp_path: Path) -> None: ledger = _open(tmp_path, anthropic="10") unit = _reserve(ledger, "anthropic", "2") @@ -375,6 +405,43 @@ def test_a_second_open_on_the_same_directory_is_refused(tmp_path: Path) -> None: _open(tmp_path, anthropic="10").close() # released by close() +def test_ledger_open_closes_its_descriptor_when_setup_is_interrupted( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + opened = [] + + def interrupt(fd: int, mode: int) -> None: + opened.append(fd) + raise KeyboardInterrupt("chmod interrupted") + + with monkeypatch.context() as setup: + setup.setattr(os, "fchmod", interrupt) + with pytest.raises(KeyboardInterrupt, match="chmod interrupted"): + Ledger.open(tmp_path, run_id=RUN_ID) + (fd,) = opened + with pytest.raises(OSError): + os.fstat(fd) + Ledger.open(tmp_path, run_id=RUN_ID).close() + + +def test_ledger_close_closes_its_descriptor_if_unlock_is_interrupted( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + ledger = Ledger.open(tmp_path, run_id=RUN_ID) + with monkeypatch.context() as setup: + + def interrupt(*args: Any) -> None: + raise KeyboardInterrupt("unlock interrupted") + + setup.setattr(fcntl, "flock", interrupt) + with pytest.raises(KeyboardInterrupt, match="unlock interrupted"): + ledger.close() + try: + Ledger.open(tmp_path, run_id="following").close() + finally: + ledger.close() + + def test_the_lock_file_is_private_to_its_owner(tmp_path: Path) -> None: _open(tmp_path, anthropic="10").close() assert (tmp_path / ".lock").stat().st_mode & 0o077 == 0 @@ -475,6 +542,73 @@ async def test_service_releases_the_provider_when_a_reserve_is_refused(tmp_path: ledger.close() +@pytest.mark.parametrize("provider,model_id", [("anthropic", "a"), ("ollama", "local")]) +async def test_service_stop_denies_fresh_and_queued_grants_but_settles_existing_units( + tmp_path: Path, provider: str, model_id: str +) -> None: + ledger, service = _service(tmp_path, anthropic="10", openai="10") + pending = [] + try: + first = await service.reserve( + provider=provider, model_id=model_id, input_bound=10, output_bound=10 + ) + other = await service.reserve( + provider="openai", model_id="o", input_bound=10, output_bound=10 + ) + assert first is not None and other is not None + for _ in range(2): + pending.append(asyncio.create_task(service.reserve( + provider=provider, model_id=model_id, input_bound=10, output_bound=10 + ))) + await asyncio.sleep(0) + assert all(not task.done() for task in pending) + before = ledger.invocation_events() + service.stop_grants() + service.stop_grants() # irreversible and idempotent for this invocation + # Refuse even while these providers still hold their already granted units. + for p, model in ((provider, model_id), ("openai", "o")): + assert await asyncio.wait_for(service.reserve( + provider=p, model_id=model, input_bound=10, output_bound=10 + ), 1) is None + await service.settle(first, outcome="ok", buckets=Buckets(10, 0, 0, 10)) + await service.settle(other, outcome="worker_lost", buckets=None) + assert await asyncio.wait_for(asyncio.gather(*pending), 1) == [None, None] + assert all(not lock.locked() for lock in service._locks.values()) + assert [e for e in ledger.invocation_events() if e["event"] == "reserve"] == before + assert ledger.spent("openai") == D("0.00004") + assert not [e for e in ledger.invocation_events() if e["event"] == "stop"] + finally: + for task in pending: + task.cancel() + await asyncio.gather(*pending, return_exceptions=True) + ledger.close() + + +async def test_service_stop_is_invocation_local_and_preserves_pending_unit_recovery( + tmp_path: Path, +) -> None: + ledger, service = _service(tmp_path, anthropic="10") + try: + unit = await service.reserve( + provider="anthropic", model_id="a", input_bound=10, output_bound=10 + ) + assert unit is not None + service.stop_grants() + finally: + ledger.close() # simulate a lost process after the stop, before settlement + ledger, service = _service(tmp_path, anthropic="10") + try: + assert _event(ledger, "settle", unit)["outcome"] == "unsettled_at_load" + assert ledger.spent("anthropic") == D("0.00004") + fresh = await service.reserve( + provider="anthropic", model_id="a", input_bound=10, output_bound=10 + ) + assert fresh is not None + await service.settle(fresh, outcome="ok", buckets=Buckets(10, 0, 0, 10)) + finally: + ledger.close() + + async def test_service_prices_a_bound_above_the_tier_threshold_at_the_high_tier( tmp_path: Path, ) -> None: @@ -559,3 +693,76 @@ def test_caps_and_margins_add_up_to_the_budget() -> None: "openai": D(75), "google": D(200), } + + +def test_ollama_buckets_split_cached_prompt_tokens() -> None: + usage = { + "prompt_tokens": 120, + "completion_tokens": 30, + "prompt_tokens_details": {"cached_tokens": 20}, + } + assert ollama_buckets(usage) == Buckets(100, 0, 20, 30, 0) + + +def test_ollama_buckets_without_cache_details() -> None: + usage: dict[str, Any] = {"prompt_tokens": 120, "completion_tokens": 30} + assert ollama_buckets(usage) == Buckets(120, 0, 0, 30, 0) + assert ollama_buckets({**usage, "prompt_tokens_details": None}) == Buckets(120, 0, 0, 30, 0) + + +async def test_an_unmetered_provider_gets_one_unit_at_a_time_and_is_never_booked( + tmp_path: Path, +) -> None: + assert UNMETERED_PROVIDERS == frozenset({"ollama"}) + ledger, service = _service(tmp_path, anthropic="10", openai="10") + first = await service.reserve( + provider="ollama", model_id="gemma4:12b", input_bound=1_000, output_bound=1_000 + ) + assert first is not None and first.startswith("ollama-") + second = asyncio.ensure_future( + service.reserve( + provider="ollama", model_id="gemma4:12b", input_bound=1_000, output_bound=1_000 + ) + ) + await asyncio.sleep(0.05) + assert not second.done() # one unit in flight per provider + await service.settle(first, outcome="ok", buckets=Buckets(10, 0, 0, 10)) + unit = await asyncio.wait_for(second, timeout=1) + assert unit is not None and unit != first + await service.settle(unit, outcome="worker_lost", buckets=None) + assert not (tmp_path / "ollama.jsonl").exists() + assert ledger.events(RUN_ID) == [] + assert (ledger.spent("anthropic"), ledger.spent("openai")) == (0, 0) + ledger.close() + + +def test_reserve_events_without_job_id_still_load(tmp_path: Path) -> None: + ledger = _open(tmp_path, anthropic="10") + unit = _reserve(ledger, "anthropic", "1") + assert unit is not None + assert _event(ledger, "reserve", unit)["job_id"] is None + named = ledger.reserve + ledger.settle(unit, outcome="server", actual=None, buckets=None) + other = named( + "anthropic", + model_id="m", + kind="model_call", + bound=D("1"), + input_bound=1, + output_bound=1, + job_id="j--s", + ) + assert other is not None and _event(ledger, "reserve", other)["job_id"] == "j--s" + ledger.settle(other, outcome="ok", actual=D("3"), buckets=None) # an overrun: stops + spent, stopped = ledger.spent("anthropic"), ledger.stopped("anthropic") + ledger.close() + # The pre-PR-4 format: reserve lines without the job_id key at all. + path = tmp_path / "anthropic.jsonl" + lines = [json.loads(line) for line in path.read_text().splitlines()] + for event in lines: + event.pop("job_id", None) + path.write_text("".join(json.dumps(e, sort_keys=True) + "\n" for e in lines)) + reopened = _open(tmp_path, anthropic="10") + assert (reopened.spent("anthropic"), reopened.stopped("anthropic")) == (spent, stopped) + assert spent == D("5") and stopped == "overrun" + reopened.close() diff --git a/tests/benchmarks/test_agentic_live.py b/tests/benchmarks/test_agentic_live.py new file mode 100644 index 00000000..e170df8a --- /dev/null +++ b/tests/benchmarks/test_agentic_live.py @@ -0,0 +1,611 @@ +"""Live-run safety: the one authorization gate, reference rates and the full-run gate. + +No test makes a live call: the gate's refusals are the subject, and every run is scripted. +""" + +from __future__ import annotations + +import hashlib +import io +import json +import shutil +from dataclasses import replace +from datetime import date +from decimal import Decimal +from pathlib import Path +from typing import Any + +import pytest +import yaml + +from benchmarks.agentic.host import WorkerJob +from benchmarks.agentic.ledger import PROVIDER_CAPS, Ledger +from benchmarks.agentic.live import ( + PILOT_TRAJECTORIES_PER_PROVIDER, + SAFETY, + WINDOW_S, + ProviderPlan, + ReferenceRate, + authorize_live, + confirmation_text, + full_run_gate, + interactive_confirm, + provider_plans, + reference_rates, +) +from benchmarks.agentic.loop import HOSTED_CAPS +from benchmarks.model_matrix import METHODOLOGY_TOKEN_LABEL +from benchmarks.runner import BenchmarkValidationError +from tests.benchmarks.test_agentic_sandbox import FAMILIES, SYSTEMS + +D = Decimal +SLOW_ANSWER = {"text": "ok", "delay_s": 0.05, "usage": {"input_tokens": 1000, "output_tokens": 100}} + + +class _Tty(io.StringIO): + def isatty(self) -> bool: + return True + + +def _jobs(**counts: int) -> list[WorkerJob]: + """One no-docs job per family id, with ``count`` trajectories each.""" + jobs = [] + for family_id, count in counts.items(): + family = FAMILIES[family_id] + trajectories = tuple( + {"corpus_id": f"Q{i}", "prompt": "q", "repeat": 1} for i in range(count) + ) + job = WorkerJob( + f"{family.id}--no-docs", family, SYSTEMS["no-docs"], trajectories, HOSTED_CAPS + ) + jobs.append(job) + return jobs + + +def _rate(family_id: str, provider: str, usd: str, seconds: float = 10.0) -> ReferenceRate: + family = FAMILIES[family_id] + return ReferenceRate(family_id, provider, 90, D(usd), seconds, family.model_id, family.api) + + +def _write_record( + path: Path, + family_id: str, + provider: str, + wall_ms: float, + wait_ms: float, + *, + model_id: str | None = None, + api: str = "openai-responses", + unit_id: str = "u1", + outcome: str = "ok", +) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + cell, corpus = path.parent.name, path.name.split("--")[0].removesuffix(".json") + record = { + "competitor_id": cell, + "system_id": "no-docs", + "corpus_id": corpus, + "model_family_id": family_id, + "model_id": model_id or family_id, + "provider": provider, + "repeat": int(cell.rsplit("--r", 1)[1]), + "attempt": int(path.stem.rsplit("--attempt", 1)[1]) if "--attempt" in path.stem else 1, + "execution": {"provider": provider, "model_id": model_id or family_id, "api": api}, + "model_calls": [ + { + "request_params": {"model": model_id or family_id}, + "attempts": [{"unit_id": unit_id, "outcome": outcome}], + "buckets": { + "uncached_input": 1000, + "cache_write_input": 0, + "cached_input": 0, + "output": 100, + "reasoning": 0, + } + if outcome == "ok" + else None, + "raw_response": {"id": "response-1"} if outcome == "ok" else None, + } + ], + "timing": {"wall_ms": wall_ms, "grant_wait_ms": wait_ms}, + } + path.write_text(json.dumps(record), encoding="utf-8") + + +def _transcript_inventory(run: Path) -> list[dict[str, Any]]: + """Synthetic publication records, built when the fixture's bytes are finalized.""" + inventory = [] + for kind in ("transcripts", "discarded"): + for path in sorted((run / kind).glob("*/*.json")): + content = path.read_bytes() + record = json.loads(content) + inventory.append( + { + **{ + field: record[field] + for field in ( + "competitor_id", + "corpus_id", + "system_id", + "model_family_id", + "provider", + "model_id", + "repeat", + "attempt", + ) + }, + "path": path.relative_to(run).as_posix(), + "sha256": hashlib.sha256(content).hexdigest(), + } + ) + return inventory + + +def _bind_reference_transcripts(run: Path) -> None: + path = run / "run-summary.json" + summary = json.loads(path.read_bytes()) + summary["transcript_inventory"] = _transcript_inventory(run) + path.write_text(json.dumps(summary)) + + +def _pilot_summary(run: Path, status: str, planned: int, scored: int, openai_spend: str) -> None: + summary = { + "run_id": "pilot", + "status": status, + "planned_cells": planned, + "scored_cells": scored, + "transcript_inventory": _transcript_inventory(run), + "discarded": [ + {"cell": path.parent.name, "corpus_id": path.name.split("--")[0], "attempt": 1} + for path in (run / "discarded").glob("*/*.json") + ], + "ledger": {"openai": {"spent_before": "4", "spent_after": str(D(4) + D(openai_spend))}}, + } + (run / "run-summary.json").write_text(json.dumps(summary)) + + +def _settled_unit( + unit_id: str, family: str, booked: str, outcome: str, *, model_id: str | None = None +) -> list[dict[str, str]]: + unit = {"provider": "openai", "unit_id": unit_id, "run_id": "pilot"} + return [ + { + **unit, + "event": "reserve", + "kind": "model_call", + "bound": booked if outcome == "ok" else str(D(booked) / 2), + "input_bound": 1000, + "output_bound": 100, + "job_id": f"{family}--no-docs", + "model_id": model_id or family, + }, + { + **unit, + "event": "settle", + "booked": booked, + "outcome": outcome, + "actual": booked if outcome == "ok" else None, + "buckets": { + "uncached_input": 1000, + "cache_write_input": 0, + "cached_input": 0, + "output": 100, + "reasoning": 0, + } + if outcome == "ok" + else None, + }, + ] + + +def _write_snapshot(run: Path, *families: dict[str, Any]) -> None: + path = run / "snapshots" / "model-matrix.yml" + path.parent.mkdir(parents=True) + path.write_text( + yaml.safe_dump( + { + "methodology_token_label": METHODOLOGY_TOKEN_LABEL, + "model_families": [*families, FAMILIES["scripted-google"].raw], + } + ) + ) + + +def test_same_model_scripted_pilot_is_refused_before_confirmation(tmp_path: Path) -> None: + from benchmarks.agentic.run import run_agentic + from tests.benchmarks.test_agentic_run import ( + COMMITTED_PRICES, + _config, + _container, + _live_config, + _matrix_with, + ) + + family = FAMILIES["gpt-6.1-sol"] + alias = FAMILIES["scripted-openai"].raw | {"id": family.id, "model_id": family.model_id} + matrix = _matrix_with(tmp_path, {family.id: [SLOW_ANSWER]}, extra=[alias]) + pilot = tmp_path / "pilot" + config = _config( + tmp_path, + matrix_path=matrix, + prices_path=COMMITTED_PRICES, + out_dir=pilot, + models=(family.id,), + systems=("no-docs",), + questions=("SYN-EX-001",), + repeats=1, + ) + summary = run_agentic(config) + assert summary["scored_cells"] == summary["planned_cells"] == 1 + assert reference_rates(pilot)[family.id].usd_per_cell > 0 + matrix.unlink() # Only the pilot's snapshot is available at authorization. + launcher, docker = _container(tmp_path) + with pytest.raises(BenchmarkValidationError, match="reference"): + run_agentic( + _live_config(tmp_path, models=(family.id,), repeats=91, reference_run=pilot), + launcher=launcher, + today=date(2026, 11, 4), + confirm=lambda _: pytest.fail("scripted pilot reached confirmation"), + ) + assert docker.calls == [] + + +def _single_cell_reference( + run: Path, + model_id: str, + api: str, + *, + transcript_model: str | None = None, + reserved_model: str | None = None, +) -> None: + family = FAMILIES["gpt-6.1-sol"] + _write_snapshot(run, family.raw | {"model_id": model_id, "api": api}) + record = run / "transcripts" / f"no-docs--{family.id}--r1" / "Q1.json" + _write_record( + record, family.id, family.provider, 200, 100, model_id=transcript_model or model_id, api=api + ) + _pilot_summary(run, "completed", 1, 1, "0.10") + events = _settled_unit("u1", family.id, "0.10", "ok", model_id=reserved_model or model_id) + (run / "ledger-events.jsonl").write_text("".join(json.dumps(e) + "\n" for e in events)) + + +@pytest.mark.parametrize( + ("model_id", "api", "usable"), + [ + ("other-model", "openai-responses", False), + ("gpt-6.1-sol", "openai-chat-completions", False), + ("gpt-6.1-sol", "openai-responses", True), + ], +) +def test_only_matching_live_measurements_estimate_a_full_run( + tmp_path: Path, model_id: str, api: str, usable: bool +) -> None: + _single_cell_reference(tmp_path, model_id, api) + rates = reference_rates(tmp_path) + jobs = _jobs(**{"gpt-6.1-sol": 91}) + plans = provider_plans(jobs, {}, PROVIDER_CAPS, rates) + assert plans[0].estimate == (D("9.10") if usable else None) + assert (full_run_gate(plans, jobs, rates) == []) == usable + + +@pytest.mark.parametrize("overrides", [{"transcript_model": "other"}, {"reserved_model": "other"}]) +def test_reference_measurements_must_belong_to_the_snapshot_model( + tmp_path: Path, overrides: dict[str, str] +) -> None: + _single_cell_reference(tmp_path, "gpt-6.1-sol", "openai-responses", **overrides) + with pytest.raises(BenchmarkValidationError, match="reference"): + reference_rates(tmp_path) + + +@pytest.mark.parametrize("previous_id", ["interrupted", "pilot"]) +def test_reference_spend_excludes_recovery_of_an_earlier_run( + tmp_path: Path, previous_id: str +) -> None: + from benchmarks.agentic.run import run_agentic + from tests.benchmarks.test_agentic_run import _config, _matrix_with + + ledger = Ledger.open(tmp_path / "ledger", run_id=previous_id) + try: + unit = ledger.reserve( + "openai", + model_id="scripted-2", + kind="model_call", + bound=D("1"), + input_bound=1000, + output_bound=100, + job_id="previous--no-docs", + ) + assert unit is not None + finally: + ledger.close() + config = _config( + tmp_path, + models=("scripted-openai",), + systems=("no-docs",), + questions=("SYN-EX-001",), + repeats=1, + run_id="pilot", + matrix_path=_matrix_with(tmp_path, {"scripted-openai": [SLOW_ANSWER]}), + ) + summary = run_agentic(config) + assert D(summary["ledger"]["openai"]["spent_before"]) == 2 + assert D(summary["ledger"]["openai"]["spent_after"]) == D("2.002") + events_path = config.out_dir / "ledger-events.jsonl" + events = [json.loads(line) for line in events_path.read_text().splitlines()] + assert events[0]["unit_id"] == unit and events[0]["outcome"] == "unsettled_at_load" + assert reference_rates(config.out_dir)["scripted-openai"].usd_per_cell == D("0.002") + + # An unmatched ordinary settlement is invalid even if provider balances still reconcile. + corrupt = shutil.copytree(config.out_dir, tmp_path / "corrupt") + events[0]["outcome"] = "timeout" + (corrupt / events_path.name).write_text("".join(json.dumps(e) + "\n" for e in events)) + with pytest.raises(BenchmarkValidationError, match="reference"): + reference_rates(corrupt) + + +def test_reference_rates_aggregate_every_attempt_of_a_cell(tmp_path: Path) -> None: + run = tmp_path / "pilot" + _write_snapshot(run, FAMILIES["gpt-6.1-sol"].raw) + for r in range(1, 31): + cell = f"no-docs--gpt-6.1-sol--r{r}" + for q in ("Q1", "Q2", "Q3"): + _write_record( + run / "transcripts" / cell / f"{q}.json", + "gpt-6.1-sol", + "openai", + 2000, + 500, + unit_id=f"{cell}/{q}/ok", + ) + discarded = run / "discarded" / cell / f"{q}--attempt1.json" + _write_record( + discarded, + "gpt-6.1-sol", + "openai", + 1000, + 0, + unit_id=f"{cell}/{q}/timeout", + outcome="timeout", + ) + _pilot_summary(run, "completed", 90, 90, "9") + events = [] + for r in range(1, 31): + for q in ("Q1", "Q2", "Q3"): + for outcome in ("timeout", "ok"): + unit = f"no-docs--gpt-6.1-sol--r{r}/{q}/{outcome}" + events.extend(_settled_unit(unit, "gpt-6.1-sol", "0.05", outcome)) + (run / "ledger-events.jsonl").write_text("".join(json.dumps(e) + "\n" for e in events)) + (rate,) = reference_rates(run).values() + assert (rate.family_id, rate.provider, rate.cells) == ("gpt-6.1-sol", "openai", 90) + assert rate.usd_per_cell == D("0.10") # $9 over 90 logical cells, not over 180 records + assert rate.seconds_per_cell == pytest.approx(2.5) # (2.0 - 0.5) + 1.0, per cell + # A partial copy still has all scored cells and spend, but loses some retry time. + (run / "discarded/no-docs--gpt-6.1-sol--r1/Q1--attempt1.json").unlink() + with pytest.raises(BenchmarkValidationError, match="discarded"): + reference_rates(run) + + +@pytest.mark.parametrize( + ("status", "scored", "booked", "outcome", "wall_ms"), + [ + ("aborted", False, None, None, 200), + ("aborted", True, "0.20", "ok", 200), + ("completed", False, "0.20", "timeout", 200), + ("completed", True, None, None, 200), + ("completed", True, "0", "rejected", 200), + ("completed", True, "0.20", "timeout", 200), + ("completed", True, "0.20", "ok", 100), + ], +) +def test_unusable_reference_is_refused_before_confirmation( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + status: str, + scored: bool, + booked: str | None, + outcome: str | None, + wall_ms: int, +) -> None: + from benchmarks.agentic.run import run_agentic + from tests.benchmarks.test_agentic_run import _container, _live_config + + family = "gpt-6.1-sol" + pilot = tmp_path / "pilot" + _write_snapshot(pilot, FAMILIES[family].raw) + kind, filename = ("transcripts", "Q1.json") if scored else ("discarded", "Q1--attempt1.json") + _write_record( + pilot / kind / f"no-docs--{family}--r1" / filename, family, "openai", wall_ms, 100 + ) + _pilot_summary(pilot, status, 1, int(scored), booked or "0") + events = [] + if booked is not None and outcome is not None: + events = _settled_unit("u1", family, booked, outcome) + (pilot / "ledger-events.jsonl").write_text("".join(json.dumps(e) + "\n" for e in events)) + launcher, docker = _container(tmp_path) + config = _live_config(tmp_path, models=(family,), repeats=91, reference_run=pilot) + monkeypatch.delenv("CI", raising=False) + with pytest.raises(BenchmarkValidationError, match="reference"): + run_agentic( + config, + launcher=launcher, + today=date(2026, 11, 4), + confirm=lambda text: pytest.fail(f"unexpected confirmation: {text}"), + ) + assert docker.calls == [] + + +def test_reference_spend_and_time_follow_the_family_that_incurred_them(tmp_path: Path) -> None: + _write_snapshot( + tmp_path, + *(FAMILIES["gpt-6.1-sol"].raw | {"id": f, "model_id": f} for f in ("cheap", "expensive")), + ) + events = [] + for family, price, wall in [("cheap", "0.01", 200), ("expensive", "3.00", 4000)]: + record = tmp_path / "transcripts" / f"no-docs--{family}--r1" / "Q1.json" + _write_record(record, family, "openai", wall, 100, unit_id=family) + events.extend(_settled_unit(family, family, price, "ok")) + (tmp_path / "ledger-events.jsonl").write_text("".join(json.dumps(e) + "\n" for e in events)) + _pilot_summary(tmp_path, "completed", 2, 2, "3.01") + rates = reference_rates(tmp_path) + assert rates["cheap"] == ReferenceRate( + "cheap", "openai", 1, D("0.01"), 0.1, "cheap", "openai-responses" + ) + assert rates["expensive"] == ReferenceRate( + "expensive", "openai", 1, D(3), 3.9, "expensive", "openai-responses" + ) + # Losing even a suffix of complete ledger lines can leave positive but understated rates. + _pilot_summary(tmp_path, "completed", 2, 2, "3.02") + with pytest.raises(BenchmarkValidationError, match="reference"): + reference_rates(tmp_path) + + +def test_positive_subcent_estimate_does_not_display_as_zero() -> None: + plan = ProviderPlan("openai", 1, D(0), D(65), D("0.001")) + text = confirmation_text([plan]) + assert "estimate <$0.01" in text and "$0.00" not in text + + +@pytest.mark.parametrize("rates", [{}, {"gpt-6.1-sol": _rate("gpt-6.1-sol", "google", "1")}]) +def test_explicit_reference_must_cover_the_requested_metered_family( + rates: dict[str, ReferenceRate], +) -> None: + jobs = _jobs(**{"gpt-6.1-sol": 1}) + plans = provider_plans(jobs, {}, PROVIDER_CAPS, rates) + assert any("gpt-6.1-sol" in reason for reason in full_run_gate(plans, jobs, rates)) + + +def test_reference_rates_from_a_finished_scripted_run(tmp_path: Path) -> None: + from benchmarks.agentic.run import run_agentic + from tests.benchmarks.test_agentic_run import _config + + config = _config( + tmp_path, + models=("scripted-anthropic", "scripted-openai"), + systems=("no-docs",), + questions=("SYN-EX-001",), + repeats=2, + ) + summary = run_agentic(config) + rates = reference_rates(tmp_path / "run") + assert set(rates) == {"scripted-anthropic", "scripted-openai"} + anthropic = rates["scripted-anthropic"] + assert anthropic.cells == 2 and anthropic.provider == "anthropic" + spent = D(summary["ledger"]["anthropic"]["spent_after"]) + assert anthropic.usd_per_cell == spent / 2 and anthropic.seconds_per_cell > 0 + + +def test_the_gate_refuses_a_provider_whose_scaled_cost_exceeds_its_remaining_cap() -> None: + jobs = _jobs(**{"gpt-6.1-sol": 90}) + rates = {"gpt-6.1-sol": _rate("gpt-6.1-sol", "openai", "0.05")} # $4.50 x 1.25 = $5.625 + plans = provider_plans(jobs, {"openai": D(60)}, PROVIDER_CAPS, rates) + assert plans == [ProviderPlan("openai", 90, D(60), D(65), D("4.50"))] + problems = full_run_gate(plans, jobs, rates) + assert len(problems) == 1 and "openai" in problems[0] and "5.625" in problems[0] + assert ( + full_run_gate(provider_plans(jobs, {"openai": D(0)}, PROVIDER_CAPS, rates), jobs, rates) + == [] + ) + + +def test_the_gate_refuses_a_model_whose_scaled_time_exceeds_24_hours() -> None: + jobs = _jobs(**{"claude-sonnet-5-5": 90}) + seconds = WINDOW_S / 90 / float(SAFETY) + 1 # just over the window once scaled + rates = {"claude-sonnet-5-5": _rate("claude-sonnet-5-5", "anthropic", "0.01", seconds)} + plans = provider_plans(jobs, {"anthropic": D(0)}, PROVIDER_CAPS, rates) + problems = full_run_gate(plans, jobs, rates) + assert len(problems) == 1 and "claude-sonnet-5-5" in problems[0] and "24" in problems[0] + + +def test_a_live_run_larger_than_the_pilot_needs_a_reference_run() -> None: + jobs = _jobs(**{"gpt-6.1-sol": PILOT_TRAJECTORIES_PER_PROVIDER + 1}) + plans = provider_plans(jobs, {"openai": D(0)}, PROVIDER_CAPS, None) + assert plans[0].estimate is None + problems = full_run_gate(plans, jobs, None) + assert len(problems) == 1 and "--reference-run" in problems[0] and "91" in problems[0] + pilot = _jobs(**{"gpt-6.1-sol": PILOT_TRAJECTORIES_PER_PROVIDER}) + assert ( + full_run_gate(provider_plans(pilot, {"openai": D(0)}, PROVIDER_CAPS, None), pilot, None) + == [] + ) + + +def test_confirmation_lists_every_provider_with_its_remaining_cap_and_estimate() -> None: + jobs = _jobs(**{"claude-sonnet-5-5": 90, "gpt-6.1-sol": 30, "gemma4-12b": 30}) + rates = {"claude-sonnet-5-5": _rate("claude-sonnet-5-5", "anthropic", "0.05")} + plans = provider_plans(jobs, {"anthropic": D(10), "openai": D(1)}, PROVIDER_CAPS, rates) + assert [p.provider for p in plans] == ["anthropic", "ollama", "openai"] + lines = confirmation_text(plans).splitlines() + (anthropic,) = [line for line in lines if line.startswith("anthropic")] + for part in ("90 trajectories", "spent $10", "cap $180", "$170 remaining", "estimate $4.50"): + assert part in anthropic + assert "the ledger stops at the cap; one overrun is at most the $20 margin" in anthropic + (openai,) = [line for line in lines if line.startswith("openai")] + assert "no reference run" in openai and "$64 remaining" in openai + (ollama,) = [line for line in lines if line.startswith("ollama")] + assert "30 trajectories" in ollama and "local, unmetered" in ollama + assert ProviderPlan("ollama", 30, None, None, None) in plans + + +@pytest.mark.parametrize("value", ["1", "true", "TRUE", "yes", " on "]) +def test_ci_refuses_a_live_run_even_with_a_terminal(value: str) -> None: + asked: list[str] = [] + + def confirm(text: str) -> bool: + asked.append(text) + return True + + with pytest.raises(BenchmarkValidationError, match="refused under CI"): + authorize_live("plan", environ={"CI": value}, confirm=confirm) + assert asked == [] + + +@pytest.mark.parametrize("value", [None, "", "0", "false", "no", " FALSE "]) +def test_a_ci_value_that_is_not_truthy_reaches_the_confirmation(value: str | None) -> None: + environ = {} if value is None else {"CI": value} + authorize_live("plan", environ=environ, confirm=lambda text: True) + + +def test_a_non_tty_stdin_refuses_a_live_run(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.delenv("CI", raising=False) + stdin, stderr = io.StringIO("yes\n"), io.StringIO() + assert interactive_confirm("plan", stdin=stdin, stderr=stderr) is False + with pytest.raises(BenchmarkValidationError, match="not confirmed"): + authorize_live( + "plan", + environ={}, + confirm=lambda text: interactive_confirm( + text, stdin=io.StringIO("yes\n"), stderr=stderr + ), + ) + + +@pytest.mark.parametrize( + "answer,accepted", + [("y\n", False), ("YES \n", False), ("\n", False), ("", False), ("yes\n", True), ("yes", True)], +) +def test_interactive_confirm_accepts_only_yes(answer: str, accepted: bool) -> None: + assert interactive_confirm("plan", stdin=_Tty(answer), stderr=io.StringIO()) is accepted + + +def test_the_confirmation_prompt_never_reaches_stdout( + capsys: pytest.CaptureFixture[str], monkeypatch: pytest.MonkeyPatch +) -> None: + monkeypatch.setattr("sys.stdin", _Tty("yes\n")) + assert interactive_confirm("anthropic: 90 trajectories") is True + captured = capsys.readouterr() + assert captured.out == "" + assert "anthropic: 90 trajectories" in captured.err + assert "Type yes to start this live run: " in captured.err + + +def test_local_fallback_requires_its_own_timing_reference() -> None: + jobs = _jobs(**{"gemma4-12b": 300}) + original = jobs[0] + jobs[0] = replace(original, family=replace(original.family, model_id="gemma4:e4b")) + rate = _rate(original.family.id, "ollama", "0") + rates = {rate.family_id: rate} + plans = provider_plans(jobs, {}, PROVIDER_CAPS, rates) + problems = full_run_gate(plans, jobs, rates) + assert len(problems) == 1 and "gemma4-12b" in problems[0] + smoke = _jobs(**{"gemma4-12b": 10}) + assert full_run_gate(provider_plans(smoke, {}, PROVIDER_CAPS, None), smoke, None) == [] diff --git a/tests/benchmarks/test_agentic_loop.py b/tests/benchmarks/test_agentic_loop.py index b6e1badd..6bac588f 100644 --- a/tests/benchmarks/test_agentic_loop.py +++ b/tests/benchmarks/test_agentic_loop.py @@ -4,6 +4,7 @@ import asyncio import hashlib +import json from decimal import Decimal from pathlib import Path from typing import Any @@ -30,6 +31,7 @@ run_trajectory, ) from benchmarks.agentic.prompt import SYSTEM_PROMPT +from benchmarks.agentic.protocol import KeyLeakError from benchmarks.agentic.schemas import schemas_sha256 from benchmarks.agentic.types import Buckets, Conversation, ModelTurn, ToolSpec from benchmarks.model_matrix import ModelFamily, load_model_matrix, model_family_from_raw @@ -251,7 +253,18 @@ async def test_reservations_carry_independently_computed_bounds(harness: Harness {"tools": [SEARCH], "usage": None}, # call 1, retry {"text": "done", "usage": openai_usage}, # call 2, after the call without usage ] - sizes = {(0, 1): 500, (1, 3): 300, (0, 5): 2_000} + # Full rendering at call 1 is also validated before each attempt, but does not + # replace the usage-based incremental bound or change any reserved amount. + sizes = { + (0, 1): 500, + (1, 3): 300, + (0, 3): 9_000, + (0, 5): 2_000, + # Post-settlement replay scans never contribute to reservation bounds. + (0, 2): 800, + (0, 4): 1_900, + (0, 6): 2_200, + } client = FixedBytesClient(sizes, "openai", "gpt-6.1-sol", steps) record = await harness.run(client=client, family=family, price=price) assert record["status"] == "succeeded" @@ -273,7 +286,12 @@ async def test_reservations_carry_independently_computed_bounds(harness: Harness async def test_all_zero_usage_counts_as_no_usage(harness: Harness) -> None: zero = {"input_tokens": 0, "output_tokens": 0} steps = [{"tools": [SEARCH], "usage": zero}, ANSWER] - client = FixedBytesClient({(0, 1): 500, (0, 3): 2_000}, "anthropic", "scripted-1", steps) + client = FixedBytesClient( + {(0, 1): 500, (0, 3): 2_000, (0, 2): 1_000, (0, 4): 2_500}, + "anthropic", + "scripted-1", + steps, + ) record = await harness.run(client=client) assert _outcomes(record, 0) == ["no_usage"] # The next bound is the full request again (2_000 + 256 * 4), not 0 + 0 + added bytes. @@ -372,6 +390,29 @@ async def test_unknown_tool_call_is_returned_to_the_model_and_the_loop_continues assert record["canonical_messages"][2]["content"][0]["is_error"] is True +@pytest.mark.parametrize("case", ["native-url", "serialized-field", "raw-only", "malformed"]) +async def test_contaminated_tool_turn_aborts_before_any_bridge_call( + harness: Harness, case: str +) -> None: + key = "AIza" + "g" * 35 + arguments = { + "native-url": {"url": "https://docs.python.org/3/?token=" + key}, + "serialized-field": json.dumps({"nested": [{key: True}]}).replace("AIza", r"\u0041Iza"), + # Decoding adds a token character just after the otherwise complete raw key. + "raw-only": '{"url":"' + key + r'\u0041"}', + "malformed": '{"url":"bad' + r"\x20" + key + '"}', + }[case] + bridge = FakeBridge(("fetch",)) + tools = [ + {"name": "fetch", "arguments": {"url": "https://docs.python.org/3/"}}, + {"name": "fetch", "arguments": arguments}, + ] + with pytest.raises(KeyLeakError, match="tool arguments") as caught: + await harness.run([{"tools": tools, "usage": USAGE}, ANSWER], bridge=bridge) + assert bridge.calls == [] + assert key not in str(caught.value) + + @pytest.mark.parametrize("arguments", [[1, 2], "x", 3, None, True]) async def test_non_object_tool_arguments_are_returned_to_the_model( harness: Harness, arguments: Any diff --git a/tests/benchmarks/test_agentic_mcp_boundary.py b/tests/benchmarks/test_agentic_mcp_boundary.py new file mode 100644 index 00000000..f75e4c6f --- /dev/null +++ b/tests/benchmarks/test_agentic_mcp_boundary.py @@ -0,0 +1,338 @@ +"""Exercise the normal stdio/ClientSession boundary with unvalidated MCP replies.""" + +from __future__ import annotations + +import asyncio +import sys +from contextlib import AsyncExitStack +from dataclasses import replace +from decimal import Decimal +from pathlib import Path +from unittest.mock import AsyncMock + +import pytest +from mcp import ClientSession, MCPError, StdioServerParameters, stdio_client + +from benchmarks.agentic import mcp_stdio, worker +from benchmarks.agentic.bridge import Bridge, BridgeCrash, open_bridge, system_spec_from_raw +from benchmarks.agentic.host import LocalLauncher, run_jobs +from benchmarks.agentic.protocol import WORKER_LEAK_REASON, FrameTooLarge, KeyLeakError +from tests.benchmarks.test_agentic_host import REPO_ROOT, Host, _job +from tests.benchmarks.test_agentic_sandbox import FAMILIES + +SERVER = Path(__file__).parent / "fixtures/agentic/raw_result_server.py" +CASES = [ + "missing-structured", + "invalid-structured", + "malformed-content", + "dropped-field", + "escaped-field", + "trailing-encoded", + "truncated-utf8", + "unfinished-encoded", + "broken-encoded", + "error-result", + "rpc-error", + "dropped-error", + "malformed-envelope", + "listing", + "handshake", +] + + +@pytest.fixture +def host(tmp_path, monkeypatch): + from benchmarks.adapters.guard import PROVIDER_API_KEY_ENV + + for name in PROVIDER_API_KEY_ENV.values(): + monkeypatch.delenv(name, raising=False) + value = Host(tmp_path, caps={"google": Decimal(180)}) + yield value + value.ledger.close() + + +def _system(case, kind): + return system_spec_from_raw( + { + "id": "synthetic", + "adapter": "mcp-stdio", + "command": ["{python}", str(SERVER), case, kind], + } + ) + + +@pytest.mark.parametrize("kind", ["literal", "bound-shaped", "lexical"]) +@pytest.mark.parametrize("case", CASES) +async def test_real_worker_stops_before_second_paid_dispatch( + tmp_path, monkeypatch, host, case, kind +): + """Removing the pre-validation scan must restore a second grant or a normal crash.""" + calls = tmp_path / "calls.txt" + exit_code = tmp_path / "exit-code.txt" + program = tmp_path / "worker.py" + program.write_text(f""" +import sys +sys.path.insert(0, {str(REPO_ROOT)!r}) +from pathlib import Path +from benchmarks.agentic import clients, worker +from tests.benchmarks.test_agentic_clients import ( + GeminiRecorder, _gemini_ok, _gemini_response) +from tests.benchmarks.fixtures.agentic.raw_result_server import token + +class RecordingTransport(GeminiRecorder): + def transport(self): + import httpx + original = super().transport() + async def dispatch(request): + assert token({kind!r}).encode() not in request.content + assert request.headers['x-goog-api-key'] == token({kind!r}) + with Path({str(calls)!r}).open('a') as stream: + stream.write('provider\\n') + return await original.handle_async_request(request) + return httpx.MockTransport(dispatch) + +rec = RecordingTransport( + _gemini_ok(_gemini_response([{{'functionCall': {{'name': 'search_docs', 'args': {{}}}}}}])), + *[_gemini_ok(_gemini_response([{{'text': 'done'}}])) for _ in range(3)]) +clients.make_client = lambda family, **kw: clients.GeminiClient( + clients.gemini_sdk(token({kind!r}), 5, transport=rec.transport()), family.model_id, 32768) +async def limits(client): + return None +clients.fetch_model_limits = limits +# Synthetic bootstrap stays in this worker; the host holds no credential. +worker.read_frame_fd = lambda fd: {{ + 'type': 'bootstrap', 'env': {{'GOOGLE_API_KEY': token({kind!r})}}}} +code = worker.main_worker() +Path({str(exit_code)!r}).write_text(str(code)) +raise SystemExit(code) +""") + job = replace( + _job(tmp_path, [], job_id="synthetic"), + family=FAMILIES["gemini-3.8-flash"], + system=_system(case, kind), + trajectories=tuple( + {"corpus_id": q, "repeat": 1, "prompt": "question"} for q in ("Q1", "Q2") + ), + ) + monkeypatch.setattr( + LocalLauncher, "command", lambda self, job: ([sys.executable, "-I", str(program)], {}) + ) + monkeypatch.setattr(LocalLauncher, "supports", lambda self, family: True) + service = host.service(job.family) + with pytest.raises(KeyLeakError, match=WORKER_LEAK_REASON): + await run_jobs( + [job], + launcher=LocalLauncher(), + ledger=service, + on_message=host.on_message, + log_dir=tmp_path / "logs", + cwd=REPO_ROOT, + ) + initial = case in ("handshake", "listing") + if initial: + assert not calls.exists() + else: + assert calls.read_text().splitlines() == ["provider"] + events = host.ledger.invocation_events() + assert [e["event"] for e in events] == ([] if initial else ["reserve", "settle"]) + assert not [m for m in host.messages() if m["type"] in ("trajectory", "discarded", "done")] + assert ( + await service.reserve( + provider=job.family.provider, + model_id=job.family.model_id, + input_bound=1, + output_bound=1, + ) + is None + ) + logs = b"".join(p.read_bytes() for p in (tmp_path / "logs").rglob("*.log")) + assert b"synthetic server diagnostic retained" in logs + from tests.benchmarks.fixtures.agentic.raw_result_server import token + + assert token(kind).encode() not in logs + assert exit_code.read_text() == "3" + + +@pytest.mark.parametrize("case", ["missing-clean", "valid", "rpc-clean"]) +async def test_clean_sdk_outcomes_are_preserved(case): + async with open_bridge(_system(case, "literal")) as bridge: + if case == "missing-clean": + with pytest.raises(BridgeCrash, match="did not return structured content"): + await bridge.call("search_docs", {}) + elif case == "rpc-clean": + result = await bridge.call("search_docs", {}) + assert result.is_error and result.text == "clean error" + else: + result = await bridge.call("search_docs", {}) + assert result.text == '{"answer":"clean answer"}' + + +@pytest.mark.parametrize( + "case", + [ + "missing-structured", + "invalid-structured", + "malformed-content", + "dropped-field", + "error-result", + "rpc-error", + "dropped-error", + "valid", + ], +) +async def test_clean_raw_data_keeps_exact_sdk_validation_outcome(case): + async def outcome(session): + try: + result = await session.call_tool("search_docs", {}) + except Exception as error: + return type(error), str(error) + return type(result), result.model_dump(mode="json", by_alias=True) + + params = StdioServerParameters(command=sys.executable, args=[str(SERVER), case, "clean"]) + async with stdio_client(params) as (read, write): + async with ClientSession(read, write) as session: + await session.initialize() + await session.list_tools() + expected = await outcome(session) + async with open_bridge(_system(case, "clean")) as bridge: + assert await outcome(bridge._session) == expected + + +@pytest.mark.parametrize("wrapped", ["group", "cancel-group", "mcp", "context"]) +async def test_bridge_preserves_nested_key_failure(wrapped): + leak = KeyLeakError("synthetic credential failure") + if wrapped == "group": + error = ExceptionGroup("MCP tasks", [RuntimeError("clean"), leak]) + elif wrapped == "cancel-group": + error = BaseExceptionGroup("MCP tasks", [asyncio.CancelledError(), leak]) + else: + error = MCPError(-32603, "clean") if wrapped == "mcp" else RuntimeError("clean") + if wrapped == "context": + error.__context__ = leak + leak.__context__ = error # implicit chains may have cycles + else: + error.__cause__ = leak + bridge = Bridge(type("Session", (), {"call_tool": AsyncMock(side_effect=error)})(), {}, []) + with pytest.raises(KeyLeakError) as caught: + await bridge.call("search_docs", {}) + assert caught.value is leak + + +@pytest.mark.parametrize("cancelled", [False, True]) +async def test_close_does_not_swallow_grouped_key_failure(cancelled): + stack = AsyncExitStack() + leak = KeyLeakError("synthetic credential failure") + + async def close(): + other = asyncio.CancelledError() if cancelled else RuntimeError("clean") + raise BaseExceptionGroup("MCP teardown", [other, leak]) + + stack.push_async_callback(close) + with pytest.raises(KeyLeakError) as caught: + await worker._close(stack) + assert caught.value is leak + + +def test_mcp_reply_checks_escaped_values_before_duplicate_fields_are_discarded(): + from benchmarks.agentic.mcp_stdio import ReplyGuard + from benchmarks.agentic.worker import ProtocolChannel + + channel = ProtocolChannel(-1, (b"opaque_marker",), -1, None, ()) + guard = ReplyGuard(channel.check_content) + line = ( + rb'{"jsonrpc":"2.0","id":2,"result":{"content":[],' + rb'"note":"prefix\u006fpaque_marker-suffix","note":"safe"}}' + ) + with pytest.raises(KeyLeakError): + guard.parse(line, StdioServerParameters(command="unused")) + with pytest.raises(KeyLeakError): + guard.raise_if_failed() + + +async def test_caller_cancellation_reaps_only_the_owned_stdio_process(monkeypatch): + processes = [] + create = mcp_stdio._create_platform_compatible_process + + async def capture(**kwargs): + process = await create(**kwargs) + processes.append(process) + return process + + monkeypatch.setattr(mcp_stdio, "_create_platform_compatible_process", capture) + with pytest.raises(TimeoutError): + async with asyncio.timeout(0.5): + async with open_bridge(_system("wait", "clean")) as bridge: + await bridge.call("search_docs", {}) + assert len(processes) == 1 and processes[0].returncode is not None + # A cancelled caller can immediately create and use a fresh, independent session. + async with open_bridge(_system("valid", "clean")) as bridge: + assert (await bridge.call("search_docs", {})).text == '{"answer":"clean answer"}' + assert len(processes) == 2 and processes[1].returncode == 0 + + +async def test_stdio_line_limit_bounds_buffer_and_releases_process(monkeypatch): + monkeypatch.setattr(mcp_stdio, "MAX_FRAME_BYTES", 512) + # The request cannot wait indefinitely when the raw peer sends no valid reply. + with pytest.raises(BaseExceptionGroup) as caught: + async with asyncio.timeout(5): + async with open_bridge(_system("oversize", "clean")) as bridge: + with pytest.raises(FrameTooLarge): + await bridge.call("search_docs", {}) + assert caught.value.subgroup(FrameTooLarge) is not None + + +@pytest.mark.parametrize("suffix", [" trailing", ' "note":"ordinary', ' "note":"ordinary\n', "\n"]) +def test_clean_malformed_reply_keeps_sdk_disposition(suffix): + from mcp.client.stdio import _parse_line + + from benchmarks.agentic.mcp_stdio import checked_line + + text = '{"jsonrpc":"2.0","id":2,"result":{"content":[]}}' + suffix + expected = _parse_line(text) + actual = checked_line(text.encode(), StdioServerParameters(command="unused"), None) + assert type(actual) is type(expected) + if isinstance(actual, Exception): + assert str(actual) == str(expected) + else: + assert actual == expected + + +async def test_broken_stdio_scans_the_pending_partial_line(monkeypatch): + from contextlib import suppress + from types import SimpleNamespace + + import anyio + + from benchmarks.agentic.protocol import find_key_leak + + async def broken_stdout(): + yield b'{"result":"prefixopaque_marker-suffix' + raise anyio.BrokenResourceError + + process = SimpleNamespace(stdout=broken_stdout(), stdin=object()) + monkeypatch.setattr( + mcp_stdio, "_create_platform_compatible_process", AsyncMock(return_value=process) + ) + monkeypatch.setattr(mcp_stdio, "_stop_server_process", AsyncMock()) + channel = worker.ProtocolChannel(-1, (b"opaque_marker",), -1, None, ()) + guard = mcp_stdio.ReplyGuard(channel.check_content) + try: + async with mcp_stdio.checked_stdio_client( + StdioServerParameters(command="unused"), errlog=sys.stderr, guard=guard + ) as (read, _): + with suppress(anyio.EndOfStream): + await read.receive() + except BaseExceptionGroup as group: + assert find_key_leak(group) is guard.failure + with pytest.raises(KeyLeakError): + guard.raise_if_failed() + + +@pytest.mark.parametrize("errors", ["strict", "replace"]) +def test_undecodable_reply_checks_the_complete_text_prefix(errors): + seen = [] + params = StdioServerParameters(command="unused", encoding_error_handler=errors) + line = rb'{"note":"\u006frchard","truncated":"' + b"\xe2\x82" + with pytest.raises(KeyLeakError): + mcp_stdio.checked_line(line, params, seen.append) + assert b"orchard" in seen diff --git a/tests/benchmarks/test_agentic_outgoing.py b/tests/benchmarks/test_agentic_outgoing.py new file mode 100644 index 00000000..ccb48be0 --- /dev/null +++ b/tests/benchmarks/test_agentic_outgoing.py @@ -0,0 +1,486 @@ +"""R14 owner repros at the normal trajectory and local CLI boundaries; no network.""" + +from __future__ import annotations + +import json +import sys +from copy import deepcopy +from dataclasses import replace +from pathlib import Path +from typing import Any +from unittest.mock import AsyncMock, Mock + +import pytest +from mcp import MCPError +from mcp.types import CONNECTION_CLOSED, CallToolResult, TextContent + +from benchmarks.agentic.bridge import Bridge +from benchmarks.agentic.clients import GeminiClient, ScriptedClient, gemini_sdk +from benchmarks.agentic.loop import Caps, run_trajectory +from benchmarks.agentic.protocol import KEY_SHAPED, KeyLeakError +from benchmarks.agentic.types import ModelClient, ProviderCallError +from benchmarks.agentic.worker import ProtocolChannel +from tests.benchmarks.test_agentic_clients import ( + ANTHROPIC_ANSWER, + ANTHROPIC_TOOL_TURN, + OPENAI_CALL, + OPENAI_MESSAGE, + GeminiRecorder, + Recorder, + _anthropic, + _chat_completion, + _gemini, + _gemini_ok, + _gemini_response, + _ok, + _ollama, + _openai, + _openai_response, + _tool_call, +) +from tests.benchmarks.test_agentic_loop import ANSWER, FAMILY, TOOL, FakeBridge + +MARKER = "AIza" + "g" * 35 +PROVIDERS = ["anthropic", "openai", "google", "ollama", "scripted"] +CASES = [ + "text", + "structured", + "structured-name", + "hidden-text", + "truncated", + "beyond-cap", + "json-boundary", + "error-result", + "mcp-error", + "mcp-error-data", + "closed", + "exception", +] + + +def _result(case: str) -> CallToolResult | Exception: + text = "diagnostic: " + MARKER + structured = None + if case == "structured": + text, structured = "safe", {"nested": [{"token": MARKER}]} + elif case == "structured-name": + text, structured = "safe", {"nested": [{MARKER: "value"}]} + elif case == "hidden-text": + structured = {"output": "safe"} + elif case == "truncated": + text += "X" # The raw token is too long; clipping gives it a new boundary. + assert KEY_SHAPED.search(text) is None + elif case == "beyond-cap": + text = "x" * 100 + " " + MARKER + elif case == "json-boundary": + text = "\x00xxx" + MARKER + assert KEY_SHAPED.search(text) is None + assert KEY_SHAPED.search(json.dumps(text)) is not None + elif case == "mcp-error": + return MCPError(-32603, text) + elif case == "mcp-error-data": + return MCPError(-32603, "safe error", {"token": MARKER}) + elif case == "closed": + return MCPError(CONNECTION_CLOSED, text) + elif case == "exception": + return RuntimeError(text) + return CallToolResult( + content=[TextContent(type="text", text=text)], + structuredContent=structured, + isError=case == "error-result", + ) + + +def _bridge(result: CallToolResult | Exception) -> tuple[Bridge, AsyncMock]: + call = AsyncMock( + **({"side_effect": result} if isinstance(result, Exception) else {"return_value": result}) + ) + bridge = Bridge( + type("Session", (), {"call_tool": call})(), + {}, + [{"name": "search_docs", "description": "d", "inputSchema": {"type": "object"}}], + ) + return bridge, call + + +def _client(provider: str) -> tuple[Any, Any]: + if provider == "anthropic": + rec = Recorder(_ok(ANTHROPIC_TOOL_TURN), _ok(ANTHROPIC_ANSWER)) + return _anthropic(rec), rec + if provider == "openai": + rec = Recorder( + _ok(_openai_response([OPENAI_CALL])), _ok(_openai_response([OPENAI_MESSAGE])) + ) + return _openai(rec), rec + if provider == "google": + rec = GeminiRecorder( + _gemini_ok(_gemini_response([{"functionCall": {"name": "search_docs", "args": {}}}])), + _gemini_ok(_gemini_response([{"text": "done"}])), + ) + return _gemini(rec), rec + if provider == "ollama": + rec = Recorder( + _ok( + _chat_completion( + {"role": "assistant", "tool_calls": [_tool_call("search_docs", "{}", "c1")]} + ) + ), + _ok(_chat_completion({"role": "assistant", "content": "done"})), + ) + return _ollama(rec), rec + + class RecordingScript(ScriptedClient): + seen: list[Any] + + async def call(self, conv): + self.seen.append(deepcopy(conv)) + return await super().call(conv) + + client = RecordingScript("anthropic", "scripted-1", [TOOL, ANSWER]) + client.seen = [] + return client, client + + +class RecordingLedger: + """No pricing or model-limit dependencies; the actual spend gate is recorded.""" + + def __init__(self): + self.reserves: list[dict[str, Any]] = [] + self.settles: list[dict[str, Any]] = [] + + async def reserve(self, **kwargs): + self.reserves.append(kwargs) + return str(len(self.reserves)) + + async def settle(self, unit_id, **kwargs): + self.settles.append({"unit_id": unit_id, **kwargs}) + + +async def _run(client: ModelClient, bridge, ledger, **kwargs): + return await run_trajectory( + client=client, + bridge=bridge, + ledger=ledger, + family=replace(FAMILY, model_id=client.model_id, provider=client.provider), + prompt=kwargs.pop("prompt", "question"), + caps=kwargs.pop("caps", Caps()), + seen_tool_args=set(), + **kwargs, + ) + + +async def _close(client): + if client.provider == "google": + await client._sdk.aio.aclose() + client._sdk.close() + elif hasattr(client, "_sdk"): + await client._sdk.close() + + +@pytest.mark.parametrize("provider", PROVIDERS) +@pytest.mark.parametrize("case", CASES) +async def test_tool_evidence_stops_before_the_next_request_and_reservation(provider, case): + client, recorder = _client(provider) + ledger = RecordingLedger() + bridge, call = _bridge(_result(case)) + try: + with pytest.raises(KeyLeakError) as error: + await _run(client, bridge, ledger, caps=Caps(result_bytes=len("diagnostic: " + MARKER))) + assert MARKER not in str(error.value) + assert len(recorder.seen) == len(ledger.reserves) == len(ledger.settles) == 1 + call.assert_awaited_once() + finally: + await _close(client) + + +@pytest.mark.parametrize( + "provider,source", + [ + (provider, source) + for provider in PROVIDERS + for source in ("prompt", "schema", "replay", "replay-json") + ] + + [("google", "replay-ascii")], +) +async def test_first_request_and_provider_replay_are_checked(provider, source): + client, recorder = _client(provider) + ledger = RecordingLedger() + bridge, call = _bridge(CallToolResult(content=[TextContent(type="text", text="safe")])) + kwargs = {} + if source == "prompt": + kwargs["prompt"] = MARKER + elif source == "schema": + bridge.tools[0].input_schema["description"] = MARKER + else: + original = client.call + value = { + "replay-json": "\x00xxx" + MARKER, + "replay-ascii": "éx" + MARKER, + }.get(source, MARKER) + + async def poisoned(conv): + turn = await original(conv) + # Visible content stays safe: the provider-native replay alone is contaminated. + if provider == "anthropic": + turn.replay[0]["signature"] = value + elif provider == "openai": + turn.replay.append({"type": "reasoning", "encrypted_content": value}) + elif provider == "google": + turn.replay.parts[0].text = value + elif provider == "ollama": + turn.replay["content"] = value + else: + turn = replace(turn, text=value) + return turn + + client.call = poisoned + try: + with pytest.raises(KeyLeakError) as error: + await _run(client, bridge, ledger, **kwargs) + assert MARKER not in str(error.value) + assert ( + len(recorder.seen) == len(ledger.reserves) == (1 if source.startswith("replay") else 0) + ) + finally: + await _close(client) + + +@pytest.mark.parametrize("provider", PROVIDERS) +@pytest.mark.parametrize("case", ["text", "truncated", "json-boundary"]) +async def test_loop_checks_tool_text_even_without_the_mcp_bridge(provider, case): + client, recorder = _client(provider) + ledger = RecordingLedger() + bridge = FakeBridge(text=_result(case).content[0].text) + try: + with pytest.raises(KeyLeakError) as error: + await _run(client, bridge, ledger, caps=Caps(result_bytes=len("diagnostic: " + MARKER))) + assert MARKER not in str(error.value) + assert len(recorder.seen) == len(ledger.reserves) == len(ledger.settles) == 1 + assert len(bridge.calls) == 1 + finally: + await _close(client) + + +@pytest.mark.parametrize("provider", PROVIDERS) +@pytest.mark.parametrize("is_error", [False, True]) +async def test_valid_tool_transcripts_still_have_two_calls(provider, is_error): + client, recorder = _client(provider) + ledger = RecordingLedger() + bridge, call = _bridge( + CallToolResult( + content=[TextContent(type="text", text="ordinary diagnostic")], isError=is_error + ) + ) + try: + record = await _run(client, bridge, ledger) + assert record["status"] == "succeeded" + assert len(recorder.seen) == len(ledger.reserves) == len(ledger.settles) == 2 + call.assert_awaited_once() + assert record["tool_calls"][0]["is_error"] is is_error + assert record["canonical_messages"][-2]["content"][0]["content"] == "ordinary diagnostic" + finally: + await _close(client) + + +@pytest.mark.parametrize("provider", PROVIDERS) +@pytest.mark.parametrize("status", [400, 500]) +async def test_provider_errors_are_clean_and_cannot_authorize_a_retry(provider, status): + client, recorder = _client(provider) + ledger = RecordingLedger() + waits = [] + + async def sleep(seconds): + waits.append(seconds) + + if provider == "scripted": + + async def fail(conv): + recorder.seen.append(deepcopy(conv)) + raise ProviderCallError( + "server" if status == 500 else "rejected", MARKER, status=status + ) + + client.call = fail + else: + body = {"error": {"code": status, "type": "api_error", "message": MARKER}} + recorder.responses[0] = (_gemini_ok if provider == "google" else _ok)(body, status) + try: + with pytest.raises(KeyLeakError) as error: + await _run(client, None, ledger, sleep=sleep) + assert MARKER not in str(error.value) + assert len(recorder.seen) == len(ledger.reserves) == len(ledger.settles) == 1 + assert waits == [] + finally: + await _close(client) + + +@pytest.mark.parametrize("provider", ["anthropic", "openai", "google"]) +async def test_synthetic_sdk_auth_headers_are_allowed(provider): + client, recorder = _client(provider) + # Only the SDK auth credential is key-shaped; no content contains it. + if provider == "google": + await _close(client) + client = GeminiClient( + gemini_sdk(MARKER, 30, transport=recorder.transport()), client.model_id, 32_768 + ) + else: + client._sdk.api_key = MARKER + ledger = RecordingLedger() + channel = ProtocolChannel(-1, (MARKER.encode(),), -1, Mock(), (Mock(), Mock())) + try: + record = await _run(client, None, ledger, check_content=channel.check_content) + assert record["status"] == "succeeded" + assert len(recorder.seen) == len(ledger.reserves) == 2 + header = {"anthropic": "x-api-key", "openai": "authorization", "google": "x-goog-api-key"}[ + provider + ] + assert MARKER in recorder.seen[0].headers[header] + assert all(MARKER.encode() not in request.content for request in recorder.seen) + finally: + await _close(client) + + +@pytest.mark.parametrize("provider", PROVIDERS) +@pytest.mark.parametrize("shaped", [False, True]) +async def test_worker_literal_check_covers_native_provider_replay(provider, shaped): + literal = ("AIza" + "q" * 35) if shaped else "dummy_bootstrap_opaque" + value = "prefix" + literal + "-suffix" + assert KEY_SHAPED.search(value) is None + channel = ProtocolChannel(-1, (literal.encode(),), -1, Mock(), (Mock(), Mock())) + client, recorder = _client(provider) + ledger = RecordingLedger() + bridge, call = _bridge(CallToolResult(content=[TextContent(type="text", text="safe")])) + original = client.call + + async def poisoned(conv): + turn = await original(conv) + if provider == "anthropic": + turn.replay[0]["signature"] = value + elif provider == "openai": + turn.replay.append({"type": "reasoning", "encrypted_content": value}) + elif provider == "google": + turn.replay.parts[0].text = value + elif provider == "ollama": + turn.replay["content"] = value + else: + turn = replace(turn, text=value) + return turn + + client.call = poisoned + try: + with pytest.raises(KeyLeakError) as caught: + await _run(client, bridge, ledger, check_content=channel.check_content) + assert literal not in str(caught.value) + assert len(recorder.seen) == len(ledger.reserves) == len(ledger.settles) == 1 + call.assert_not_awaited() # unsafe native replay is checked before MCP dispatch + if provider != "scripted": + assert all(literal.encode() not in request.content for request in recorder.seen) + finally: + await _close(client) + + +@pytest.mark.parametrize( + "case", + [ + "text", + "structured", + "truncated", + "json-boundary", + "mcp-error", + "mcp-error-data", + "exception", + ], +) +def test_cli_worker_withholds_transcript_and_never_reserves_again( + tmp_path: Path, monkeypatch, capsys, case +): + from benchmarks.__main__ import main + from benchmarks.agentic.host import LocalLauncher + from tests.benchmarks.test_agentic_run import _cli_args + + count = tmp_path / "calls.txt" + program = tmp_path / "recording_worker.py" + program.write_text( + "import sys\n" + f"sys.path.insert(0, {str(Path(__file__).resolve().parents[2])!r})\n" + "from pathlib import Path\n" + "from benchmarks.agentic import clients, worker\n" + "from tests.benchmarks.test_agentic_outgoing import _client, _bridge, _result\n" + "from benchmarks.agentic.clients import ScriptedClient\n" + "from tests.benchmarks.test_agentic_loop import TOOL, ANSWER\n" + "class RecordingClient(ScriptedClient):\n" + " async def call(self, conv):\n" + f" with Path({str(count)!r}).open('a') as f: f.write('call\\n')\n" + " return await super().call(conv)\n" + "clients.make_client = lambda family, **kw: RecordingClient(\n" + " family.provider, family.model_id, [TOOL, ANSWER])\n" + "async def open_bridge(stack, system, **kwargs):\n" + f" return _bridge(_result({case!r}))[0]\n" + "worker._open = open_bridge\n" + "raise SystemExit(worker.main_worker())\n" + ) + monkeypatch.setattr( + LocalLauncher, "command", lambda self, job: ([sys.executable, "-I", str(program)], {}) + ) + monkeypatch.setattr( + "benchmarks.agentic.run.HOSTED_CAPS", Caps(result_bytes=len("diagnostic: " + MARKER)) + ) + with pytest.raises(SystemExit) as error: + main( + [ + *_cli_args(tmp_path), + "--models", + "scripted-anthropic", + "--systems", + "no-docs", + "--questions", + "SYN-EX-001", + "--repeats", + "1", + ] + ) + assert error.value.code == 3 + assert count.read_text().splitlines() == ["call"] + captured = capsys.readouterr() + assert "key leak" in captured.err and MARKER not in captured.err + captured.out + run = tmp_path / "run" + assert not list((run / "transcripts").rglob("*.json")) + assert all(MARKER.encode() not in p.read_bytes() for p in run.rglob("*") if p.is_file()) + events = [ + json.loads(line) + for line in (tmp_path / "ledger" / "anthropic.jsonl").read_text().splitlines() + ] + assert sum(e["event"] == "reserve" for e in events) == 1 + assert sum(e["event"] == "settle" for e in events) == 1 + + +@pytest.mark.parametrize("provider", ["anthropic", "openai", "google", "ollama"]) +async def test_provider_refuses_key_in_tool_arguments(provider: str) -> None: + key = "AIza" + "g" * 35 + args = {"query": "https://docs.python.org/3/?token=" + key} + if provider == "anthropic": + block = {"type": "tool_use", "id": "id", "name": "search_docs", "input": args} + client = _anthropic(Recorder(_ok({**ANTHROPIC_TOOL_TURN, "content": [block]}))) + elif provider == "openai": + response = _openai_response([{**OPENAI_CALL, "arguments": json.dumps(args)}]) + client = _openai(Recorder(_ok(response))) + elif provider == "google": + response = _gemini_response([{"functionCall": {"name": "search_docs", "args": args}}]) + client = _gemini(GeminiRecorder(_gemini_ok(response))) + else: + calls = [_tool_call("search_docs", json.dumps(args), "id")] + response = _chat_completion({"role": "assistant", "tool_calls": calls}, "tool_calls") + client = _ollama(Recorder(_ok(response))) + ledger, bridge = RecordingLedger(), FakeBridge() + try: + # The normal loop must settle known response usage before rejecting content, + # and reject the entire turn before dispatching any MCP call. + with pytest.raises(KeyLeakError) as caught: + await _run(client, bridge, ledger) + assert key not in str(caught.value) + assert bridge.calls == [] + assert len(ledger.reserves) == len(ledger.settles) == 1 + assert ledger.settles[0]["outcome"] == "ok" + assert ledger.settles[0]["buckets"] is not None + finally: + await _close(client) diff --git a/tests/benchmarks/test_agentic_probe.py b/tests/benchmarks/test_agentic_probe.py new file mode 100644 index 00000000..eb1a14aa --- /dev/null +++ b/tests/benchmarks/test_agentic_probe.py @@ -0,0 +1,727 @@ +"""The isolation probe: in-container checks, the host verdict and the probe containers. + +Listeners and fake proxies bind 127.0.0.1 only; every docker command goes to FakeDocker. +""" + +from __future__ import annotations + +import asyncio +import json +import socket +import subprocess +import threading +import traceback +from collections.abc import Callable, Iterator, Sequence +from contextlib import contextmanager, nullcontext +from dataclasses import replace +from decimal import Decimal +from pathlib import Path +from types import SimpleNamespace +from typing import Any +from unittest.mock import AsyncMock, Mock + +import pytest + +import benchmarks.agentic.probe as probe +from benchmarks.__main__ import main +from benchmarks.agentic.egress import ProxyEvent, write_egress_summary +from benchmarks.agentic.host import run_jobs +from benchmarks.agentic.ledger import Ledger, LedgerService +from benchmarks.agentic.probe import ( + IsolationProbeFailed, + control_probe, + host_addresses, + isolation_probe, + probe_verdict, + run_probe_checks, +) +from benchmarks.agentic.protocol import KeyLeakError +from benchmarks.agentic.sandbox import ContainerLauncher, Sandbox +from benchmarks.runner import BenchmarkValidationError +from tests.benchmarks.test_agentic_egress import PROBE_LINES, PYPI_LINE +from tests.benchmarks.test_agentic_run import _cli +from tests.benchmarks.test_agentic_sandbox import ( + SYNTHETIC, + FakeDocker, + LateCreate, + _config, + _done, + _job, + _verified, +) + +TOKEN = "probe-token-0123456789abcdef" + + +@pytest.fixture(autouse=True) +def _loopback_canary(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setattr(probe, "_CANARY_BIND", "127.0.0.1") # never every interface in a test + + +DENIED = ("example.com", 443) +CANARY = ("host.docker.internal", 50000) + + +@contextmanager +def _listener(reply: Callable[[bytes], bytes] | None = None) -> Iterator[tuple[int, list[bytes]]]: + """A TCP server on 127.0.0.1 that records what each connection sends, and may answer.""" + server = socket.create_server(("127.0.0.1", 0)) + received: list[bytes] = [] + stop = threading.Event() + + def serve() -> None: + server.settimeout(0.1) + while not stop.is_set(): + try: + conn, _ = server.accept() + except TimeoutError: + continue + with conn: + conn.settimeout(2) + data = b"" + try: + while b"\r\n\r\n" not in data and (chunk := conn.recv(4096)): + data += chunk + except TimeoutError: + pass # a client that sends no blank line: keep what arrived + received.append(data) + if reply is not None: + conn.sendall(reply(data)) + + thread = threading.Thread(target=serve, daemon=True) + thread.start() + try: + yield server.getsockname()[1], received + finally: + stop.set() + thread.join(5) + server.close() + + +def _check(results: list[dict[str, Any]], name: str) -> list[dict[str, Any]]: + return [r for r in results if r["check"] == name] + + +def test_direct_check_fails_and_sends_the_token_when_something_listens() -> None: + with _listener() as (port, received): + results = run_probe_checks({"direct": [["127.0.0.1", port]], "token": TOKEN}) + (direct,) = _check(results, "direct") + assert direct["passed"] is False and direct["target"] == f"127.0.0.1:{port}" + assert any(f"Bearer {TOKEN}".encode() in data for data in received) + + +def test_direct_check_passes_when_nothing_listens() -> None: + with socket.socket() as reserved: + reserved.bind(("127.0.0.1", 0)) + port = reserved.getsockname()[1] + (direct,) = _check( + run_probe_checks({"direct": [["127.0.0.1", port]], "token": TOKEN}), "direct" + ) + assert direct["passed"] is True + + +def test_dns_check(monkeypatch: pytest.MonkeyPatch) -> None: + def unresolvable(*args: Any, **kwargs: Any) -> Any: + raise socket.gaierror(socket.EAI_NONAME, "no name") + + monkeypatch.setattr(probe.socket, "getaddrinfo", unresolvable) + (dns,) = _check(run_probe_checks({"dns_name": "pypi.org"}), "dns") + assert dns["passed"] is True and dns["target"] == "pypi.org" + monkeypatch.setattr(probe.socket, "getaddrinfo", lambda *a, **k: [("x",)]) + (dns,) = _check(run_probe_checks({"dns_name": "pypi.org"}), "dns") + assert dns["passed"] is False + + +def test_host_addresses_work_offline(monkeypatch: pytest.MonkeyPatch) -> None: + def no_name(name: str) -> Any: + raise socket.gaierror(socket.EAI_NONAME, "offline") + + class NoRoute: + def __init__(self, *args: Any) -> None: + pass + + def __enter__(self) -> NoRoute: + return self + + def __exit__(self, *args: Any) -> None: + return None + + def connect(self, address: Any) -> None: + raise OSError(51, "Network is unreachable") + + def getsockname(self) -> Any: + raise AssertionError("unreachable") + + monkeypatch.setattr(probe.socket, "gethostbyname_ex", no_name) + monkeypatch.setattr(probe.socket, "socket", NoRoute) + assert host_addresses() == [] + + class Routed(NoRoute): + def connect(self, address: Any) -> None: + return None + + def getsockname(self) -> Any: + return ("192.168.1.20", 50123) + + monkeypatch.setattr(probe.socket, "socket", Routed) + assert host_addresses() == ["192.168.1.20"] + + +def _proxy_reply(statuses: dict[str, int]) -> Callable[[bytes], bytes]: + def reply(request: bytes) -> bytes: + method = request.split(b" ", 1)[0].decode() + is_version = b"/api/version" in request.split(b"\r\n", 1)[0] + status = statuses["version"] if is_version else statuses[method] + return f"HTTP/1.1 {status} X\r\nContent-Length: 0\r\n\r\n".encode() + + return reply + + +def test_proxy_checks_read_the_status_line() -> None: + spec = { + "token": TOKEN, + "denied": list(DENIED), + "canary_via_proxy": list(CANARY), + "allowed_http": ["http://host.docker.internal:11434/api/version"], + } + deny = _proxy_reply({"CONNECT": 403, "GET": 403, "version": 200}) + with _listener(deny) as (port, received): + results = run_probe_checks(spec, proxy=("127.0.0.1", port)) + for name in ("proxy_denied", "proxy_canary", "allowed_http"): + assert [r["passed"] for r in _check(results, name)] == [True], name + assert any(f"Bearer {TOKEN}".encode() in data for data in received) # the canary request + allow = _proxy_reply({"CONNECT": 200, "GET": 200, "version": 403}) + with _listener(allow) as (port, _): + results = run_probe_checks(spec, proxy=("127.0.0.1", port)) + for name in ("proxy_denied", "proxy_canary", "allowed_http"): + assert [r["passed"] for r in _check(results, name)] == [False], name + + +def test_env_check_names_forbidden_variables_only(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setenv("HTTPS_PROXY", "http://user:secret@x:1") + (env,) = _check(run_probe_checks({}), "env") + assert env["passed"] is False and "HTTPS_PROXY" in env["detail"] + assert "secret" not in json.dumps(env) + # The failure names the variables, so the operator sees which one the docker CLI injected. + failed = probe_verdict([env], **_verdict_args()) + assert failed == ["env HTTPS_PROXY"] and "secret" not in json.dumps(failed) + + +def _passing() -> list[dict[str, Any]]: + return [{"check": "dns", "target": "pypi.org", "passed": True, "detail": "gaierror"}] + + +def _denials(*, canary: bool = True) -> list[ProxyEvent]: + events = [ProxyEvent("t", "172.30.0.2", "CONNECT", *DENIED, 403, "TCP_DENIED")] + if canary: + events.append(ProxyEvent("t", "172.30.0.2", "GET", *CANARY, 403, "TCP_DENIED")) + return events + + +def _verdict(**overrides: Any) -> list[str]: + values: dict[str, Any] = { + "canary_received": [], + "token": TOKEN, + "proxy_events": _denials(), + "denied": DENIED, + "canary": CANARY, + } + return probe_verdict(_passing(), **(values | overrides)) + + +def test_verdict_fails_when_the_canary_saw_the_token() -> None: + assert _verdict(canary_received=[f"Bearer {TOKEN}".encode()]) == ["canary_saw_token"] + + +def test_verdict_needs_both_denials_logged() -> None: + assert _verdict(proxy_events=_denials(canary=False)) == ["denial_not_logged"] + allowed = [ProxyEvent("t", "c", "CONNECT", *DENIED, 200, "TCP_TUNNEL"), _denials()[1]] + assert _verdict(proxy_events=allowed) == ["denial_not_logged"] + + +def test_verdict_passes_with_every_check_and_both_denials() -> None: + assert _verdict() == [] + failed = [{"check": "direct", "target": "h:1", "passed": False, "detail": "connected"}] + assert probe_verdict(failed, **_verdict_args()) == ["direct h:1"] + + +def _verdict_args() -> dict[str, Any]: + return { + "canary_received": [], + "token": TOKEN, + "proxy_events": _denials(), + "denied": DENIED, + "canary": CANARY, + } + + +class ProbeDocker(FakeDocker): + """A FakeDocker whose probe container 'runs': it logs both denials and reports checks.""" + + def __init__(self, *, passed: bool = True, **kwargs: Any) -> None: + super().__init__(**kwargs) + self.passed = passed + self.specs: list[dict[str, Any]] = [] + + async def __call__(self, argv: Sequence[str]) -> Any: + argv = list(argv) + if argv[1:3] != ["start", "--attach"]: + return await super().__call__(argv) + self.calls.append(argv) + (create,) = [c for c in self.ran("create") if f"id-{c[c.index('--name') + 1]}" == argv[-1]] + spec = json.loads(create[create.index("--spec") + 1]) + self.specs.append(spec) + if "control" in spec: + checks = [{"check": "control", "target": "x", "passed": self.passed, "detail": ""}] + return _done(argv, out=json.dumps({"checks": checks})) + lines = [ + f"2026-11-04T10:00:00.001Z 172.30.0.2 CONNECT {spec['denied'][0]} " + f"{spec['denied'][1]} 403 TCP_DENIED", + f"2026-11-04T10:00:00.002Z 172.30.0.2 GET {spec['canary_via_proxy'][0]} " + f"{spec['canary_via_proxy'][1]} 403 TCP_DENIED", + ] + if spec["allowed_http"]: + lines.append( + "2026-11-04T10:00:00.003Z 172.30.0.2 GET host.docker.internal 11434 200 TCP_MISS" + ) + spec_job = ( + create[create.index("--name") + 1].removeprefix("pdmcp-r1-").removesuffix("-probe") + ) + (self.squid_spool(spec_job) / "access.log").write_text( + "".join(f"{line}\n" for line in lines) + ) + checks = [{"check": "env", "target": "", "passed": self.passed, "detail": ""}] + return _done(argv, out=json.dumps({"checks": checks})) + + +async def _egress( + tmp_path: Path, + docker: FakeDocker, + gateways: Sequence[str], + allow: tuple[tuple[str, int], ...] = (("api.anthropic.com", 443),), +) -> Any: + (tmp_path / "run").mkdir(exist_ok=True) + docker.gateways = gateways + sandbox = Sandbox(_config(tmp_path), docker=docker, verify=_verified) + return sandbox, await sandbox.open_egress("j", allow) + + +async def test_read_only_artifacts_cannot_disclose_squid_logs( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + monkeypatch.setattr( + probe, "Canary", lambda: nullcontext(SimpleNamespace(port=50000, received=[])) + ) + monkeypatch.setattr(probe, "host_addresses", lambda: []) + job = _job("scripted-anthropic") + docker = ProbeDocker() + sandbox = Sandbox(_config(tmp_path), docker=docker, verify=_verified) + out = sandbox.config.out_dir + out.mkdir() + launcher = ContainerLauncher(sandbox, control=AsyncMock()) + await launcher.prepare([job]) + spool = docker.squid_spool(job.job_id) + (spool / "cache.log").write_text(f"header {SYNTHETIC}") + (spool / "unknown").write_text(SYNTHETIC) + + def read_only(*args: Any, **kwargs: Any) -> None: + raise PermissionError("simulated artifact volume read-only") + + monkeypatch.setattr("benchmarks.agentic.sandbox.write_new", read_only) + assert {p.name for p in (out / "egress" / job.job_id).iterdir()} == {"squid.conf"} + failure = None + try: + await launcher.close() + except KeyLeakError as exc: + failure = exc + assert all(SYNTHETIC.encode() not in p.read_bytes() for p in out.rglob("*") if p.is_file()) + assert failure is not None and "cache.log" in str(failure) + assert (out / "probe" / f"{job.job_id}.collection-pending").is_file() + assert not spool.parent.exists() + assert not docker.resources + + +@pytest.mark.parametrize("source", ["access.log", "checks", "checks-newline"]) +async def test_leaking_probe_never_publishes_a_prefix_or_allows_clean_collection( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, source: str +) -> None: + monkeypatch.setattr( + probe, "Canary", lambda: nullcontext(SimpleNamespace(port=50000, received=[])) + ) + monkeypatch.setattr(probe, "host_addresses", lambda: []) + job = _job("scripted-anthropic") + docker = FakeDocker() + sandbox = Sandbox(_config(tmp_path), docker=docker, verify=_verified) + out = sandbox.config.out_dir + out.mkdir() + launcher = ContainerLauncher(sandbox, control=AsyncMock()) + + key = "AIza" + "g" * 35 if source == "checks-newline" else SYNTHETIC + + async def one_shot(*args: Any) -> list[dict[str, Any]]: + spool = docker.squid_spool(job.job_id) + lines = list(PROBE_LINES) + if source == "access.log": + lines.append(PYPI_LINE.replace("pypi.org", SYNTHETIC)) + (spool / "access.log").write_text("\n".join(lines) + "\n") + (spool / "cache.log").write_text("squid started\n") + detail = {"checks": key, "checks-newline": "\n" + key}.get(source, "") + return [{"check": "env", "passed": True, "detail": detail}] + + monkeypatch.setattr(probe, "_one_shot", one_shot) + with pytest.raises(KeyLeakError) as detected: + await launcher.prepare([job]) + assert key not in str(detected.value) + assert not (out / "probe" / f"{job.job_id}.json").exists() + # Even if Squid replaces a leaking prefix before collection, the verdict stays failed. + spool = docker.squid_spool(job.job_id) + (spool / "access.log").write_text("\n".join(PROBE_LINES) + "\n") + with pytest.raises(KeyLeakError): + await launcher.close() + assert not spool.parent.exists() + assert all(key.encode() not in p.read_bytes() for p in out.rglob("*") if p.is_file()) + assert (out / "probe" / f"{job.job_id}.collection-pending").is_file() + assert json.loads((out / "egress" / job.job_id / "collected.json").read_text())["ok"] is False + + +async def test_the_probe_targets_every_ipam_gateway_and_records_the_inspect( + tmp_path: Path, +) -> None: + docker = ProbeDocker() + sandbox, egress = await _egress(tmp_path, docker, ("172.30.0.1", "fd00::1")) + job = _job("claude-sonnet-5-5") + record = await isolation_probe( + sandbox, egress, job_id="j", family=job.family, system_id="no-docs" + ) + (spec,) = docker.specs + hosts = {host for host, _ in spec["direct"]} + assert {"172.30.0.1", "fd00::1", "host.docker.internal", "gateway.docker.internal"} <= hosts + assert {port for _, port in spec["direct"]} >= {11434} + assert spec["dns_name"] == "pypi.org" and spec["denied"] == list(DENIED) + assert spec["allowed_http"] == [] + assert record["passed"] is True and record["failed"] == [] + assert record["network_inspect"] == egress.inspect + log = (egress.spool_dir / "access.log").read_text().splitlines() + assert record["proxy_prefix"] == log and len(log) == 2 + written = json.loads((tmp_path / "run" / "probe" / "j.json").read_text()) + assert written == record + (run,) = docker.ran("create")[-1:] + assert "-i" not in run and "--rm" in run and run[run.index("--name") + 1].endswith("-j-probe") + assert not [arg for arg in run if "API_KEY" in arg] + assert docker.ran("rm", "-f", "id-pdmcp-r1-j-probe") + + +async def test_scripted_offline_probe_has_no_ollama_request(tmp_path: Path) -> None: + docker = ProbeDocker() + sandbox, egress = await _egress(tmp_path, docker, ("172.30.0.1",), allow=()) + scripted = replace(_job("gemma4-12b").family, api="scripted") + await isolation_probe(sandbox, egress, job_id="j", family=scripted, system_id="no-docs") + assert docker.specs[0]["allowed_http"] == [] + + +async def test_an_ollama_probe_checks_its_version_url(tmp_path: Path) -> None: + docker = ProbeDocker() + sandbox, egress = await _egress( + tmp_path, docker, ("172.30.0.1",), allow=(("host.docker.internal", 11434),) + ) + family = _job("gemma4-12b").family + await isolation_probe(sandbox, egress, job_id="j", family=family, system_id="no-docs") + assert docker.specs[0]["allowed_http"] == ["http://host.docker.internal:11434/api/version"] + + +@pytest.mark.parametrize("initial", ["missing", "denials", "never_logged", "no_peer_reply"]) +async def test_probe_waits_for_its_log_before_freezing_query_prefix( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, initial: str +) -> None: + # No sockets or containers. The proxy publishes the completed log on the next loop turn. + monkeypatch.setattr( + probe, "Canary", lambda: nullcontext(SimpleNamespace(port=50000, received=[])) + ) + monkeypatch.setattr(probe, "host_addresses", lambda: []) + job = _job("gemma4-12b") + sandbox, egress = await _egress( + tmp_path, FakeDocker(), (), allow=(("host.docker.internal", 11434),) + ) + log = egress.spool_dir / "access.log" + ollama = "2026-11-04T10:00:03.000Z 172.30.0.3 GET host.docker.internal 11434 200 TCP_MISS" + prefix = [*PROBE_LINES, ollama] + if initial == "no_peer_reply": + prefix = [*(line + " HIER_NONE -" for line in PROBE_LINES), ollama + " HIER_DIRECT -"] + + async def one_shot(*args: Any) -> list[dict[str, Any]]: + if initial != "missing": + log.write_text("\n".join(PROBE_LINES) + "\n") + if initial == "no_peer_reply": + log.write_text("\n".join(prefix) + "\n") + elif initial != "never_logged": + asyncio.get_running_loop().call_soon(log.write_text, "\n".join(prefix) + "\n") + return [ + { + "check": "allowed_http", + "target": probe._OLLAMA_VERSION_URL, + "passed": True, + "detail": "200", + } + ] + + monkeypatch.setattr(probe, "_one_shot", one_shot) + if initial in ("never_logged", "no_peer_reply"): + monkeypatch.setattr(probe, "_SETTLE_S", 0) + with pytest.raises(IsolationProbeFailed): + await isolation_probe( + sandbox, egress, job_id="j", family=job.family, system_id="no-docs" + ) + assert json.loads((tmp_path / "run/probe/j.json").read_text())["passed"] is False + return + record = await isolation_probe( + sandbox, egress, job_id="j", family=job.family, system_id="no-docs" + ) + assert record["proxy_prefix"] == prefix + out = tmp_path / "run" + with log.open("a") as file: + file.write(PYPI_LINE + "\n") + (egress.spool_dir / "cache.log").write_text("squid started\n") + problems = await sandbox.close_egress(egress) + assert problems == [] + (out / "probe/control.json").write_text('{"passed":true}') + summary = write_egress_summary(out, [replace(job, job_id="j")], []) + assert summary["isolation_probe"] == "pass" + assert summary["jobs"]["j"]["hosts_allowed"] == [] + assert summary["jobs"]["j"]["hosts_denied"] == ["pypi.org:443"] + + +async def test_a_failed_check_raises_and_still_writes_the_record(tmp_path: Path) -> None: + docker = ProbeDocker(passed=False) + sandbox, egress = await _egress(tmp_path, docker, ("172.30.0.1",)) + family = _job("claude-sonnet-5-5").family + with pytest.raises(IsolationProbeFailed, match="env"): + await isolation_probe(sandbox, egress, job_id="j", family=family, system_id="no-docs") + assert json.loads((tmp_path / "run" / "probe" / "j.json").read_text())["passed"] is False + + +async def test_a_completed_probe_accepts_docker_auto_removal(tmp_path: Path) -> None: + name = "pdmcp-r1-control" + checks = [{"check": "control", "passed": True}] + + class AutoRemove(FakeDocker): + async def __call__(self, argv: Sequence[str]) -> Any: + if argv[1:3] == ["start", "--attach"]: + assert argv[-1] == f"id-{name}" + del self.resources[argv[-1]] + return _done(argv, out=json.dumps({"checks": checks})) + if argv[1:3] == ["rm", "-f"]: + assert argv[-1] == f"id-{name}" + return _done(argv, 1, err="Error response from daemon: No such container") + return await super().__call__(argv) + + docker = AutoRemove() + sandbox = Sandbox(_config(tmp_path), docker=docker) + argv = probe._probe_argv(sandbox, name, "test-net", {}, {}) + assert await probe._one_shot(sandbox, argv, name) == checks + assert not docker.resources + + +@pytest.mark.parametrize("source", ["stderr-tail", "decoder"]) +async def test_probe_failure_never_echoes_key_in_traceback( + source: str, monkeypatch: pytest.MonkeyPatch +) -> None: + key = "AIza" + "g" * 35 + proc = _done([], 1, err="X" + key + " " + "." * 260) + if source == "decoder": + proc = _done([], out="invalid") + error = json.JSONDecodeError("invalid token " + key, "invalid", 0) + monkeypatch.setattr(probe.json, "loads", Mock(side_effect=error)) + sandbox = Mock( + create_resource=AsyncMock(return_value="fake-id"), + docker=AsyncMock(return_value=proc), + remove_container=AsyncMock(), + ) + with pytest.raises((KeyLeakError, IsolationProbeFailed)) as caught: + await probe._one_shot(sandbox, ["create"], "probe") + assert key not in str(caught.value) + assert key not in "".join(traceback.format_exception(caught.value)) + sandbox.remove_container.assert_awaited_once() + + +@pytest.mark.parametrize("delimiter", ["\n", r"\x20"]) +def test_cli_withholds_structured_probe_stderr( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + capsys: pytest.CaptureFixture[str], + delimiter: str, +) -> None: + key = "sk-proj-" + "k" * 40 + stderr = json.dumps({"error": "." * 350 + delimiter + key}) + sandbox = Mock( + create_resource=AsyncMock(return_value="fake-id"), + docker=AsyncMock(return_value=_done([], 1, err=stderr)), + remove_container=AsyncMock(), + ) + + async def prepare(*args: Any) -> None: + await probe._one_shot(sandbox, ["create"], "probe") + + monkeypatch.setattr("benchmarks.agentic.host.LocalLauncher.prepare", prepare) + with pytest.raises(SystemExit) as caught: + main(_cli(tmp_path, "--systems", "no-docs")) + captured = capsys.readouterr() + assert key not in captured.out + captured.err + assert caught.value.code == 3 and "probe stderr" in captured.err + summary = json.loads((tmp_path / "run/run-summary.json").read_bytes()) + assert "KeyLeakError" in summary["abort_reason"] and key not in summary["abort_reason"] + + +async def test_probe_create_conflict_does_not_remove_the_existing_container(tmp_path: Path) -> None: + name = "pdmcp-r1-j-probe" + docker = FakeDocker(fail=lambda args: name in args and args[0] in {"run", "create"}) + docker.resources[f"id-{name}"] = {"a different invocation"} + sandbox = Sandbox(_config(tmp_path), docker=docker) + argv = probe._probe_argv(sandbox, name, "test-net", {}, {}) + with pytest.raises(BenchmarkValidationError): + await probe._one_shot(sandbox, argv, name) + assert not docker.ran("rm") + assert f"id-{name}" in docker.resources + + +async def test_probe_creation_finishes_before_cancellation_removes_it(tmp_path: Path) -> None: + name = "pdmcp-r1-j-probe" + docker = LateCreate(name) + sandbox = Sandbox(_config(tmp_path), docker=docker) + argv = probe._probe_argv(sandbox, name, "test-net", {}, {}) + await docker.cancel_create(asyncio.create_task(probe._one_shot(sandbox, argv, name))) + assert not docker.resources + assert not docker.ran("start") + + +@pytest.mark.parametrize(("timeout", "rm_fails"), [(False, False), (True, False), (False, True)]) +async def test_a_timed_out_or_cancelled_probe_container_is_removed( + tmp_path: Path, timeout: bool, rm_fails: bool +) -> None: + name = "pdmcp-r1-j-probe" + started = asyncio.Event() + + interrupted: list[asyncio.CancelledError] = [] + + class Hangs(FakeDocker): + async def __call__(self, argv: Sequence[str]) -> Any: + if argv[1:3] == ["start", "--attach"]: + assert argv[-1] == f"id-{name}" + started.set() + if timeout: + raise subprocess.TimeoutExpired(list(argv), 120) + try: + await asyncio.Event().wait() + except asyncio.CancelledError as exc: + interrupted.append(exc) + raise + return await super().__call__(argv) + + docker = Hangs(fail=lambda args: rm_fails and args[:2] == ["rm", "-f"]) + sandbox = Sandbox(_config(tmp_path), docker=docker) + argv = probe._probe_argv(sandbox, name, "test-net", {}, {}) + task = asyncio.create_task(probe._one_shot(sandbox, argv, name)) + await asyncio.wait_for(started.wait(), 2) + if not timeout: + task.cancel("signal SIGTERM") + with pytest.raises(subprocess.TimeoutExpired if timeout else asyncio.CancelledError) as error: + await task + assert docker.calls[-1] == ["docker", "rm", "-f", f"id-{name}"] + if not timeout: + assert error.value is interrupted[0] + assert str(error.value) == "signal SIGTERM" + if rm_fails: + assert isinstance(error.value.__cause__, BenchmarkValidationError) + assert "boom" in str(error.value.__cause__) + else: + assert not docker.resources + + +async def test_a_failed_control_makes_the_probe_inconclusive(tmp_path: Path) -> None: + (tmp_path / "run").mkdir() + docker = ProbeDocker(passed=False) + sandbox = Sandbox(_config(tmp_path), docker=docker, verify=_verified) + with pytest.raises(IsolationProbeFailed, match="inconclusive"): + await control_probe(sandbox) + (spec,) = docker.specs + assert spec["control"][0] == "host.docker.internal" + run = docker.ran("create")[-1] + assert run[run.index("--network") + 1] == "pdmcp-r1-out" + assert docker.calls[-1] == ["docker", "rm", "-f", "id-pdmcp-r1-control"] + assert json.loads((tmp_path / "run" / "probe" / "control.json").read_text())["passed"] is False + + +async def test_no_worker_starts_when_a_probe_fails(tmp_path: Path) -> None: + started: list[str] = [] + + class Recording(ContainerLauncher): + def command(self, job: Any) -> tuple[list[str], dict[str, str]]: + started.append(job.job_id) + raise AssertionError("no worker may start") + + async def close(self) -> list[str]: + started.append("close") + return await super().close() + + async def failing(sandbox: Sandbox, egress: Any, **kwargs: Any) -> dict[str, Any]: + raise IsolationProbeFailed(f"isolation probe failed for {kwargs['job_id']}: direct") + + async def control(sandbox: Sandbox) -> dict[str, Any]: + return {"passed": True} + + (tmp_path / "run").mkdir() + docker = FakeDocker() + sandbox = Sandbox(_config(tmp_path), docker=docker, verify=_verified) + launcher = Recording(sandbox, probe=failing, control=control) + ledger = Ledger.open(tmp_path / "ledger", run_id="r1", caps={"anthropic": Decimal(1)}) + + async def ignore(job: Any, message: dict[str, Any]) -> None: + return None + + try: + with pytest.raises(IsolationProbeFailed): + await run_jobs( + [_job("scripted-anthropic")], + launcher=launcher, + ledger=LedgerService(ledger, {}, {}), + on_message=ignore, + log_dir=tmp_path / "logs", + cwd=tmp_path, + ) + finally: + ledger.close() + assert started == ["close"] + assert not [c for c in docker.calls if "agentic-worker" in c] + + +@pytest.mark.parametrize("fail_immediately", [False, True]) +async def test_probe_listener_close_preserves_attach_cancellation( + monkeypatch: pytest.MonkeyPatch, + fail_immediately: bool, +) -> None: + closing, release = asyncio.Event(), asyncio.Event() + failure = OSError("listener close failed") + + async def wait_closed() -> None: + closing.set() + await release.wait() + raise failure + + server = Mock( + wait_closed=wait_closed, close=Mock(side_effect=failure if fail_immediately else None) + ) + server.sockets = [Mock(getsockname=lambda: ("localhost", 1234))] + monkeypatch.setattr(asyncio, "start_server", AsyncMock(return_value=server)) + original = asyncio.CancelledError("signal SIGTERM") + + async def probe_with_listener() -> None: + async with probe.Canary(): + raise original + + task = asyncio.create_task(probe_with_listener()) + if not fail_immediately: + await asyncio.wait_for(closing.wait(), 2) + task.cancel("signal SIGHUP") + release.set() + with pytest.raises(asyncio.CancelledError, match="signal SIGTERM") as error: + await task + assert error.value is original and error.value.__cause__ is failure diff --git a/tests/benchmarks/test_agentic_reference_evidence.py b/tests/benchmarks/test_agentic_reference_evidence.py new file mode 100644 index 00000000..1f86cdeb --- /dev/null +++ b/tests/benchmarks/test_agentic_reference_evidence.py @@ -0,0 +1,838 @@ +"""Reference evidence is scanned before diagnostics and proves the executed client. + +All authorization runs stop before launching; adapter traffic uses mock transports. +""" + +from __future__ import annotations + +import asyncio +import json +import shutil +from dataclasses import asdict +from datetime import date +from decimal import Decimal +from pathlib import Path +from unittest.mock import AsyncMock, Mock + +import pytest +import yaml + +from benchmarks.__main__ import main +from benchmarks.agentic import clients, worker +from benchmarks.agentic.ledger import PROVIDER_CAPS +from benchmarks.agentic.live import full_run_gate, provider_plans, reference_rates +from benchmarks.agentic.protocol import encode_frame +from benchmarks.agentic.run import run_agentic +from benchmarks.runner import BenchmarkValidationError +from tests.benchmarks import test_agentic_clients as adapters +from tests.benchmarks.test_agentic_live import ( + _bind_reference_transcripts, + _jobs, + _pilot_summary, + _single_cell_reference, + _write_record, + _write_snapshot, +) +from tests.benchmarks.test_agentic_run import ( + COMMITTED_MATRIX, + COMMITTED_PRICES, + _cli_args, + _config, + _container, + _live_config, + _matrix_with, +) +from tests.benchmarks.test_agentic_sandbox import FAMILIES, SYSTEMS + +KEY = "AIza" + "g" * 35 + + +def _record(run: Path) -> Path: + return next((run / "transcripts").glob("*/*.json")) + + +@pytest.mark.parametrize("live", [False, True]) +@pytest.mark.parametrize( + "source,encoding", + [ + ("matrix", "raw"), + ("matrix", "escaped"), + ("matrix", "merge"), + ("matrix", "alias"), + ("summary", "raw"), + ("summary", "escaped"), + ("summary", "duplicate"), + ("transcript", "raw"), + ("transcript", "escaped"), + ("transcript", "duplicate"), + ("discarded", "escaped"), + ("ledger", "raw"), + ("ledger", "escaped"), + ("ledger", "duplicate"), + ], +) +def test_cli_scans_all_reference_inputs_before_diagnostics_or_authorization( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + capsys: pytest.CaptureFixture[str], + live: bool, + source: str, + encoding: str, +) -> None: + pilot = tmp_path / "pilot" + _single_cell_reference(pilot, "gpt-6.1-sol", "openai-responses") + encoded = KEY.replace("A", r"\u0041", 1) + if source == "matrix": + path = pilot / "snapshots/model-matrix.yml" + text = path.read_text() + if encoding in {"merge", "alias"}: + text = ( + f'defaults: &base {{api: "{encoded}"}}\n' + + ("unused: *base\n" if encoding == "alias" else "") + + text.replace("- api: openai-responses", "- <<: *base\n api: openai-responses", 1) + ) + else: + text = text.replace( + "api: openai-responses", f'api: "{KEY if encoding == "raw" else encoded}"', 1 + ) + else: + path = { + "summary": pilot / "run-summary.json", + "transcript": _record(pilot), + "discarded": pilot / "discarded/no-docs--gpt-6.1-sol--r1/Q1--attempt1.json", + "ledger": pilot / "ledger-events.jsonl", + }[source] + text = _record(pilot).read_text() if source == "discarded" else path.read_text() + marker = KEY if encoding == "raw" else encoded + # The contaminated first value is lost by ordinary JSON duplicate-key decoding. + injected = f'"hidden": "{marker}", ' + ( + '"hidden": "safe", ' if encoding == "duplicate" else "" + ) + text = text.replace("{", "{" + injected, 1) + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(text) + launcher, docker = _container(tmp_path) + monkeypatch.setattr("benchmarks.__main__._container_launcher", lambda *_: launcher) + monkeypatch.setattr("sys.stdin", Mock(isatty=lambda: pytest.fail("prompted"))) + monkeypatch.delenv("CI", raising=False) + args = [ + *_cli_args(tmp_path), + "--launcher", + "container", + "--image", + "fake", + "--models", + "gpt-6.1-sol", + "--systems", + "no-docs", + "--matrix", + str(COMMITTED_MATRIX), + "--prices", + str(COMMITTED_PRICES), + "--reference-run", + str(pilot), + ] + with pytest.raises(SystemExit) as stopped: + main([*args, "--live" if live else "--dry-run"]) + output = capsys.readouterr() + assert stopped.value.code == 3 + assert "key leak" in output.err and KEY not in output.err and not output.out + assert docker.calls == [] + for artifact in (tmp_path / "run").rglob("*"): + if artifact.is_file(): + assert KEY.encode() not in artifact.read_bytes() + + +@pytest.mark.parametrize("kind", ["transcripts", "discarded"]) +@pytest.mark.parametrize( + "identity", [None, {}, {"api": "scripted"}, {"provider": "google"}, {"model_id": "other"}] +) +def test_unproven_or_mismatched_execution_never_reaches_confirmation( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, kind: str, identity: dict[str, str] | None +) -> None: + pilot = tmp_path / "pilot" + _single_cell_reference(pilot, "gpt-6.1-sol", "openai-responses") + path = _record(pilot) + record = json.loads(path.read_text()) + if identity is None: + record.pop("execution") # Legacy evidence cannot establish the API. + elif not identity: + record["execution"] = {} + else: + record["execution"].update(identity) + if kind == "discarded": + path = pilot / "discarded" / path.parent.name / "Q1--attempt1.json" + path.parent.mkdir(parents=True) + summary_path = pilot / "run-summary.json" + summary = json.loads(summary_path.read_text()) + summary["discarded"] = [{"cell": path.parent.name, "corpus_id": "Q1", "attempt": 1}] + summary_path.write_text(json.dumps(summary)) + path.write_text(json.dumps(record)) + _bind_reference_transcripts(pilot) + launcher, docker = _container(tmp_path) + monkeypatch.delenv("CI", raising=False) + with pytest.raises(BenchmarkValidationError, match="reference"): + run_agentic( + _live_config(tmp_path, models=("gpt-6.1-sol",), repeats=91, reference_run=pilot), + launcher=launcher, + today=date(2026, 11, 4), + confirm=lambda _: pytest.fail("unproven reference reached confirmation"), + ) + assert docker.calls == [] + + +def test_scripted_response_cannot_claim_live_execution(tmp_path: Path) -> None: + _single_cell_reference(tmp_path, "gpt-6.1-sol", "openai-responses") + path = _record(tmp_path) + record = json.loads(path.read_text()) + record["model_calls"][0]["raw_response"] = {"scripted_step": {"text": "ok"}} + path.write_text(json.dumps(record)) + _bind_reference_transcripts(tmp_path) + with pytest.raises(BenchmarkValidationError, match="scripted"): + reference_rates(tmp_path) + + +def test_actual_owner_r13_pilot_is_rejected_before_a_paid_estimate( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + fixture = Path(__file__).parent / "fixtures/agentic/r13-scripted-live" + pilot = shutil.copytree(fixture, tmp_path / "pilot") + matrix = pilot / "snapshots/model-matrix.yml" + prices = tmp_path / "prices.yml" + # The owner used this same family and snapshot, refreshing prices only for authorization. + from tests.benchmarks.test_agentic_run import FIX + + price_data = yaml.safe_load((FIX / "prices.yml").read_bytes()) + price_data["expires_on"] = "2026-11-30" + prices.write_text(yaml.safe_dump(price_data)) + launcher, docker = _container(tmp_path) + monkeypatch.delenv("CI", raising=False) + with pytest.raises(BenchmarkValidationError, match="reference"): + run_agentic( + _config( + tmp_path, + matrix_path=matrix, + prices_path=prices, + models=("scripted-anthropic",), + systems=("no-docs",), + questions=("SYN-EX-001",), + repeats=91, + reference_run=pilot, + ), + launcher=launcher, + today=date(2026, 11, 4), + confirm=lambda _: pytest.fail("owner's scripted pilot reached paid confirmation"), + ) + assert docker.calls == [] + + +def test_legitimate_reference_reaches_authorization_with_measured_estimate( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + pilot = tmp_path / "pilot" + _single_cell_reference(pilot, "gpt-6.1-sol", "openai-responses") + launcher, docker = _container(tmp_path) + shown: list[str] = [] + monkeypatch.delenv("CI", raising=False) + with pytest.raises(BenchmarkValidationError, match="not confirmed"): + run_agentic( + _live_config(tmp_path, models=("gpt-6.1-sol",), repeats=91, reference_run=pilot), + launcher=launcher, + today=date(2026, 11, 4), + confirm=lambda text: bool(shown.append(text)), + ) + assert len(shown) == 1 and "91 trajectories" in shown[0] and "estimate $9.10" in shown[0] + assert "x 1.25 = $11.38" in shown[0] and "$65" in shown[0] + assert docker.calls == [] + + +@pytest.mark.parametrize("wall_ms,allowed", [(3000, True), (1_000_000, False)]) +def test_proven_local_reference_preserves_unmetered_timing_gate( + tmp_path: Path, wall_ms: float, allowed: bool +) -> None: + family = FAMILIES["gemma4-12b"] + _write_snapshot(tmp_path, family.raw, FAMILIES["gpt-6.1-sol"].raw) + _write_record( + tmp_path / "transcripts/no-docs--gemma4-12b--r1/Q1.json", + family.id, + "ollama", + wall_ms, + 500, + model_id=family.model_id, + api="openai-chat-completions", + ) + _pilot_summary(tmp_path, "completed", 1, 1, "0") + (tmp_path / "ledger-events.jsonl").write_bytes(b"") + rates = reference_rates(tmp_path) + assert rates[family.id].cells == 1 and rates[family.id].usd_per_cell == 0 + assert rates[family.id].seconds_per_cell == (wall_ms - 500) / 1000 + jobs = _jobs(**{family.id: 90}) + plans = provider_plans(jobs, {}, PROVIDER_CAPS, rates) + assert plans[0].cap is None and plans[0].estimate is None + problems = full_run_gate(plans, jobs, rates) + assert (problems == []) == allowed + if not allowed: + assert "24-hour window" in problems[0] + + +def test_reference_keeps_benign_yaml_alias_and_override_behavior(tmp_path: Path) -> None: + _single_cell_reference(tmp_path, "gpt-6.1-sol", "openai-responses") + matrix = tmp_path / "snapshots/model-matrix.yml" + matrix.write_text( + "defaults: &base {api: scripted}\nunused: *base\n" + + matrix.read_text().replace( + "- api: openai-responses", "- <<: *base\n api: openai-responses", 1 + ) + ) + assert reference_rates(tmp_path)["gpt-6.1-sol"].api == "openai-responses" + + +@pytest.mark.parametrize( + "family_id", + ["claude-sonnet-5-5", "gpt-6.1-sol", "gemini-3.8-flash", "gemma4-12b", "scripted-openai"], +) +async def test_worker_records_actual_client_identity_on_success_and_discard( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, family_id: str +) -> None: + family = FAMILIES[family_id] + if family_id == "claude-sonnet-5-5": + client = adapters._anthropic(adapters.Recorder(adapters._ok(adapters.ANTHROPIC_ANSWER))) + elif family_id == "gpt-6.1-sol": + client = adapters._openai( + adapters.Recorder(adapters._ok(adapters._openai_response([adapters.OPENAI_MESSAGE]))) + ) + elif family_id == "gemini-3.8-flash": + client = adapters._gemini( + adapters.GeminiRecorder( + adapters._gemini_ok(adapters._gemini_response([{"text": "ok"}])) + ) + ) + elif family_id == "gemma4-12b": + client = adapters._ollama( + adapters.Recorder( + adapters._ok(adapters._chat_completion({"role": "assistant", "content": "ok"})) + ) + ) + else: + client = clients.ScriptedClient( + "openai", + "scripted-2", + [{"text": "ok", "usage": {"input_tokens": 10, "output_tokens": 1}}], + ) + expected = {"provider": family.provider, "model_id": family.model_id, "api": family.api} + monkeypatch.setattr(clients, "make_client", lambda *_args, **_kwargs: client) + monkeypatch.setattr(clients, "fetch_model_limits", AsyncMock(return_value=None)) + # Plan a scripted client with a different model: evidence must describe the instance + # that really ran, even when the caller has supplied an inconsistent family. + planned = FAMILIES["scripted-openai"].raw | {"model_id": "planned-only"} + job = { + "type": "job", + "family": planned, + "system": SYSTEMS["no-docs"].raw, + "caps": {}, + "trajectories": [ + {"corpus_id": "Q1", "repeat": 1, "prompt": "q"}, + {"corpus_id": "Q2", "repeat": 1, "prompt": "q"}, + ], + } + reader = asyncio.StreamReader() + for reply in ( + {"type": "grant", "unit_id": "u1"}, + {"type": "ack"}, + {"type": "ack"}, + {"type": "stop"}, + {"type": "ack"}, + ): + reader.feed_data(encode_frame(reply)) + reader.feed_eof() + channel = Mock() + assert await worker._run_job(channel, reader, first=job) == 0 + records = [ + call.args[0] + for call in channel.send.call_args_list + if call.args[0]["type"] in {"trajectory", "discarded"} + ] + assert [message["type"] for message in records] == ["trajectory", "discarded"] + assert all(message["record"]["execution"] == expected for message in records) + + +def test_scripted_reruns_save_execution_in_every_attempt(tmp_path: Path) -> None: + matrix = _matrix_with( + tmp_path, {"scripted-openai": [{"error": {"kind": "rate_limited", "retry_after_s": 121}}]} + ) + config = _config( + tmp_path, + matrix_path=matrix, + models=("scripted-openai",), + systems=("no-docs",), + questions=("SYN-EX-001",), + repeats=1, + ) + summary = run_agentic(config) + records = list((config.out_dir / "discarded").glob("*/*.json")) + assert len(records) == len(summary["discarded"]) == 3 + for path in records: + assert json.loads(path.read_text())["execution"] == { + "provider": "openai", + "model_id": "scripted-2", + "api": "scripted", + } + + +@pytest.mark.parametrize( + "mutation", + [ + "foreign_units", + "foreign_run", + "request_model", + "missing_request_model", + "duplicate_attempt", + "missing_attempt", + "missing_unit", + "duplicate_reserve", + "duplicate_settle", + "dropped_unit", + "orphan_unit", + "wrong_job", + "wrong_provider", + "wrong_kind", + "wrong_outcome", + "wrong_actual", + "wrong_buckets", + "negative_bound", + "negative_before", + "negative_after", + "nonfinite_balance", + "legacy_run", + "malformed_call", + "missing_calls", + "boolean_cells", + "negative_cap", + "negative_attempt_time", + "contradictory_input_bound", + ], +) +def test_unbound_or_inconsistent_units_cannot_authorize_full_run( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, mutation: str +) -> None: + pilot = tmp_path / "pilot" + _single_cell_reference(pilot, "gpt-6.1-sol", "openai-responses") + transcript = _record(pilot) + record = json.loads(transcript.read_bytes()) + call = record["model_calls"][0] + ledger_path = pilot / "ledger-events.jsonl" + events = [json.loads(line) for line in ledger_path.read_bytes().splitlines()] + summary_path = pilot / "run-summary.json" + summary = json.loads(summary_path.read_bytes()) + if mutation == "foreign_units": + for event in events: + event["unit_id"] = "another-valid-pilot-unit" + elif mutation == "foreign_run": + for event in events: + event["run_id"] = "another-pilot" + elif mutation == "request_model": + call["request_params"]["model"] = "other-model" + elif mutation == "missing_request_model": + del call["request_params"]["model"] + elif mutation == "duplicate_attempt": + call["attempts"] *= 2 + elif mutation == "missing_attempt": + call["attempts"] = [] + elif mutation == "missing_unit": + call["attempts"][0].pop("unit_id") + elif mutation == "duplicate_reserve": + events.insert(1, events[0].copy()) + elif mutation == "duplicate_settle": + events.append(events[1].copy()) + summary["ledger"]["openai"]["spent_after"] = "4.20" + elif mutation == "dropped_unit": + events = [] + summary["ledger"]["openai"]["spent_after"] = "4" + elif mutation == "orphan_unit": + events.extend([event | {"unit_id": "orphan"} for event in events[:2]]) + summary["ledger"]["openai"]["spent_after"] = "4.20" + elif mutation == "wrong_job": + events[0]["job_id"] = "gpt-6.1-sol--python-docs" + elif mutation == "wrong_provider": + events[0]["provider"] = "google" + elif mutation == "wrong_kind": + events[0]["kind"] = "batch" + elif mutation == "wrong_outcome": + events[1]["outcome"] = "timeout" + elif mutation == "wrong_actual": + events[1]["actual"] = "0.001" + elif mutation == "wrong_buckets": + events[1]["buckets"]["output"] = -1 + elif mutation == "negative_bound": + events[0]["bound"] = "-1" + elif mutation == "negative_before": + summary["ledger"]["openai"] = {"spent_before": "-1", "spent_after": "-0.90"} + elif mutation == "negative_after": + summary["ledger"]["openai"] = {"spent_before": "-0.20", "spent_after": "-0.10"} + elif mutation == "nonfinite_balance": + summary["ledger"]["openai"]["spent_before"] = "NaN" + elif mutation == "legacy_run": + summary.pop("run_id") + elif mutation == "malformed_call": + record["model_calls"] = [None] + elif mutation == "missing_calls": + record.pop("model_calls") + elif mutation == "boolean_cells": + summary["scored_cells"] = summary["planned_cells"] = True + elif mutation == "negative_cap": + summary["ledger"]["openai"]["cap"] = "-1" + elif mutation == "negative_attempt_time": + call["attempts"][0]["wall_ms"] = -1 + elif mutation == "contradictory_input_bound": + call["input_bound"] = 1 + + transcript.write_text(json.dumps(record)) + ledger_path.write_text("".join(json.dumps(event) + "\n" for event in events)) + summary_path.write_text(json.dumps(summary)) + _bind_reference_transcripts(pilot) + launcher, docker = _container(tmp_path) + monkeypatch.delenv("CI", raising=False) + shown = [] + with pytest.raises(BenchmarkValidationError, match="reference"): + run_agentic( + _live_config(tmp_path, models=("gpt-6.1-sol",), repeats=91, reference_run=pilot), + launcher=launcher, + today=date(2026, 11, 4), + confirm=lambda text: bool(shown.append(text)), + ) + assert shown == [] and docker.calls == [] + + +def _hosted_mock_pilot(tmp_path: Path, monkeypatch: pytest.MonkeyPatch, *, retries=False) -> Path: + """Run the real worker, loop, collector and ledger; replace only host I/O and HTTP.""" + from benchmarks.agentic.types import Buckets + + tmp_path.mkdir(parents=True, exist_ok=True) + responses = [] + if retries: + responses = [ + adapters._ok(adapters.ERROR_BODY, 500, {"retry-after": "121"}), + adapters._ok(adapters.ERROR_BODY, 429, {"retry-after": "0"}), + ] + transport = adapters.Recorder( + *responses, adapters._ok(adapters._openai_response([adapters.OPENAI_MESSAGE])) + ) + client = adapters._openai(transport) + + async def run_jobs(jobs, *, ledger, on_message, **kwargs): + for job in jobs: + + async def request(self, message): + if message["type"] == "reserve": + unit = await ledger.reserve( + **{k: v for k, v in message.items() if k != "type"}, job_id=job.job_id + ) + return {"type": "grant", "unit_id": unit} + if message["type"] == "settle": + await ledger.settle( + message["unit_id"], + outcome=message["outcome"], + buckets=Buckets(**message["buckets"]) if message["buckets"] else None, + ) + else: + await on_message(job, message) + return {"type": "ack"} + + with monkeypatch.context() as patch: + patch.setattr(worker._HostLedger, "request", request) + patch.setattr(clients, "make_client", lambda *_args, **_kwargs: client) + patch.setattr(clients, "fetch_model_limits", AsyncMock(return_value=None)) + first = { + "type": "job", + "family": job.family.raw, + "system": job.system.raw, + "caps": asdict(job.caps), + "trajectories": list(job.trajectories), + } + await worker._run_job( + Mock(), asyncio.StreamReader(), first=first, bootstrapped=True + ) + + launcher, _ = _container(tmp_path) + with monkeypatch.context() as patch: + patch.delenv("CI", raising=False) + patch.setattr("benchmarks.agentic.run.run_jobs", run_jobs) + summary = run_agentic( + _live_config(tmp_path, models=("gpt-6.1-sol",), repeats=1, run_id=tmp_path.name), + launcher=launcher, + today=date(2026, 11, 4), + confirm=lambda _: True, + ) + assert summary["scored_cells"] == summary["planned_cells"] == 1 + assert len(transport.seen) == (3 if retries else 1) + return tmp_path / "run" + + +@pytest.mark.parametrize("channel", ["summary_ledger", "transcripts", "attempt_id", "ledger_id"]) +def test_two_valid_pilots_cannot_mix_identity_and_charges( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, channel: str +) -> None: + live = _hosted_mock_pilot(tmp_path / "hosted", monkeypatch) + cheap_root = tmp_path / "scripted" + cheap_root.mkdir() + family = FAMILIES["gpt-6.1-sol"] + alias = FAMILIES["scripted-openai"].raw | {"id": family.id, "model_id": family.model_id} + matrix = _matrix_with( + cheap_root, + {family.id: [{"text": "ok", "usage": {"input_tokens": 1, "output_tokens": 1}}]}, + extra=[alias], + ) + config = _config( + cheap_root, + matrix_path=matrix, + prices_path=COMMITTED_PRICES, + models=(family.id,), + systems=("no-docs",), + questions=("SYN-EX-001",), + repeats=1, + run_id="scripted", + ) + run_agentic(config) + cheap = config.out_dir + assert reference_rates(live)[family.id].api == family.api + assert reference_rates(cheap)[family.id].api == "scripted" + assert ( + reference_rates(cheap)[family.id].usd_per_cell + < reference_rates(live)[family.id].usd_per_cell + ) + mixed = shutil.copytree(live, tmp_path / "mixed") + if channel == "summary_ledger": + for name in ("run-summary.json", "ledger-events.jsonl"): + shutil.copyfile(cheap / name, mixed / name) + elif channel == "transcripts": + other = _hosted_mock_pilot(tmp_path / "other-hosted", monkeypatch) + assert reference_rates(other)[family.id].api == family.api + shutil.copyfile(_record(other), _record(mixed)) + else: + path = _record(mixed) + record = json.loads(path.read_bytes()) + cheap_record = json.loads(_record(cheap).read_bytes()) + unit = cheap_record["model_calls"][0]["attempts"][0]["unit_id"] + if channel == "attempt_id": + record["model_calls"][0]["attempts"][0]["unit_id"] = unit + path.write_text(json.dumps(record)) + else: + ledger = mixed / "ledger-events.jsonl" + ledger.write_text( + "".join( + json.dumps(json.loads(line) | {"unit_id": unit}) + "\n" + for line in ledger.read_bytes().splitlines() + ) + ) + launcher, docker = _container(tmp_path) + monkeypatch.delenv("CI", raising=False) + shown = [] + with pytest.raises(BenchmarkValidationError, match="reference"): + run_agentic( + _live_config(tmp_path, models=(family.id,), repeats=91, reference_run=mixed), + launcher=launcher, + today=date(2026, 11, 4), + confirm=lambda text: bool(shown.append(text)), + ) + assert shown == [] and docker.calls == [] + + +def test_produced_hosted_discard_retry_reference_keeps_all_charges( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + pilot = _hosted_mock_pilot(tmp_path / "hosted", monkeypatch, retries=True) + summary = json.loads((pilot / "run-summary.json").read_bytes()) + assert len(summary["discarded"]) == 1 + events = [ + json.loads(line) for line in (pilot / "ledger-events.jsonl").read_bytes().splitlines() + ] + assert [e["outcome"] for e in events if e["event"] == "settle"] == [ + "server", + "rate_limited", + "ok", + ] + rate = reference_rates(pilot)["gpt-6.1-sol"] + assert rate.cells == 1 + assert rate.usd_per_cell == Decimal(summary["ledger"]["openai"]["spent_after"]) + assert rate.usd_per_cell > Decimal(events[-1]["booked"]) + launcher, docker = _container(tmp_path) + shown = [] + monkeypatch.delenv("CI", raising=False) + with pytest.raises(BenchmarkValidationError, match="not confirmed"): + run_agentic( + _live_config(tmp_path, models=("gpt-6.1-sol",), repeats=1, reference_run=pilot), + launcher=launcher, + today=date(2026, 11, 4), + confirm=lambda text: bool(shown.append(text)), + ) + assert len(shown) == 1 and "estimate $" in shown[0] and docker.calls == [] + + +@pytest.mark.parametrize("live", [False, True]) +@pytest.mark.parametrize("mutation", ["unit", "request_model", "malformed_call"]) +def test_cli_refuses_invalid_reference_before_output_ledger_or_prompt( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + capsys: pytest.CaptureFixture[str], + live: bool, + mutation: str, +) -> None: + pilot = tmp_path / "pilot" + _single_cell_reference(pilot, "gpt-6.1-sol", "openai-responses") + path = _record(pilot) + record = json.loads(path.read_bytes()) + if mutation == "unit": + record["model_calls"][0]["attempts"][0]["unit_id"] = "foreign" + elif mutation == "request_model": + record["model_calls"][0]["request_params"]["model"] = "other" + else: + record["model_calls"] = [None] + path.write_text(json.dumps(record)) + _bind_reference_transcripts(pilot) + launcher, docker = _container(tmp_path) + monkeypatch.setattr("benchmarks.__main__._container_launcher", lambda *_: launcher) + monkeypatch.setattr("sys.stdin", Mock(isatty=lambda: pytest.fail("prompted"))) + monkeypatch.delenv("CI", raising=False) + with pytest.raises(SystemExit) as caught: + main( + [ + *_cli_args(tmp_path), + "--launcher", + "container", + "--image", + "fake", + "--models", + "gpt-6.1-sol", + "--systems", + "no-docs", + "--repeats", + "91", + "--matrix", + str(COMMITTED_MATRIX), + "--prices", + str(COMMITTED_PRICES), + "--reference-run", + str(pilot), + "--live" if live else "--dry-run", + ] + ) + output = capsys.readouterr() + assert caught.value.code == 2 and "reference" in output.err and not output.out + assert docker.calls == [] + assert not (tmp_path / "run").exists() and not (tmp_path / "ledger").exists() + + +def test_reference_validates_each_scanned_source_buffer_without_reopening( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + _single_cell_reference(tmp_path, "gpt-6.1-sol", "openai-responses") + read = Path.read_bytes + counts: dict[Path, int] = {} + + def replace_after_capture(path): + counts[path] = counts.get(path, 0) + 1 + data = read(path) + # A second open sees a different identity and an unsafe value. + path.write_text(json.dumps({"unit_id": "foreign", "credential": KEY})) + return data + + monkeypatch.setattr(Path, "read_bytes", replace_after_capture) + rate = reference_rates(tmp_path)["gpt-6.1-sol"] + assert rate.usd_per_cell == Decimal("0.10") and rate.api == "openai-responses" + assert len(counts) == 4 and set(counts.values()) == {1} + + +def test_real_offline_pilot_retains_unmetered_reference_timing( + tmp_path: Path, +) -> None: + from tests.benchmarks.test_agentic_airgap import _counting, _local_config + + config = _local_config(tmp_path) + checks, rounds = _counting() + summary = run_agentic(config, offline_checks=checks) + assert summary["status"] == "completed" and len(rounds) == 4 + assert (config.out_dir / "ledger-events.jsonl").read_bytes() == b"" + rate = reference_rates(config.out_dir)["scripted-local"] + assert rate.cells == 2 and rate.usd_per_cell == 0 and rate.seconds_per_cell > 0 + + +@pytest.mark.parametrize( + "outcome,booked", + [ + ("timeout", "0.20"), + ("server", "0.20"), + ("connection", "0.20"), + ("no_usage", "0.20"), + ("rejected", "0"), + ("rate_limited", "0"), + ], +) +def test_every_attempt_outcome_uses_ledger_booking_rules( + tmp_path: Path, outcome: str, booked: str +) -> None: + from tests.benchmarks.test_agentic_live import _settled_unit + + _single_cell_reference(tmp_path, "gpt-6.1-sol", "openai-responses") + path = _record(tmp_path) + record = json.loads(path.read_bytes()) + extra = { + "request_params": {"model": "gpt-6.1-sol"}, + "attempts": [{"unit_id": "u2", "outcome": outcome}], + "buckets": None, + "raw_response": {} if outcome == "no_usage" else None, + } + record["model_calls"].append(extra) + path.write_text(json.dumps(record)) + ledger_path = tmp_path / "ledger-events.jsonl" + events = _settled_unit("u2", "gpt-6.1-sol", booked, outcome) + events[0]["bound"] = "0.10" + ledger_path.write_text(ledger_path.read_text() + "".join(json.dumps(e) + "\n" for e in events)) + summary_path = tmp_path / "run-summary.json" + summary = json.loads(summary_path.read_bytes()) + summary["ledger"]["openai"]["spent_after"] = str(Decimal("4.10") + Decimal(booked)) + summary_path.write_text(json.dumps(summary)) + _bind_reference_transcripts(tmp_path) + assert reference_rates(tmp_path)["gpt-6.1-sol"].usd_per_cell == Decimal("0.10") + Decimal( + booked + ) + # Keep the summary coherent with the forged booked total: only the unit rule catches it. + events[-1]["booked"] = str(Decimal(booked) + Decimal("0.01")) + ledger_path.write_text( + ledger_path.read_text().splitlines()[0] + + "\n" + + ledger_path.read_text().splitlines()[1] + + "\n" + + "".join(json.dumps(e) + "\n" for e in events) + ) + summary["ledger"]["openai"]["spent_after"] = str(Decimal("4.11") + Decimal(booked)) + summary_path.write_text(json.dumps(summary)) + with pytest.raises(BenchmarkValidationError, match="reference"): + reference_rates(tmp_path) + + +def test_same_model_families_cannot_swap_billed_unit_ownership(tmp_path: Path) -> None: + from tests.benchmarks.test_agentic_live import _settled_unit + + family = FAMILIES["gpt-6.1-sol"] + _write_snapshot(tmp_path, *(family.raw | {"id": name} for name in ("first", "second"))) + events = [] + for name in ("first", "second"): + _write_record( + tmp_path / "transcripts" / f"no-docs--{name}--r1" / "Q1.json", + name, + "openai", + 200, + 100, + model_id=family.model_id, + unit_id=name, + ) + events.extend(_settled_unit(name, name, "0.10", "ok", model_id=family.model_id)) + _pilot_summary(tmp_path, "completed", 2, 2, "0.20") + ledger = tmp_path / "ledger-events.jsonl" + ledger.write_text("".join(json.dumps(e) + "\n" for e in events)) + assert set(reference_rates(tmp_path)) == {"first", "second"} + for event in events: + event["unit_id"] = "second" if event["unit_id"] == "first" else "first" + ledger.write_text("".join(json.dumps(e) + "\n" for e in events)) + with pytest.raises(BenchmarkValidationError, match="reference"): + reference_rates(tmp_path) diff --git a/tests/benchmarks/test_agentic_reference_inventory.py b/tests/benchmarks/test_agentic_reference_inventory.py new file mode 100644 index 00000000..0dc27f5d --- /dev/null +++ b/tests/benchmarks/test_agentic_reference_inventory.py @@ -0,0 +1,265 @@ +"""Bind exact published pilot bytes, including zero-dollar local timing, to the host.""" + +from __future__ import annotations + +import asyncio +import hashlib +import json +import shutil +from dataclasses import asdict +from datetime import date +from decimal import Decimal +from types import SimpleNamespace +from unittest.mock import AsyncMock, Mock + +import pytest + +from benchmarks.agentic import clients, worker +from benchmarks.agentic.live import reference_rates +from benchmarks.agentic.run import run_agentic +from benchmarks.agentic.types import Buckets +from benchmarks.runner import BenchmarkValidationError +from benchmarks.scoring import score_run +from tests.benchmarks import test_agentic_clients as adapters +from tests.benchmarks.test_agentic_run import CORPUS_SCHEMA, SAMPLE_CORPUS, _container, _live_config + + +def _pilot(root, monkeypatch, *, family, seconds=2, discard=False, failed=False, run_id="reused"): + """Real orchestration/worker/collector/ledger, synthetic HTTP and a local clock.""" + root.mkdir(parents=True) + clock = [1000.0] + count = 0 + + def respond(request): + nonlocal count + count += 1 + clock[0] += seconds if count == 1 else 2 + if discard and count == 1: + return adapters._ok(adapters.ERROR_BODY, 429, {"retry-after": "121"}) + if failed: + return adapters._ok(adapters.ERROR_BODY, 400) + if family == "gemma4-12b": + return adapters._ok( + adapters._chat_completion({"role": "assistant", "content": "answer"}) + ) + return adapters._ok(adapters._openai_response([adapters.OPENAI_MESSAGE])) + + transport = adapters.Recorder(*([respond] * (1 + int(discard)))) + client = adapters._ollama(transport) if family == "gemma4-12b" else adapters._openai(transport) + + async def run_jobs(jobs, *, ledger, on_message, **kwargs): + for job in jobs: + + async def request(self, message): + if message["type"] == "reserve": + unit = await ledger.reserve( + **{k: v for k, v in message.items() if k != "type"}, job_id=job.job_id + ) + return {"type": "grant", "unit_id": unit} + if message["type"] == "settle": + await ledger.settle( + message["unit_id"], + outcome=message["outcome"], + buckets=Buckets(**message["buckets"]) if message["buckets"] else None, + ) + else: + await on_message(job, message) + return {"type": "ack"} + + with monkeypatch.context() as patch: + patch.setattr(worker._HostLedger, "request", request) + patch.setattr(clients, "make_client", lambda *_a, **_kw: client) + patch.setattr(clients, "fetch_model_limits", AsyncMock(return_value=None)) + patch.setattr( + "benchmarks.agentic.loop.time", SimpleNamespace(perf_counter=lambda: clock[0]) + ) + await worker._run_job( + Mock(), + asyncio.StreamReader(), + bootstrapped=True, + first={ + "type": "job", + "family": job.family.raw, + "system": job.system.raw, + "caps": asdict(job.caps), + "trajectories": list(job.trajectories), + }, + ) + + launcher, docker = _container(root) + with monkeypatch.context() as patch: + patch.delenv("CI", raising=False) + patch.setattr("benchmarks.agentic.run.run_jobs", run_jobs) + summary = run_agentic( + _live_config(root, models=(family,), repeats=1, run_id=run_id), + launcher=launcher, + today=date(2026, 11, 4), + confirm=lambda _: True, + offline_checks=lambda: [], + preflight=lambda _: {}, + ) + assert summary["status"] == "completed" + assert summary["scored_cells"] == summary["planned_cells"] == 1 + assert summary["failed_cells"] == int(failed) + assert len(summary["discarded"]) == int(discard) + assert count == 1 + int(discard) and docker.calls == [] + return root / "run" + + +def _gate(root, pilot, monkeypatch, family, error): + launcher, docker = _container(root) + shown = [] + monkeypatch.delenv("CI", raising=False) + with pytest.raises(BenchmarkValidationError, match=error): + run_agentic( + _live_config(root, models=(family,), repeats=300, reference_run=pilot), + launcher=launcher, + today=date(2026, 11, 4), + confirm=lambda text: bool(shown.append(text)), + ) + assert docker.calls == [] + return shown + + +@pytest.mark.parametrize("family", ["gemma4-12b", "gpt-6.1-sol"]) +@pytest.mark.parametrize("kind", ["transcripts", "discarded"]) +@pytest.mark.parametrize("reuse_id", [False, True]) +def test_partial_restore_from_another_real_pilot_refuses_before_authorization( + tmp_path, monkeypatch, family, kind, reuse_id +): + slow = _pilot( + tmp_path / "slow", monkeypatch, family=family, seconds=300, discard=kind == "discarded" + ) + fast = _pilot( + tmp_path / "fast", + monkeypatch, + family=family, + discard=kind == "discarded", + run_id="reused" if reuse_id else "other", + ) + slow_rate, fast_rate = reference_rates(slow)[family], reference_rates(fast)[family] + assert slow_rate.seconds_per_cell == 300 + (2 if kind == "discarded" else 0) + assert fast_rate.seconds_per_cell == 2 + (2 if kind == "discarded" else 0) + if family == "gemma4-12b": + assert slow_rate.usd_per_cell == fast_rate.usd_per_cell == Decimal(0) + assert _gate(tmp_path / "slow-gate", slow, monkeypatch, family, "24-hour window") == [] + assert len(_gate(tmp_path / "fast-gate", fast, monkeypatch, family, "not confirmed")) == 1 + mixed = shutil.copytree(slow, tmp_path / "mixed") + source = next((fast / kind).glob("*/*.json")) + shutil.copyfile(source, mixed / source.relative_to(fast)) + assert _gate(tmp_path / "mixed-gate", mixed, monkeypatch, family, "reference.*SHA256") == [] + + +@pytest.mark.parametrize("kind", ["transcripts", "discarded"]) +def test_metered_timing_edit_preserving_all_units_and_usage_is_refused(tmp_path, monkeypatch, kind): + family = "gpt-6.1-sol" + pilot = _pilot( + tmp_path / "pilot", monkeypatch, family=family, seconds=300, discard=kind == "discarded" + ) + path = next((pilot / kind).glob("*/*.json")) + record = json.loads(path.read_bytes()) + record["timing"]["wall_ms"] = 1 + path.write_text(json.dumps(record)) + assert _gate(tmp_path / "gate", pilot, monkeypatch, family, "reference.*SHA256") == [] + + +@pytest.mark.parametrize("failed,discard", [(False, False), (True, False), (False, True)]) +def test_producer_retains_exact_published_bytes_and_coordinates( + tmp_path, monkeypatch, failed, discard +): + pilot = _pilot( + tmp_path / "pilot", monkeypatch, family="gemma4-12b", failed=failed, discard=discard + ) + summary = json.loads((pilot / "run-summary.json").read_bytes()) + inventory = summary["transcript_inventory"] + paths = { + p.relative_to(pilot).as_posix() + for kind in ("transcripts", "discarded") + for p in (pilot / kind).glob("*/*.json") + } + assert {item["path"] for item in inventory} == paths + assert len(inventory) == 1 + int(discard) + for item in inventory: + content = (pilot / item["path"]).read_bytes() + record = json.loads(content) + assert item["sha256"] == hashlib.sha256(content).hexdigest() + for field in ( + "competitor_id", + "corpus_id", + "system_id", + "model_family_id", + "provider", + "model_id", + "repeat", + "attempt", + ): + assert item[field] == record[field] + assert record["attempt"] == ( + 2 if discard and item["path"].startswith("transcripts/") else 1 + ) + assert reference_rates(pilot)["gemma4-12b"].usd_per_cell == 0 + + +@pytest.mark.parametrize( + "mutation", + [ + "legacy", + "empty", + "duplicate", + "missing_hash", + "path", + "corpus_id", + "repeat", + "attempt", + "model_id", + "missing_file", + "extra_file", + "whitespace", + ], +) +def test_incomplete_or_unmatched_inventory_refuses_before_authorization( + tmp_path, monkeypatch, mutation +): + pilot = _pilot(tmp_path / "pilot", monkeypatch, family="gemma4-12b") + summary_path = pilot / "run-summary.json" + summary = json.loads(summary_path.read_bytes()) + inventory = summary["transcript_inventory"] + if mutation == "legacy": + del summary["transcript_inventory"] + elif mutation == "empty": + summary["transcript_inventory"] = [] + elif mutation == "duplicate": + inventory.append(inventory[0]) + elif mutation == "missing_hash": + del inventory[0]["sha256"] + elif mutation in {"path", "corpus_id", "model_id"}: + inventory[0][mutation] = "other" + elif mutation in {"repeat", "attempt"}: + inventory[0][mutation] = 2 + else: + path = pilot / inventory[0]["path"] + if mutation == "missing_file": + path.unlink() + elif mutation == "extra_file": + shutil.copyfile(path, path.with_name("extra.json")) + else: + path.write_bytes(path.read_bytes() + b"\n") + summary_path.write_text(json.dumps(summary)) + assert ( + _gate(tmp_path / "gate", pilot, monkeypatch, "gemma4-12b", "reference.*(inventory|SHA256)") + == [] + ) + + +def test_intact_prepaid_pilot_survives_copy_and_scoring_regeneration(tmp_path, monkeypatch): + pilot = _pilot(tmp_path / "pilot", monkeypatch, family="gpt-6.1-sol", discard=True) + expected = reference_rates(pilot) + moved = shutil.copytree(pilot, tmp_path / "moved") + assert ( + score_run(moved, corpus_path=SAMPLE_CORPUS, schema_path=CORPUS_SCHEMA)["total_cells"] == 1 + ) + # These derived artifacts do not change the already-paid transcript evidence. + token_path = next((moved / "tokens").glob("*/*.json")) + token_path.write_text(json.dumps({"status": "regenerated"})) + assert reference_rates(moved) == expected + assert len(_gate(tmp_path / "gate", moved, monkeypatch, "gpt-6.1-sol", "not confirmed")) == 1 diff --git a/tests/benchmarks/test_agentic_run.py b/tests/benchmarks/test_agentic_run.py index 451f6696..91220e9d 100644 --- a/tests/benchmarks/test_agentic_run.py +++ b/tests/benchmarks/test_agentic_run.py @@ -6,18 +6,22 @@ from __future__ import annotations import asyncio +import errno import hashlib import json +import os import random import signal import subprocess import sys import time +from collections.abc import Iterator from concurrent.futures import ThreadPoolExecutor from datetime import date from decimal import Decimal from pathlib import Path from typing import Any +from unittest.mock import AsyncMock import pytest import yaml @@ -32,12 +36,15 @@ from benchmarks.agentic.run import ( OUTPUT_CAP_STOPS, AgenticConfig, + _Collector, _until_signalled, cell_id, + limits_mismatch, plan_jobs, run_agentic, tool_model_key, ) +from benchmarks.agentic.sandbox import ContainerLauncher, Sandbox, SandboxConfig from benchmarks.agentic.types import Buckets from benchmarks.model_matrix import load_model_matrix from benchmarks.report import generate_report @@ -212,6 +219,55 @@ def test_cell_and_tool_model_keys() -> None: assert OUTPUT_CAP_STOPS == {"max_tokens", "max_output_tokens", "MAX_TOKENS", "CONTINUATION"} +@pytest.mark.parametrize("kind", ["discarded", "trajectory"]) +async def test_forged_report_cannot_write_outside_run(tmp_path: Path, kind: str) -> None: + question = _load_questions(_load_yaml_mapping(SAMPLE_CORPUS, "corpus"))[0] + family = load_model_matrix(FIX / "model-matrix.yml").model_families[0] + system = load_systems(COMMITTED_MANIFEST)[0] + (job,) = plan_jobs([question], [family], [system], repeats=1, seed=7, matrix_dir=FIX) + collector = _Collector(tmp_path / "run", {question.id: question}, [family]) + outside = tmp_path / "outside" + outside.mkdir() + canary = outside / ("proof--attempt1.json" if kind == "discarded" else f"{question.id}.json") + canary.write_text("untouched") + record = { + "status": "discarded" if kind == "discarded" else "succeeded", + "error": None, + "answer": "ok", + "model_calls": [], + "started_at": "2026-11-04T00:00:00Z", + "completed_at": "2026-11-04T00:00:01Z", + "timing": { + f"{k}_ms": 0 for k in ("grant_wait", "failed_attempt", "retry_wait", "used", "overhead") + }, + } + report = { + "type": kind, + "reason": "budget_stop", + "record": record, + "attempt": 1, + "corpus_id": str(outside / "proof") if kind == "discarded" else question.id, + "repeat": 1 if kind == "discarded" else "/../../../outside", + } + try: + with pytest.raises(BenchmarkValidationError): + await collector.on_message(job, report) + finally: + assert canary.read_text() == "untouched" + assert collector.families[family.id].first_started_at is None + assert not collector.out.exists() + + await collector.on_message(job, {**report, "corpus_id": question.id, "repeat": 1, "attempt": 3}) + cell = cell_id(system.id, family.id, 1) + path = ( + collector.out / "discarded" / cell / f"{question.id}--attempt3.json" + if kind == "discarded" + else collector.out / "transcripts" / cell / f"{question.id}.json" + ) + stored = json.loads(path.read_text()) + assert (stored["corpus_id"], stored["repeat"]) == (question.id, 1) + + def test_agentic_run_budget_stop_discards_and_lists_cells_not_run( tmp_path: Path, monkeypatch: pytest.MonkeyPatch ) -> None: @@ -247,6 +303,130 @@ def command(self, job: Any) -> Any: assert not (tmp_path / "ledger").exists() +class _EveryFamily(LocalLauncher): + def supports(self, family: Any) -> bool: + return True + + def command(self, job: Any) -> Any: + raise AssertionError("no process may start") + + +def test_an_air_gapped_dry_run_ignores_the_price_snapshot_expiry(tmp_path: Path) -> None: + def config(models: tuple[str, ...], out: str) -> AgenticConfig: + return _config( + tmp_path, + matrix_path=COMMITTED_MATRIX, + prices_path=COMMITTED_PRICES, + models=models, + out_dir=tmp_path / out, + dry_run=True, + ) + + late = date(2027, 1, 2) + summary = run_agentic(config(("gemma4-12b",), "local"), launcher=_EveryFamily(), today=late) + assert summary["dry_run"] is True and summary["models"] == ["gemma4-12b"] + with pytest.raises(BenchmarkValidationError, match="expires"): + run_agentic(config(("claude-sonnet-5-5",), "hosted"), launcher=_EveryFamily(), today=late) + + +def test_every_reserve_event_names_its_job(tmp_path: Path) -> None: + config = _config( + tmp_path, + models=("scripted-anthropic", "scripted-openai"), + systems=("no-docs",), + questions=("SYN-EX-001",), + repeats=1, + ) + summary = run_agentic(config) + assert summary["status"] == "completed" + providers = {"scripted-anthropic": "anthropic", "scripted-openai": "openai"} + lines = (tmp_path / "run" / "ledger-events.jsonl").read_text().splitlines() + reserves = [e for e in map(json.loads, lines) if e["event"] == "reserve"] + assert {e["job_id"] for e in reserves} == {f"{f}--no-docs" for f in providers} + for event in reserves: + family_id, system_id = event["job_id"].split("--") + assert system_id == "no-docs" and providers[family_id] == event["provider"] + + +def test_limits_mismatch_reports_each_difference() -> None: + family = {f.id: f for f in load_model_matrix(COMMITTED_MATRIX).model_families}[ + "claude-sonnet-5-5" + ] + assert limits_mismatch(None, family) == [] + assert limits_mismatch({"max_input_tokens": 1_000_000, "max_tokens": 128_000}, family) == [] + assert limits_mismatch({"max_input_tokens": 999, "max_tokens": 1_024}, family) == [ + "max_input_tokens 999 != max_input_tokens 1000000 in the model matrix", + "max_tokens 1024 < max_output_tokens 32768 in the model matrix", + ] + assert limits_mismatch({"error": "APIConnectionError"}, family) == [ + "model limits could not be read (APIConnectionError)" + ] + + +class _ReportsLimits(LocalLauncher): + """A worker that reports model limits in its system_info, then finishes.""" + + def command(self, job: Any) -> tuple[list[str], dict[str, str]]: + _, env = super().command(job) + info = {"type": "system_info", "model_limits": {"max_input_tokens": 999}} + code = ( + "import json, sys\n" + "inp, out = sys.stdin.buffer, sys.stdout.buffer\n" + "inp.read(int.from_bytes(inp.read(8), 'big'))\n" + f"for frame in ({info!r}, {{'type': 'done'}}):\n" + " body = json.dumps(frame).encode()\n" + " out.write(len(body).to_bytes(8, 'big') + body)\n" + " out.flush()\n" + ) + return [sys.executable, "-c", code], env + + +def test_a_mismatch_reaches_the_run_summary(tmp_path: Path) -> None: + summary = run_agentic(_scripted_config(tmp_path), launcher=_ReportsLimits()) + assert summary["model_limits_mismatch"] == [ + "scripted-anthropic--no-docs: max_input_tokens 999 != max_input_tokens 200000 in the " + "model matrix" + ] + written = json.loads((tmp_path / "run" / "run-summary.json").read_text()) + assert written["model_limits_mismatch"] == summary["model_limits_mismatch"] + + +def test_a_failed_probe_run_still_writes_fail(tmp_path: Path) -> None: + from tests.benchmarks.test_agentic_sandbox import FakeDocker, Probes, _verified + + config = _config( + tmp_path, + models=("scripted-anthropic",), + systems=("no-docs", "python-docs"), + questions=("SYN-EX-001",), + repeats=1, + ) + sandbox = Sandbox( + SandboxConfig( + image="sha256:" + "ab" * 32, + run_id="r1", + out_dir=config.out_dir, + index_path=tmp_path / "index.db", + keys_file=None, + repo_commit="c" * 40, + ), + docker=FakeDocker(), + verify=_verified, + ) + sandbox.config.index_path.touch() + probes = Probes(fail_on="scripted-anthropic--python-docs") + launcher = ContainerLauncher(sandbox, probe=probes, control=probes.control) + with pytest.raises(BenchmarkValidationError, match="isolation probe failed"): + run_agentic(config, launcher=launcher) + summary = json.loads((tmp_path / "run" / "egress" / "summary.json").read_text()) + assert summary["isolation_probe"] == "fail" + assert set(summary["jobs"]) == { + "scripted-anthropic--no-docs", + "scripted-anthropic--python-docs", + } + assert json.loads((tmp_path / "run" / "run-summary.json").read_text())["status"] == "aborted" + + def test_run_summary_counts_retries_and_reruns(tmp_path: Path) -> None: limited = {"error": {"kind": "rate_limited", "status": 429, "retry_after_s": 0}} answer = {"text": "ok", "usage": {"input_tokens": 1000, "output_tokens": 100}} @@ -324,7 +504,10 @@ def _start_host(tmp_path: Path, prelude: str = "") -> tuple[subprocess.Popen[byt "inp.read()\n" ) host_code = ( - prelude + "import sys\n" + # Only this child resets inherited ignores; a prelude can install its own handlers. + "import signal\n" + "signal.signal(signal.SIGHUP, signal.SIG_DFL)\n" + "signal.signal(signal.SIGTERM, signal.SIG_DFL)\n" + prelude + "import sys\n" "from pathlib import Path\n" "from benchmarks.agentic.host import LocalLauncher\n" "from benchmarks.agentic.run import AgenticConfig, run_agentic\n" @@ -448,8 +631,19 @@ def _scripted_config(tmp_path: Path) -> AgenticConfig: ) +@pytest.fixture +def default_signal_handlers(monkeypatch: pytest.MonkeyPatch) -> Iterator[None]: + getsignal = signal.getsignal + before = {s: getsignal(s) for s in (signal.SIGTERM, signal.SIGHUP)} + monkeypatch.setattr( + signal, "getsignal", lambda s: signal.SIG_DFL if s in before else getsignal(s) + ) + yield + assert {s: getsignal(s) for s in before} == before + + def test_run_agentic_completes_off_the_main_thread( - tmp_path: Path, capsys: pytest.CaptureFixture[str] + tmp_path: Path, capsys: pytest.CaptureFixture[str], default_signal_handlers: None ) -> None: # No signal handler can be installed off the main thread: the run goes on without one, # and says so. @@ -462,6 +656,7 @@ def test_run_agentic_completes_off_the_main_thread( def test_a_loop_without_signal_support_runs_without_handlers( capsys: pytest.CaptureFixture[str], + default_signal_handlers: None, ) -> None: before = {signum: signal.getsignal(signum) for signum in (signal.SIGTERM, signal.SIGHUP)} removed: list[int] = [] @@ -489,6 +684,34 @@ async def run() -> None: assert "SIGTERM, SIGHUP" in err and "NotImplementedError" in err +def test_an_ignored_sighup_is_left_out_of_the_skipped_handlers_line( + capsys: pytest.CaptureFixture[str], + default_signal_handlers: None, + monkeypatch: pytest.MonkeyPatch, +) -> None: + getsignal = signal.getsignal + monkeypatch.setattr( + signal, "getsignal", lambda s: signal.SIG_IGN if s == signal.SIGHUP else getsignal(s) + ) + + async def scenario() -> None: + loop = asyncio.get_running_loop() + + def unsupported(*args: Any) -> None: + raise NotImplementedError + + loop.add_signal_handler = unsupported # type: ignore[method-assign] + + async def run() -> None: + return None + + await _until_signalled(run()) + + asyncio.run(scenario()) + line = next(line for line in capsys.readouterr().err.splitlines() if "handler" in line) + assert "SIGTERM" in line and "SIGHUP" not in line + + def test_run_agentic_restores_the_previous_signal_dispositions(tmp_path: Path) -> None: def previous(signum: int, frame: Any) -> None: raise AssertionError("no signal is sent in this test") @@ -673,6 +896,27 @@ def test_late_max_tokens_answers_count_as_answer_turns_and_cap_stops( assert (fam["output_cap_stops"], fam["answer_turns"]) == (2, 100) +def test_run_refuses_escaped_keys_before_writing_json_evidence( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + key = "AIza" + "g" * 35 + config = _config(tmp_path, run_id="run\n" + key, dry_run=True) + with pytest.raises(KeyLeakError) as caught: + run_agentic(config) + assert key not in str(caught.value) + assert not (config.out_dir / "environment.json").exists() + + # Check the run's exported events separately from the persistent provider ledger. + config = _config(tmp_path, out_dir=tmp_path / "export") + events = [{"event": "stop", "provider": "google", "reason": "é" + key}] + monkeypatch.setattr(Ledger, "invocation_events", lambda self: events) + monkeypatch.setattr("benchmarks.agentic.run.run_jobs", AsyncMock()) + with pytest.raises(KeyLeakError) as caught: + run_agentic(config) + assert key not in str(caught.value) + assert not (config.out_dir / "ledger-events.jsonl").exists() + + def test_a_key_shape_in_an_input_file_is_refused_before_any_snapshot(tmp_path: Path) -> None: manifest = tmp_path / "manifest.yml" key_shape = "sk-ant-api03-" + "A" * 90 @@ -683,6 +927,235 @@ def test_a_key_shape_in_an_input_file_is_refused_before_any_snapshot(tmp_path: P assert not (tmp_path / "run" / "snapshots").exists() +@pytest.mark.parametrize("escape_key", [False, True]) +def test_dry_run_refuses_an_escaped_key_in_corpus_before_writing_snapshots( + tmp_path: Path, escape_key: bool +) -> None: + data = yaml.safe_load(SAMPLE_CORPUS.read_bytes()) + key = "AIza" + "g" * 35 + data["questions"][0]["prompt"] += "\n" + key + text = json.dumps(data) + if escape_key: + text = text.replace(key, r"\u0041" + key[1:]) + corpus = tmp_path / "encoded.yml" + corpus.write_text(text) + with pytest.raises(KeyLeakError) as error: + run_agentic(_config(tmp_path, corpus_path=corpus, dry_run=True)) + assert key not in str(error.value) + assert not (tmp_path / "run" / "snapshots").exists() + + +def _assert_input_refused( + tmp_path: Path, capsys: pytest.CaptureFixture[str], args: list[str], key: str +) -> None: + with pytest.raises(SystemExit) as caught: + main([*_cli_args(tmp_path), "--dry-run", *args]) + output = capsys.readouterr() + assert caught.value.code == 3 + assert "key leak" in output.err and key not in output.err and not output.out + assert not (tmp_path / "run").exists() + assert not (tmp_path / "ledger").exists() + + +@pytest.mark.parametrize( + "case, delimiter", + [("merge", r"\_"), ("merge", r"\x20"), ("duplicate", r"\_"), ("alias", r"\_")], +) +def test_cli_checks_scalar_before_yaml_discards_it( + tmp_path: Path, capsys: pytest.CaptureFixture[str], case: str, delimiter: str +) -> None: + key = "AIza" + "g" * 35 + quoted = f'"defaults{delimiter}{key}"' + entries = { + "merge": f" <<: {{prompt: {quoted}}}\n", + "duplicate": f" prompt: {quoted}\n", + "alias": f" prompt: &hidden {quoted}\n other: *hidden\n other: safe\n", + } + corpus = tmp_path / "input.yml" + corpus.write_text("questions:\n - id: SYN-EX-001\n" + entries[case] + " prompt: safe\n") + _assert_input_refused( + tmp_path, capsys, ["--corpus", str(corpus), "--questions", "SYN-EX-001"], key + ) + + +@pytest.mark.parametrize("field, original", [("model_id", "scripted-1"), ("api", "scripted")]) +def test_cli_checks_matrix_before_validation_or_price_lookup( + tmp_path: Path, capsys: pytest.CaptureFixture[str], field: str, original: str +) -> None: + key = "AIza" + "g" * 35 + matrix = tmp_path / "matrix.yml" + matrix.write_text( + (FIX / "model-matrix.yml").read_text().replace(f"{field}: {original}", f"{field}: {key}", 1) + ) + _assert_input_refused(tmp_path, capsys, ["--matrix", str(matrix)], key) + + +@pytest.mark.parametrize( + "option", ["--models", "--systems", "--questions", "--out", "--image", "--repeats"] +) +def test_cli_checks_runtime_inputs_before_errors_or_artifacts( + tmp_path: Path, capsys: pytest.CaptureFixture[str], option: str +) -> None: + key = "AIza" + "g" * 35 + value = str(tmp_path / key) if option == "--out" else key + extra = ["--launcher", "container"] if option == "--image" else [] + _assert_input_refused(tmp_path, capsys, [*extra, option, value], key) + assert not (tmp_path / key).exists() + + +@pytest.mark.parametrize( + "bad", ['"private-source\\q"', "[private-source, }", "!private-source discarded"] +) +def test_cli_reports_malformed_yaml_without_source_excerpt( + tmp_path: Path, capsys: pytest.CaptureFixture[str], bad: str +) -> None: + corpus = tmp_path / "malformed.yml" + corpus.write_text(f"questions: {bad}\n") + with pytest.raises(SystemExit) as caught: + main([*_cli_args(tmp_path), "--dry-run", "--corpus", str(corpus)]) + output = capsys.readouterr() + assert caught.value.code == 2 + assert "corpus" in output.err and "YAML" in output.err and "line 1" in output.err + assert "private-source" not in output.err and not output.out + assert not (tmp_path / "run").exists() + assert not (tmp_path / "ledger").exists() + + +def test_cli_accepts_benign_yaml_overrides_aliases_and_token_boundaries( + tmp_path: Path, capsys: pytest.CaptureFixture[str] +) -> None: + corpus = tmp_path / "valid.yml" + key = "AIza" + "g" * 35 + corpus.write_text( + f"defaults: &base {{prompt: prefix{key}}}\n" + "unused: &loop [*loop]\n" + "questions:\n - <<: *base\n id: SYN-EX-001\n prompt: first\n prompt: second\n" + ) + assert ( + main( + [ + *_cli_args(tmp_path), + "--dry-run", + "--corpus", + str(corpus), + "--questions", + "SYN-EX-001", + ] + ) + == 0 + ) + assert json.loads(capsys.readouterr().out)["corpus_ids"] == ["SYN-EX-001"] + assert (tmp_path / "run" / "snapshots" / "corpus.yml").read_bytes() == corpus.read_bytes() + + +def test_cli_plans_and_snapshots_the_same_files_even_if_replaced( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str] +) -> None: + args = _cli_args(tmp_path) + sources: dict[Path, bytes] = {} + for flag, name, original in ( + ("--corpus", "corpus.yml", SAMPLE_CORPUS), + ("--manifest", "competitor-manifest.yml", COMMITTED_MANIFEST), + ("--matrix", "model-matrix.yml", FIX / "model-matrix.yml"), + ("--prices", "price-snapshot.yml", FIX / "prices.yml"), + ): + path = tmp_path / name + sources[path] = original.read_bytes() + path.write_bytes(sources[path]) + args.extend([flag, str(path)]) + opened: list[Path] = [] + original_open = Path.open + + def open_then_replace(path: Path, *args: Any, **kwargs: Any) -> Any: + stream = original_open(path, *args, **kwargs) + if path in sources: + opened.append(path) + replacement = tmp_path / "replacement" + replacement.write_bytes(b"questions: []\n") + replacement.replace(path) # the open descriptor still refers to the original + return stream + + monkeypatch.setattr(Path, "open", open_then_replace) + assert main([*args, "--dry-run", "--repeats", "1"]) == 0 + assert json.loads(capsys.readouterr().out)["planned_cells"] == 18 + assert sorted(opened) == sorted(sources) + for path, data in sources.items(): + assert (tmp_path / "run" / "snapshots" / path.name).read_bytes() == data + + +def test_decoded_scan_visits_yaml_aliases_only_once() -> None: + from benchmarks.agentic.protocol import assert_no_key_shaped_json + + key = "AIza" + "g" * 35 + value = yaml.safe_load('items: &loop [*loop, "text\\n' + key + '"]') + with pytest.raises(KeyLeakError): + assert_no_key_shaped_json(value, where="aliased input") + + +@pytest.mark.parametrize( + "case", + [ + "malformed", + "malformed-hex", + "valid-nested", + "native-url", + "serialized-field", + "truncated", + "base64", + ], +) +def test_transcript_checks_escaped_tool_arguments( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, case: str +) -> None: + key = "AIza" + "g" * 35 + raw = '{"url":"failure' + r"\n" + key + '"' # missing the closing brace + arguments: str | dict[str, Any] = raw + if case == "valid-nested": + arguments = json.dumps({"url": r"\n" + key}, indent=2) + elif case == "truncated": + # Only the clipped tool error ends exactly at the 39-character Google shape. + arguments = raw[:-1] + "X" + limit = len("tool arguments must be a JSON object: " + arguments) - 1 + monkeypatch.setattr("benchmarks.agentic.run.HOSTED_CAPS", Caps(result_bytes=limit)) + elif case == "base64": + arguments = raw.replace(r"\n", "bn") + elif case == "malformed-hex": + arguments = '{"url":"bad' + r"\x20" + key + '"}' + elif case == "native-url": + arguments = {"url": "https://docs.python.org/3/?token=" + key} + elif case == "serialized-field": + arguments = json.dumps({"nested": [{key: True}]}) + usage = {"input_tokens": 1000, "output_tokens": 100} + steps = [ + {"tools": [{"name": "fetch", "arguments": arguments}], "usage": usage}, + {"text": "done", "usage": usage}, + ] + config = _config( + tmp_path, + manifest_path=_write_manifest(tmp_path), + matrix_path=_matrix_with(tmp_path, {"scripted-anthropic": steps}), + models=("scripted-anthropic",), + systems=("docs-fetch",), + questions=("SYN-EX-001",), + repeats=1, + ) + transcript = config.out_dir / "transcripts/docs-fetch--scripted-anthropic--r1/SYN-EX-001.json" + if case == "base64": + assert run_agentic(config)["succeeded_cells"] == 1 + (call,) = json.loads(transcript.read_text())["tool_calls"] + assert call["raw_arguments"] == arguments and arguments in call["result"] + else: + with pytest.raises(KeyLeakError) as caught: + run_agentic(config) + if case == "native-url": + assert "worker output failed its credential check" in str(caught.value) + assert key not in str(caught.value) + assert not transcript.exists() + assert all( + key.encode() not in p.read_bytes() for p in config.out_dir.rglob("*") if p.is_file() + ) + + def _ref_tools_manifest(tmp_path: Path, **fields: Any) -> Path: template = yaml.safe_load(TEMPLATE_MANIFEST.read_text(encoding="utf-8")) (ref,) = [c for c in template["competitors"] if c["id"] == "ref-tools"] @@ -921,6 +1394,116 @@ def test_runs_share_one_durable_ledger_by_default( assert (expected / "anthropic.jsonl").is_file() +@pytest.mark.parametrize("stage", ["opening_balance", "collector"]) +def test_initialization_interrupt_does_not_leave_an_open_ledger( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, stage: str +) -> None: + interrupt = KeyboardInterrupt("stop during setup") + config = _config(tmp_path, models=("scripted-anthropic",), systems=("no-docs",)) + with monkeypatch.context() as setup: + if stage == "opening_balance": + original = Ledger.spent + interrupted = False + + def spent(ledger: Ledger, provider: str) -> Decimal: + nonlocal interrupted + if not interrupted: + interrupted = True + raise interrupt + return original(ledger, provider) + + setup.setattr(Ledger, "spent", spent) + else: + + def interrupted_collector(*args: Any, **kwargs: Any) -> None: + raise interrupt + + setup.setattr("benchmarks.agentic.run._Collector", interrupted_collector) + with pytest.raises(KeyboardInterrupt) as error: + run_agentic(config) + assert error.value is interrupt + Ledger.open(config.ledger_dir, run_id="next-invocation").close() + + +@pytest.mark.parametrize("stage", ["export", "run", "export_after_failure"]) +def test_keyboard_interrupt_survives_finalization_and_releases_the_ledger( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, stage: str +) -> None: + interrupt = KeyboardInterrupt("operator interrupt") + config = _config(tmp_path, models=("scripted-anthropic",), systems=("no-docs",)) + + def before_workers(*args: Any, **kwargs: Any) -> None: + if stage == "run": + raise interrupt + if stage == "export_after_failure": + raise BenchmarkValidationError("earlier failure") + + def fail_export(path: Path, data: bytes) -> int: + if path.name == "ledger-events.jsonl": + if stage == "run": + raise KeyLeakError("key found in evidence") + raise interrupt + return write(path, data) + + write = Path.write_bytes + monkeypatch.setattr(Path, "write_bytes", fail_export) + monkeypatch.setattr("benchmarks.agentic.run.LedgerService", before_workers) + monkeypatch.setattr("benchmarks.agentic.run.run_jobs", AsyncMock()) + with pytest.raises(KeyboardInterrupt) as error: + run_agentic(config) + assert error.value is interrupt + if stage != "export": + reason = "key found in evidence" if stage == "run" else "earlier failure" + assert reason in str(interrupt.__cause__) + Ledger.open(config.ledger_dir, run_id="after-interrupt").close() + + +def test_cli_leak_stays_primary_when_the_artifact_volume_is_full( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str] +) -> None: + from tests.benchmarks.test_agentic_host import SYNTHETIC_KEY, _fake_worker, _reserve_frame + + code = f"import os; os.write(2, {SYNTHETIC_KEY.encode()!r})\n" + _fake_worker( + _reserve_frame(1024) + ) + monkeypatch.setattr( + LocalLauncher, "command", lambda self, job: ([sys.executable, "-I", "-c", code], {}) + ) + replace = os.replace + write = Path.write_bytes + failures = [] + + def no_space(src: Any, dst: Any, **kwargs: Any) -> None: + if str(dst).endswith(".stderr.log"): + failures.append("stderr") + raise OSError(errno.ENOSPC, "artifact volume full") + replace(src, dst, **kwargs) + + def no_export(path: Path, data: bytes) -> int: + if path.name == "ledger-events.jsonl": + failures.append("export") + raise OSError(errno.ENOSPC, "artifact volume full") + return write(path, data) + + monkeypatch.setattr(os, "replace", no_space) + monkeypatch.setattr(Path, "write_bytes", no_export) + with pytest.raises(SystemExit) as error: + main([*_cli_args(tmp_path), "--models", "scripted-anthropic", "--systems", "no-docs"]) + assert error.value.code == 3 + message = capsys.readouterr().err + assert "key leak" in message and SYNTHETIC_KEY not in message + assert failures == ["stderr", "export"] + events = [ + json.loads(line) + for line in (tmp_path / "ledger" / "anthropic.jsonl").read_text().splitlines() + ] + reserve, settle = (e for e in events if e["event"] in ("reserve", "settle")) + assert settle["outcome"] == "worker_lost" and Decimal(settle["booked"]) == 2 * Decimal( + reserve["bound"] + ) + assert not list((tmp_path / "run" / "logs").glob("*.stderr.log")) + + def _cli_args(tmp_path: Path) -> list[str]: return [ "agentic-run", @@ -937,3 +1520,222 @@ def _cli_args(tmp_path: Path) -> list[str]: "--questions", "SYN-EX-001,SYN-EX-002", ] + + +# --- the live gate inside run_agentic, and the agentic-run CLI (Task 13) ------------------------- + + +def _container(tmp_path: Path, keys_file: Path | None = None) -> tuple[ContainerLauncher, Any]: + from tests.benchmarks.test_agentic_sandbox import FakeDocker, Probes, _verified + + docker = FakeDocker() + sandbox = Sandbox( + SandboxConfig( + image="sha256:" + "ab" * 32, + run_id="r1", + out_dir=tmp_path / "run", + index_path=tmp_path / "index.db", + keys_file=keys_file, + repo_commit="c" * 40, + ), + docker=docker, + verify=_verified, + ) + probes = Probes() + return ContainerLauncher(sandbox, probe=probes, control=probes.control), docker + + +def _live_config(tmp_path: Path, **overrides: Any) -> AgenticConfig: + values: dict[str, Any] = { + "matrix_path": COMMITTED_MATRIX, + "prices_path": COMMITTED_PRICES, + "models": ("claude-sonnet-5-5",), + "systems": ("no-docs",), + "questions": ("SYN-EX-001",), + "repeats": 1, + } + return _config(tmp_path, **(values | overrides)) + + +def test_the_gate_runs_before_any_key_is_read_or_container_started( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + monkeypatch.setenv("CI", "1") + launcher, docker = _container(tmp_path, keys_file=tmp_path / "missing.env") + with pytest.raises(BenchmarkValidationError, match="refused under CI"): + run_agentic(_live_config(tmp_path), launcher=launcher, today=date(2026, 11, 4)) + assert docker.calls == [] + summary = json.loads((tmp_path / "run" / "run-summary.json").read_text()) + assert summary["status"] == "aborted" and "refused under CI" in summary["abort_reason"] + + +def test_a_declined_confirmation_starts_nothing( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + monkeypatch.delenv("CI", raising=False) + launcher, docker = _container(tmp_path, keys_file=tmp_path / "missing.env") + shown: list[str] = [] + + def decline(text: str) -> bool: + shown.append(text) + return False + + with pytest.raises(BenchmarkValidationError, match="not confirmed"): + run_agentic( + _live_config(tmp_path), launcher=launcher, today=date(2026, 11, 4), confirm=decline + ) + assert docker.calls == [] + assert len(shown) == 1 and shown[0].startswith("anthropic: 1 trajectories") + summary = json.loads((tmp_path / "run" / "run-summary.json").read_text()) + assert summary["status"] == "aborted" and summary["live_confirmation"] == shown[0] + + +def test_the_full_run_gate_stops_a_run_before_the_confirmation( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + monkeypatch.delenv("CI", raising=False) + launcher, docker = _container(tmp_path) + config = _live_config(tmp_path, models=("gpt-6.1-sol",), repeats=91) + + def never(text: str) -> bool: + raise AssertionError("the gate refuses first") + + with pytest.raises(BenchmarkValidationError, match="--reference-run"): + run_agentic(config, launcher=launcher, today=date(2026, 11, 4), confirm=never) + assert docker.calls == [] + + +def test_the_default_model_set_is_the_hosted_arm(tmp_path: Path) -> None: + launcher, _ = _container(tmp_path) + config = _live_config(tmp_path, models=None, dry_run=True) + summary = run_agentic(config, launcher=launcher, today=date(2026, 11, 4)) + assert summary["models"] == ["claude-sonnet-5-5", "gpt-6.1-sol", "gemini-3.8-flash"] + named = _live_config(tmp_path, models=("gemma4-12b",), dry_run=True, out_dir=tmp_path / "g") + assert run_agentic(named, launcher=launcher, today=date(2026, 11, 4))["models"] == [ + "gemma4-12b" + ] + + +def test_run_agentic_refuses_mixing_the_air_gapped_and_hosted_arms(tmp_path: Path) -> None: + launcher, _ = _container(tmp_path) + config = _live_config(tmp_path, models=("claude-sonnet-5-5", "gemma4-12b"), dry_run=True) + with pytest.raises(BenchmarkValidationError, match="the air-gapped arm runs alone"): + run_agentic(config, launcher=launcher, today=date(2026, 11, 4)) + + +def _cli(tmp_path: Path, *extra: str) -> list[str]: + return [ + "agentic-run", + "--corpus", + str(SAMPLE_CORPUS), + "--out", + str(tmp_path / "run"), + "--matrix", + str(FIX / "model-matrix.yml"), + "--prices", + str(FIX / "prices.yml"), + "--ledger-dir", + str(tmp_path / "ledger"), + "--models", + "scripted-anthropic", + "--questions", + "SYN-EX-001", + "--repeats", + "1", + *extra, + ] + + +def test_cli_container_launcher_defaults_to_a_dry_run( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str] +) -> None: + import benchmarks.agentic.sandbox as sandbox_module + + def no_docker(env: Any) -> Any: + async def run(argv: Any) -> Any: + raise AssertionError(f"docker must not run in a dry run: {argv}") + + return run + + monkeypatch.setattr(sandbox_module, "docker_runner", no_docker) + image = "sha256:" + "0" * 64 + assert main(_cli(tmp_path, "--launcher", "container", "--image", image)) == 0 + summary = json.loads(capsys.readouterr().out) + assert summary["dry_run"] is True and summary["planned_cells"] == 3 + assert not (tmp_path / "ledger").exists() + + +def test_cli_builds_the_production_sandbox_with_the_real_check( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str] +) -> None: + # Amendment 6: on the production path the sandbox keeps the real verify_image. + import benchmarks.agentic.run as agentic_run + from benchmarks.agentic.sandbox import verify_image + + seen: dict[str, Any] = {} + + def capture(config: AgenticConfig, **kwargs: Any) -> dict[str, Any]: + seen.update(config=config, **kwargs) + return {"dry_run": config.dry_run} + + monkeypatch.setattr(agentic_run, "run_agentic", capture) + keys = tmp_path / "keys.env" + image = "sha256:" + "1" * 64 + argv = ["--launcher", "container", "--image", image, "--keys-file", str(keys), "--live"] + assert main(_cli(tmp_path, *argv, "--run-id", "run-42", "--index", str(tmp_path / "i.db"))) == 0 + launcher = seen["launcher"] + assert isinstance(launcher, ContainerLauncher) + assert launcher.sandbox.verify is verify_image + sandbox_config = launcher.sandbox.config + assert sandbox_config.run_id == seen["config"].run_id == "run-42" + assert (sandbox_config.image, sandbox_config.keys_file) == (image, keys) + assert sandbox_config.index_path == tmp_path / "i.db" + assert sandbox_config.out_dir == tmp_path / "run" + assert seen["config"].dry_run is False + + +@pytest.mark.parametrize( + "extra", + [ + ("--live",), # the local launcher runs scripted models only + ("--launcher", "container", "--image", "sha256:" + "0" * 64, "--live", "--dry-run"), + ("--launcher", "container"), # no --image + ], +) +def test_cli_refuses_live_with_the_local_launcher(tmp_path: Path, extra: tuple[str, ...]) -> None: + with pytest.raises(SystemExit) as caught: + main(_cli(tmp_path, *extra)) + assert caught.value.code == 2 + + +async def test_first_managed_signal_survives_spawn_unwinding( + default_signal_handlers: None, monkeypatch: pytest.MonkeyPatch +) -> None: + loop = asyncio.get_running_loop() + callbacks: dict[int, Any] = {} + + def register(signum: int, callback: Any, *args: Any) -> None: + callbacks[signum] = lambda: callback(*args) + + monkeypatch.setattr(loop, "add_signal_handler", register) + monkeypatch.setattr(loop, "remove_signal_handler", lambda signum: True) + monkeypatch.setattr(signal, "signal", lambda *args: None) + ready, unwinding, release = asyncio.Event(), asyncio.Event(), asyncio.Event() + + async def spawning() -> None: + ready.set() + try: + await asyncio.Future() + except asyncio.CancelledError: + unwinding.set() + await release.wait() + raise + + run = asyncio.create_task(_until_signalled(spawning())) + await asyncio.wait_for(ready.wait(), 2) + callbacks[signal.SIGTERM]() + await asyncio.wait_for(unwinding.wait(), 2) + callbacks[signal.SIGHUP]() + release.set() + with pytest.raises(asyncio.CancelledError, match="signal SIGTERM"): + await run diff --git a/tests/benchmarks/test_agentic_run_recognition.py b/tests/benchmarks/test_agentic_run_recognition.py new file mode 100644 index 00000000..674940f5 --- /dev/null +++ b/tests/benchmarks/test_agentic_run_recognition.py @@ -0,0 +1,358 @@ +"""Run-wide recognition and terminal-status fallback, using owned, keyless workers.""" + +import asyncio +import subprocess +import sys +from dataclasses import replace +from pathlib import Path +from typing import Any + +import pytest + +from benchmarks.adapters.guard import PROVIDER_API_KEY_ENV +from benchmarks.agentic import host, worker +from benchmarks.agentic.host import LocalLauncher, WorkerJob, run_jobs +from benchmarks.agentic.loop import Caps +from benchmarks.agentic.protocol import ( + WORKER_LEAK_REASON, + FrameTooLarge, + KeyLeakError, + encode_frame, +) +from tests.benchmarks.test_agentic_cleanup_failure import ( + _assert_safe_chain, + _storage_error, + _worker_code, +) +from tests.benchmarks.test_agentic_host import ANSWER, REPO_ROOT, SYNTHETIC_KEY, D, Host, _job + + +@pytest.fixture +def harness(tmp_path: Path, monkeypatch: pytest.MonkeyPatch): + for name in PROVIDER_API_KEY_ENV.values(): + monkeypatch.delenv(name, raising=False) + h = Host(tmp_path) + yield h + h.ledger.close() + + +@pytest.mark.parametrize( + "secret, interrupted, error_type, reason", + [ + ("", False, KeyLeakError, WORKER_LEAK_REASON), + (SYNTHETIC_KEY, False, KeyLeakError, WORKER_LEAK_REASON), + ("", True, KeyLeakError, WORKER_LEAK_REASON), + (SYNTHETIC_KEY, True, KeyLeakError, WORKER_LEAK_REASON), + ("", False, FrameTooLarge, "FrameTooLarge: test limit"), + ], +) +async def test_sibling_storage_failure_cannot_displace_recognition( + harness: Host, + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + secret: str, + interrupted: bool, + error_type: type[Exception], + reason: str, +) -> None: + jobs = [ + _job(tmp_path, [ANSWER], job_id=name) for name in ("recognized", "storage", "late-storage") + ] + service = harness.service(jobs[0].family) + recognized, draining, release = asyncio.Event(), asyncio.Event(), asyncio.Event() + failure = _storage_error(secret) + late_failure = OSError("later storage failure during cancellation") + pending = [] + stopped = set() + reserve, stop_grants = service.reserve, service.stop_grants + + async def reserve_and_queue(**kwargs: Any) -> str | None: + unit = await reserve(**kwargs) + if unit is not None: + pending.append(asyncio.create_task(reserve(**kwargs))) + return unit + + def recognize() -> None: + stop_grants() + recognized.set() + + async def on_message(job: WorkerJob, message: dict[str, Any]) -> None: + if job.job_id == "storage": + await recognized.wait() + await harness.on_message(job, message) + + class Launcher(LocalLauncher): + closed = False + + def command(self, job: WorkerJob) -> tuple[list[str], dict[str, str]]: + if job.job_id == "recognized": + # Keep its supervisor in proc.wait after recognition, until the sibling fails. + code = _worker_code(reason=reason).replace( + f"sys.exit({3 if error_type is KeyLeakError else 2})", + "import time; time.sleep(30)", + ) + else: + code = ( + "import os, json, sys\n" + "n = int.from_bytes(sys.stdin.buffer.read(8), 'big')\n" + "sys.stdin.buffer.read(n)\n" + "body = json.dumps({'type': 'ready'}).encode()\n" + "os.write(1, len(body).to_bytes(8, 'big') + body)\n" + ) + if job.job_id == "late-storage": + code += "import time; time.sleep(30)\n" + return [sys.executable, "-I", "-c", code], {} + + async def stop_worker(self, job: WorkerJob) -> None: + stopped.add(job.job_id) + if job.job_id == "recognized": + draining.set() + await release.wait() + if job.job_id == "late-storage": + await draining.wait() + + async def close(self) -> list[str]: + self.closed = True + return [] + + publish = host._publish_worker_log + + def publish_or_fail(data: bytes, path: Path) -> None: + if path.name.startswith("storage."): + raise failure + if path.name.startswith("late-storage."): + raise late_failure + publish(data, path) + + monkeypatch.setattr(service, "reserve", reserve_and_queue) + monkeypatch.setattr(service, "stop_grants", recognize) + monkeypatch.setattr(host, "_publish_worker_log", publish_or_fail) + launcher = Launcher() + task = asyncio.create_task( + run_jobs( + jobs, + launcher=launcher, + ledger=service, + on_message=on_message, + log_dir=tmp_path / "logs", + cwd=REPO_ROOT, + ) + ) + try: + async with asyncio.timeout(10): + await draining.wait() + if interrupted: + task.cancel("operator interrupt") + await asyncio.sleep(0) + task.cancel("later interrupt") + await asyncio.sleep(0) + release.set() + with pytest.raises(asyncio.CancelledError if interrupted else error_type) as caught: + await task + trace = _assert_safe_chain(caught.value, failure) + _assert_safe_chain(caught.value, late_failure) + assert "artifact volume full" in trace + assert "later storage failure during cancellation" in trace + if interrupted: + assert str(caught.value) == "operator interrupt" + else: + assert reason in str(caught.value) + assert stopped == {"recognized", "storage", "late-storage"} and launcher.closed + events = harness.ledger.invocation_events() + assert [event["event"] for event in events] == ["reserve", "settle"] + assert events[1]["outcome"] == "worker_lost" + assert D(events[1]["booked"]) == 2 * D(events[0]["bound"]) + assert len(pending) == 1 and await pending[0] is None + assert ( + await reserve( + provider="anthropic", + model_id=jobs[0].family.model_id, + input_bound=1000, + output_bound=1024, + ) + is None + ) + assert harness.ledger.invocation_events() == events + finally: + release.set() + task.cancel() + await asyncio.gather(task, *pending, return_exceptions=True) + + +def _closed_report_worker(*, reserve: bool, failure_type: str = "KeyLeakError") -> str: + # Exercise main_worker, protect_output, run_worker and ProtocolChannel.send. Only + # this child's own protocol fd and a fresh pipe are closed. No credentials exist. + return ( + "import asyncio, os, sys\n" + f"sys.path.insert(0, {str(REPO_ROOT)!r})\n" + "from benchmarks.agentic import worker\n" + f"from benchmarks.agentic.protocol import {failure_type}\n" + "async def job(channel, reader, *args, **kwargs):\n" + + ( + " await worker._HostLedger(channel, reader).reserve(\n" + " provider='anthropic', model_id='scripted-1',\n" + " input_bound=1000, output_bound=1024)\n" + if reserve + else "" + ) + + " read_fd, write_fd = os.pipe()\n" + " os.close(read_fd)\n" + " os.close(channel._fd)\n" + " channel._fd = write_fd\n" + " await asyncio.sleep(0.05)\n" # EOF precedes terminal status becoming available. + f" raise {failure_type}('synthetic content refusal')\n" + "worker._run_job = job\n" + "sys.exit(worker.main_worker())\n" + ) + + +@pytest.mark.parametrize("failure_type, status", [("KeyLeakError", 3), ("FrameTooLarge", 4)]) +def test_genuine_worker_retains_harness_failure_when_error_pipe_is_closed(failure_type, status): + proc = subprocess.run( + [ + sys.executable, + "-I", + "-c", + _closed_report_worker(reserve=False, failure_type=failure_type), + ], + env={}, + input=encode_frame({"type": "job"}), + capture_output=True, + timeout=10, + ) + assert proc.returncode == status, proc.stderr + assert proc.stdout == proc.stderr == b"" + + +@pytest.mark.parametrize( + "error, reason, status", + [ + (KeyLeakError, WORKER_LEAK_REASON, 3), + (FrameTooLarge, "frame limit", 4), + ], +) +async def test_eof_recovers_genuine_worker_recognition_and_settles_once( + harness: Host, + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + error, + reason, + status, +) -> None: + job = _job(tmp_path, [ANSWER]) + processes = [] + spawn = asyncio.create_subprocess_exec + + async def record_process(*args: Any, **kwargs: Any) -> asyncio.subprocess.Process: + proc = await spawn(*args, **kwargs) + processes.append(proc) + return proc + + class Launcher(LocalLauncher): + def command(self, job: WorkerJob) -> tuple[list[str], dict[str, str]]: + return [ + sys.executable, + "-I", + "-c", + _closed_report_worker(reserve=True, failure_type=error.__name__), + ], {} + + monkeypatch.setattr(asyncio, "create_subprocess_exec", record_process) + service = harness.service(job.family) + with pytest.raises(error, match=reason): + await run_jobs( + [job], + launcher=Launcher(), + ledger=service, + on_message=harness.on_message, + log_dir=tmp_path / "logs", + cwd=REPO_ROOT, + ) + assert [proc.returncode for proc in processes] == [status] + events = harness.ledger.invocation_events() + assert [event["event"] for event in events] == ["reserve", "settle"] + assert events[1]["outcome"] == "worker_lost" + assert D(events[1]["booked"]) == 2 * D(events[0]["bound"]) + assert harness.messages() == [] + assert ( + await service.reserve( + provider="anthropic", + model_id=job.family.model_id, + input_bound=1000, + output_bound=1024, + ) + is None + ) + assert harness.ledger.invocation_events() == events + # Both the retained error and the stopped ledger arbiter belong to this invocation. + fresh = _job(tmp_path, [ANSWER], count=1, job_id="next-invocation") + await harness.run([fresh]) + assert harness.messages(fresh.job_id)[-1] == {"type": "done"} + + +@pytest.mark.parametrize("ending", ["death", "timeout", "closed-stdout"]) +async def test_unrelated_worker_loss_allows_a_healthy_sibling( + harness: Host, + tmp_path: Path, + ending: str, +) -> None: + lost = replace( + _job(tmp_path, [ANSWER], job_id="lost"), + caps=Caps(trajectory_s=0.1, model_call_timeout_s=0.1), + ) + healthy = _job(tmp_path, [ANSWER], count=1, job_id="healthy") + + class Launcher(LocalLauncher): + def command(self, job: WorkerJob) -> tuple[list[str], dict[str, str]]: + if job.job_id != "lost": + return super().command(job) + end = { + "death": "sys.exit(1)", + "timeout": "time.sleep(30)", + "closed-stdout": "os.close(1); time.sleep(30)", + }[ending] + code = _worker_code(leak=False).replace("sys.exit(2)", end) + return [sys.executable, "-I", "-c", "import time\n" + code], {} + + async with asyncio.timeout(5): + await harness.run([lost, healthy], launcher=Launcher()) + assert {m["reason"] for m in harness.messages("lost")} == {"worker_lost"} + assert harness.messages("healthy")[-1] == {"type": "done"} + events = harness.ledger.invocation_events() + assert [event["event"] for event in events] == ["reserve", "settle", "reserve", "settle"] + assert [event["outcome"] for event in events if event["event"] == "settle"] == [ + "worker_lost", + "ok", + ] + + +@pytest.mark.parametrize("report_leak", [False, True]) +async def test_reporting_preserves_recognition_when_fallback_pipe_breaks( + monkeypatch: pytest.MonkeyPatch, + report_leak: bool, +) -> None: + class Channel: + def send(self, message: dict[str, Any]) -> None: + if report_leak and message["reason"] != WORKER_LEAK_REASON: + raise KeyLeakError("synthetic diagnostic refusal") + raise BrokenPipeError("closed protocol pipe") + + async def fail(*args: Any, **kwargs: Any) -> int: + if report_leak: + raise ValueError("synthetic ordinary error") + raise KeyLeakError("synthetic content refusal") + + monkeypatch.setattr(worker, "_run_job", fail) + assert await worker.run_worker(Channel(), asyncio.StreamReader()) == 3 # type: ignore[arg-type] + + +async def test_diagnostic_refusal_preserves_worker_credential_status(monkeypatch): + class Channel: + def send(self, message): + raise KeyLeakError("synthetic diagnostic refusal") + + async def fail(*args, **kwargs): + raise KeyLeakError("recognized content failure") + + monkeypatch.setattr(worker, "_run_job", fail) + assert await worker.run_worker(Channel(), asyncio.StreamReader()) == 3 diff --git a/tests/benchmarks/test_agentic_sandbox.py b/tests/benchmarks/test_agentic_sandbox.py new file mode 100644 index 00000000..3f8087e5 --- /dev/null +++ b/tests/benchmarks/test_agentic_sandbox.py @@ -0,0 +1,1926 @@ +"""The container sandbox and ContainerLauncher (design §7.2, §7.3), with a recorded FakeDocker. + +No test runs docker or reaches a network host: every docker command goes to FakeDocker. +""" + +from __future__ import annotations + +import asyncio +import json +import os +import subprocess +import sys +import tempfile +import traceback +from collections.abc import Callable, Iterator, Sequence +from dataclasses import replace +from pathlib import Path +from typing import Any +from unittest.mock import AsyncMock, Mock + +import pytest + +from benchmarks.adapters.guard import PROVIDER_API_KEY_ENV +from benchmarks.agentic.bridge import SystemSpec, load_systems +from benchmarks.agentic.egress import allowlist, squid_conf, write_egress_summary +from benchmarks.agentic.host import WorkerJob, run_jobs +from benchmarks.agentic.loop import HOSTED_CAPS +from benchmarks.agentic.protocol import KeyLeakError +from benchmarks.agentic.sandbox import ( + RUN_LABEL, + SQUID_IMAGE, + ContainerLauncher, + Egress, + Sandbox, + SandboxConfig, + cli_env, + read_key, + verify_image, +) +from benchmarks.model_matrix import ModelFamily, load_model_matrix +from benchmarks.runner import BenchmarkValidationError + +REPO_ROOT = Path(__file__).resolve().parents[2] +FIX = Path(__file__).parent / "fixtures" / "agentic" +IMAGE = "sha256:" + "ab" * 32 +COMMIT = "c" * 40 +RUN = "r1" +SYNTHETIC = "sk-ant-api03-" + "s" * 90 +FAMILIES: dict[str, ModelFamily] = { + f.id: f + for path in (REPO_ROOT / "docs" / "benchmarks" / "model-matrix.yml", FIX / "model-matrix.yml") + for f in load_model_matrix(path).model_families +} +SYSTEMS: dict[str, SystemSpec] = { + s.id: s for s in load_systems(REPO_ROOT / "docs" / "benchmarks" / "agentic-manifest.yml") +} +RUNNING = {"Running": True, "ExitCode": 0, "OOMKilled": False} +STOPPED = {"Running": False, "ExitCode": 0, "OOMKilled": False} + + +def _done(argv: Sequence[str], code: int = 0, out: str = "", err: str = "") -> Any: + return subprocess.CompletedProcess(list(argv), code, out.encode(), err.encode()) + + +class FakeDocker: + """Records every docker argv and answers like a local Docker Desktop, success by default.""" + + def __init__( + self, + *, + context_host: str = "unix:///Users/x/.docker/run/docker.sock", + engine: str = "29.9.2", + revision: str = COMMIT, + image_id: str = IMAGE, + ipv6: bool = False, + gateways: Sequence[str] = ("172.30.0.1",), + states: Sequence[dict[str, Any]] = (RUNNING, STOPPED), + squid_present: bool = True, + fail: Callable[[list[str]], bool] | None = None, + ) -> None: + self.calls: list[list[str]] = [] + self.context_host, self.engine, self.revision = context_host, engine, revision + self.image_id, self.ipv6, self.gateways = image_id, ipv6, gateways + self.states, self.squid_present, self.fail = states, squid_present, fail + self._inspected: dict[str, int] = {} + self.resources: dict[str, set[str]] = {} + + async def __call__(self, argv: Sequence[str]) -> Any: + argv = list(argv) + self.calls.append(argv) + args = argv[1:] + if self.fail is not None and self.fail(args): + return _done(argv, 1, err="Error response from daemon: boom") + if args[:2] == ["network", "create"] or args[0] in {"create", "run"}: + name = args[args.index("--name") + 1] if "--name" in args else args[-1] + resource_id = f"id-{name}" + self.resources[resource_id] = {v for k, v in zip(args, args[1:]) if k == "--label"} + return _done(argv, out=resource_id + "\n") + if args[:2] in (["container", "ls"], ["network", "ls"]): + label = args[args.index("--filter") + 1].removeprefix("label=") + ids = [i for i, labels in self.resources.items() if label in labels] + return _done(argv, out="\n".join(ids)) + if args[:2] in (["rm", "-f"], ["network", "rm"]): + self.resources.pop(args[-1], None) + if args[:2] == ["context", "inspect"]: + ctx = {"Name": "desktop-linux", "Endpoints": {"docker": {"Host": self.context_host}}} + return _done(argv, out=json.dumps(ctx)) + if args[:2] == ["image", "inspect"]: + if args[-1] == SQUID_IMAGE: + if not self.squid_present: + return _done(argv, 1, err=f"Error: No such image: {SQUID_IMAGE}") + return _done(argv, out=json.dumps({"Id": "sha256:" + "5" * 64})) + labels = {"org.opencontainers.image.revision": self.revision} + return _done(argv, out=json.dumps({"Id": self.image_id, "Config": {"Labels": labels}})) + if args[:1] == ["version"]: + return _done(argv, out=self.engine + "\n") + if args[:2] == ["network", "inspect"]: + config = [{"Subnet": "172.30.0.0/16", "Gateway": g} for g in self.gateways] + net = {"Name": args[-1], "EnableIPv6": self.ipv6, "IPAM": {"Config": config}} + return _done(argv, out=json.dumps([net])) + if args[:1] == ["inspect"]: + seen = self._inspected.get(args[-1], 0) + self._inspected[args[-1]] = seen + 1 + return _done(argv, out=json.dumps(self.states[min(seen, len(self.states) - 1)])) + return _done(argv) + + def squid_spool(self, job_id: str) -> Path: + (run,) = [c for c in self.ran("run") if f"pdmcp-{RUN}-{job_id}-proxy" in c] + (mount,) = [m for m in _mounts(run) if m.endswith(",dst=/var/log/squid-bench")] + return Path(mount.removeprefix("type=bind,src=").split(",dst=")[0]) + + def ran(self, *prefix: str) -> list[list[str]]: + return [c for c in self.calls if c[1 : 1 + len(prefix)] == list(prefix)] + + +async def _verified(sandbox: Sandbox) -> dict[str, str]: + return {"image": sandbox.config.image} + + +class Probes: + def __init__(self, fail_on: str | None = None) -> None: + self.jobs: list[str] = [] + self.fail_on = fail_on + + async def __call__(self, sandbox: Sandbox, egress: Egress, **kwargs: Any) -> dict[str, Any]: + self.jobs.append(kwargs["job_id"]) + if kwargs["job_id"] == self.fail_on: + raise BenchmarkValidationError(f"isolation probe failed for {kwargs['job_id']}") + return {"passed": True} + + async def control(self, sandbox: Sandbox) -> dict[str, Any]: + self.jobs.append("control") + return {"passed": True} + + +def _config(tmp_path: Path, keys_file: Path | None = None, **overrides: Any) -> SandboxConfig: + values: dict[str, Any] = { + "image": IMAGE, + "run_id": RUN, + "out_dir": tmp_path / "run", + "index_path": tmp_path / "index.db", + "keys_file": keys_file, + "repo_commit": COMMIT, + } + return SandboxConfig(**(values | overrides)) + + +def _sandbox(tmp_path: Path, docker: FakeDocker, **config: Any) -> Sandbox: + (tmp_path / "run").mkdir(exist_ok=True) + return Sandbox(_config(tmp_path, **config), docker=docker, verify=_verified) + + +def _job(family_id: str, system_id: str = "no-docs") -> WorkerJob: + family = FAMILIES[family_id] + if family.api == "scripted": + family = replace(family, raw={**family.raw, "script": str(FIX / family.raw["script"])}) + trajectories = ({"corpus_id": "Q1", "prompt": "q", "repeat": 1},) + return WorkerJob( + f"{family_id}--{system_id}", family, SYSTEMS[system_id], trajectories, HOSTED_CAPS + ) + + +def _keys(tmp_path: Path, text: str, mode: int = 0o600) -> Path: + path = tmp_path / "keys.env" + path.write_text(text, encoding="utf-8") + path.chmod(mode) + return path + + +def _env_names(argv: Sequence[str]) -> list[str]: + return [argv[i + 1].split("=", 1)[0] for i, arg in enumerate(argv) if arg == "-e"] + + +def _mounts(argv: Sequence[str]) -> list[str]: + return [argv[i + 1] for i, arg in enumerate(argv) if arg == "--mount"] + + +@pytest.fixture +def umask_077() -> Iterator[None]: + previous = os.umask(0o077) + try: + yield + finally: + os.umask(previous) + + +# --- keys -------------------------------------------------------------------------------------- + + +def test_read_key_returns_only_the_named_key(tmp_path: Path) -> None: + text = ( + "# c\nexport OPENAI_API_KEY_OLD=x\nOPENAI_API_KEY='sk-a'\n\n" + 'export ANTHROPIC_API_KEY="sk-b"\n' + ) + path = _keys(tmp_path, text) + assert read_key(path, "OPENAI_API_KEY") == "sk-a" + assert read_key(path, "ANTHROPIC_API_KEY") == "sk-b" + + +@pytest.mark.parametrize("mode", [0o640, 0o604]) +def test_read_key_refuses_a_group_or_world_readable_file(tmp_path: Path, mode: int) -> None: + path = _keys(tmp_path, "OPENAI_API_KEY=sk-secret-value\n", mode) + with pytest.raises(BenchmarkValidationError, match="OPENAI_API_KEY") as caught: + read_key(path, "OPENAI_API_KEY") + assert str(path) in str(caught.value) and "sk-secret-value" not in str(caught.value) + + +@pytest.mark.parametrize("name", ["GOOGLE_API_KEY", "ANTHROPIC_API_KEY"]) +def test_read_key_errors_never_hold_a_value(tmp_path: Path, name: str) -> None: + path = _keys(tmp_path, "OPENAI_API_KEY=sk-secret-value\nANTHROPIC_API_KEY=\n") + with pytest.raises(BenchmarkValidationError, match=name) as caught: + read_key(path, name) + assert str(path) in str(caught.value) and "sk-secret-value" not in str(caught.value) + with pytest.raises(BenchmarkValidationError, match=name): + read_key(tmp_path / "missing.env", name) + + +# --- the worker container ---------------------------------------------------------------------- + + +def test_worker_argv_carries_the_design_hardening(tmp_path: Path) -> None: + launcher = ContainerLauncher( + _sandbox(tmp_path, FakeDocker()), probe=(probes := Probes()), control=probes.control + ) + argv = launcher.worker_create_argv(_job("scripted-anthropic")) + text = " ".join(argv) + for flag in ( + "--read-only", + "--cap-drop ALL", + "--security-opt no-new-privileges", + "--user 10001:10001", + "--init", + "--rm", + "--pull never", + "--log-driver none", + f"--network pdmcp-{RUN}-scripted-anthropic--no-docs-net", + "--memory 1g", + "--cpus 1", + "--pids-limit 256", + "--tmpfs /tmp", + f"--label {RUN_LABEL}={RUN}", + f"--name pdmcp-{RUN}-scripted-anthropic--no-docs", + ): + assert flag in text + assert "-i" in argv and "-t" not in argv and "-it" not in argv + for banned in ("--privileged", "docker.sock", "--network host", "--network=host"): + assert banned not in text + assert argv[argv.index(IMAGE) + 1 :] == ["python", "-m", "benchmarks", "agentic-worker"] + assert argv[:2] == ["docker", "create"] + + +def test_only_python_docs_jobs_mount_the_index_read_only(tmp_path: Path) -> None: + launcher = ContainerLauncher( + _sandbox(tmp_path, FakeDocker()), probe=(probes := Probes()), control=probes.control + ) + index = f"type=bind,src={tmp_path / 'index.db'},dst=/cache/mcp-python-docs/index.db,readonly" + for system_id, mounted in (("python-docs", True), ("docs-fetch", False), ("no-docs", False)): + mounts = _mounts(launcher.worker_create_argv(_job("claude-sonnet-5-5", system_id))) + assert (index in mounts) is mounted + assert "type=tmpfs,dst=/cache/mcp-python-docs,tmpfs-mode=1777" in mounts + script = str(FIX / "script-anthropic.yml") + mounts = _mounts(launcher.worker_create_argv(_job("scripted-anthropic"))) + assert f"type=bind,src={script},dst={script},readonly" in mounts + + +async def test_worker_env_is_the_allowlist(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: + for name in ("HTTPS_PROXY", "ALL_PROXY", "SSL_CERT_FILE", "REQUESTS_CA_BUNDLE", "LANG"): + monkeypatch.setenv(name, "http://user:secret@proxy.invalid:1") + monkeypatch.setenv("DOCKER_CONTEXT", "desktop-linux") + allowed = { + "HOME", + "XDG_CACHE_HOME", + "PYTHON_DOCS_MCP_DISABLE_AUTO_INDEX", + "BENCHMARK_EGRESS_URL", + "BENCHMARK_LIVE_PROVIDERS_ENABLED", + "OLLAMA_BASE_URL", + } + docker = FakeDocker() + keys = _keys(tmp_path, "ANTHROPIC_API_KEY=dummy") + launcher = ContainerLauncher( + _sandbox(tmp_path, docker, keys_file=keys), + probe=(probes := Probes()), + control=probes.control, + ) + jobs = [_job(family) for family in ("scripted-anthropic", "claude-sonnet-5-5", "gemma4-12b")] + await launcher.prepare(jobs) + for job in jobs: + (argv,) = [c for c in docker.ran("create") if launcher.sandbox.worker_name(job.job_id) in c] + _, env = launcher.command(job) + assert set(_env_names(argv)) <= allowed + assert set(env) <= { + "PATH", + "HOME", + "DOCKER_HOST", + "DOCKER_CONTEXT", + "DOCKER_CONFIG", + "DOCKER_CERT_PATH", + "DOCKER_TLS_VERIFY", + } + assert env["DOCKER_CONTEXT"] == "desktop-linux" + gemma = launcher.worker_create_argv(_job("gemma4-12b")) + assert "OLLAMA_BASE_URL=http://host.docker.internal:11434/v1" in gemma + assert "BENCHMARK_LIVE_PROVIDERS_ENABLED=1" in gemma + scripted = launcher.worker_create_argv(_job("scripted-anthropic")) + assert "BENCHMARK_LIVE_PROVIDERS_ENABLED=1" not in scripted + assert "BENCHMARK_EGRESS_URL=http://egress:3128" in scripted + await launcher.close() + + +async def test_no_key_in_argv_cli_env_or_container_config( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + for name in PROVIDER_API_KEY_ENV.values(): + monkeypatch.delenv(name, raising=False) + keys = _keys(tmp_path, f"ANTHROPIC_API_KEY={SYNTHETIC}\n") + docker = FakeDocker() + sandbox = _sandbox(tmp_path, docker, keys_file=keys) + launcher = ContainerLauncher(sandbox, probe=(probes := Probes()), control=probes.control) + job = _job("claude-sonnet-5-5", "python-docs") + sandbox.config.index_path.touch() + await launcher.prepare([job]) + argv, env = launcher.command(job) + recorded = json.dumps({"calls": docker.calls, "argv": argv, "env": env, "cli": sandbox.env}) + assert SYNTHETIC not in recorded and "ANTHROPIC_API_KEY" not in recorded + assert launcher.bootstrap_frame(job) == { + "type": "bootstrap", + "env": {"ANTHROPIC_API_KEY": SYNTHETIC}, + } + assert "ANTHROPIC_API_KEY" not in os.environ + await launcher.close() + + +def test_each_live_bootstrap_holds_only_its_own_providers_key(tmp_path: Path) -> None: + keys = _keys(tmp_path, "ANTHROPIC_API_KEY=sk-a\nOPENAI_API_KEY=sk-o\nGOOGLE_API_KEY=g-k\n") + launcher = ContainerLauncher( + _sandbox(tmp_path, FakeDocker(), keys_file=keys), + probe=(probes := Probes()), + control=probes.control, + ) + assert launcher.bootstrap_frame(_job("gpt-6.1-sol")) == { + "type": "bootstrap", + "env": {"OPENAI_API_KEY": "sk-o"}, + } + assert launcher.bootstrap_frame(_job("gemini-3.8-flash"))["env"] == {"GOOGLE_API_KEY": "g-k"} # type: ignore[index] + assert launcher.bootstrap_frame(_job("gemma4-12b")) == {"type": "bootstrap", "env": {}} + assert launcher.bootstrap_frame(_job("scripted-anthropic")) is None + + +def test_a_live_family_without_a_keys_file_is_refused(tmp_path: Path) -> None: + launcher = ContainerLauncher( + _sandbox(tmp_path, FakeDocker()), probe=(probes := Probes()), control=probes.control + ) + with pytest.raises(BenchmarkValidationError, match="keys file"): + launcher.bootstrap_frame(_job("claude-sonnet-5-5")) + + +# --- networks and proxies ---------------------------------------------------------------------- + + +async def test_internal_networks_are_ipv4_only_with_an_isolated_gateway(tmp_path: Path) -> None: + docker = FakeDocker(gateways=("172.30.0.1", "fd00::1")) + sandbox = _sandbox(tmp_path, docker) + egress = await sandbox.open_egress("j", (("api.anthropic.com", 443),)) + net = f"pdmcp-{RUN}-j-net" + (create,) = [c for c in docker.ran("network", "create") if c[-1] == net] + text = " ".join(create) + assert "--internal --ipv6=false -o com.docker.network.bridge.gateway_mode_ipv4=isolated" in text + assert f"--label {RUN_LABEL}={RUN}" in text + assert egress.gateways == ("172.30.0.1", "fd00::1") and egress.network == net + assert egress.inspect["EnableIPv6"] is False + docker = FakeDocker(ipv6=True) + (tmp_path / "v6").mkdir() + sandbox = _sandbox(tmp_path / "v6", docker) + with pytest.raises(BenchmarkValidationError, match=net): + await sandbox.open_egress("j", ()) + assert docker.ran("network", "rm", f"id-{net}") + assert not docker.ran("run") and not docker.ran("network", "connect") + + +class LateCreate(FakeDocker): + """The daemon finishes creating the resource even if the CLI awaiter is cancelled.""" + + def __init__(self, name: str) -> None: + super().__init__() + self.name = name + self.started = asyncio.Event() + self.release = asyncio.Event() + self.published = asyncio.Event() + + async def __call__(self, argv: Sequence[str]) -> Any: + if self.name in argv and ("create" in argv or "run" in argv): + return await asyncio.shield(asyncio.create_task(self._publish(argv))) + return await super().__call__(argv) + + async def _publish(self, argv: Sequence[str]) -> Any: + self.started.set() + await self.release.wait() + result = await super().__call__(argv) + self.published.set() + return result + + async def cancel_create(self, task: asyncio.Task[Any]) -> None: + await asyncio.wait_for(self.started.wait(), 2) + task.cancel() + await asyncio.sleep(0) + task.cancel() + await asyncio.sleep(0) + self.release.set() + with pytest.raises(asyncio.CancelledError): + await task + await asyncio.wait_for(self.published.wait(), 2) + + +async def test_worker_published_after_interrupt_is_removed_by_id(tmp_path: Path) -> None: + job = _job("scripted-anthropic") + name = f"pdmcp-{RUN}-{job.job_id}" + docker = LateCreate(name) + probes = Probes() + launcher = ContainerLauncher(_sandbox(tmp_path, docker), probes, probes.control) + + async def launch() -> None: + try: + await launcher.prepare([job]) + try: + await docker(launcher.command(job)[0]) + finally: + await launcher.stop_worker(job) + finally: + await launcher.close() + + await docker.cancel_create(asyncio.create_task(launch())) + assert not docker.resources + assert docker.ran("rm", "-f", f"id-{name}") + assert not docker.ran("start") + + +async def test_workers_attach_and_stop_independently_after_prepare(tmp_path: Path) -> None: + docker, probes = FakeDocker(), Probes() + launcher = ContainerLauncher(_sandbox(tmp_path, docker), probes, probes.control) + jobs = [_job("scripted-anthropic"), _job("scripted-anthropic", "docs-fetch")] + await launcher.prepare(jobs) + assert not docker.ran("start") + for job in jobs: + name = f"pdmcp-{RUN}-{job.job_id}" + (create,) = [c for c in docker.ran("create") if name in c] + assert "-i" in create and "-t" not in create + assert launcher.command(job)[0] == ["docker", "start", "-ai", f"id-{name}"] + await launcher.stop_worker(jobs[1]) + first, second = (f"id-pdmcp-{RUN}-{job.job_id}" for job in jobs) + assert second not in docker.resources and first in docker.resources + await launcher.close() # the first worker never started + assert not docker.resources + + +async def test_worker_conflict_after_partial_prepare_precedes_key_reads( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + jobs = [_job("scripted-anthropic"), _job("claude-sonnet-5-5")] + name = f"pdmcp-{RUN}-{jobs[1].job_id}" + docker = FakeDocker(fail=lambda args: name in args and args[0] in {"create", "run"}) + foreign = {f"id-{name}": {f"{RUN_LABEL}={RUN}"}} + docker.resources.update(foreign) + probes = Probes() + box = _sandbox(tmp_path, docker, keys_file=tmp_path / "unused") + launcher = ContainerLauncher(box, probes, probes.control) + + def premature_read(*args: Any) -> str: + pytest.fail("the worker create conflict must be detected before reading keys") + + monkeypatch.setattr("benchmarks.agentic.sandbox.read_key", premature_read) + try: + with pytest.raises(BenchmarkValidationError, match="boom"): + await launcher.prepare(jobs) + finally: + await launcher.close() + assert probes.jobs == ["control", *(job.job_id for job in jobs)] + assert docker.resources == foreign + assert docker.ran("rm", "-f", f"id-{box.worker_name(jobs[0].job_id)}") + assert not [c for c in docker.calls if "rm" in c and c[-1] in {name, f"id-{name}"}] + assert not docker.ran("start") + + +async def test_keyless_direct_probe_preserves_conflicting_container(tmp_path: Path) -> None: + from tests.benchmarks.test_agentic_sandbox_docker import _probe_container + + name = f"pdmcp-{RUN}-direct-probe" + docker = FakeDocker(fail=lambda args: name in args and args[0] in {"run", "create"}) + foreign = {f"id-{name}": {f"{RUN_LABEL}={RUN}"}} + docker.resources.update(foreign) + box = _sandbox(tmp_path, docker) + with pytest.raises(BenchmarkValidationError, match="boom"): + await _probe_container(box, "net", {}) + assert not docker.ran("rm") + assert docker.resources == foreign + + +def test_keyless_fixture_cleans_its_outside_network_by_id( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + from tests.benchmarks import test_agentic_sandbox_docker as keyless + + monkeypatch.setattr(keyless, "_sandbox_config", _config) + fixture = keyless.sandbox.__wrapped__(tmp_path) + box = next(fixture) + box.docker = docker = FakeDocker() + asyncio.run(box.ensure_outside()) + assert box.outside_id is not None + owned = box.outside_id + # A replacement can acquire the same name between creation and fixture teardown. + del docker.resources[owned] + docker.resources[box.outside] = {"foreign"} + with pytest.raises(StopIteration): + next(fixture) + assert docker.ran("network", "rm", owned) + assert docker.resources == {box.outside: {"foreign"}} + + +@pytest.mark.parametrize("resource", ["out", "j-net", "j-proxy"]) +async def test_cancel_waits_for_docker_to_publish_the_created_resource( + tmp_path: Path, resource: str +) -> None: + name = f"pdmcp-{RUN}-{resource}" + docker = LateCreate(name) + sandbox = _sandbox(tmp_path, docker) + await docker.cancel_create(asyncio.create_task(sandbox.open_egress("j", ()))) + await ContainerLauncher(sandbox).close() + assert docker.resources == {} + assert any("rm" in argv and argv[-1] == f"id-{name}" for argv in docker.calls) + + +@pytest.mark.parametrize("resource", ["out", "j-net", "j-proxy"]) +async def test_create_conflict_never_removes_the_existing_resource( + tmp_path: Path, resource: str +) -> None: + name = f"pdmcp-{RUN}-{resource}" + docker = FakeDocker(fail=lambda args: name in args and ("create" in args or "run" in args)) + foreign_id = f"id-{name}" + docker.resources[foreign_id] = {f"{RUN_LABEL}={RUN}"} + sandbox = _sandbox(tmp_path, docker) + with pytest.raises(BenchmarkValidationError, match="boom"): + await sandbox.open_egress("j", ()) + await ContainerLauncher(sandbox).close() + assert docker.resources == {foreign_id: {f"{RUN_LABEL}={RUN}"}} + assert not [c for c in docker.calls if "rm" in c and c[-1] in {name, foreign_id}] + + +async def test_cancelled_create_that_hits_a_conflict_preserves_cancellation(tmp_path: Path) -> None: + name = f"pdmcp-{RUN}-out" + docker = LateCreate(name) + docker.fail = lambda args: args[:2] == ["network", "create"] + sandbox = _sandbox(tmp_path, docker) + await docker.cancel_create(asyncio.create_task(sandbox.ensure_outside())) + assert not docker.ran("network", "rm") + + +async def test_timed_out_create_can_appear_after_the_docker_cli_exits(tmp_path: Path) -> None: + name = f"pdmcp-{RUN}-out" + + class TimeoutDocker(FakeDocker): + pending: Sequence[str] = () + + async def __call__(self, argv: Sequence[str]) -> Any: + if argv[1:3] == ["network", "create"]: + self.pending = argv + raise subprocess.TimeoutExpired(argv, 120) + result = await super().__call__(argv) + if self.pending and argv[1:3] == ["network", "ls"]: + # The first list snapshots an empty daemon, then the original POST lands. + await super().__call__(self.pending) + self.pending = () + return result + + docker = TimeoutDocker() + sandbox = _sandbox(tmp_path, docker) + with pytest.raises(subprocess.TimeoutExpired): + await sandbox.ensure_outside() + assert docker.ran("network", "rm", f"id-{name}") + assert not docker.resources + + +async def test_unobserved_create_timeout_reports_the_ownership_label( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + monkeypatch.setattr("benchmarks.agentic.sandbox._RESOURCE_RECOVERY_S", 0) + + class TimeoutDocker(FakeDocker): + async def __call__(self, argv: Sequence[str]) -> Any: + if argv[1:3] == ["network", "create"]: + raise subprocess.TimeoutExpired(argv, 120) + return await super().__call__(argv) + + docker = TimeoutDocker() + with pytest.raises(BenchmarkValidationError, match="outcome is unknown") as caught: + await _sandbox(tmp_path, docker).ensure_outside() + assert docker.ran("network", "ls")[0][-1] in str(caught.value) + assert not docker.ran("network", "rm") + + +async def test_a_failed_proxy_start_removes_the_proxy_and_the_network(tmp_path: Path) -> None: + for step in (["run"], ["network", "connect"]): + root = tmp_path / step[-1] + root.mkdir() + + class FailedStart(FakeDocker): + async def __call__(self, argv: Sequence[str]) -> Any: + result = await super().__call__(argv) + if list(argv[1 : 1 + len(step)]) == step: + # docker run -d can fail its start after the daemon created the proxy. + return _done(argv, 1, err="cannot start or connect") + return result + + docker = FailedStart() + with pytest.raises(BenchmarkValidationError): + await _sandbox(root, docker).open_egress("j", (("api.openai.com", 443),)) + assert not docker.squid_spool("j").parent.exists() + assert docker.ran("rm", "-f", f"id-pdmcp-{RUN}-j-proxy") + assert docker.ran("network", "rm", f"id-pdmcp-{RUN}-j-net") + + +async def test_prepare_builds_one_network_and_proxy_per_job_with_a_file_log( + tmp_path: Path, umask_077: None +) -> None: + docker = FakeDocker() + probes = Probes() + keys = _keys(tmp_path, "ANTHROPIC_API_KEY=dummy") + launcher = ContainerLauncher( + _sandbox(tmp_path, docker, keys_file=keys), probe=probes, control=probes.control + ) + jobs = [_job("claude-sonnet-5-5", "docs-fetch"), _job("scripted-anthropic", "no-docs")] + await launcher.prepare(jobs) + outside = f"pdmcp-{RUN}-out" + assert [c for c in docker.ran("network", "create") if c[-1] == outside] != [] + assert len([c for c in docker.ran("network", "create") if c[-1] == outside]) == 1 + runs = docker.ran("run") + assert len(runs) == 2 and all(SQUID_IMAGE in run for run in runs) + assert len(docker.ran("network", "connect", "--alias", "egress")) == 2 + for job in jobs: + log_dir = tmp_path / "run" / "egress" / job.job_id + conf = (log_dir / "squid.conf").read_text() + assert conf == squid_conf(allowlist(job.family, job.system.id)) + spool = docker.squid_spool(job.job_id) + assert not spool.is_relative_to(tmp_path / "run") + assert spool.stat().st_mode & 0o777 == 0o777 + assert spool.parent.stat().st_mode & 0o777 == 0o700 + assert log_dir.stat().st_mode & 0o022 == 0 + assert (log_dir / "squid.conf").stat().st_mode & 0o777 == 0o644 + (run,) = [r for r in runs if f"pdmcp-{RUN}-{job.job_id}-proxy" in r] + text = " ".join(run) + assert f"type=bind,src={log_dir}/squid.conf,dst=/etc/squid/squid.conf,readonly" in text + assert f"type=bind,src={spool},dst=/var/log/squid-bench" in text + for flag in ("--read-only", "--cap-drop ALL", "--user proxy", "--pull never", "-d"): + assert flag in text + assert run[-3:] == ["-N", "-f", "/etc/squid/squid.conf"] + assert probes.jobs == ["control", *[job.job_id for job in jobs]] + await launcher.close() + + +def _git_repo(path: Path) -> Path: + path.mkdir() + subprocess.run(["git", "init", "-q", str(path)], check=True, capture_output=True) + return path + + +def _real(tmp_path: Path, docker: FakeDocker, repo: Path) -> Sandbox: + async def verify(sandbox: Sandbox) -> dict[str, str]: + return await verify_image(sandbox, repo_root=repo) + + (tmp_path / "run").mkdir(exist_ok=True) + return Sandbox(_config(tmp_path), docker=docker, verify=verify) + + +async def test_the_real_check_passes_and_records_the_sandbox(tmp_path: Path) -> None: + docker = FakeDocker() + sandbox = _real(tmp_path, docker, _git_repo(tmp_path / "repo")) + record = await sandbox.verify(sandbox) + written = json.loads((tmp_path / "run" / "sandbox.json").read_text()) + assert written == record + assert record["image"] == IMAGE and record["revision"] == COMMIT + assert record["engine_version"] == "29.9.2" and record["docker_context"] == "desktop-linux" + assert record["proxy_image"] == SQUID_IMAGE + assert docker.ran("image", "inspect", "--format", "{{json .}}", SQUID_IMAGE) + + +@pytest.mark.parametrize("scheme", ["unix://", "tcp://"]) +async def test_sandbox_metadata_refuses_a_key_in_a_daemon_endpoint( + tmp_path: Path, scheme: str +) -> None: + key = "AIza" + "Q" * 35 + sandbox = _real( + tmp_path, FakeDocker(context_host=f"{scheme}/daemon\n{key}"), _git_repo(tmp_path / "repo") + ) + with pytest.raises(KeyLeakError) as error: + await sandbox.verify(sandbox) + assert not (tmp_path / "run" / "sandbox.json").exists() + assert key not in "".join(traceback.format_exception(error.value)) + + +async def test_prepare_refuses_a_daemon_that_is_not_local( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + repo = _git_repo(tmp_path / "repo") + remote = FakeDocker(context_host="tcp://10.0.0.5:2376") + launcher = ContainerLauncher( + _real(tmp_path, remote, repo), probe=(probes := Probes()), control=probes.control + ) + with pytest.raises(BenchmarkValidationError, match="unix://"): + await launcher.prepare([_job("scripted-anthropic")]) + monkeypatch.setenv("DOCKER_HOST", "tcp://10.0.0.5:2376") + local = FakeDocker() + launcher = ContainerLauncher( + _real(tmp_path, local, repo), probe=(probes := Probes()), control=probes.control + ) + with pytest.raises(BenchmarkValidationError, match="DOCKER_HOST"): + await launcher.prepare([_job("scripted-anthropic")]) + for docker in (remote, local): + assert not docker.ran("run") and not docker.ran("network", "create") + assert not docker.ran("image", "inspect") + + +async def test_the_real_check_refuses_a_dirty_tree(tmp_path: Path) -> None: + repo = _git_repo(tmp_path / "repo") + # Amendment 1: a config that hides untracked files cannot hide them from the check. + subprocess.run( + ["git", "-C", str(repo), "config", "status.showUntrackedFiles", "no"], check=True + ) + (repo / "untracked.txt").write_text("x", encoding="utf-8") + sandbox = _real(tmp_path, FakeDocker(), repo) + with pytest.raises(BenchmarkValidationError, match="dirty"): + await sandbox.verify(sandbox) + + +async def test_prepare_refuses_an_image_from_another_commit(tmp_path: Path) -> None: + docker = FakeDocker(revision="d" * 40) + probes = Probes() + launcher = ContainerLauncher( + _real(tmp_path, docker, _git_repo(tmp_path / "r")), probes, probes.control + ) + with pytest.raises(BenchmarkValidationError, match="d" * 40): + await launcher.prepare([_job("scripted-anthropic")]) + assert not docker.ran("run") + other = FakeDocker(image_id="sha256:" + "e" * 64) + sandbox = _real(tmp_path, other, _git_repo(tmp_path / "r2")) + with pytest.raises(BenchmarkValidationError, match="sha256:e"): + await sandbox.verify(sandbox) + + +async def test_prepare_refuses_a_missing_proxy_image(tmp_path: Path) -> None: + docker = FakeDocker(squid_present=False) + sandbox = _real(tmp_path, docker, _git_repo(tmp_path / "repo")) + with pytest.raises(BenchmarkValidationError, match="ubuntu/squid"): + await sandbox.verify(sandbox) + + +async def test_prepare_refuses_an_engine_older_than_28(tmp_path: Path) -> None: + docker = FakeDocker(engine="27.5.1") + sandbox = _real(tmp_path, docker, _git_repo(tmp_path / "repo")) + with pytest.raises(BenchmarkValidationError, match="27.5.1"): + await sandbox.verify(sandbox) + + +def test_sandbox_config_refuses_a_tag(tmp_path: Path) -> None: + with pytest.raises(BenchmarkValidationError, match="python-docs:latest"): + _config(tmp_path, image="python-docs:latest") + + +async def test_stop_worker_removes_only_its_own_container(tmp_path: Path) -> None: + docker = FakeDocker() + launcher = ContainerLauncher( + _sandbox(tmp_path, docker), probe=(probes := Probes()), control=probes.control + ) + job = _job("scripted-anthropic") + name = launcher.sandbox.worker_name(job.job_id) + # Even the same run ID from an earlier invocation is not ours. + other = ContainerLauncher(_sandbox(tmp_path, docker)) + foreign_id = await other.sandbox.create_resource(name, *other.worker_create_argv(job)[1:]) + await launcher.stop_worker(job) + assert not docker.ran("rm") + await other.sandbox.remove_container(foreign_id) + initial_removals = len(docker.ran("rm")) + + second = _job("scripted-anthropic", "docs-fetch") + await launcher.prepare([job, second]) + await launcher.stop_worker(job) + assert docker.ran("rm", "-f", f"id-{name}") + assert f"id-{name}" not in docker.resources + await launcher.stop_worker(job) # repeated teardown has nothing left to remove + assert len(docker.ran("rm")) == initial_removals + 1 + + docker.fail = lambda args: args[:2] == ["rm", "-f"] + with pytest.raises(BenchmarkValidationError, match="boom"): + await launcher.stop_worker(second) + docker.fail = None + await launcher.close() # retry the failed remove before closing the networks + assert not docker.resources + + +# --- collection and close ---------------------------------------------------------------------- + +PROBE_PREFIX = ( + "2026-11-04T10:00:00.001Z 172.30.0.2 CONNECT example.com 443 403 TCP_DENIED\n" + "2026-11-04T10:00:00.002Z 172.30.0.2 GET 192.168.65.254 50000 403 TCP_DENIED\n" +) +PARTIAL = PROBE_PREFIX + ( + "2026-11-04T10:00:01.000Z 172.30.0.3 CONNECT api.anthropic.com 443 200 TCP_TUNNEL\n" +) + + +async def _opened(tmp_path: Path, docker: FakeDocker, job_id: str = "j") -> tuple[Sandbox, Egress]: + sandbox = _sandbox(tmp_path, docker) + egress = await sandbox.open_egress(job_id, (("api.anthropic.com", 443),)) + _logs(docker.squid_spool(job_id)) + return sandbox, egress + + +def _logs(log_dir: Path, access: str = PARTIAL, cache: str = "squid started\n") -> None: + """The two files a running Squid writes into its bind-mounted log directory.""" + (log_dir / "access.log").write_text(access, encoding="utf-8") + (log_dir / "cache.log").write_text(cache, encoding="utf-8") + + +async def test_network_remove_failure_names_the_owned_id_and_scrubs_daemon_stderr( + tmp_path: Path, +) -> None: + sandbox = _sandbox(tmp_path, FakeDocker()) + await sandbox.ensure_outside() + owned = sandbox.outside_id + assert owned is not None + + async def disconnected(argv: Sequence[str]) -> Any: + return _done(argv, 1, err=f"daemon disconnected: {SYNTHETIC}") + + sandbox.docker = disconnected + problems = await ContainerLauncher(sandbox).close() + assert len(problems) == 1 + assert owned in problems[0] and "daemon disconnected: [redacted]" in problems[0] + assert SYNTHETIC not in problems[0] + + +@pytest.mark.parametrize("cli_raises", [False, True]) +async def test_removal_diagnostic_cannot_expose_an_adjacent_key( + tmp_path: Path, cli_raises: bool +) -> None: + sandbox = _sandbox(tmp_path, FakeDocker()) + google = "AIza" + "g" * 35 + + async def disconnected(argv: Sequence[str]) -> Any: + detail = f"unavailable: {google}{SYNTHETIC}" + if cli_raises: + raise OSError(detail) + return _done(argv, 1, err=detail) + + sandbox.docker = disconnected + owned = "b" * 64 + with pytest.raises(BenchmarkValidationError, match=owned) as error: + await sandbox.run("network", "rm", owned) + trace = "".join(traceback.format_exception(error.value)) + assert SYNTHETIC not in trace and google not in trace + + +@pytest.mark.parametrize("kind", ["container", "network"]) +async def test_remove_cli_start_failure_identifies_owned_resource_and_scrubs_error( + tmp_path: Path, kind: str +) -> None: + sandbox = _sandbox(tmp_path, FakeDocker()) + owned = "a" * 64 + + async def unavailable(argv: Sequence[str]) -> Any: + raise OSError(f"cannot start CLI: {SYNTHETIC}") + + sandbox.docker = unavailable + with pytest.raises(BenchmarkValidationError, match=owned) as error: + if kind == "container": + await sandbox.remove_container(owned) + else: + await sandbox.run("network", "rm", owned) + trace = "".join(traceback.format_exception(error.value)) + assert SYNTHETIC not in trace and "cannot start CLI: [redacted]" in trace + + +async def test_close_stops_each_proxy_then_removes_what_it_created(tmp_path: Path) -> None: + docker = FakeDocker() + keys = _keys(tmp_path, "ANTHROPIC_API_KEY=dummy") + launcher = ContainerLauncher( + _sandbox(tmp_path, docker, keys_file=keys), + probe=(probes := Probes()), + control=probes.control, + ) + jobs = [_job("claude-sonnet-5-5", "no-docs"), _job("scripted-anthropic", "no-docs")] + await launcher.prepare(jobs) + for job in jobs: + _logs(docker.squid_spool(job.job_id)) + start = len(docker.calls) + problems = await launcher.close() + assert problems == [] + tail = [" ".join(c[1:3]) + " " + c[-1] for c in docker.calls[start:]] + expected = [f"rm -f id-pdmcp-{RUN}-{job.job_id}" for job in jobs] + for job in jobs: + proxy, net = f"pdmcp-{RUN}-{job.job_id}-proxy", f"pdmcp-{RUN}-{job.job_id}-net" + expected += [ + f"inspect --format id-{proxy}", + f"stop -t id-{proxy}", + f"inspect --format id-{proxy}", + f"rm -f id-{proxy}", + f"network rm id-{net}", + ] + collected = json.loads( + (tmp_path / "run" / "egress" / job.job_id / "collected.json").read_text() + ) + assert collected == { + "ok": True, + "problems": [], + "state_before_stop": RUNNING, + "state_after_stop": STOPPED, + } + assert tail == [*expected, f"network rm id-pdmcp-{RUN}-out"] + assert docker.ran("stop", "-t", "5") + + +@pytest.mark.parametrize( + "before,after,named", + [ + ( + {"Running": False, "ExitCode": 137, "OOMKilled": False}, + {"Running": False, "ExitCode": 137, "OOMKilled": False}, + "137", + ), + ( + {"Running": True, "ExitCode": 0, "OOMKilled": True}, + {"Running": False, "ExitCode": 0, "OOMKilled": True}, + "OOMKilled", + ), + (RUNNING, {"Running": False, "ExitCode": 137, "OOMKilled": False}, "137"), + (RUNNING, {"Running": True, "ExitCode": 0, "OOMKilled": False}, "running"), + ], +) +async def test_an_abnormal_proxy_exit_fails_the_collection( + tmp_path: Path, before: dict[str, Any], after: dict[str, Any], named: str +) -> None: + # Every cleanup command succeeds and the log is well formed but may be partial. The third + # case is a forced kill after our own stop (round-4 item 1); the fourth a proxy that is + # still running after it (amendment 7). + sandbox, egress = await _opened(tmp_path, FakeDocker(states=(before, after))) + problems = await sandbox.close_egress(egress) + collected = json.loads((egress.log_dir / "collected.json").read_text()) + assert collected["ok"] is False and problems == collected["problems"] != [] + assert any(named in problem for problem in problems) + assert (collected["state_before_stop"], collected["state_after_stop"]) == (before, after) + + +@pytest.mark.parametrize( + "line,key", + [ + (f"WARNING: header {SYNTHETIC}\n", SYNTHETIC), + (json.dumps({"error": "bad\n" + "AIza" + "g" * 35}) + "\n", "AIza" + "g" * 35), + (json.dumps({"error": repr(b"\x00" + b"AIza" + b"g" * 35)}) + "\n", "AIza" + "g" * 35), + ], + ids=["plain", "structured", "bytes-repr"], +) +async def test_close_redacts_a_key_shaped_proxy_log_and_raises_after_cleanup( + tmp_path: Path, line: str, key: str +) -> None: + docker = FakeDocker() + launcher = ContainerLauncher( + _sandbox(tmp_path, docker), probe=(probes := Probes()), control=probes.control + ) + job = _job("scripted-anthropic") + await launcher.prepare([job]) + log_dir = tmp_path / "run" / "egress" / job.job_id + _logs(docker.squid_spool(job.job_id), cache=line) + with pytest.raises(KeyLeakError, match="cache.log"): + await launcher.close() + assert (log_dir / "cache.log").read_bytes() == line.replace(key, "[redacted]").encode() + assert docker.ran("rm", "-f", f"id-pdmcp-{RUN}-{job.job_id}-proxy") + assert docker.ran("network", "rm", f"id-pdmcp-{RUN}-out") + assert json.loads((log_dir / "collected.json").read_text())["ok"] is False + assert (tmp_path / "run/probe" / f"{job.job_id}.collection-pending").is_file() + + +@pytest.mark.parametrize("failure", [MemoryError, PermissionError]) +async def test_a_failed_private_read_cannot_publish_or_certify_a_log( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, failure: type[Exception] +) -> None: + from benchmarks.agentic import sandbox as module + + job = _job("scripted-anthropic") + sandbox, egress = await _opened(tmp_path, FakeDocker(), job.job_id) + (egress.spool_dir / "cache.log").write_text(SYNTHETIC) + read = module.read_log + + def unreadable(path: Path) -> bytes: + if path.name == "cache.log": + raise failure("cannot read private log") + return read(path) + + monkeypatch.setattr(module, "read_log", unreadable) + problems = await sandbox.close_egress(egress) + assert problems and not sandbox.leaks + assert not egress.spool_dir.parent.exists() + assert not (egress.log_dir / "cache.log").exists() + assert (egress.log_dir / "access.log").read_text() == PARTIAL + assert json.loads((egress.log_dir / "collected.json").read_text())["ok"] is False + out = sandbox.config.out_dir + assert (out / "probe" / f"{job.job_id}.collection-pending").is_file() + assert write_egress_summary(out, [job], [])["isolation_probe"] == "fail" + + +async def test_scan_memory_error_leaves_only_complete_scanned_files( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + from benchmarks.agentic import sandbox as module + + sandbox, egress = await _opened(tmp_path, FakeDocker()) + (egress.spool_dir / "cache.log").write_text(SYNTHETIC) + scrub = module.redact_key_shaped + + def exhausted(data: bytes) -> tuple[bytes, str | None]: + if data == SYNTHETIC.encode(): + raise MemoryError("cannot scan") + return scrub(data) + + monkeypatch.setattr(module, "redact_key_shaped", exhausted) + assert await sandbox.close_egress(egress) + assert not (egress.log_dir / "cache.log").exists() + assert (egress.log_dir / "access.log").read_text() == PARTIAL + assert (sandbox.config.out_dir / "probe/j.collection-pending").is_file() + assert not egress.spool_dir.parent.exists() + + +async def test_a_linked_spool_is_neither_collected_nor_cleaned_through(tmp_path: Path) -> None: + sandbox, egress = await _opened(tmp_path, FakeDocker()) + elsewhere = tmp_path / "elsewhere" + elsewhere.mkdir() + _logs(elsewhere, cache=SYNTHETIC) + egress.spool_dir.rename(egress.spool_dir.with_name("moved")) + egress.spool_dir.symlink_to(elsewhere, target_is_directory=True) + problems = await sandbox.close_egress(egress) + assert any("link" in problem for problem in problems) + assert not sandbox.leaks and not egress.spool_dir.parent.exists() + assert (elsewhere / "cache.log").read_text() == SYNTHETIC + assert not (egress.log_dir / "cache.log").exists() + assert not (egress.log_dir / "access.log").exists() + assert json.loads((egress.log_dir / "collected.json").read_text())["ok"] is False + + +async def test_only_intended_regular_files_leave_the_spool(tmp_path: Path) -> None: + sandbox, egress = await _opened(tmp_path, FakeDocker()) + canary = _canary(tmp_path) + (egress.spool_dir / "collected.json").symlink_to(canary) + (egress.spool_dir / "squid.conf").write_text(SYNTHETIC) + (egress.spool_dir / "unexpected").write_text(SYNTHETIC) + assert await sandbox.close_egress(egress) == [] + assert not egress.spool_dir.parent.exists() + assert {p.name for p in egress.log_dir.iterdir()} == { + "cache.log", + "access.log", + "squid.conf", + "collected.json", + } + assert canary.read_text() == f"host secret {SYNTHETIC}\n" + assert all(SYNTHETIC.encode() not in p.read_bytes() for p in egress.log_dir.iterdir()) + + +async def test_close_keeps_going_after_a_failed_step(tmp_path: Path) -> None: + docker = FakeDocker(fail=lambda args: args[:1] == ["stop"]) + sandbox, egress = await _opened(tmp_path, docker) + problems = await sandbox.close_egress(egress) + assert problems and any("stop" in p for p in problems) + assert docker.ran("rm", "-f", egress.proxy_id) + assert docker.ran("network", "rm", egress.network_id) + assert json.loads((egress.log_dir / "collected.json").read_text())["ok"] is False + + +def test_container_launcher_supports_scripted_and_every_live_api(tmp_path: Path) -> None: + launcher = ContainerLauncher( + _sandbox(tmp_path, FakeDocker()), probe=(probes := Probes()), control=probes.control + ) + assert all(launcher.supports(family) for family in FAMILIES.values()) + + +def test_cli_env_is_the_docker_allowlist() -> None: + environ = { + "PATH": "/bin", + "HOME": "/h", + "DOCKER_HOST": "unix:///x.sock", + "ANTHROPIC_API_KEY": "not-a-real-key", + "HTTPS_PROXY": "http://x:1", + "LANG": "C", + } + assert cli_env(environ) == {"PATH": "/bin", "HOME": "/h", "DOCKER_HOST": "unix:///x.sock"} + + +def test_the_sandbox_module_loads_no_provider_sdk() -> None: + # run.sh imports SQUID_IMAGE from it on the host. + code = ( + "import sys\n" + "import benchmarks.agentic.sandbox\n" + "print(sorted(m for m in ('anthropic', 'openai', 'google.genai') if m in sys.modules))\n" + ) + proc = subprocess.run( + [sys.executable, "-c", code], cwd=REPO_ROOT, capture_output=True, text=True, timeout=60 + ) + assert proc.returncode == 0, proc.stderr + assert proc.stdout.strip() == "[]" + + +# --- the 0777 log directory: the host never follows a link in it (security review) ----------- + + +def _canary(tmp_path: Path) -> Path: + canary = tmp_path / "canary.txt" # a stand-in for a host file outside the log directory + canary.write_text(f"host secret {SYNTHETIC}\n", encoding="utf-8") + return canary + + +async def test_a_linked_access_log_is_never_followed(tmp_path: Path) -> None: + canary = _canary(tmp_path) + sandbox, egress = await _opened(tmp_path, FakeDocker()) + access = egress.spool_dir / "access.log" + access.unlink() + access.symlink_to(canary) + problems = await sandbox.close_egress(egress) + assert canary.read_text() == f"host secret {SYNTHETIC}\n" # unchanged + assert sandbox.leaks == [] # unread: its key shape was never seen + assert not os.path.lexists(egress.log_dir / "access.log") + assert any("access.log" in p for p in problems) + assert json.loads((egress.log_dir / "collected.json").read_text())["ok"] is False + + +@pytest.mark.parametrize("kind", ["fifo", "directory"]) +async def test_a_cache_log_that_is_not_a_regular_file_is_refused(tmp_path: Path, kind: str) -> None: + sandbox, egress = await _opened(tmp_path, FakeDocker()) + cache = egress.spool_dir / "cache.log" + cache.unlink() + if kind == "fifo": + os.mkfifo(cache) + else: + cache.mkdir() + async with asyncio.timeout(10): # a FIFO must never block the teardown + problems = await sandbox.close_egress(egress) + assert any("cache.log" in p for p in problems) + assert json.loads((egress.log_dir / "collected.json").read_text())["ok"] is False + + +async def test_a_key_shaped_log_is_scrubbed_into_a_new_file(tmp_path: Path) -> None: + sandbox, egress = await _opened(tmp_path, FakeDocker()) + cache = egress.spool_dir / "cache.log" + cache.write_text(f"WARNING: header {SYNTHETIC}\n", encoding="utf-8") + original = tmp_path / "original-inode" + os.link(cache, original) # a second name for the original inode + await sandbox.close_egress(egress) + cache = egress.log_dir / "cache.log" + assert cache.read_text() == "WARNING: header [redacted]\n" + assert original.read_text() == f"WARNING: header {SYNTHETIC}\n" # never written + assert cache.stat().st_ino != original.stat().st_ino + assert sandbox.leaks and [p.name for p in egress.log_dir.glob("*.tmp")] == [] + + +async def test_a_linked_collected_json_is_replaced_not_followed(tmp_path: Path) -> None: + canary = _canary(tmp_path) + sandbox, egress = await _opened(tmp_path, FakeDocker()) + collected = egress.log_dir / "collected.json" + collected.symlink_to(canary) + await sandbox.close_egress(egress) + assert canary.read_text() == f"host secret {SYNTHETIC}\n" + assert not collected.is_symlink() and json.loads(collected.read_text())["ok"] is True + + +async def test_a_linked_log_dir_is_refused(tmp_path: Path) -> None: + # Before the proxy starts: a log directory that already exists as a link is refused. + elsewhere = tmp_path / "elsewhere" + elsewhere.mkdir() + docker = FakeDocker() + sandbox = _sandbox(tmp_path, docker) + (tmp_path / "run" / "egress").mkdir(parents=True) + (tmp_path / "run" / "egress" / "j").symlink_to(elsewhere) + with pytest.raises(BenchmarkValidationError, match="link"): + await sandbox.open_egress("j", (("api.anthropic.com", 443),)) + assert not docker.ran("run") and list(elsewhere.iterdir()) == [] + # At teardown: a log directory swapped for a link is neither read nor written. + (tmp_path / "late").mkdir() + job = _job("claude-sonnet-5-5") + sandbox, egress = await _opened(tmp_path / "late", FakeDocker(), job.job_id) + out = sandbox.config.out_dir + probe = out / "probe" + probe.mkdir(exist_ok=True) + (probe / "control.json").write_text('{"passed": true}') + (probe / f"{job.job_id}.json").write_text( + json.dumps({"passed": True, "proxy_prefix": PROBE_PREFIX.splitlines()}) + ) + _logs(elsewhere, cache=f"key {SYNTHETIC}\n") + moved = egress.log_dir.with_name("moved") + egress.log_dir.rename(moved) + egress.log_dir.symlink_to(elsewhere) + problems = await sandbox.close_egress(egress) + assert any("link" in p for p in problems) and sandbox.leaks == [] + assert (elsewhere / "cache.log").read_text() == f"key {SYNTHETIC}\n" + assert not (elsewhere / "collected.json").exists() + (elsewhere / "collected.json").write_text('{"ok": true}') + assert write_egress_summary(out, [job], [])["isolation_probe"] == "fail" + # A regular directory with exactly the same files cannot undo teardown's refusal. + egress.log_dir.unlink() + elsewhere.rename(egress.log_dir) + assert write_egress_summary(out, [job], [])["isolation_probe"] == "fail" + + +async def test_missing_docs_index_stops_preparation_before_probes(tmp_path: Path) -> None: + probes = Probes() + launcher = ContainerLauncher( + _sandbox(tmp_path, FakeDocker()), probe=probes, control=probes.control + ) + with pytest.raises(BenchmarkValidationError, match="index"): + await launcher.prepare([_job("scripted-anthropic", "python-docs")]) + assert probes.jobs == [] + + +@pytest.mark.parametrize("second", ["", 'OPENAI_API_KEY="dummy has spaces"']) +async def test_invalid_second_key_refuses_preparation_after_all_probes( + tmp_path: Path, second: str +) -> None: + keys = _keys(tmp_path, f"ANTHROPIC_API_KEY=dummy-one\n{second}") + probes = Probes() + launcher = ContainerLauncher( + _sandbox(tmp_path, FakeDocker(), keys_file=keys), probe=probes, control=probes.control + ) + jobs = [_job("claude-sonnet-5-5"), _job("gpt-6.1-sol")] + try: + with pytest.raises(BenchmarkValidationError, match="OPENAI_API_KEY") as error: + await launcher.prepare(jobs) + assert "dummy has spaces" not in str(error.value) + assert probes.jobs == ["control", *(job.job_id for job in jobs)] + finally: + await launcher.close() + + +async def test_worker_cleanup_waits_for_daemon_auto_removal(tmp_path: Path) -> None: + responses = iter(("removal of container owned-id is already in progress", "No such container")) + + async def removing(argv: Sequence[str]) -> Any: + assert list(argv) == ["docker", "rm", "-f", "owned-id"] + return _done(argv, 1, err=next(responses)) + + sandbox = Sandbox(_config(tmp_path), docker=removing, verify=_verified) + await sandbox.remove_container("owned-id") + assert list(responses) == [] + + +async def test_worker_cleanup_reports_stalled_daemon_removal( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + monkeypatch.setattr("benchmarks.agentic.sandbox._RESOURCE_RECOVERY_S", 0) + + async def stalled(argv: Sequence[str]) -> Any: + return _done(argv, 1, err="removal of container owned-id is already in progress") + + sandbox = Sandbox(_config(tmp_path), docker=stalled, verify=_verified) + with pytest.raises(BenchmarkValidationError, match="already in progress"): + await sandbox.remove_container("owned-id") + + +@pytest.mark.parametrize("repeat_cancel", [False, True]) +async def test_cleanup_failure_preserves_pending_cancellation( + tmp_path: Path, repeat_cancel: bool +) -> None: + started, release = asyncio.Event(), asyncio.Event() + + async def failing(argv: Sequence[str]) -> Any: + started.set() + await release.wait() + return _done(argv, 1, err="daemon disconnected") + + box = Sandbox(_config(tmp_path), docker=failing, verify=_verified) + cleanup = asyncio.create_task(box.remove_container("owned-id")) + await asyncio.wait_for(started.wait(), 1) + cleanup.cancel("operator interrupt") + if repeat_cancel: + await asyncio.sleep(0) + cleanup.cancel("second interrupt") + release.set() + with pytest.raises(asyncio.CancelledError, match="operator interrupt") as error: + await cleanup + assert isinstance(error.value.__cause__, BenchmarkValidationError) + assert "daemon disconnected" in str(error.value.__cause__) + + +@pytest.mark.parametrize("resource", ["network", "container", "partial"]) +async def test_cancelled_create_preserves_signal_when_rollback_fails( + tmp_path: Path, resource: str +) -> None: + name = "late" + docker = LateCreate(name) + # A failed create is recovered by label. Its first removal must not skip the next ID. + docker.fail = lambda args: ( + args[0] == "create" and resource == "partial" or ("rm" in args and args[-1] == "id-late") + ) + box = _sandbox(tmp_path, docker) + if resource == "partial": + docker.resources.update(dict.fromkeys(("id-late", "id-extra"), {box._ownership(name)})) + args = ("network", "create", name) if resource == "network" else ("create", "--name", name) + create = asyncio.create_task(box.create_resource(name, *args)) + await asyncio.wait_for(docker.started.wait(), 2) + create.cancel("signal SIGTERM") + docker.release.set() + with pytest.raises(asyncio.CancelledError, match="signal SIGTERM") as error: + await create + assert isinstance(error.value.__cause__, BenchmarkValidationError) + assert "rm" in str(error.value.__cause__) and "boom" in str(error.value.__cause__) + assert "id-extra" not in docker.resources + + +@pytest.mark.parametrize("failed_rm", ["proxy", "net"]) +async def test_cancelled_open_egress_finishes_both_removals(tmp_path: Path, failed_rm: str) -> None: + connecting, connected = asyncio.Event(), asyncio.Event() + removing, release = asyncio.Event(), asyncio.Event() + + class InterruptedConnect(FakeDocker): + async def __call__(self, argv: Sequence[str]) -> Any: + if argv[1:3] == ["network", "connect"]: + connecting.set() + await connected.wait() + if argv[1:3] == ["rm", "-f"]: + removing.set() + await release.wait() + return await super().__call__(argv) + + docker = InterruptedConnect(fail=lambda args: "rm" in args and args[-1].endswith(failed_rm)) + opening = asyncio.create_task(_sandbox(tmp_path, docker).open_egress("j", ())) + await asyncio.wait_for(connecting.wait(), 2) + opening.cancel("signal SIGTERM") + connected.set() + await asyncio.wait_for(removing.wait(), 2) + opening.cancel("signal SIGHUP") + await asyncio.sleep(0) + assert not opening.done() + release.set() + with pytest.raises(asyncio.CancelledError, match="signal SIGTERM") as error: + await opening + assert isinstance(error.value.__cause__, BenchmarkValidationError) + assert "boom" in str(error.value.__cause__) + assert docker.ran("rm", "-f", "id-pdmcp-r1-j-proxy") + assert docker.ran("network", "rm", "id-pdmcp-r1-j-net") + + +async def test_launcher_close_preserves_both_failed_network_ids_on_cancellation( + tmp_path: Path, +) -> None: + job = _job("scripted-anthropic") + network = f"pdmcp-{RUN}-{job.job_id}-net" + docker = LateCreate(network) + docker.fail = lambda args: args[:2] == ["network", "rm"] + sandbox = _sandbox(tmp_path, docker) + probes = Probes() + interrupted: list[asyncio.CancelledError] = [] + + class Launcher(ContainerLauncher): + async def prepare(self, jobs: Sequence[WorkerJob]) -> None: + try: + await super().prepare(jobs) + except asyncio.CancelledError as exc: + interrupted.append(exc) + raise + + task = asyncio.create_task( + run_jobs( + [job], + launcher=Launcher(sandbox, probe=probes, control=probes.control), + ledger=Mock(), + on_message=AsyncMock(), + log_dir=tmp_path / "logs", + cwd=tmp_path, + ) + ) + await asyncio.wait_for(docker.started.wait(), 2) + task.cancel("signal SIGTERM") + docker.release.set() + with pytest.raises(asyncio.CancelledError, match="signal SIGTERM") as error: + await task + assert error.value is interrupted[0] + trace = "".join(traceback.format_exception(error.value)) + for name in (network, sandbox.outside): + assert docker.ran("network", "rm", f"id-{name}") + assert f"id-{name}" in trace + + +async def test_cancelled_create_preserves_signal_when_cli_cannot_start(tmp_path: Path) -> None: + starting, release = asyncio.Event(), asyncio.Event() + failure = OSError("cannot start docker") + + async def unavailable(argv: Sequence[str]) -> Any: + starting.set() + await release.wait() + raise failure + + box = Sandbox(_config(tmp_path), docker=unavailable) + task = asyncio.create_task(box.ensure_outside()) + await asyncio.wait_for(starting.wait(), 2) + task.cancel("signal SIGTERM") + release.set() + with pytest.raises(asyncio.CancelledError, match="signal SIGTERM") as error: + await task + assert error.value.__cause__ is failure + + +def test_docker_rollback_helper_isolated_from_the_foreground_group() -> None: + # Only this test's new session can receive the group signal. + host = """ +import asyncio, json, signal, sys +from benchmarks.agentic.sandbox import docker_runner +received = [] +signal.signal(signal.SIGHUP, lambda sig, frame: received.append(sig)) +result = asyncio.run(docker_runner({})([sys.executable, "-c", sys.argv[1]])) +print(json.dumps([result.returncode, result.stdout.decode().strip(), bool(received)])) +""" + helper = """ +import os, signal, sys +parent = os.getppid() +assert parent > 1 and os.getpgid(parent) == os.getsid(parent) == parent +os.killpg(parent, signal.SIGHUP) +print("rollback complete" if sys.stdin.read(1) == "" else "read host input") +""" + run = subprocess.run( + [sys.executable, "-c", host, helper], + start_new_session=True, + input="host input", + capture_output=True, + text=True, + timeout=15, + check=True, + ) + assert json.loads(run.stdout) == [0, "rollback complete", True] + + +async def _run_prepare(box: Sandbox, job: WorkerJob) -> None: + probes = Probes() + await run_jobs( + [job], + launcher=ContainerLauncher(box, probe=probes, control=probes.control), + ledger=Mock(), + on_message=AsyncMock(), + log_dir=box.config.out_dir / "logs", + cwd=box.config.out_dir, + ) + + +@pytest.mark.parametrize("owned_ids", [("owned-a",), ("owned-a", "owned-b"), ()]) +async def test_lost_network_create_response_during_prepare( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, owned_ids: tuple[str, ...] +) -> None: + monkeypatch.setattr("benchmarks.agentic.sandbox._RESOURCE_RECOVERY_S", 0.2) + + class LostResponse(FakeDocker): + async def __call__(self, argv: Sequence[str]) -> Any: + if argv[1:3] == ["network", "create"]: + self.calls.append(list(argv)) + return _done(argv, 1, err="lost create response") + result = await super().__call__(argv) + if argv[1:3] == ["network", "ls"] and len(self.ran("network", "ls")) == 1: + assert not result.stdout + # The daemon publishes after the first list has taken its snapshot. + (create,) = self.ran("network", "create") + labels = {v for k, v in zip(create, create[1:]) if k == "--label"} + self.resources.update({i: labels for i in owned_ids}) + return result + + docker = LostResponse() + box = _sandbox(tmp_path, docker) + foreign = {"foreign-id": {f"{RUN_LABEL}={RUN}"}} + docker.resources.update(foreign) + with pytest.raises(BenchmarkValidationError, match="lost create response") as caught: + await _run_prepare(box, _job("scripted-anthropic")) + selector = f"label={box._ownership(box.outside)}" + lookups = docker.ran("network", "ls") + assert 2 <= len(lookups) <= 4 + assert all(c[3:] == ["--no-trunc", "--quiet", "--filter", selector] for c in lookups) + assert [c[-1] for c in docker.ran("network", "rm")] == list(owned_ids) + assert docker.resources == foreign + if not owned_ids: + assert "outcome is unknown" in str(caught.value) + assert selector in str(caught.value) + + +@pytest.mark.parametrize("network_failure", ["exit", "start", "timeout", "spool"]) +def test_failed_connect_reports_both_removals_to_caller_and_cli( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + capsys: pytest.CaptureFixture[str], + network_failure: str, +) -> None: + from benchmarks.__main__ import main + + if network_failure == "spool": + cleanup = tempfile.TemporaryDirectory.cleanup + + def denied(staging: tempfile.TemporaryDirectory[str]) -> None: + cleanup(staging) + raise OSError(f"private spool failure: {SYNTHETIC}") + + monkeypatch.setattr(tempfile.TemporaryDirectory, "cleanup", denied) + + job = _job("scripted-anthropic") + + class Disconnected(FakeDocker): + async def __call__(self, argv: Sequence[str]) -> Any: + args = argv[1:3] + if ( + args == ["network", "connect"] + or args == ["rm", "-f"] + or (args == ["network", "rm"] and argv[-1].endswith("-net")) + ): + self.calls.append(list(argv)) + if args == ["network", "rm"]: + if network_failure == "start": + raise OSError(f"cannot start {SYNTHETIC}") + if network_failure == "timeout": + raise subprocess.TimeoutExpired(["docker", SYNTHETIC], 120) + return _done(argv, 1, err=f"{args[-1]} disconnected {SYNTHETIC}") + return await super().__call__(argv) + + docker = Disconnected() + box = _sandbox(tmp_path, docker) + failures = [] + + def run(*args: Any, **kwargs: Any) -> None: + try: + asyncio.run(_run_prepare(box, job)) + except BenchmarkValidationError as exc: + failures.append(exc) + raise + + monkeypatch.setattr("benchmarks.agentic.run.run_agentic", run) + with pytest.raises(SystemExit) as stopped: + main(["agentic-run", "--corpus", "unused", "--out", str(tmp_path)]) + assert stopped.value.code == 2 + summary = capsys.readouterr().err + (failure,) = failures + proxy = f"id-{box.worker_name(job.job_id)}-proxy" + network = f"id-{box.worker_name(job.job_id)}-net" + assert [c[-1] for c in docker.calls if "rm" in c] == [proxy, network, f"id-{box.outside}"] + for message in (str(failure), summary): + assert proxy in message and network in message and "connect disconnected" in message + if network_failure == "spool": + assert "private spool failure: [redacted]" in message + assert SYNTHETIC not in message + assert SYNTHETIC not in "".join(traceback.format_exception(failure)) + + +@pytest.mark.parametrize("lookup_failure", ["exit", "start", "timeout", "multiple ids"]) +async def test_partial_proxy_recovery_reports_safe_selector_or_all_failed_ids( + tmp_path: Path, + lookup_failure: str, +) -> None: + job = _job("scripted-anthropic") + + class PartialProxy(FakeDocker): + async def __call__(self, argv: Sequence[str]) -> Any: + if argv[1:3] == ["run", "-d"]: + await super().__call__(argv) # created, but the caller did not receive an ID + return _done(argv, 1, err="proxy start failed") + if argv[1:3] == ["container", "ls"]: + self.calls.append(list(argv)) + if lookup_failure == "start": + raise OSError(f"cannot start {SYNTHETIC}") + if lookup_failure == "timeout": + raise subprocess.TimeoutExpired(["docker", SYNTHETIC], 120) + if lookup_failure == "exit": + return _done(argv, 1, err=f"daemon unavailable {SYNTHETIC}") + owned = next(i for i in self.resources if i.endswith("-proxy")) + self.resources["second-id"] = self.resources[owned] + return _done(argv, out=f"{owned}\nsecond-id") + if argv[1:3] == ["rm", "-f"]: + self.calls.append(list(argv)) + return _done(argv, 1, err=f"removal failed {SYNTHETIC}") + return await super().__call__(argv) + + docker = PartialProxy() + box = _sandbox(tmp_path, docker) + with pytest.raises(BenchmarkValidationError) as caught: + await _run_prepare(box, job) + proxy = f"{box.worker_name(job.job_id)}-proxy" + selector = f"label={box._ownership(proxy)}" + assert docker.ran("container", "ls")[0][-1] == selector + message = str(caught.value) + assert "proxy start failed" in message + if lookup_failure == "multiple ids": + ids = [f"id-{proxy}", "second-id"] + assert [c[-1] for c in docker.ran("rm", "-f")] == ids + assert all(i in message for i in ids) + else: + assert not docker.ran("rm", "-f") + assert selector in message + reason = {"exit": "daemon unavailable", "start": "cannot start", "timeout": "timed out"} + assert reason[lookup_failure] in message + assert SYNTHETIC not in "".join(traceback.format_exception(caught.value)) + + +@pytest.mark.parametrize("cancel_during_create", [True, False]) +async def test_repeated_interrupt_during_partial_proxy_recovery_retains_selector( + tmp_path: Path, + cancel_during_create: bool, +) -> None: + job = _job("scripted-anthropic") + proxy = f"pdmcp-{RUN}-{job.job_id}-proxy" + removing, removed = asyncio.Event(), asyncio.Event() + + class InterruptedLookup(LateCreate): + async def __call__(self, argv: Sequence[str]) -> Any: + if argv[1:3] == ["container", "ls"]: + self.calls.append(list(argv)) + raise OSError(f"daemon unavailable {SYNTHETIC}") + if argv[1:3] == ["network", "rm"]: + removing.set() + await removed.wait() + return await super().__call__(argv) + + docker = InterruptedLookup(proxy) + docker.fail = lambda args: ( + args[:2] == ["run", "-d"] + or (args[:2] == ["network", "rm"] and (cancel_during_create or args[-1].endswith("-out"))) + ) + box = _sandbox(tmp_path, docker) + task = asyncio.create_task(_run_prepare(box, job)) + await asyncio.wait_for(docker.started.wait(), 2) + if cancel_during_create: + task.cancel("signal SIGTERM") + docker.release.set() + await asyncio.wait_for(removing.wait(), 2) + if not cancel_during_create: + task.cancel("signal SIGTERM") + await asyncio.sleep(0) + task.cancel("second interrupt") + removed.set() + with pytest.raises(asyncio.CancelledError, match="signal SIGTERM") as caught: + await task + trace = "".join(traceback.format_exception(caught.value)) + assert docker.ran("container", "ls")[0][-1] == f"label={box._ownership(proxy)}" + assert f"label={box._ownership(proxy)}" in trace and "daemon unavailable" in trace + assert SYNTHETIC not in trace + assert [c[-1] for c in docker.ran("network", "rm")] == [ + f"id-{box.worker_name(job.job_id)}-net", + f"id-{box.outside}", + ] + assert f"id-{box.outside}" in trace + if cancel_during_create: + assert f"id-{box.worker_name(job.job_id)}-net" in trace + + +def test_cli_keeps_rollback_ids_when_an_earlier_proxy_log_leaks( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str] +) -> None: + from benchmarks.__main__ import main + + first = _job("scripted-anthropic") + second = _job("scripted-anthropic", "docs-fetch") + docker = FakeDocker() + box = _sandbox(tmp_path, docker) + failed_proxy = f"id-{box.worker_name(second.job_id)}-proxy" + failed_network = f"id-{box.worker_name(second.job_id)}-net" + docker.fail = lambda args: ( + args[-1] in (failed_proxy, failed_network) + and (args[:2] == ["network", "connect"] or "rm" in args) + ) + + async def probe(sandbox: Sandbox, egress: Egress, **kwargs: Any) -> dict[str, Any]: + _logs(egress.spool_dir, cache=f"warning {SYNTHETIC}") + return {"passed": True} + + def run(*args: Any, **kwargs: Any) -> None: + asyncio.run( + run_jobs( + [first, second], + launcher=ContainerLauncher(box, probe=probe, control=Probes().control), + ledger=Mock(), + on_message=AsyncMock(), + log_dir=tmp_path / "logs", + cwd=tmp_path, + ) + ) + + monkeypatch.setattr("benchmarks.agentic.run.run_agentic", run) + with pytest.raises(SystemExit) as stopped: + main(["agentic-run", "--corpus", "unused", "--out", str(tmp_path)]) + assert stopped.value.code == 3 + message = capsys.readouterr().err + assert failed_proxy in message and failed_network in message + assert "cache.log" in message and SYNTHETIC not in message + + +# Exercise real prepare, close and evidence reporting with scripted jobs and no Docker process. +_PAIR = [_job("scripted-anthropic"), replace(_job("scripted-anthropic"), job_id="second")] +_FIRST = _PAIR[0].job_id +_PROXY = f"id-pdmcp-{RUN}-{_FIRST}-proxy" +_NETWORK = f"id-pdmcp-{RUN}-{_FIRST}-net" +_GOOGLE = "AIza" + "g" * 35 +_PRIVATE_DETAIL = "private synthetic detail" + + +async def _run_collection_pair( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + docker: FakeDocker, + *, + setup_first: Callable[[Path], None] | None = None, + interruption: asyncio.CancelledError | None = None, +) -> None: + box = _sandbox(tmp_path, docker) + out = box.config.out_dir + + async def probe(sandbox: Sandbox, egress: Egress, **kwargs: Any) -> dict[str, Any]: + _logs(egress.spool_dir, access=PROBE_PREFIX) + record = {"passed": True, "proxy_prefix": PROBE_PREFIX.splitlines()} + (out / "probe/control.json").write_text('{"passed":true}') + (out / "probe" / f"{egress.job_id}.json").write_text(json.dumps(record)) + if setup_first is not None and egress.job_id == _FIRST: + setup_first(egress.spool_dir) + return record + + monkeypatch.setattr("benchmarks.agentic.host._supervise", AsyncMock(side_effect=interruption)) + try: + await run_jobs( + _PAIR, + launcher=ContainerLauncher(box, probe=probe, control=Probes().control), + ledger=Mock(), + on_message=AsyncMock(), + log_dir=out / "logs", + cwd=tmp_path, + ) + finally: + for job in _PAIR: + assert not docker.squid_spool(job.job_id).parent.exists() + assert docker.ran("network", "rm", f"id-{box.outside}") + assert json.loads((out / "egress/second/collected.json").read_text())["ok"] is True + assert not (out / "probe/second.collection-pending").exists() + + +def _check_first_collection(tmp_path: Path, *, ok: bool) -> Path: + out = tmp_path / "run" + assert (out / "probe" / f"{_FIRST}.collection-pending").exists() == (not ok) + assert write_egress_summary(out, _PAIR, [])["isolation_probe"] == ("pass" if ok else "fail") + return out / "egress" / _FIRST + + +@pytest.mark.parametrize( + "shape,interrupted", + [("newline", False), ("adjacent", False), ("field-name", False), ("adjacent", True)], +) +async def test_run_jobs_withholds_key_shaped_collection_state( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, shape: str, interrupted: bool +) -> None: + class Docker(FakeDocker): + async def __call__(self, argv: Sequence[str]) -> Any: + result = await super().__call__(argv) + if argv[1] == "inspect" and argv[-1] == _PROXY: + state = json.loads(result.stdout) + field = _PRIVATE_DETAIL + "\n" + _GOOGLE + if shape == "field-name": + state["Error"] = {field: _PRIVATE_DETAIL} + else: + state["Error"] = field + (SYNTHETIC if shape == "adjacent" else "") + result.stdout = json.dumps(state).encode() + return result + + failed_ids = {_PROXY, _NETWORK} if shape == "adjacent" else set() + docker = Docker(fail=lambda args: "rm" in args and args[-1] in failed_ids) + interrupt = asyncio.CancelledError("original test interruption") if interrupted else None + with pytest.raises(asyncio.CancelledError if interrupted else KeyLeakError) as caught: + await _run_collection_pair(tmp_path, monkeypatch, docker, interruption=interrupt) + if interrupted: + assert caught.value is interrupt and isinstance(caught.value.__cause__, KeyLeakError) + record = (_check_first_collection(tmp_path, ok=False) / "collected.json").read_text() + assert json.loads(record)["ok"] is False + trace = "".join(traceback.format_exception(caught.value)) + assert "collected.json" in trace + for output in (trace, record): + assert all(private not in output for private in (_PRIVATE_DETAIL, _GOOGLE, SYNTHETIC)) + assert all(owned in output for owned in failed_ids) + assert set(docker.resources) == failed_ids + + +@pytest.mark.parametrize("removal_fails", [False, True]) +async def test_one_time_encoding_oom_publishes_failed_collection_record( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, removal_fails: bool +) -> None: + survivors = {_PROXY, _NETWORK} if removal_fails else set() + docker = FakeDocker(fail=lambda args: "rm" in args and args[-1] in survivors) + dumps = json.dumps + failed = False + + def fail_full_record_once(value: Any, **kwargs: Any) -> str: + nonlocal failed + if not failed and isinstance(value, dict) and value.get("state_before_stop"): + failed = True + raise MemoryError(_PRIVATE_DETAIL + _GOOGLE) + return dumps(value, **kwargs) + + monkeypatch.setattr(json, "dumps", fail_full_record_once) + with pytest.raises(BenchmarkValidationError, match="MemoryError") as caught: + await _run_collection_pair(tmp_path, monkeypatch, docker) + assert failed and set(docker.resources) == survivors + directory = _check_first_collection(tmp_path, ok=False) + record = json.loads((directory / "collected.json").read_text()) + assert record["ok"] is False + assert record["state_before_stop"] == record["state_after_stop"] == {} + for output in (" ".join(record["problems"]), "".join(traceback.format_exception(caught.value))): + assert "MemoryError" in output and all(owned in output for owned in survivors) + assert _PRIVATE_DETAIL not in output and _GOOGLE not in output + + +@pytest.mark.parametrize( + "fault", ["memory", "encoding", "publish", "publish-leak", "collector", "interrupted", "cancel"] +) +async def test_run_jobs_preserves_removal_ids_after_collection_error( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, fault: str +) -> None: + from benchmarks.agentic import sandbox as module + + docker = FakeDocker(fail=lambda args: "rm" in args and args[-1] in {_PROXY, _NETWORK}) + interrupt = asyncio.CancelledError("original test interruption") + attempted_states = [] + if fault in {"encoding", "memory"}: + dumps = json.dumps + + def fail_encode(value: Any, **kwargs: Any) -> str: + if isinstance(value, dict) and "state_before_stop" in value and value["problems"]: + attempted_states.append(value["state_before_stop"]) + raise (ValueError if fault == "encoding" else MemoryError)(_PRIVATE_DETAIL) + return dumps(value, **kwargs) + + monkeypatch.setattr(json, "dumps", fail_encode) + else: + write = module.write_new + fail_name = "collected.json" if fault.startswith("publish") else "cache.log" + + def fail_write(dir_fd: int, name: str, data: bytes, **kwargs: Any) -> None: + if name == fail_name and len(docker.ran("stop")) == 1: + if fault == "cancel": + raise interrupt + if fault == "publish-leak": + raise KeyLeakError(_PRIVATE_DETAIL + _GOOGLE) + raise (OSError if fault == "publish" else RuntimeError)(_PRIVATE_DETAIL + _GOOGLE) + write(dir_fd, name, data, **kwargs) + + monkeypatch.setattr(module, "write_new", fail_write) + cancelled = fault in {"interrupted", "cancel"} + with pytest.raises(asyncio.CancelledError if cancelled else BenchmarkValidationError) as caught: + await _run_collection_pair( + tmp_path, + monkeypatch, + docker, + interruption=interrupt if fault == "interrupted" else None, + ) + if cancelled: + assert caught.value is interrupt + elif fault == "publish-leak": + assert isinstance(caught.value, KeyLeakError) + trace = "".join(traceback.format_exception(caught.value)) + assert _PROXY in trace and _NETWORK in trace + assert _PRIVATE_DETAIL not in trace and _GOOGLE not in trace + assert set(docker.resources) == {_PROXY, _NETWORK} + directory = _check_first_collection(tmp_path, ok=False) + if fault in {"encoding", "memory"}: + assert attempted_states == [RUNNING, {}] + assert not (directory / "collected.json").exists() + + +@pytest.mark.parametrize("size_case", ["sparse", "growing", "limit"]) +async def test_run_jobs_bounds_squid_reads( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, request: pytest.FixtureRequest, size_case: str +) -> None: + limit = 8 * 1024 * 1024 + read_sizes: list[int] = [] + + def prepare_log(spool: Path) -> None: + path = spool / "cache.log" + size = {"sparse": limit + 1, "growing": 1, "limit": limit}[size_case] + # Hold the original inode through both jobs so Linux cannot recycle it after unlink. + stream = path.open("r+b") + request.addfinalizer(stream.close) + stream.truncate(size) + identity = os.fstat(stream.fileno()) + read = os.read + + def instrument(fd: int, count: int) -> bytes: + if os.path.samestat(os.fstat(fd), identity): + read_sizes.append(count) + if size_case == "growing" and len(read_sizes) == 1: + with path.open("r+b") as writer: + writer.truncate(limit + 1) + return read(fd, count) + + monkeypatch.setattr(os, "read", instrument) + + docker = FakeDocker() + run = _run_collection_pair(tmp_path, monkeypatch, docker, setup_first=prepare_log) + if size_case == "limit": + await run + directory = _check_first_collection(tmp_path, ok=True) + assert (directory / "cache.log").stat().st_size == limit + else: + with pytest.raises(BenchmarkValidationError, match="cache.log"): + await run + directory = _check_first_collection(tmp_path, ok=False) + assert not (directory / "cache.log").exists() + if size_case == "sparse": + assert not read_sizes # refuse the descriptor before its first read + else: + assert 0 < sum(read_sizes) <= 2 # at most the original byte and one overflow byte + assert docker.resources == {} diff --git a/tests/benchmarks/test_agentic_sandbox_docker.py b/tests/benchmarks/test_agentic_sandbox_docker.py new file mode 100644 index 00000000..92d042c3 --- /dev/null +++ b/tests/benchmarks/test_agentic_sandbox_docker.py @@ -0,0 +1,275 @@ +"""The opt-in keyless docker test: the real sandbox on Docker Desktop, with scripted models only. + +Skipped unless ``BENCHMARK_DOCKER_TESTS=1`` and ``BENCHMARK_SANDBOX_IMAGE`` (the worker image +ID, built from HEAD by ``benchmarks/sandbox/run.sh``) are set. Never run in CI. It reads no +key, sets no key, makes no provider call and pulls nothing: every image is local, by ID or +digest. It settles the Docker behaviours no document covers (design note §§B, C), and the +runbook's "Docker Desktop results" records what it found. +""" + +from __future__ import annotations + +import asyncio +import json +import os +import socket +import subprocess +import threading +from collections.abc import Iterator +from pathlib import Path +from typing import Any + +import pytest + +from benchmarks.adapters.guard import PROVIDER_API_KEY_ENV +from benchmarks.agentic.egress import parse_proxy_log, read_log +from benchmarks.agentic.host import WorkerJob +from benchmarks.agentic.probe import IsolationProbeFailed, _one_shot, _probe_argv, isolation_probe +from benchmarks.agentic.run import run_agentic +from benchmarks.agentic.sandbox import ( + RUN_LABEL, + ContainerLauncher, + Sandbox, + SandboxConfig, +) +from benchmarks.runner import _repo_commit_sha +from tests.benchmarks.test_agentic_run import _config, _matrix_with +from tests.benchmarks.test_agentic_sandbox import _job +from tests.test_mcp_get_docs_cache_smoke import _create_contentful_json_index + +IMAGE = os.environ.get("BENCHMARK_SANDBOX_IMAGE", "") +pytestmark = pytest.mark.skipif( + os.environ.get("BENCHMARK_DOCKER_TESTS") != "1" or not IMAGE, + reason="opt-in: set BENCHMARK_DOCKER_TESTS=1 and BENCHMARK_SANDBOX_IMAGE=", +) +REPO_ROOT = Path(__file__).resolve().parents[2] +RUN_ID = f"docker-test-{os.getpid()}" +BIG = 150_000 # a trajectory frame well over 100,000 bytes + + +@pytest.fixture(autouse=True) +def _keyless(monkeypatch: pytest.MonkeyPatch) -> None: + for name in PROVIDER_API_KEY_ENV.values(): + monkeypatch.delenv(name, raising=False) # removed unread: this test holds no key + monkeypatch.delenv("CI", raising=False) + + +@pytest.fixture +def image() -> str: + return IMAGE + + +def _sandbox_config(tmp_path: Path, index: Path | None = None) -> SandboxConfig: + return SandboxConfig( + image=IMAGE, + run_id=RUN_ID, + out_dir=tmp_path / "run", + index_path=index or tmp_path / "no-index.db", + keys_file=None, + repo_commit=_repo_commit_sha(), + ) + + +def _docker(*args: str) -> subprocess.CompletedProcess[str]: + return subprocess.run(["docker", *args], capture_output=True, text=True, timeout=120) + + +@pytest.fixture +def sandbox(tmp_path: Path) -> Iterator[Sandbox]: + """A sandbox for single steps; every egress it opened is closed afterwards.""" + (tmp_path / "run").mkdir() + box = Sandbox(_sandbox_config(tmp_path)) + opened: list[Any] = [] + real_open = box.open_egress + + async def open_egress(job_id: str, allow: Any) -> Any: + egress = await real_open(job_id, allow) + opened.append(egress) + return egress + + box.open_egress = open_egress # type: ignore[method-assign] + yield box + + async def cleanup() -> None: + for egress in opened: + await box.close_egress(egress) + if box.outside_id is not None: + await box.run("network", "rm", box.outside_id) + + asyncio.run(cleanup()) + + +async def _probe_container(box: Sandbox, network: str, spec: dict[str, Any]) -> dict[str, Any]: + name = f"{box.worker_name('direct')}-probe" + argv = _probe_argv(box, name, network, spec, {"HOME": "/tmp"}) + return {c["check"]: c for c in await _one_shot(box, argv, name)} + + +def test_image_runs_unprivileged_with_cat_without_node_or_proxy(image: str) -> None: + script = "id -u; command -v cat; command -v node || echo no-node; env" + proc = _docker("run", "--rm", "--pull", "never", image, "sh", "-c", script) + assert proc.returncode == 0, proc.stderr + lines = proc.stdout.splitlines() + assert lines[:3] == ["10001", "/usr/bin/cat", "no-node"] + assert not [line for line in lines if "PROXY" in line.upper().split("=", 1)[0]] + assert ( + _docker( + "run", "--rm", "--pull", "never", image, "sh", "-c", "command -v mcp-server-fetch" + ).stdout.strip() + == "/usr/local/bin/mcp-server-fetch" + ) + + +def test_a_scripted_run_completes_inside_containers(tmp_path: Path, image: str) -> None: + index = _create_contentful_json_index(tmp_path / "index") + config = _config( + tmp_path, + models=("scripted-anthropic",), + systems=("python-docs", "no-docs"), + questions=("SYN-EX-001",), + repeats=1, + run_id=RUN_ID, + ) + + class CacheCheckingLauncher(ContainerLauncher): + def worker_create_argv(self, job: WorkerJob) -> list[str]: + argv = super().worker_create_argv(job) + if job.system.id == "python-docs": + worker = argv.index(self.sandbox.config.image) + 1 + argv[worker:] = [ + "sh", + "-c", + '"$@" && test -s /cache/mcp-python-docs/retrieved-docs-cache.sqlite3 ' + "&& echo cache-file-present >&2", + "sh", + *argv[worker:], + ] + return argv + + launcher = CacheCheckingLauncher(Sandbox(_sandbox_config(tmp_path, index))) + summary = run_agentic(config, launcher=launcher) + run = tmp_path / "run" + assert summary["status"] == "completed" and summary["succeeded_cells"] == 2 + control = json.loads((run / "probe" / "control.json").read_text()) + assert control["passed"] is True + for job_id in ("scripted-anthropic--python-docs", "scripted-anthropic--no-docs"): + probe = json.loads((run / "probe" / f"{job_id}.json").read_text()) + assert probe["passed"] is True, probe["failed"] + assert probe["network_inspect"]["EnableIPv6"] is False + events = parse_proxy_log((run / "egress" / job_id / "access.log").read_text()) + denied = {(e.method, e.host) for e in events if not e.allowed} + assert ("CONNECT", "example.com") in denied + assert any(m == "GET" and h == "host.docker.internal" for m, h in denied) + collected = json.loads((run / "egress" / job_id / "collected.json").read_text()) + assert collected["ok"] is True, collected["problems"] + assert collected["state_after_stop"]["ExitCode"] == 0 # Ubuntu's Squid, after SIGTERM + egress = json.loads((run / "egress" / "summary.json").read_text()) + assert set(egress) == {"jobs", "isolation_probe"} and egress["isolation_probe"] == "pass" + for entry in egress["jobs"].values(): + assert entry["hosts_allowed"] == [] and entry["hosts_denied"] == [] + transcript = run / "transcripts" / "python-docs--scripted-anthropic--r1" / "SYN-EX-001.json" + calls = json.loads(transcript.read_text())["tool_calls"] + assert calls and not calls[0]["is_error"] + worker_log = run / "logs" / "scripted-anthropic--python-docs.stderr.log" + assert "cache-file-present" in worker_log.read_text().splitlines() + + +def test_a_trajectory_frame_over_100000_bytes_round_trips_through_a_container( + tmp_path: Path, image: str +) -> None: + answer = "x" * BIG + script = [{"text": answer, "usage": {"input_tokens": 1000, "output_tokens": 100}}] + config = _config( + tmp_path, + matrix_path=_matrix_with(tmp_path, {"scripted-anthropic": script}), + models=("scripted-anthropic",), + systems=("no-docs",), + questions=("SYN-EX-001",), + repeats=1, + run_id=RUN_ID, + ) + launcher = ContainerLauncher(Sandbox(_sandbox_config(tmp_path))) + summary = run_agentic(config, launcher=launcher) + assert summary["status"] == "completed", summary.get("abort_reason") + transcript = tmp_path / "run" / "transcripts" / "no-docs--scripted-anthropic--r1" + assert json.loads((transcript / "SYN-EX-001.json").read_text())["answer"] == answer + + +async def test_an_ip_literal_connect_whose_ptr_names_an_allowlisted_host_is_denied( + sandbox: Sandbox, +) -> None: + egress = await sandbox.open_egress("ptr", (("localhost", 443),)) + checks = await _probe_container( + sandbox, egress.network, {"token": "t", "denied": ["127.0.0.1", 443]} + ) + assert checks["proxy_denied"]["passed"] is True, checks["proxy_denied"] + await asyncio.sleep(1) + events = parse_proxy_log(read_log(egress.spool_dir / "access.log").decode()) + # TCP_DENIED, or TCP_DENIED_ABORTED when the probe closes after reading the status line. + assert [(e.host, e.port, e.allowed) for e in events] == [("127.0.0.1", 443, False)] + assert events[0].result.startswith("TCP_DENIED") + + +@pytest.fixture +def loopback_service() -> Iterator[int]: + """An HTTP service bound to the Mac's 127.0.0.1 only, as Ollama is by default.""" + server = socket.create_server(("127.0.0.1", 0)) + stop = threading.Event() + + def serve() -> None: + server.settimeout(0.2) + while not stop.is_set(): + try: + conn, _ = server.accept() + except TimeoutError: + continue + with conn: + conn.recv(4096) + conn.sendall(b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\nConnection: close\r\n\r\nok") + + thread = threading.Thread(target=serve, daemon=True) + thread.start() + yield server.getsockname()[1] + stop.set() + thread.join(5) + server.close() + + +async def test_a_service_bound_to_the_macs_loopback_through_the_proxy( + sandbox: Sandbox, loopback_service: int +) -> None: + egress = await sandbox.open_egress("loop", (("host.docker.internal", loopback_service),)) + url = f"http://host.docker.internal:{loopback_service}/api/version" + checks = await _probe_container(sandbox, egress.network, {"token": "t", "allowed_http": [url]}) + assert checks["allowed_http"]["passed"] is True, checks["allowed_http"] + + +async def test_a_docker_config_with_proxies_fails_the_isolation_probe( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, request: pytest.FixtureRequest +) -> None: + endpoint = json.loads(_docker("context", "inspect", "--format", "{{json .}}").stdout) + host = endpoint["Endpoints"]["docker"]["Host"] + config_dir = tmp_path / "docker-config" + config_dir.mkdir() + proxies = {"proxies": {"default": {"httpsProxy": "http://proxy.invalid:3128"}}} + (config_dir / "config.json").write_text(json.dumps(proxies)) + monkeypatch.setenv("DOCKER_CONFIG", str(config_dir)) + monkeypatch.setenv("DOCKER_HOST", host) # the same local daemon, without the context store + # Construct the fixture after setting the environment captured by the sandbox CLI. + box: Sandbox = request.getfixturevalue("sandbox") + egress = await box.open_egress("cfg", (("api.anthropic.com", 443),)) + family = _job("scripted-anthropic").family + with pytest.raises(IsolationProbeFailed, match="HTTPS_PROXY"): + await isolation_probe(box, egress, job_id="cfg", family=family, system_id="no-docs") + + +def test_no_container_or_network_with_the_run_label_remains(image: str) -> None: + containers = _docker( + "ps", "-a", "--filter", f"label={RUN_LABEL}={RUN_ID}", "--format", "{{.Names}}" + ) + networks = _docker( + "network", "ls", "--filter", f"label={RUN_LABEL}={RUN_ID}", "--format", "{{.Name}}" + ) + containers.check_returncode() + networks.check_returncode() + assert containers.stdout.strip() == "" and networks.stdout.strip() == "" diff --git a/tests/benchmarks/test_agentic_sandbox_files.py b/tests/benchmarks/test_agentic_sandbox_files.py new file mode 100644 index 00000000..2bdee7e9 --- /dev/null +++ b/tests/benchmarks/test_agentic_sandbox_files.py @@ -0,0 +1,92 @@ +"""Static checks of the sandbox's committed files: no Docker and no network.""" + +from __future__ import annotations + +import os +import subprocess +from pathlib import Path + +import pytest + +REPO_ROOT = Path(__file__).resolve().parents[2] +SANDBOX = REPO_ROOT / "benchmarks" / "sandbox" + + +def _requirements(path: Path) -> list[str]: + """Logical requirement lines: continuations joined, comments and blanks dropped.""" + text = path.read_text(encoding="utf-8").replace("\\\n", " ") + lines = (line.strip() for line in text.splitlines()) + return [line for line in lines if line and not line.startswith("#")] + + +def test_fetch_requirements_pin_the_researched_release_with_hashes() -> None: + requirements = _requirements(SANDBOX / "fetch-requirements.txt") + assert any(line.startswith("mcp-server-fetch==2026.10.19 ") for line in requirements) + assert requirements and all("--hash=sha256:" in line for line in requirements) + assert all("==" in line.split()[0] for line in requirements) # every package pinned + + +PYTHON_IMAGE = ( + "python:3.14.10-slim-trixie" + "@sha256:930e1abba7c4e8f96ed93e8012c35d174d7732752731bbd5e8e757d7ec6f3966" +) +UV_IMAGE = ( + "ghcr.io/astral-sh/uv:0.13.4" + "@sha256:9f130421e930bfbdc563c00740466603f8723158e90297d07957c2294640262b" +) + + +def test_dockerfile_pins_every_base_by_digest_and_runs_unprivileged() -> None: + text = (SANDBOX / "Dockerfile").read_text(encoding="utf-8") + lines = [line.strip() for line in text.splitlines()] + assert [line for line in lines if line.startswith("FROM ")][0] == f"FROM {PYTHON_IMAGE}" + copies = [line for line in lines if line.startswith("COPY --from=")] + assert copies == [f"COPY --from={UV_IMAGE} /uv /uvx /bin/"] + assert not [line for line in lines if line.lower().startswith("# syntax")] + assert [line for line in lines if line.startswith("USER ")][-1] == "USER 10001:10001" + env = " ".join(line for line in lines if line.startswith("ENV ")) + assert not any(name in env for name in ("PROXY", "SSL_CERT", "REQUESTS_CA")) + for needed in ("uv sync --locked", "command -v cat", "! command -v node"): + assert needed in text + + +def test_run_sh_builds_from_git_archive_and_defaults_to_a_dry_run() -> None: + path = SANDBOX / "run.sh" + text = path.read_text(encoding="utf-8") + assert os.access(path, os.X_OK) + assert "git archive --format=tar HEAD" in text and "set -euo pipefail" in text + assert "--live" not in text # live only when the operator passes it + for banned in ("git status", "printenv", "env |", "set -x", "cat .env"): + assert banned not in text + for tool in ("git", "docker", "uv", "cat"): + assert tool in text.split("for tool in", 1)[1].split(";", 1)[0] + + +@pytest.mark.parametrize("key", ["ANTHROPIC_API_KEY", "OPENAI_API_KEY", "GOOGLE_API_KEY", None]) +def test_run_sh_filters_the_build_environment_before_docker( + tmp_path: Path, key: str | None +) -> None: + docker = tmp_path / "docker" + docker.write_text( + '#!/bin/sh\ncat >/dev/null\nprintf "%s" "${BUILD_CANARY-}" > "$0.started"\nexit 42\n' + ) + docker.chmod(0o700) + marker = Path(f"{docker}.started") + env = {name: os.environ[name] for name in ("HOME", "PATH")} + env.update(PATH=f"{tmp_path}:{env['PATH']}", BUILD_CANARY="exported") + if key is not None: + env[key] = "dummy-key-for-test" + result = subprocess.run( + [str(SANDBOX / "run.sh")], + env=env, + cwd=REPO_ROOT, + capture_output=True, + text=True, + timeout=45, + ) + if key is not None: + assert result.returncode != 0 and not marker.exists() + assert key in result.stderr and env[key] not in result.stderr + else: + assert result.returncode == 42 + assert marker.read_text() == "" diff --git a/tests/benchmarks/test_agentic_schemas.py b/tests/benchmarks/test_agentic_schemas.py index 067107f5..83cb0271 100644 --- a/tests/benchmarks/test_agentic_schemas.py +++ b/tests/benchmarks/test_agentic_schemas.py @@ -10,6 +10,7 @@ schemas_sha256, to_anthropic, to_gemini, + to_openai_chat, to_openai_responses, ) from benchmarks.agentic.types import ToolSpec @@ -106,3 +107,17 @@ def test_gemini_schema_keys_come_from_the_pinned_sdk() -> None: def test_schemas_sha256_ignores_key_order() -> None: assert schemas_sha256([{"a": 1, "b": "é"}]) == schemas_sha256([{"b": "é", "a": 1}]) assert schemas_sha256([{"a": 1}]) != schemas_sha256([{"a": 2}]) + + +def test_to_openai_chat_wraps_each_tool_with_strict_false() -> None: + converted = to_openai_chat(TOOLS) + assert len(converted) == 7 + assert converted[0] == { + "type": "function", + "function": { + "name": TOOLS[0].name, + "description": TOOLS[0].description, + "parameters": TOOLS[0].input_schema, + "strict": False, + }, + } diff --git a/tests/benchmarks/test_agentic_stdio_cancellation.py b/tests/benchmarks/test_agentic_stdio_cancellation.py new file mode 100644 index 00000000..84a47088 --- /dev/null +++ b/tests/benchmarks/test_agentic_stdio_cancellation.py @@ -0,0 +1,239 @@ +"""SDK reader cancellation must stop a job even while its host owes a reply.""" + +import asyncio +import json +import sys +from pathlib import Path + +import pytest + +from benchmarks.adapters.guard import PROVIDER_API_KEY_ENV +from benchmarks.agentic import clients, mcp_stdio, worker +from benchmarks.agentic.bridge import system_spec_from_raw +from benchmarks.agentic.host import LocalLauncher, run_jobs +from benchmarks.agentic.protocol import FrameTooLarge, KeyLeakError +from tests.benchmarks.test_agentic_host import ANSWER, REPO_ROOT, Host, _job +from tests.benchmarks.test_agentic_loop import TOOL + +SERVER = Path(__file__).parent / "fixtures/agentic/grant_fault_server.py" + + +@pytest.fixture +def host(tmp_path, monkeypatch): + for name in PROVIDER_API_KEY_ENV.values(): + monkeypatch.delenv(name, raising=False) + value = Host(tmp_path) + yield value + value.ledger.close() + + +@pytest.mark.parametrize( + "kind,code,error", [("frame", 4, FrameTooLarge), ("credential", 3, KeyLeakError)] +) +@pytest.mark.parametrize("boundary", ["first-grant", "next-grant", "settlement"]) +async def test_sdk_fault_while_host_owes_reply_stops_run( + tmp_path, monkeypatch, host, kind, code, error, boundary +): + marker, calls, outcome = (tmp_path / name for name in ("notify", "calls", "outcome")) + program = tmp_path / "worker.py" + program.write_text(f""" +import sys +sys.path.insert(0, {str(REPO_ROOT)!r}) +import json +from pathlib import Path +from benchmarks.agentic import clients, mcp_stdio, worker +from benchmarks.agentic.protocol import KeyLeakError +mcp_stdio.MAX_FRAME_BYTES = 512 +check = worker.ProtocolChannel.check_content +def check_content(self, content): + check(self, content) + if b'orchard' in content: + raise KeyLeakError('benign content-check sentinel') +worker.ProtocolChannel.check_content = check_content +call = clients.ScriptedClient.call +async def record_call(self, conv): + with Path({str(calls)!r}).open('a') as file: + file.write('provider\\n') + return await call(self, conv) +clients.ScriptedClient.call = record_call +processes = [] +create = mcp_stdio._create_platform_compatible_process +async def capture(**kwargs): + process = await create(**kwargs) + processes.append(process) + return process +mcp_stdio._create_platform_compatible_process = capture +code = worker.main_worker() +Path({str(outcome)!r}).write_text(json.dumps({{ + 'code': code, 'children': [p.returncode for p in processes]}})) +raise SystemExit(code) +""") + system = system_spec_from_raw( + { + "id": "synthetic", + "adapter": "mcp-stdio", + "command": ["{python}", str(SERVER), str(marker), kind], + } + ) + job = _job(tmp_path, [TOOL, ANSWER, ANSWER], system=system) + processes = [] + spawn = asyncio.create_subprocess_exec + + async def start(*args, **kwargs): + process = await spawn(*args, **kwargs) + processes.append(process) + return process + + monkeypatch.setattr(asyncio, "create_subprocess_exec", start) + monkeypatch.setattr( + LocalLauncher, "command", lambda self, job: ([sys.executable, "-I", str(program)], {}) + ) + service = host.service(job.family) + operation = "settle" if boundary == "settlement" else "reserve" + original = getattr(service, operation) + requests = 0 + + async def delayed_reply(*args, **kwargs): + nonlocal requests + requests += 1 + if requests == (2 if boundary == "next-grant" else 1): + marker.touch() + # The worker must terminate without needing the outstanding host reply. + await asyncio.wait_for(processes[0].wait(), 5) + return await original(*args, **kwargs) + + monkeypatch.setattr(service, operation, delayed_reply) + async with asyncio.timeout(10): + with pytest.raises(error): + await run_jobs( + [job], + launcher=LocalLauncher(), + ledger=service, + on_message=host.on_message, + log_dir=tmp_path / "logs", + cwd=REPO_ROOT, + ) + assert processes[0].returncode == code + assert json.loads(outcome.read_text()) == {"code": code, "children": [0]} + assert (calls.read_text().splitlines() if calls.exists() else []) == ( + [] if boundary == "first-grant" else ["provider"] + ) + assert [m["type"] for m in host.messages()] == ["system_info"] + events = host.ledger.invocation_events() + assert [e["event"] for e in events] == ( + ["reserve", "settle", "reserve", "settle"] + if boundary == "next-grant" + else ["reserve", "settle"] + ) + assert [e["outcome"] for e in events if e["event"] == "settle"] == { + "first-grant": ["worker_lost"], + "next-grant": ["ok", "worker_lost"], + "settlement": ["ok"], + }[boundary] + assert ( + await service.reserve( + provider=job.family.provider, + model_id=job.family.model_id, + input_bound=1, + output_bound=1, + ) + is None + ) + + +@pytest.mark.parametrize("kind", ["frame", "credential"]) +@pytest.mark.parametrize("fault", [False, True]) +@pytest.mark.parametrize("cancellation", ["operator", "repeated", "timeout"]) +async def test_operator_cancellation_wins_and_drains_sdk_job( + tmp_path, monkeypatch, kind, fault, cancellation +): + marker = tmp_path / "notify" + system = system_spec_from_raw( + { + "id": "synthetic", + "adapter": "mcp-stdio", + "command": ["{python}", str(SERVER), str(marker), kind], + } + ) + job = _job(tmp_path, [TOOL, ANSWER], system=system) + monkeypatch.setattr(mcp_stdio, "MAX_FRAME_BYTES", 512) + reader = asyncio.StreamReader() + messages, processes = [], [] + create = mcp_stdio._create_platform_compatible_process + + async def capture(**kwargs): + process = await create(**kwargs) + processes.append(process) + return process + + monkeypatch.setattr(mcp_stdio, "_create_platform_compatible_process", capture) + client = clients.ScriptedClient("anthropic", "scripted-1", [TOOL, ANSWER]) + monkeypatch.setattr(clients, "make_client", lambda *args, **kwargs: client) + + def interrupt(): + if cancellation == "timeout": + timer.reschedule(asyncio.get_running_loop().time()) + else: + owner.cancel("operator interrupt") + if cancellation == "repeated": + asyncio.get_running_loop().call_soon(owner.cancel, "later interrupt") + + class Channel: + def check_content(self, content): + if b"orchard" in content: + raise KeyLeakError("benign content-check sentinel") + + def send(self, message): + messages.append(message) + if message["type"] == "reserve": + if fault: + marker.touch() + else: + interrupt() + + close = worker._close + + async def cancel_during_unwind(stack, pending=None): + if fault and pending is not None: + interrupt() + await close(stack, pending) + + monkeypatch.setattr(worker, "_close", cancel_during_unwind) + before = asyncio.all_tasks() + timer = asyncio.timeout(None) + + async def invoke(): + async with timer: + return await worker.run_worker( + Channel(), + reader, + { + "type": "job", + "family": job.family.raw, + "system": job.system.raw, + "caps": {}, + "trajectories": list(job.trajectories), + }, + ) + + owner = asyncio.create_task(invoke()) + with pytest.raises( + TimeoutError if cancellation == "timeout" else asyncio.CancelledError, + match=None if cancellation == "timeout" else "operator interrupt", + ): + await asyncio.wait_for(owner, 5) + assert timer.expired() == (cancellation == "timeout") + assert owner.done() + assert len(processes) == 1 and processes[0].returncode is not None + assert [m["type"] for m in messages] == ["system_info", "reserve"] + await asyncio.sleep(0) # Run done callbacks before checking for abandoned SDK tasks. + assert not (asyncio.all_tasks() - before - {asyncio.current_task()}) + + +async def test_unrecognized_job_cancellation_is_not_a_frame_failure(monkeypatch): + async def cancelled(*args, **kwargs): + raise asyncio.CancelledError("job cancelled without a recognized reply failure") + + monkeypatch.setattr(worker, "_run_job", cancelled) + with pytest.raises(asyncio.CancelledError, match="without a recognized reply failure"): + await worker.run_worker(None, None) diff --git a/tests/benchmarks/test_agentic_worker_content.py b/tests/benchmarks/test_agentic_worker_content.py new file mode 100644 index 00000000..bac3215e --- /dev/null +++ b/tests/benchmarks/test_agentic_worker_content.py @@ -0,0 +1,243 @@ +"""Literal bootstrap credentials stay inside synthetic workers, before any side effect.""" + +from __future__ import annotations + +import json +import sys +from pathlib import Path +from textwrap import dedent + +import pytest + +from benchmarks.agentic.loop import Caps + + +@pytest.mark.parametrize("shaped", [False, True]) +@pytest.mark.parametrize( + "source", + [ + "prompt", + "schema", + "settings", + "limits", + "args", + "later-args", + "name", + "id", + "raw-args", + "text", + "structured", + "hidden-text", + "error-result", + "mcp-error", + "mcp-error-data", + "closed", + "exception", + "beyond-cap", + "truncation-marker", + "provider-error", + "answer", + ], +) +def test_bootstrap_literal_stops_worker_before_outgoing_side_effects( + tmp_path: Path, monkeypatch, capsys, shaped, source +): + from benchmarks.__main__ import main + from benchmarks.agentic.host import LocalLauncher + from tests.benchmarks.test_agentic_run import _cli_args + + # Only the worker constructs and holds the synthetic bootstrap value. It is never + # passed as argv, a host bootstrap, an environment file, or a public record. + program = tmp_path / "literal_worker.py" + calls = tmp_path / "calls.txt" + program.write_text( + dedent(f"""\ + import sys + sys.path.insert(0, {str(Path(__file__).resolve().parents[2])!r}) + from pathlib import Path + from dataclasses import replace + from mcp import MCPError + from mcp.types import CallToolResult, TextContent, CONNECTION_CLOSED + from benchmarks.agentic import clients, worker + from benchmarks.agentic.types import ProviderCallError + from tests.benchmarks.test_agentic_outgoing import _bridge + from tests.benchmarks.test_agentic_loop import TOOL, ANSWER + + token = ('AIza' + 'q' * 35) if {shaped!r} else ('dummy_bootstrap_' + 'opaque') + if {source!r} == 'truncation-marker': + token = 'UTF-8 ' + 'bytes' + value = 'prefix' + token + '-suffix' + source = {source!r} + def note(kind): + with Path({str(calls)!r}).open('a') as file: + file.write(kind + '\\n') + # A private synthetic first frame, followed by the host's ordinary job on stdin. + worker.read_frame_fd = lambda fd: {{ + 'type': 'bootstrap', 'env': {{'GOOGLE_API_KEY': token}}}} + read = worker.read_frame + async def read_job(reader): + frame = await read(reader) + if source == 'prompt' and frame and frame.get('type') == 'job': + frame['trajectories'][0]['prompt'] = value + if source == 'limits' and frame and frame.get('type') == 'job': + frame['family']['api'] = 'anthropic-messages' + return frame + worker.read_frame = read_job + + class RecordingClient(clients.ScriptedClient): + def request_params(self): + return {{'model': value}} if source == 'settings' else super().request_params() + async def call(self, conv): + note('provider') + if source == 'provider-error': + raise ProviderCallError('server', value, status=500) + turn = await super().call(conv) + call = turn.tool_calls[0] if turn.tool_calls else None + if source in ('args', 'later-args'): + bad = replace(call, arguments={{'query': value}}) + turn = replace(turn, tool_calls=(bad,) if source == 'args' else (call, bad)) + elif source == 'name': + turn = replace(turn, tool_calls=(replace(call, name=value),)) + elif source == 'id': + turn = replace(turn, tool_calls=(replace(call, id=value),)) + elif source == 'raw-args': + turn = replace(turn, tool_calls=(replace(call, raw_arguments=value),)) + elif source == 'answer': + turn = replace(turn, text=value, tool_calls=()) + return turn + clients.make_client = lambda family, **kw: RecordingClient( + family.provider, value if source == 'limits' else family.model_id, [TOOL, ANSWER]) + if source == 'limits': + RecordingClient.api = 'anthropic-messages' + async def fetch_limits(client): + note('limits') + return None + clients.fetch_model_limits = fetch_limits + async def open_bridge(stack, system, **kwargs): + text, structured = 'safe', None + if source in ('text', 'error-result', 'hidden-text'): + text = value + if source in ('structured', 'mcp-error-data'): + structured = {{'nested': [{{value: 'safe'}}]}} + elif source == 'hidden-text': + structured = {{'output': 'safe'}} + elif source == 'beyond-cap': + text = 'z' * 200 + value + elif source == 'truncation-marker': + text = 'z' * 200 + result = CallToolResult(content=[TextContent(type='text', text=text)], + structuredContent=structured, isError=source == 'error-result') + if source in ('mcp-error', 'closed', 'mcp-error-data'): + result = MCPError(CONNECTION_CLOSED if source == 'closed' else -32603, + 'safe' if source == 'mcp-error-data' else value, structured) + elif source == 'exception': + result = RuntimeError(value) + bridge, call = _bridge(result) + original = bridge._session.call_tool + async def dispatch(*args, **kwargs): + note('bridge') + return await original(*args, **kwargs) + bridge._session.call_tool = dispatch + if source == 'schema': + bridge.tools[0].input_schema['description'] = value + return bridge + worker._open = open_bridge + raise SystemExit(worker.main_worker()) + """) + ) + monkeypatch.setattr( + LocalLauncher, "command", lambda self, job: ([sys.executable, "-I", str(program)], {}) + ) + monkeypatch.setattr("benchmarks.agentic.run.HOSTED_CAPS", Caps(result_bytes=100)) + with pytest.raises(SystemExit) as error: + main( + [ + *_cli_args(tmp_path), + "--models", + "scripted-anthropic", + "--systems", + "no-docs", + "--questions", + "SYN-EX-001", + "--repeats", + "1", + ] + ) + assert error.value.code == 3 + seen = calls.read_text().splitlines() if calls.exists() else [] + initial = source in ("prompt", "schema", "settings", "limits") + no_bridge = initial or source in ( + "args", + "later-args", + "name", + "id", + "raw-args", + "provider-error", + "answer", + ) + assert seen.count("provider") == (0 if initial else 1) + assert seen.count("bridge") == (0 if no_bridge else 1) + assert seen.count("limits") == 0 + ledger = tmp_path / "ledger" / "anthropic.jsonl" + events = ( + [json.loads(line) for line in ledger.read_text().splitlines()] if ledger.exists() else [] + ) + assert sum(e["event"] == "reserve" for e in events) == (0 if initial else 1) + assert sum(e["event"] == "settle" for e in events) == (0 if initial else 1) + captured = capsys.readouterr() + assert "key leak" in captured.err + # Reconstruct only for assertions after the worker exits; never give it to the host. + token = ("AIza" + "q" * 35) if shaped else ("dummy_bootstrap_" + "opaque") + if source == "truncation-marker": + token = "UTF-8 bytes" + assert token not in captured.err + captured.out + assert not list((tmp_path / "run" / "transcripts").rglob("*.json")) + for root in (tmp_path / "run", tmp_path / "ledger"): + assert all(token.encode() not in p.read_bytes() for p in root.rglob("*") if p.is_file()) + + +@pytest.mark.parametrize("location", ["env", "command"]) +async def test_bootstrapped_job_cannot_pass_worker_secret_to_mcp_child(monkeypatch, location): + import asyncio + from tempfile import TemporaryFile + from unittest.mock import AsyncMock, Mock + + from benchmarks.agentic import bridge, clients, worker + from benchmarks.agentic.protocol import WORKER_LEAK_REASON, encode_frame + from tests.benchmarks.test_agentic_sandbox import FAMILIES, SYSTEMS + + token = "AI" + "za" + "g" * 35 + embedded = "prefix" + token + "-suffix" + system = dict(SYSTEMS["python-docs"].raw) + if location == "env": + system["env"] = {"MCP_AUTH": embedded} + else: + system["command"] = [*system["command"], embedded] + job = { + "type": "job", + "family": FAMILIES["gemini-3.8-flash"].raw, + "system": system, + "caps": {}, + "trajectories": [], + } + reader = asyncio.StreamReader() + reader.feed_data(encode_frame(job, where="job frame")) + reader.feed_eof() + client = Mock() + client.request_params.return_value = {"model": job["family"]["model_id"]} + create = Mock(return_value=client) + limits = AsyncMock(return_value=None) + launch = Mock(side_effect=RuntimeError("child launch intercepted")) + monkeypatch.setattr(clients, "make_client", create) + monkeypatch.setattr(clients, "fetch_model_limits", limits) + monkeypatch.setattr(bridge, "checked_stdio_client", launch) + + with TemporaryFile() as output: + channel = worker.ProtocolChannel(output.fileno(), (token.encode(),), -1, None, ()) + code = await worker.run_worker(channel, reader, bootstrapped=True) + output.seek(0) + frame = json.loads(output.read()[8:]) + assert (code, frame) == (3, {"type": "error", "reason": WORKER_LEAK_REASON}) + create.assert_not_called() + limits.assert_not_awaited() + launch.assert_not_called() diff --git a/tests/test_ci_workflows.py b/tests/test_ci_workflows.py index ee67655b..a8a95137 100644 --- a/tests/test_ci_workflows.py +++ b/tests/test_ci_workflows.py @@ -214,3 +214,11 @@ def test_release_build_job_never_builds_the_project_with_an_unpinned_backend() - "UV_BUILD_CONSTRAINT": ".github/build-constraints.txt", "UV_REQUIRE_HASHES": "1", } + + +def test_security_audit_covers_the_sandbox_fetch_requirements() -> None: + workflow = PROJECT_ROOT / ".github" / "workflows" / "security.yml" + job = yaml.safe_load(workflow.read_text(encoding="utf-8"))["jobs"]["dependency-audit"] + (step,) = [s for s in job["steps"] if s.get("name") == "Audit dependencies"] + assert "--requirement requirements-audit.txt" in step["run"] + assert "--requirement benchmarks/sandbox/fetch-requirements.txt" in step["run"]